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.

261045 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() + 8) >> 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 (commonBitLength <= 0
  4485. || (commonBitLength == 1 && thisPath [1] == File::separator))
  4486. return fullPath;
  4487. thisPath = thisPath.substring (commonBitLength);
  4488. dirPath = dirPath.substring (commonBitLength);
  4489. while (dirPath.isNotEmpty())
  4490. {
  4491. #if JUCE_WIN32
  4492. thisPath = T("..\\") + thisPath;
  4493. #else
  4494. thisPath = T("../") + thisPath;
  4495. #endif
  4496. const int sep = dirPath.indexOfChar (separator);
  4497. if (sep >= 0)
  4498. dirPath = dirPath.substring (sep + 1);
  4499. else
  4500. dirPath = String::empty;
  4501. }
  4502. return thisPath;
  4503. }
  4504. void File::findFileSystemRoots (OwnedArray<File>& destArray) throw()
  4505. {
  4506. const StringArray roots (juce_getFileSystemRoots());
  4507. for (int i = 0; i < roots.size(); ++i)
  4508. destArray.add (new File (roots[i]));
  4509. }
  4510. const String File::getVolumeLabel() const throw()
  4511. {
  4512. int serialNum;
  4513. return juce_getVolumeLabel (fullPath, serialNum);
  4514. }
  4515. int File::getVolumeSerialNumber() const throw()
  4516. {
  4517. int serialNum;
  4518. juce_getVolumeLabel (fullPath, serialNum);
  4519. return serialNum;
  4520. }
  4521. const File File::createTempFile (const String& fileNameEnding) throw()
  4522. {
  4523. String tempName (T("temp"));
  4524. static int tempNum = 0;
  4525. tempName << tempNum++ << fileNameEnding;
  4526. const File tempFile (getSpecialLocation (tempDirectory)
  4527. .getChildFile (tempName));
  4528. if (tempFile.exists())
  4529. return createTempFile (fileNameEnding);
  4530. else
  4531. return tempFile;
  4532. }
  4533. END_JUCE_NAMESPACE
  4534. /********* End of inlined file: juce_File.cpp *********/
  4535. /********* Start of inlined file: juce_FileInputStream.cpp *********/
  4536. BEGIN_JUCE_NAMESPACE
  4537. void* juce_fileOpen (const String& path, bool forWriting) throw();
  4538. void juce_fileClose (void* handle) throw();
  4539. int juce_fileRead (void* handle, void* buffer, int size) throw();
  4540. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  4541. FileInputStream::FileInputStream (const File& f)
  4542. : file (f),
  4543. currentPosition (0),
  4544. needToSeek (true)
  4545. {
  4546. totalSize = f.getSize();
  4547. fileHandle = juce_fileOpen (f.getFullPathName(), false);
  4548. }
  4549. FileInputStream::~FileInputStream()
  4550. {
  4551. juce_fileClose (fileHandle);
  4552. }
  4553. int64 FileInputStream::getTotalLength()
  4554. {
  4555. return totalSize;
  4556. }
  4557. int FileInputStream::read (void* buffer, int bytesToRead)
  4558. {
  4559. int num = 0;
  4560. if (needToSeek)
  4561. {
  4562. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  4563. return 0;
  4564. needToSeek = false;
  4565. }
  4566. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  4567. currentPosition += num;
  4568. return num;
  4569. }
  4570. bool FileInputStream::isExhausted()
  4571. {
  4572. return currentPosition >= totalSize;
  4573. }
  4574. int64 FileInputStream::getPosition()
  4575. {
  4576. return currentPosition;
  4577. }
  4578. bool FileInputStream::setPosition (int64 pos)
  4579. {
  4580. pos = jlimit ((int64) 0, totalSize, pos);
  4581. needToSeek |= (currentPosition != pos);
  4582. currentPosition = pos;
  4583. return true;
  4584. }
  4585. END_JUCE_NAMESPACE
  4586. /********* End of inlined file: juce_FileInputStream.cpp *********/
  4587. /********* Start of inlined file: juce_FileOutputStream.cpp *********/
  4588. BEGIN_JUCE_NAMESPACE
  4589. void* juce_fileOpen (const String& path, bool forWriting) throw();
  4590. void juce_fileClose (void* handle) throw();
  4591. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  4592. void juce_fileFlush (void* handle) throw();
  4593. int64 juce_fileGetPosition (void* handle) throw();
  4594. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  4595. FileOutputStream::FileOutputStream (const File& f,
  4596. const int bufferSize_)
  4597. : file (f),
  4598. bufferSize (bufferSize_),
  4599. bytesInBuffer (0)
  4600. {
  4601. fileHandle = juce_fileOpen (f.getFullPathName(), true);
  4602. if (fileHandle != 0)
  4603. {
  4604. currentPosition = juce_fileGetPosition (fileHandle);
  4605. if (currentPosition < 0)
  4606. {
  4607. jassertfalse
  4608. juce_fileClose (fileHandle);
  4609. fileHandle = 0;
  4610. }
  4611. }
  4612. buffer = (char*) juce_malloc (jmax (bufferSize_, 16));
  4613. }
  4614. FileOutputStream::~FileOutputStream()
  4615. {
  4616. flush();
  4617. juce_fileClose (fileHandle);
  4618. juce_free (buffer);
  4619. }
  4620. int64 FileOutputStream::getPosition()
  4621. {
  4622. return currentPosition;
  4623. }
  4624. bool FileOutputStream::setPosition (int64 newPosition)
  4625. {
  4626. if (newPosition != currentPosition)
  4627. {
  4628. flush();
  4629. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  4630. }
  4631. return newPosition == currentPosition;
  4632. }
  4633. void FileOutputStream::flush()
  4634. {
  4635. if (bytesInBuffer > 0)
  4636. {
  4637. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  4638. bytesInBuffer = 0;
  4639. }
  4640. juce_fileFlush (fileHandle);
  4641. }
  4642. bool FileOutputStream::write (const void* const src, const int numBytes)
  4643. {
  4644. if (bytesInBuffer + numBytes < bufferSize)
  4645. {
  4646. memcpy (buffer + bytesInBuffer, src, numBytes);
  4647. bytesInBuffer += numBytes;
  4648. currentPosition += numBytes;
  4649. }
  4650. else
  4651. {
  4652. if (bytesInBuffer > 0)
  4653. {
  4654. // flush the reservoir
  4655. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  4656. bytesInBuffer = 0;
  4657. if (! wroteOk)
  4658. return false;
  4659. }
  4660. if (numBytes < bufferSize)
  4661. {
  4662. memcpy (buffer + bytesInBuffer, src, numBytes);
  4663. bytesInBuffer += numBytes;
  4664. currentPosition += numBytes;
  4665. }
  4666. else
  4667. {
  4668. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  4669. currentPosition += bytesWritten;
  4670. return bytesWritten == numBytes;
  4671. }
  4672. }
  4673. return true;
  4674. }
  4675. END_JUCE_NAMESPACE
  4676. /********* End of inlined file: juce_FileOutputStream.cpp *********/
  4677. /********* Start of inlined file: juce_FileSearchPath.cpp *********/
  4678. BEGIN_JUCE_NAMESPACE
  4679. FileSearchPath::FileSearchPath()
  4680. {
  4681. }
  4682. FileSearchPath::FileSearchPath (const String& path)
  4683. {
  4684. init (path);
  4685. }
  4686. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  4687. : directories (other.directories)
  4688. {
  4689. }
  4690. FileSearchPath::~FileSearchPath()
  4691. {
  4692. }
  4693. const FileSearchPath& FileSearchPath::operator= (const String& path)
  4694. {
  4695. init (path);
  4696. return *this;
  4697. }
  4698. void FileSearchPath::init (const String& path)
  4699. {
  4700. directories.clear();
  4701. directories.addTokens (path, T(";"), T("\""));
  4702. directories.trim();
  4703. directories.removeEmptyStrings();
  4704. for (int i = directories.size(); --i >= 0;)
  4705. directories.set (i, directories[i].unquoted());
  4706. }
  4707. int FileSearchPath::getNumPaths() const
  4708. {
  4709. return directories.size();
  4710. }
  4711. const File FileSearchPath::operator[] (const int index) const
  4712. {
  4713. return File (directories [index]);
  4714. }
  4715. const String FileSearchPath::toString() const
  4716. {
  4717. StringArray directories2 (directories);
  4718. for (int i = directories2.size(); --i >= 0;)
  4719. if (directories2[i].containsChar (T(';')))
  4720. directories2.set (i, directories2[i].quoted());
  4721. return directories2.joinIntoString (T(";"));
  4722. }
  4723. void FileSearchPath::add (const File& dir, const int insertIndex)
  4724. {
  4725. directories.insert (insertIndex, dir.getFullPathName());
  4726. }
  4727. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  4728. {
  4729. for (int i = 0; i < directories.size(); ++i)
  4730. if (File (directories[i]) == dir)
  4731. return;
  4732. add (dir);
  4733. }
  4734. void FileSearchPath::remove (const int index)
  4735. {
  4736. directories.remove (index);
  4737. }
  4738. void FileSearchPath::addPath (const FileSearchPath& other)
  4739. {
  4740. for (int i = 0; i < other.getNumPaths(); ++i)
  4741. addIfNotAlreadyThere (other[i]);
  4742. }
  4743. void FileSearchPath::removeRedundantPaths()
  4744. {
  4745. for (int i = directories.size(); --i >= 0;)
  4746. {
  4747. const File d1 (directories[i]);
  4748. for (int j = directories.size(); --j >= 0;)
  4749. {
  4750. const File d2 (directories[j]);
  4751. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  4752. {
  4753. directories.remove (i);
  4754. break;
  4755. }
  4756. }
  4757. }
  4758. }
  4759. void FileSearchPath::removeNonExistentPaths()
  4760. {
  4761. for (int i = directories.size(); --i >= 0;)
  4762. if (! File (directories[i]).isDirectory())
  4763. directories.remove (i);
  4764. }
  4765. int FileSearchPath::findChildFiles (OwnedArray<File>& results,
  4766. const int whatToLookFor,
  4767. const bool searchRecursively,
  4768. const String& wildCardPattern) const
  4769. {
  4770. int total = 0;
  4771. for (int i = 0; i < directories.size(); ++i)
  4772. total += operator[] (i).findChildFiles (results,
  4773. whatToLookFor,
  4774. searchRecursively,
  4775. wildCardPattern);
  4776. return total;
  4777. }
  4778. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  4779. const bool checkRecursively) const
  4780. {
  4781. for (int i = directories.size(); --i >= 0;)
  4782. {
  4783. const File d (directories[i]);
  4784. if (checkRecursively)
  4785. {
  4786. if (fileToCheck.isAChildOf (d))
  4787. return true;
  4788. }
  4789. else
  4790. {
  4791. if (fileToCheck.getParentDirectory() == d)
  4792. return true;
  4793. }
  4794. }
  4795. return false;
  4796. }
  4797. END_JUCE_NAMESPACE
  4798. /********* End of inlined file: juce_FileSearchPath.cpp *********/
  4799. /********* Start of inlined file: juce_NamedPipe.cpp *********/
  4800. BEGIN_JUCE_NAMESPACE
  4801. NamedPipe::NamedPipe()
  4802. : internal (0)
  4803. {
  4804. }
  4805. NamedPipe::~NamedPipe()
  4806. {
  4807. close();
  4808. }
  4809. bool NamedPipe::openExisting (const String& pipeName)
  4810. {
  4811. currentPipeName = pipeName;
  4812. return openInternal (pipeName, false);
  4813. }
  4814. bool NamedPipe::createNewPipe (const String& pipeName)
  4815. {
  4816. currentPipeName = pipeName;
  4817. return openInternal (pipeName, true);
  4818. }
  4819. bool NamedPipe::isOpen() const throw()
  4820. {
  4821. return internal != 0;
  4822. }
  4823. const String NamedPipe::getName() const throw()
  4824. {
  4825. return currentPipeName;
  4826. }
  4827. // other methods for this class are implemented in the platform-specific files
  4828. END_JUCE_NAMESPACE
  4829. /********* End of inlined file: juce_NamedPipe.cpp *********/
  4830. /********* Start of inlined file: juce_Socket.cpp *********/
  4831. #ifdef _WIN32
  4832. #include <winsock2.h>
  4833. #ifdef _MSC_VER
  4834. #pragma warning (disable : 4127 4389 4018)
  4835. #endif
  4836. #else
  4837. #ifndef LINUX
  4838. #include <Carbon/Carbon.h>
  4839. #endif
  4840. #include <sys/types.h>
  4841. #include <netdb.h>
  4842. #include <sys/socket.h>
  4843. #include <arpa/inet.h>
  4844. #include <sys/errno.h>
  4845. #include <netinet/tcp.h>
  4846. #include <netinet/in.h>
  4847. #include <fcntl.h>
  4848. #include <unistd.h>
  4849. #endif
  4850. BEGIN_JUCE_NAMESPACE
  4851. #if JUCE_WIN32
  4852. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  4853. juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  4854. static void initWin32Sockets()
  4855. {
  4856. static CriticalSection lock;
  4857. const ScopedLock sl (lock);
  4858. if (juce_CloseWin32SocketLib == 0)
  4859. {
  4860. WSADATA wsaData;
  4861. const WORD wVersionRequested = MAKEWORD (1, 1);
  4862. WSAStartup (wVersionRequested, &wsaData);
  4863. juce_CloseWin32SocketLib = &WSACleanup;
  4864. }
  4865. }
  4866. #endif
  4867. static bool resetSocketOptions (const int handle, const bool isDatagram) throw()
  4868. {
  4869. if (handle <= 0)
  4870. return false;
  4871. const int sndBufSize = 65536;
  4872. const int rcvBufSize = 65536;
  4873. const int one = 1;
  4874. return setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (int)) == 0
  4875. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (int)) == 0
  4876. && (isDatagram || (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (int)) == 0));
  4877. }
  4878. static bool bindSocketToPort (const int handle, const int port) throw()
  4879. {
  4880. if (handle == 0 || port <= 0)
  4881. return false;
  4882. struct sockaddr_in servTmpAddr;
  4883. zerostruct (servTmpAddr);
  4884. servTmpAddr.sin_family = PF_INET;
  4885. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  4886. servTmpAddr.sin_port = htons ((uint16) port);
  4887. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  4888. }
  4889. static int readSocket (const int handle,
  4890. void* const destBuffer, const int maxBytesToRead,
  4891. bool volatile& connected) throw()
  4892. {
  4893. int bytesRead = 0;
  4894. while (bytesRead < maxBytesToRead)
  4895. {
  4896. int bytesThisTime;
  4897. #if JUCE_WIN32
  4898. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  4899. #else
  4900. while ((bytesThisTime = ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  4901. && errno == EINTR
  4902. && connected)
  4903. {
  4904. }
  4905. #endif
  4906. if (bytesThisTime <= 0 || ! connected)
  4907. {
  4908. if (bytesRead == 0)
  4909. bytesRead = -1;
  4910. break;
  4911. }
  4912. bytesRead += bytesThisTime;
  4913. }
  4914. return bytesRead;
  4915. }
  4916. static int waitForReadiness (const int handle, const bool forReading,
  4917. const int timeoutMsecs) throw()
  4918. {
  4919. struct timeval timeout;
  4920. struct timeval* timeoutp;
  4921. if (timeoutMsecs >= 0)
  4922. {
  4923. timeout.tv_sec = timeoutMsecs / 1000;
  4924. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  4925. timeoutp = &timeout;
  4926. }
  4927. else
  4928. {
  4929. timeoutp = 0;
  4930. }
  4931. fd_set rset, wset;
  4932. FD_ZERO (&rset);
  4933. FD_SET (handle, &rset);
  4934. FD_ZERO (&wset);
  4935. FD_SET (handle, &wset);
  4936. fd_set* const prset = forReading ? &rset : 0;
  4937. fd_set* const pwset = forReading ? 0 : &wset;
  4938. #if JUCE_WIN32
  4939. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  4940. return -1;
  4941. #else
  4942. {
  4943. int result;
  4944. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  4945. && errno == EINTR)
  4946. {
  4947. }
  4948. if (result < 0)
  4949. return -1;
  4950. }
  4951. #endif
  4952. {
  4953. int opt;
  4954. #if defined (JUCE_LINUX) || (defined (JUCE_MAC) && ! MACOS_10_2_OR_EARLIER)
  4955. socklen_t len = sizeof (opt);
  4956. #else
  4957. int len = sizeof (opt);
  4958. #endif
  4959. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  4960. || opt != 0)
  4961. return -1;
  4962. }
  4963. if ((forReading && FD_ISSET (handle, &rset))
  4964. || ((! forReading) && FD_ISSET (handle, &wset)))
  4965. return 1;
  4966. return 0;
  4967. }
  4968. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  4969. {
  4970. #if JUCE_WIN32
  4971. u_long nonBlocking = shouldBlock ? 0 : 1;
  4972. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  4973. return false;
  4974. #else
  4975. int socketFlags = fcntl (handle, F_GETFL, 0);
  4976. if (socketFlags == -1)
  4977. return false;
  4978. if (shouldBlock)
  4979. socketFlags &= ~O_NONBLOCK;
  4980. else
  4981. socketFlags |= O_NONBLOCK;
  4982. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  4983. return false;
  4984. #endif
  4985. return true;
  4986. }
  4987. static bool connectSocket (int volatile& handle,
  4988. const bool isDatagram,
  4989. void** serverAddress,
  4990. const String& hostName,
  4991. const int portNumber,
  4992. const int timeOutMillisecs) throw()
  4993. {
  4994. struct hostent* const hostEnt = gethostbyname (hostName);
  4995. if (hostEnt == 0)
  4996. return false;
  4997. struct in_addr targetAddress;
  4998. memcpy (&targetAddress.s_addr,
  4999. *(hostEnt->h_addr_list),
  5000. sizeof (targetAddress.s_addr));
  5001. struct sockaddr_in servTmpAddr;
  5002. zerostruct (servTmpAddr);
  5003. servTmpAddr.sin_family = PF_INET;
  5004. servTmpAddr.sin_addr = targetAddress;
  5005. servTmpAddr.sin_port = htons ((uint16) portNumber);
  5006. if (handle < 0)
  5007. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  5008. if (handle < 0)
  5009. return false;
  5010. if (isDatagram)
  5011. {
  5012. *serverAddress = new struct sockaddr_in();
  5013. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  5014. return true;
  5015. }
  5016. setSocketBlockingState (handle, false);
  5017. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  5018. if (result < 0)
  5019. {
  5020. #if JUCE_WIN32
  5021. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  5022. #else
  5023. if (errno == EINPROGRESS)
  5024. #endif
  5025. {
  5026. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  5027. {
  5028. setSocketBlockingState (handle, true);
  5029. return false;
  5030. }
  5031. }
  5032. }
  5033. setSocketBlockingState (handle, true);
  5034. resetSocketOptions (handle, false);
  5035. return true;
  5036. }
  5037. StreamingSocket::StreamingSocket()
  5038. : portNumber (0),
  5039. handle (-1),
  5040. connected (false),
  5041. isListener (false)
  5042. {
  5043. #if JUCE_WIN32
  5044. initWin32Sockets();
  5045. #endif
  5046. }
  5047. StreamingSocket::StreamingSocket (const String& hostName_,
  5048. const int portNumber_,
  5049. const int handle_)
  5050. : hostName (hostName_),
  5051. portNumber (portNumber_),
  5052. handle (handle_),
  5053. connected (true),
  5054. isListener (false)
  5055. {
  5056. #if JUCE_WIN32
  5057. initWin32Sockets();
  5058. #endif
  5059. resetSocketOptions (handle_, false);
  5060. }
  5061. StreamingSocket::~StreamingSocket()
  5062. {
  5063. close();
  5064. }
  5065. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead)
  5066. {
  5067. return (connected && ! isListener) ? readSocket (handle, destBuffer, maxBytesToRead, connected)
  5068. : -1;
  5069. }
  5070. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  5071. {
  5072. if (isListener || ! connected)
  5073. return -1;
  5074. #if JUCE_WIN32
  5075. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  5076. #else
  5077. int result;
  5078. while ((result = ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  5079. && errno == EINTR)
  5080. {
  5081. }
  5082. return result;
  5083. #endif
  5084. }
  5085. int StreamingSocket::waitUntilReady (const bool readyForReading,
  5086. const int timeoutMsecs) const
  5087. {
  5088. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  5089. : -1;
  5090. }
  5091. bool StreamingSocket::bindToPort (const int port)
  5092. {
  5093. return bindSocketToPort (handle, port);
  5094. }
  5095. bool StreamingSocket::connect (const String& remoteHostName,
  5096. const int remotePortNumber,
  5097. const int timeOutMillisecs)
  5098. {
  5099. if (isListener)
  5100. {
  5101. jassertfalse // a listener socket can't connect to another one!
  5102. return false;
  5103. }
  5104. if (connected)
  5105. close();
  5106. hostName = remoteHostName;
  5107. portNumber = remotePortNumber;
  5108. isListener = false;
  5109. connected = connectSocket (handle, false, 0, remoteHostName,
  5110. remotePortNumber, timeOutMillisecs);
  5111. if (! (connected && resetSocketOptions (handle, false)))
  5112. {
  5113. close();
  5114. return false;
  5115. }
  5116. return true;
  5117. }
  5118. void StreamingSocket::close()
  5119. {
  5120. #if JUCE_WIN32
  5121. closesocket (handle);
  5122. connected = false;
  5123. #else
  5124. if (connected)
  5125. {
  5126. connected = false;
  5127. if (isListener)
  5128. {
  5129. // need to do this to interrupt the accept() function..
  5130. StreamingSocket temp;
  5131. temp.connect ("localhost", portNumber, 1000);
  5132. }
  5133. }
  5134. ::close (handle);
  5135. #endif
  5136. hostName = String::empty;
  5137. portNumber = 0;
  5138. handle = -1;
  5139. isListener = false;
  5140. }
  5141. bool StreamingSocket::createListener (const int newPortNumber)
  5142. {
  5143. if (connected)
  5144. close();
  5145. hostName = "listener";
  5146. portNumber = newPortNumber;
  5147. isListener = true;
  5148. struct sockaddr_in servTmpAddr;
  5149. zerostruct (servTmpAddr);
  5150. servTmpAddr.sin_family = PF_INET;
  5151. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5152. servTmpAddr.sin_port = htons ((uint16) portNumber);
  5153. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  5154. if (handle < 0)
  5155. return false;
  5156. const int reuse = 1;
  5157. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  5158. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  5159. || listen (handle, SOMAXCONN) < 0)
  5160. {
  5161. close();
  5162. return false;
  5163. }
  5164. connected = true;
  5165. return true;
  5166. }
  5167. StreamingSocket* StreamingSocket::waitForNextConnection() const
  5168. {
  5169. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  5170. // prepare this socket as a listener.
  5171. if (connected && isListener)
  5172. {
  5173. struct sockaddr address;
  5174. #if defined (JUCE_LINUX) || (defined (JUCE_MAC) && ! MACOS_10_2_OR_EARLIER)
  5175. socklen_t len = sizeof (sockaddr);
  5176. #else
  5177. int len = sizeof (sockaddr);
  5178. #endif
  5179. const int newSocket = (int) accept (handle, &address, &len);
  5180. if (newSocket >= 0 && connected)
  5181. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  5182. portNumber, newSocket);
  5183. }
  5184. return 0;
  5185. }
  5186. bool StreamingSocket::isLocal() const throw()
  5187. {
  5188. return hostName == T("127.0.0.1");
  5189. }
  5190. DatagramSocket::DatagramSocket (const int localPortNumber)
  5191. : portNumber (0),
  5192. handle (-1),
  5193. connected (false),
  5194. serverAddress (0)
  5195. {
  5196. #if JUCE_WIN32
  5197. initWin32Sockets();
  5198. #endif
  5199. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  5200. bindToPort (localPortNumber);
  5201. }
  5202. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  5203. const int handle_, const int localPortNumber)
  5204. : hostName (hostName_),
  5205. portNumber (portNumber_),
  5206. handle (handle_),
  5207. connected (true),
  5208. serverAddress (0)
  5209. {
  5210. #if JUCE_WIN32
  5211. initWin32Sockets();
  5212. #endif
  5213. resetSocketOptions (handle_, true);
  5214. bindToPort (localPortNumber);
  5215. }
  5216. DatagramSocket::~DatagramSocket()
  5217. {
  5218. close();
  5219. delete ((struct sockaddr_in*) serverAddress);
  5220. serverAddress = 0;
  5221. }
  5222. void DatagramSocket::close()
  5223. {
  5224. #if JUCE_WIN32
  5225. closesocket (handle);
  5226. connected = false;
  5227. #else
  5228. connected = false;
  5229. ::close (handle);
  5230. #endif
  5231. hostName = String::empty;
  5232. portNumber = 0;
  5233. handle = -1;
  5234. }
  5235. bool DatagramSocket::bindToPort (const int port)
  5236. {
  5237. return bindSocketToPort (handle, port);
  5238. }
  5239. bool DatagramSocket::connect (const String& remoteHostName,
  5240. const int remotePortNumber,
  5241. const int timeOutMillisecs)
  5242. {
  5243. if (connected)
  5244. close();
  5245. hostName = remoteHostName;
  5246. portNumber = remotePortNumber;
  5247. connected = connectSocket (handle, true, &serverAddress,
  5248. remoteHostName, remotePortNumber,
  5249. timeOutMillisecs);
  5250. if (! (connected && resetSocketOptions (handle, true)))
  5251. {
  5252. close();
  5253. return false;
  5254. }
  5255. return true;
  5256. }
  5257. DatagramSocket* DatagramSocket::waitForNextConnection() const
  5258. {
  5259. struct sockaddr address;
  5260. #if defined (JUCE_LINUX) || (defined (JUCE_MAC) && ! MACOS_10_2_OR_EARLIER)
  5261. socklen_t len = sizeof (sockaddr);
  5262. #else
  5263. int len = sizeof (sockaddr);
  5264. #endif
  5265. while (waitUntilReady (true, -1) == 1)
  5266. {
  5267. char buf[1];
  5268. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  5269. {
  5270. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  5271. ntohs (((struct sockaddr_in*) &address)->sin_port),
  5272. -1, -1);
  5273. }
  5274. }
  5275. return 0;
  5276. }
  5277. int DatagramSocket::waitUntilReady (const bool readyForReading,
  5278. const int timeoutMsecs) const
  5279. {
  5280. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  5281. : -1;
  5282. }
  5283. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead)
  5284. {
  5285. return connected ? readSocket (handle, destBuffer, maxBytesToRead, connected)
  5286. : -1;
  5287. }
  5288. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  5289. {
  5290. // You need to call connect() first to set the server address..
  5291. jassert (serverAddress != 0 && connected);
  5292. return connected ? sendto (handle, (const char*) sourceBuffer,
  5293. numBytesToWrite, 0,
  5294. (const struct sockaddr*) serverAddress,
  5295. sizeof (struct sockaddr_in))
  5296. : -1;
  5297. }
  5298. bool DatagramSocket::isLocal() const throw()
  5299. {
  5300. return hostName == T("127.0.0.1");
  5301. }
  5302. END_JUCE_NAMESPACE
  5303. /********* End of inlined file: juce_Socket.cpp *********/
  5304. /********* Start of inlined file: juce_URL.cpp *********/
  5305. BEGIN_JUCE_NAMESPACE
  5306. URL::URL() throw()
  5307. {
  5308. }
  5309. URL::URL (const String& url_)
  5310. : url (url_)
  5311. {
  5312. int i = url.indexOfChar (T('?'));
  5313. if (i >= 0)
  5314. {
  5315. do
  5316. {
  5317. const int nextAmp = url.indexOfChar (i + 1, T('&'));
  5318. const int equalsPos = url.indexOfChar (i + 1, T('='));
  5319. if (equalsPos > i + 1)
  5320. {
  5321. if (nextAmp < 0)
  5322. {
  5323. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  5324. removeEscapeChars (url.substring (equalsPos + 1)));
  5325. }
  5326. else if (nextAmp > 0 && equalsPos < nextAmp)
  5327. {
  5328. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  5329. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  5330. }
  5331. }
  5332. i = nextAmp;
  5333. }
  5334. while (i >= 0);
  5335. url = url.upToFirstOccurrenceOf (T("?"), false, false);
  5336. }
  5337. }
  5338. URL::URL (const URL& other)
  5339. : url (other.url),
  5340. parameters (other.parameters),
  5341. filesToUpload (other.filesToUpload),
  5342. mimeTypes (other.mimeTypes)
  5343. {
  5344. }
  5345. const URL& URL::operator= (const URL& other)
  5346. {
  5347. url = other.url;
  5348. parameters = other.parameters;
  5349. filesToUpload = other.filesToUpload;
  5350. mimeTypes = other.mimeTypes;
  5351. return *this;
  5352. }
  5353. URL::~URL() throw()
  5354. {
  5355. }
  5356. static const String getMangledParameters (const StringPairArray& parameters)
  5357. {
  5358. String p;
  5359. for (int i = 0; i < parameters.size(); ++i)
  5360. {
  5361. if (i > 0)
  5362. p += T("&");
  5363. p << URL::addEscapeChars (parameters.getAllKeys() [i])
  5364. << T("=")
  5365. << URL::addEscapeChars (parameters.getAllValues() [i]);
  5366. }
  5367. return p;
  5368. }
  5369. const String URL::toString (const bool includeGetParameters) const
  5370. {
  5371. if (includeGetParameters && parameters.size() > 0)
  5372. return url + T("?") + getMangledParameters (parameters);
  5373. else
  5374. return url;
  5375. }
  5376. bool URL::isWellFormed() const
  5377. {
  5378. //xxx TODO
  5379. return url.isNotEmpty();
  5380. }
  5381. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  5382. {
  5383. return (possibleURL.containsChar (T('.'))
  5384. && (! possibleURL.containsChar (T('@')))
  5385. && (! possibleURL.endsWithChar (T('.')))
  5386. && (possibleURL.startsWithIgnoreCase (T("www."))
  5387. || possibleURL.startsWithIgnoreCase (T("http:"))
  5388. || possibleURL.startsWithIgnoreCase (T("ftp:"))
  5389. || possibleURL.endsWithIgnoreCase (T(".com"))
  5390. || possibleURL.endsWithIgnoreCase (T(".net"))
  5391. || possibleURL.endsWithIgnoreCase (T(".org"))
  5392. || possibleURL.endsWithIgnoreCase (T(".co.uk")))
  5393. || possibleURL.startsWithIgnoreCase (T("file:")));
  5394. }
  5395. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  5396. {
  5397. const int atSign = possibleEmailAddress.indexOfChar (T('@'));
  5398. return atSign > 0
  5399. && possibleEmailAddress.lastIndexOfChar (T('.')) > (atSign + 1)
  5400. && (! possibleEmailAddress.endsWithChar (T('.')));
  5401. }
  5402. void* juce_openInternetFile (const String& url,
  5403. const String& headers,
  5404. const MemoryBlock& optionalPostData,
  5405. const bool isPost,
  5406. URL::OpenStreamProgressCallback* callback,
  5407. void* callbackContext,
  5408. int timeOutMs);
  5409. void juce_closeInternetFile (void* handle);
  5410. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  5411. int juce_seekInInternetFile (void* handle, int newPosition);
  5412. class WebInputStream : public InputStream
  5413. {
  5414. public:
  5415. WebInputStream (const URL& url,
  5416. const bool isPost_,
  5417. URL::OpenStreamProgressCallback* const progressCallback_,
  5418. void* const progressCallbackContext_,
  5419. const String& extraHeaders,
  5420. int timeOutMs_)
  5421. : position (0),
  5422. finished (false),
  5423. isPost (isPost_),
  5424. progressCallback (progressCallback_),
  5425. progressCallbackContext (progressCallbackContext_),
  5426. timeOutMs (timeOutMs_)
  5427. {
  5428. server = url.toString (! isPost);
  5429. if (isPost_)
  5430. createHeadersAndPostData (url);
  5431. headers += extraHeaders;
  5432. if (! headers.endsWithChar (T('\n')))
  5433. headers << "\r\n";
  5434. handle = juce_openInternetFile (server, headers, postData, isPost,
  5435. progressCallback_, progressCallbackContext_,
  5436. timeOutMs);
  5437. }
  5438. ~WebInputStream()
  5439. {
  5440. juce_closeInternetFile (handle);
  5441. }
  5442. bool isError() const throw()
  5443. {
  5444. return handle == 0;
  5445. }
  5446. int64 getTotalLength()
  5447. {
  5448. return -1;
  5449. }
  5450. bool isExhausted()
  5451. {
  5452. return finished;
  5453. }
  5454. int read (void* dest, int bytes)
  5455. {
  5456. if (finished || isError())
  5457. {
  5458. return 0;
  5459. }
  5460. else
  5461. {
  5462. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  5463. position += bytesRead;
  5464. if (bytesRead == 0)
  5465. finished = true;
  5466. return bytesRead;
  5467. }
  5468. }
  5469. int64 getPosition()
  5470. {
  5471. return position;
  5472. }
  5473. bool setPosition (int64 wantedPos)
  5474. {
  5475. if (wantedPos != position)
  5476. {
  5477. finished = false;
  5478. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  5479. if (actualPos == wantedPos)
  5480. {
  5481. position = wantedPos;
  5482. }
  5483. else
  5484. {
  5485. if (wantedPos < position)
  5486. {
  5487. juce_closeInternetFile (handle);
  5488. position = 0;
  5489. finished = false;
  5490. handle = juce_openInternetFile (server, headers, postData, isPost,
  5491. progressCallback, progressCallbackContext,
  5492. timeOutMs);
  5493. }
  5494. skipNextBytes (wantedPos - position);
  5495. }
  5496. }
  5497. return true;
  5498. }
  5499. juce_UseDebuggingNewOperator
  5500. private:
  5501. String server, headers;
  5502. MemoryBlock postData;
  5503. int64 position;
  5504. bool finished;
  5505. const bool isPost;
  5506. void* handle;
  5507. URL::OpenStreamProgressCallback* const progressCallback;
  5508. void* const progressCallbackContext;
  5509. const int timeOutMs;
  5510. void createHeadersAndPostData (const URL& url)
  5511. {
  5512. if (url.getFilesToUpload().size() > 0)
  5513. {
  5514. // need to upload some files, so do it as multi-part...
  5515. String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  5516. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  5517. appendUTF8ToPostData ("--" + boundary);
  5518. int i;
  5519. for (i = 0; i < url.getParameters().size(); ++i)
  5520. {
  5521. String s;
  5522. s << "\r\nContent-Disposition: form-data; name=\""
  5523. << url.getParameters().getAllKeys() [i]
  5524. << "\"\r\n\r\n"
  5525. << url.getParameters().getAllValues() [i]
  5526. << "\r\n--"
  5527. << boundary;
  5528. appendUTF8ToPostData (s);
  5529. }
  5530. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  5531. {
  5532. const File f (url.getFilesToUpload().getAllValues() [i]);
  5533. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  5534. String s;
  5535. s << "\r\nContent-Disposition: form-data; name=\""
  5536. << paramName
  5537. << "\"; filename=\""
  5538. << f.getFileName()
  5539. << "\"\r\n";
  5540. const String mimeType (url.getMimeTypesOfUploadFiles()
  5541. .getValue (paramName, String::empty));
  5542. if (mimeType.isNotEmpty())
  5543. s << "Content-Type: " << mimeType << "\r\n";
  5544. s << "Content-Transfer-Encoding: binary\r\n\r\n";
  5545. appendUTF8ToPostData (s);
  5546. f.loadFileAsData (postData);
  5547. s = "\r\n--" + boundary;
  5548. appendUTF8ToPostData (s);
  5549. }
  5550. appendUTF8ToPostData ("--\r\n");
  5551. }
  5552. else
  5553. {
  5554. // just a short text attachment, so use simple url encoding..
  5555. const String params (getMangledParameters (url.getParameters()));
  5556. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  5557. + String ((int) strlen (params.toUTF8()))
  5558. + "\r\n";
  5559. appendUTF8ToPostData (params);
  5560. }
  5561. }
  5562. void appendUTF8ToPostData (const String& text) throw()
  5563. {
  5564. postData.append (text.toUTF8(),
  5565. (int) strlen (text.toUTF8()));
  5566. }
  5567. WebInputStream (const WebInputStream&);
  5568. const WebInputStream& operator= (const WebInputStream&);
  5569. };
  5570. InputStream* URL::createInputStream (const bool usePostCommand,
  5571. OpenStreamProgressCallback* const progressCallback,
  5572. void* const progressCallbackContext,
  5573. const String& extraHeaders,
  5574. const int timeOutMs) const
  5575. {
  5576. WebInputStream* wi = new WebInputStream (*this, usePostCommand,
  5577. progressCallback, progressCallbackContext,
  5578. extraHeaders,
  5579. timeOutMs);
  5580. if (wi->isError())
  5581. {
  5582. delete wi;
  5583. wi = 0;
  5584. }
  5585. return wi;
  5586. }
  5587. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  5588. const bool usePostCommand) const
  5589. {
  5590. InputStream* const in = createInputStream (usePostCommand);
  5591. if (in != 0)
  5592. {
  5593. in->readIntoMemoryBlock (destData, -1);
  5594. delete in;
  5595. return true;
  5596. }
  5597. return false;
  5598. }
  5599. const String URL::readEntireTextStream (const bool usePostCommand) const
  5600. {
  5601. String result;
  5602. InputStream* const in = createInputStream (usePostCommand);
  5603. if (in != 0)
  5604. {
  5605. result = in->readEntireStreamAsString();
  5606. delete in;
  5607. }
  5608. return result;
  5609. }
  5610. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  5611. {
  5612. XmlDocument doc (readEntireTextStream (usePostCommand));
  5613. return doc.getDocumentElement();
  5614. }
  5615. const URL URL::withParameter (const String& parameterName,
  5616. const String& parameterValue) const
  5617. {
  5618. URL u (*this);
  5619. u.parameters.set (parameterName, parameterValue);
  5620. return u;
  5621. }
  5622. const URL URL::withFileToUpload (const String& parameterName,
  5623. const File& fileToUpload,
  5624. const String& mimeType) const
  5625. {
  5626. URL u (*this);
  5627. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  5628. u.mimeTypes.set (parameterName, mimeType);
  5629. return u;
  5630. }
  5631. const StringPairArray& URL::getParameters() const throw()
  5632. {
  5633. return parameters;
  5634. }
  5635. const StringPairArray& URL::getFilesToUpload() const throw()
  5636. {
  5637. return filesToUpload;
  5638. }
  5639. const StringPairArray& URL::getMimeTypesOfUploadFiles() const throw()
  5640. {
  5641. return mimeTypes;
  5642. }
  5643. const String URL::removeEscapeChars (const String& s)
  5644. {
  5645. const int len = s.length();
  5646. uint8* const resultUTF8 = (uint8*) juce_calloc (len * 4);
  5647. uint8* r = resultUTF8;
  5648. for (int i = 0; i < len; ++i)
  5649. {
  5650. char c = (char) s[i];
  5651. if (c == 0)
  5652. break;
  5653. if (c == '+')
  5654. {
  5655. c = ' ';
  5656. }
  5657. else if (c == '%')
  5658. {
  5659. c = (char) s.substring (i + 1, i + 3).getHexValue32();
  5660. i += 2;
  5661. }
  5662. *r++ = c;
  5663. }
  5664. const String stringResult (String::fromUTF8 (resultUTF8));
  5665. juce_free (resultUTF8);
  5666. return stringResult;
  5667. }
  5668. const String URL::addEscapeChars (const String& s)
  5669. {
  5670. String result;
  5671. result.preallocateStorage (s.length() + 8);
  5672. const char* utf8 = s.toUTF8();
  5673. while (*utf8 != 0)
  5674. {
  5675. const char c = *utf8++;
  5676. if (c == ' ')
  5677. {
  5678. result += T('+');
  5679. }
  5680. else if (CharacterFunctions::isLetterOrDigit (c)
  5681. || CharacterFunctions::indexOfChar ("_-$.*!'(),", c, false) >= 0)
  5682. {
  5683. result << c;
  5684. }
  5685. else
  5686. {
  5687. const int v = (int) (uint8) c;
  5688. if (v < 0x10)
  5689. result << T("%0");
  5690. else
  5691. result << T('%');
  5692. result << String::toHexString (v);
  5693. }
  5694. }
  5695. return result;
  5696. }
  5697. extern bool juce_launchFile (const String& fileName,
  5698. const String& parameters) throw();
  5699. bool URL::launchInDefaultBrowser() const
  5700. {
  5701. String u (toString (true));
  5702. if (u.contains (T("@")) && ! u.contains (T(":")))
  5703. u = "mailto:" + u;
  5704. return juce_launchFile (u, String::empty);
  5705. }
  5706. END_JUCE_NAMESPACE
  5707. /********* End of inlined file: juce_URL.cpp *********/
  5708. /********* Start of inlined file: juce_BufferedInputStream.cpp *********/
  5709. BEGIN_JUCE_NAMESPACE
  5710. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  5711. const int bufferSize_,
  5712. const bool deleteSourceWhenDestroyed_) throw()
  5713. : source (source_),
  5714. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  5715. bufferSize (jmax (256, bufferSize_)),
  5716. position (source_->getPosition()),
  5717. lastReadPos (0),
  5718. bufferOverlap (128)
  5719. {
  5720. const int sourceSize = (int) source_->getTotalLength();
  5721. if (sourceSize >= 0)
  5722. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  5723. bufferStart = position;
  5724. buffer = (char*) juce_malloc (bufferSize);
  5725. }
  5726. BufferedInputStream::~BufferedInputStream() throw()
  5727. {
  5728. if (deleteSourceWhenDestroyed)
  5729. delete source;
  5730. juce_free (buffer);
  5731. }
  5732. int64 BufferedInputStream::getTotalLength()
  5733. {
  5734. return source->getTotalLength();
  5735. }
  5736. int64 BufferedInputStream::getPosition()
  5737. {
  5738. return position;
  5739. }
  5740. bool BufferedInputStream::setPosition (int64 newPosition)
  5741. {
  5742. position = jmax ((int64) 0, newPosition);
  5743. return true;
  5744. }
  5745. bool BufferedInputStream::isExhausted()
  5746. {
  5747. return (position >= lastReadPos)
  5748. && source->isExhausted();
  5749. }
  5750. void BufferedInputStream::ensureBuffered()
  5751. {
  5752. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  5753. if (position < bufferStart || position >= bufferEndOverlap)
  5754. {
  5755. int bytesRead;
  5756. if (position < lastReadPos
  5757. && position >= bufferEndOverlap
  5758. && position >= bufferStart)
  5759. {
  5760. const int bytesToKeep = (int) (lastReadPos - position);
  5761. memmove (buffer, buffer + position - bufferStart, bytesToKeep);
  5762. bufferStart = position;
  5763. bytesRead = source->read (buffer + bytesToKeep,
  5764. bufferSize - bytesToKeep);
  5765. lastReadPos += bytesRead;
  5766. bytesRead += bytesToKeep;
  5767. }
  5768. else
  5769. {
  5770. bufferStart = position;
  5771. source->setPosition (bufferStart);
  5772. bytesRead = source->read (buffer, bufferSize);
  5773. lastReadPos = bufferStart + bytesRead;
  5774. }
  5775. while (bytesRead < bufferSize)
  5776. buffer [bytesRead++] = 0;
  5777. }
  5778. }
  5779. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  5780. {
  5781. if (position >= bufferStart
  5782. && position + maxBytesToRead <= lastReadPos)
  5783. {
  5784. memcpy (destBuffer, buffer + (position - bufferStart), maxBytesToRead);
  5785. position += maxBytesToRead;
  5786. return maxBytesToRead;
  5787. }
  5788. else
  5789. {
  5790. if (position < bufferStart || position >= lastReadPos)
  5791. ensureBuffered();
  5792. int bytesRead = 0;
  5793. while (maxBytesToRead > 0)
  5794. {
  5795. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  5796. if (bytesAvailable > 0)
  5797. {
  5798. memcpy (destBuffer, buffer + (position - bufferStart), bytesAvailable);
  5799. maxBytesToRead -= bytesAvailable;
  5800. bytesRead += bytesAvailable;
  5801. position += bytesAvailable;
  5802. destBuffer = (void*) (((char*) destBuffer) + bytesAvailable);
  5803. }
  5804. ensureBuffered();
  5805. if (isExhausted())
  5806. break;
  5807. }
  5808. return bytesRead;
  5809. }
  5810. }
  5811. const String BufferedInputStream::readString()
  5812. {
  5813. if (position >= bufferStart
  5814. && position < lastReadPos)
  5815. {
  5816. const int maxChars = (int) (lastReadPos - position);
  5817. const char* const src = buffer + (position - bufferStart);
  5818. for (int i = 0; i < maxChars; ++i)
  5819. {
  5820. if (src[i] == 0)
  5821. {
  5822. position += i + 1;
  5823. return String::fromUTF8 ((const uint8*) src, i);
  5824. }
  5825. }
  5826. }
  5827. return InputStream::readString();
  5828. }
  5829. END_JUCE_NAMESPACE
  5830. /********* End of inlined file: juce_BufferedInputStream.cpp *********/
  5831. /********* Start of inlined file: juce_FileInputSource.cpp *********/
  5832. BEGIN_JUCE_NAMESPACE
  5833. FileInputSource::FileInputSource (const File& file_) throw()
  5834. : file (file_)
  5835. {
  5836. }
  5837. FileInputSource::~FileInputSource()
  5838. {
  5839. }
  5840. InputStream* FileInputSource::createInputStream()
  5841. {
  5842. return file.createInputStream();
  5843. }
  5844. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  5845. {
  5846. return file.getSiblingFile (relatedItemPath).createInputStream();
  5847. }
  5848. int64 FileInputSource::hashCode() const
  5849. {
  5850. return file.hashCode();
  5851. }
  5852. END_JUCE_NAMESPACE
  5853. /********* End of inlined file: juce_FileInputSource.cpp *********/
  5854. /********* Start of inlined file: juce_MemoryInputStream.cpp *********/
  5855. BEGIN_JUCE_NAMESPACE
  5856. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  5857. const int sourceDataSize,
  5858. const bool keepInternalCopy) throw()
  5859. : data ((const char*) sourceData),
  5860. dataSize (sourceDataSize),
  5861. position (0)
  5862. {
  5863. if (keepInternalCopy)
  5864. {
  5865. internalCopy.append (data, sourceDataSize);
  5866. data = (const char*) internalCopy.getData();
  5867. }
  5868. }
  5869. MemoryInputStream::~MemoryInputStream() throw()
  5870. {
  5871. }
  5872. int64 MemoryInputStream::getTotalLength()
  5873. {
  5874. return dataSize;
  5875. }
  5876. int MemoryInputStream::read (void* buffer, int howMany)
  5877. {
  5878. const int num = jmin (howMany, dataSize - position);
  5879. memcpy (buffer, data + position, num);
  5880. position += num;
  5881. return num;
  5882. }
  5883. bool MemoryInputStream::isExhausted()
  5884. {
  5885. return (position >= dataSize);
  5886. }
  5887. bool MemoryInputStream::setPosition (int64 pos)
  5888. {
  5889. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  5890. return true;
  5891. }
  5892. int64 MemoryInputStream::getPosition()
  5893. {
  5894. return position;
  5895. }
  5896. END_JUCE_NAMESPACE
  5897. /********* End of inlined file: juce_MemoryInputStream.cpp *********/
  5898. /********* Start of inlined file: juce_MemoryOutputStream.cpp *********/
  5899. BEGIN_JUCE_NAMESPACE
  5900. MemoryOutputStream::MemoryOutputStream (const int initialSize,
  5901. const int blockSizeToIncreaseBy,
  5902. MemoryBlock* const memoryBlockToWriteTo) throw()
  5903. : data (memoryBlockToWriteTo),
  5904. position (0),
  5905. size (0),
  5906. blockSize (jmax (16, blockSizeToIncreaseBy)),
  5907. ownsMemoryBlock (memoryBlockToWriteTo == 0)
  5908. {
  5909. if (memoryBlockToWriteTo == 0)
  5910. data = new MemoryBlock (initialSize);
  5911. else
  5912. memoryBlockToWriteTo->setSize (initialSize, false);
  5913. }
  5914. MemoryOutputStream::~MemoryOutputStream() throw()
  5915. {
  5916. if (ownsMemoryBlock)
  5917. delete data;
  5918. else
  5919. flush();
  5920. }
  5921. void MemoryOutputStream::flush()
  5922. {
  5923. if (! ownsMemoryBlock)
  5924. data->setSize (size, false);
  5925. }
  5926. void MemoryOutputStream::reset() throw()
  5927. {
  5928. position = 0;
  5929. size = 0;
  5930. }
  5931. bool MemoryOutputStream::write (const void* buffer, int howMany)
  5932. {
  5933. int storageNeeded = position + howMany + 1;
  5934. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  5935. data->ensureSize (storageNeeded);
  5936. data->copyFrom (buffer, position, howMany);
  5937. position += howMany;
  5938. size = jmax (size, position);
  5939. return true;
  5940. }
  5941. const char* MemoryOutputStream::getData() throw()
  5942. {
  5943. if (data->getSize() > size)
  5944. ((char*) data->getData()) [size] = 0;
  5945. return (const char*) data->getData();
  5946. }
  5947. int MemoryOutputStream::getDataSize() const throw()
  5948. {
  5949. return size;
  5950. }
  5951. int64 MemoryOutputStream::getPosition()
  5952. {
  5953. return position;
  5954. }
  5955. bool MemoryOutputStream::setPosition (int64 newPosition)
  5956. {
  5957. if (newPosition <= size)
  5958. {
  5959. // ok to seek backwards
  5960. position = jlimit (0, size, (int) newPosition);
  5961. return true;
  5962. }
  5963. else
  5964. {
  5965. // trying to make it bigger isn't a good thing to do..
  5966. return false;
  5967. }
  5968. }
  5969. END_JUCE_NAMESPACE
  5970. /********* End of inlined file: juce_MemoryOutputStream.cpp *********/
  5971. /********* Start of inlined file: juce_SubregionStream.cpp *********/
  5972. BEGIN_JUCE_NAMESPACE
  5973. SubregionStream::SubregionStream (InputStream* const sourceStream,
  5974. const int64 startPositionInSourceStream_,
  5975. const int64 lengthOfSourceStream_,
  5976. const bool deleteSourceWhenDestroyed_) throw()
  5977. : source (sourceStream),
  5978. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  5979. startPositionInSourceStream (startPositionInSourceStream_),
  5980. lengthOfSourceStream (lengthOfSourceStream_)
  5981. {
  5982. setPosition (0);
  5983. }
  5984. SubregionStream::~SubregionStream() throw()
  5985. {
  5986. if (deleteSourceWhenDestroyed)
  5987. delete source;
  5988. }
  5989. int64 SubregionStream::getTotalLength()
  5990. {
  5991. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  5992. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  5993. : srcLen;
  5994. }
  5995. int64 SubregionStream::getPosition()
  5996. {
  5997. return source->getPosition() - startPositionInSourceStream;
  5998. }
  5999. bool SubregionStream::setPosition (int64 newPosition)
  6000. {
  6001. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  6002. }
  6003. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  6004. {
  6005. if (lengthOfSourceStream < 0)
  6006. {
  6007. return source->read (destBuffer, maxBytesToRead);
  6008. }
  6009. else
  6010. {
  6011. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  6012. if (maxBytesToRead <= 0)
  6013. return 0;
  6014. return source->read (destBuffer, maxBytesToRead);
  6015. }
  6016. }
  6017. bool SubregionStream::isExhausted()
  6018. {
  6019. if (lengthOfSourceStream >= 0)
  6020. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  6021. else
  6022. return source->isExhausted();
  6023. }
  6024. END_JUCE_NAMESPACE
  6025. /********* End of inlined file: juce_SubregionStream.cpp *********/
  6026. /********* Start of inlined file: juce_PerformanceCounter.cpp *********/
  6027. BEGIN_JUCE_NAMESPACE
  6028. PerformanceCounter::PerformanceCounter (const String& name_,
  6029. int runsPerPrintout,
  6030. const File& loggingFile)
  6031. : name (name_),
  6032. numRuns (0),
  6033. runsPerPrint (runsPerPrintout),
  6034. totalTime (0),
  6035. outputFile (loggingFile)
  6036. {
  6037. if (outputFile != File::nonexistent)
  6038. {
  6039. String s ("**** Counter for \"");
  6040. s << name_ << "\" started at: "
  6041. << Time::getCurrentTime().toString (true, true)
  6042. << "\r\n";
  6043. outputFile.appendText (s, false, false);
  6044. }
  6045. }
  6046. PerformanceCounter::~PerformanceCounter()
  6047. {
  6048. printStatistics();
  6049. }
  6050. void PerformanceCounter::start()
  6051. {
  6052. started = Time::getHighResolutionTicks();
  6053. }
  6054. void PerformanceCounter::stop()
  6055. {
  6056. const int64 now = Time::getHighResolutionTicks();
  6057. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  6058. if (++numRuns == runsPerPrint)
  6059. printStatistics();
  6060. }
  6061. void PerformanceCounter::printStatistics()
  6062. {
  6063. if (numRuns > 0)
  6064. {
  6065. String s ("Performance count for \"");
  6066. s << name << "\" - average over " << numRuns << " run(s) = ";
  6067. const int micros = (int) (totalTime * (1000.0 / numRuns));
  6068. if (micros > 10000)
  6069. s << (micros/1000) << " millisecs";
  6070. else
  6071. s << micros << " microsecs";
  6072. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  6073. Logger::outputDebugString (s);
  6074. s << "\r\n";
  6075. if (outputFile != File::nonexistent)
  6076. outputFile.appendText (s, false, false);
  6077. numRuns = 0;
  6078. totalTime = 0;
  6079. }
  6080. }
  6081. END_JUCE_NAMESPACE
  6082. /********* End of inlined file: juce_PerformanceCounter.cpp *********/
  6083. /********* Start of inlined file: juce_Uuid.cpp *********/
  6084. BEGIN_JUCE_NAMESPACE
  6085. Uuid::Uuid()
  6086. {
  6087. // do some serious mixing up of our MAC addresses and different types of time info,
  6088. // plus a couple of passes of pseudo-random numbers over the whole thing.
  6089. SystemStats::getMACAddresses (value.asInt64, 2);
  6090. int i;
  6091. for (i = 16; --i >= 0;)
  6092. {
  6093. Random r (Time::getHighResolutionTicks()
  6094. + Random::getSystemRandom().nextInt()
  6095. + value.asInt [i & 3]);
  6096. value.asBytes[i] ^= (uint8) r.nextInt();
  6097. }
  6098. value.asInt64 [0] ^= Time::getHighResolutionTicks();
  6099. value.asInt64 [1] ^= Time::currentTimeMillis();
  6100. for (i = 4; --i >= 0;)
  6101. {
  6102. Random r (Time::getHighResolutionTicks() ^ value.asInt[i]);
  6103. value.asInt[i] ^= r.nextInt();
  6104. }
  6105. }
  6106. Uuid::~Uuid() throw()
  6107. {
  6108. }
  6109. Uuid::Uuid (const Uuid& other)
  6110. : value (other.value)
  6111. {
  6112. }
  6113. Uuid& Uuid::operator= (const Uuid& other)
  6114. {
  6115. if (this != &other)
  6116. value = other.value;
  6117. return *this;
  6118. }
  6119. bool Uuid::operator== (const Uuid& other) const
  6120. {
  6121. return memcmp (value.asBytes, other.value.asBytes, 16) == 0;
  6122. }
  6123. bool Uuid::operator!= (const Uuid& other) const
  6124. {
  6125. return ! operator== (other);
  6126. }
  6127. bool Uuid::isNull() const throw()
  6128. {
  6129. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  6130. }
  6131. const String Uuid::toString() const
  6132. {
  6133. return String::toHexString (value.asBytes, 16, 0);
  6134. }
  6135. Uuid::Uuid (const String& uuidString)
  6136. {
  6137. operator= (uuidString);
  6138. }
  6139. Uuid& Uuid::operator= (const String& uuidString)
  6140. {
  6141. int destIndex = 0;
  6142. int i = 0;
  6143. for (;;)
  6144. {
  6145. int byte = 0;
  6146. for (int loop = 2; --loop >= 0;)
  6147. {
  6148. byte <<= 4;
  6149. for (;;)
  6150. {
  6151. const tchar c = uuidString [i++];
  6152. if (c >= T('0') && c <= T('9'))
  6153. {
  6154. byte |= c - T('0');
  6155. break;
  6156. }
  6157. else if (c >= T('a') && c <= T('z'))
  6158. {
  6159. byte |= c - (T('a') - 10);
  6160. break;
  6161. }
  6162. else if (c >= T('A') && c <= T('Z'))
  6163. {
  6164. byte |= c - (T('A') - 10);
  6165. break;
  6166. }
  6167. else if (c == 0)
  6168. {
  6169. while (destIndex < 16)
  6170. value.asBytes [destIndex++] = 0;
  6171. return *this;
  6172. }
  6173. }
  6174. }
  6175. value.asBytes [destIndex++] = (uint8) byte;
  6176. }
  6177. }
  6178. Uuid::Uuid (const uint8* const rawData)
  6179. {
  6180. operator= (rawData);
  6181. }
  6182. Uuid& Uuid::operator= (const uint8* const rawData)
  6183. {
  6184. if (rawData != 0)
  6185. memcpy (value.asBytes, rawData, 16);
  6186. else
  6187. zeromem (value.asBytes, 16);
  6188. return *this;
  6189. }
  6190. END_JUCE_NAMESPACE
  6191. /********* End of inlined file: juce_Uuid.cpp *********/
  6192. /********* Start of inlined file: juce_ZipFile.cpp *********/
  6193. BEGIN_JUCE_NAMESPACE
  6194. struct ZipEntryInfo
  6195. {
  6196. ZipFile::ZipEntry entry;
  6197. int streamOffset;
  6198. int compressedSize;
  6199. bool compressed;
  6200. };
  6201. class ZipInputStream : public InputStream
  6202. {
  6203. public:
  6204. ZipInputStream (ZipFile& file_,
  6205. ZipEntryInfo& zei) throw()
  6206. : file (file_),
  6207. zipEntryInfo (zei),
  6208. pos (0),
  6209. headerSize (0),
  6210. inputStream (0)
  6211. {
  6212. inputStream = file_.inputStream;
  6213. if (file_.inputSource != 0)
  6214. {
  6215. inputStream = file.inputSource->createInputStream();
  6216. }
  6217. else
  6218. {
  6219. #ifdef JUCE_DEBUG
  6220. file_.numOpenStreams++;
  6221. #endif
  6222. }
  6223. char buffer [30];
  6224. if (inputStream != 0
  6225. && inputStream->setPosition (zei.streamOffset)
  6226. && inputStream->read (buffer, 30) == 30
  6227. && littleEndianInt (buffer) == 0x04034b50)
  6228. {
  6229. headerSize = 30 + littleEndianShort (buffer + 26)
  6230. + littleEndianShort (buffer + 28);
  6231. }
  6232. }
  6233. ~ZipInputStream() throw()
  6234. {
  6235. #ifdef JUCE_DEBUG
  6236. if (inputStream != 0 && inputStream == file.inputStream)
  6237. file.numOpenStreams--;
  6238. #endif
  6239. if (inputStream != file.inputStream)
  6240. delete inputStream;
  6241. }
  6242. int64 getTotalLength() throw()
  6243. {
  6244. return zipEntryInfo.compressedSize;
  6245. }
  6246. int read (void* buffer, int howMany) throw()
  6247. {
  6248. if (headerSize <= 0)
  6249. return 0;
  6250. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  6251. if (inputStream == 0)
  6252. return 0;
  6253. int num;
  6254. if (inputStream == file.inputStream)
  6255. {
  6256. const ScopedLock sl (file.lock);
  6257. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  6258. num = inputStream->read (buffer, howMany);
  6259. }
  6260. else
  6261. {
  6262. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  6263. num = inputStream->read (buffer, howMany);
  6264. }
  6265. pos += num;
  6266. return num;
  6267. }
  6268. bool isExhausted() throw()
  6269. {
  6270. return pos >= zipEntryInfo.compressedSize;
  6271. }
  6272. int64 getPosition() throw()
  6273. {
  6274. return pos;
  6275. }
  6276. bool setPosition (int64 newPos) throw()
  6277. {
  6278. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  6279. return true;
  6280. }
  6281. private:
  6282. ZipFile& file;
  6283. ZipEntryInfo zipEntryInfo;
  6284. int64 pos;
  6285. int headerSize;
  6286. InputStream* inputStream;
  6287. ZipInputStream (const ZipInputStream&);
  6288. const ZipInputStream& operator= (const ZipInputStream&);
  6289. };
  6290. ZipFile::ZipFile (InputStream* const source_,
  6291. const bool deleteStreamWhenDestroyed_) throw()
  6292. : inputStream (source_),
  6293. inputSource (0),
  6294. deleteStreamWhenDestroyed (deleteStreamWhenDestroyed_)
  6295. #ifdef JUCE_DEBUG
  6296. , numOpenStreams (0)
  6297. #endif
  6298. {
  6299. init();
  6300. }
  6301. ZipFile::ZipFile (const File& file)
  6302. : inputStream (0),
  6303. deleteStreamWhenDestroyed (false)
  6304. #ifdef JUCE_DEBUG
  6305. , numOpenStreams (0)
  6306. #endif
  6307. {
  6308. inputSource = new FileInputSource (file);
  6309. init();
  6310. }
  6311. ZipFile::ZipFile (InputSource* const inputSource_)
  6312. : inputStream (0),
  6313. inputSource (inputSource_),
  6314. deleteStreamWhenDestroyed (false)
  6315. #ifdef JUCE_DEBUG
  6316. , numOpenStreams (0)
  6317. #endif
  6318. {
  6319. init();
  6320. }
  6321. ZipFile::~ZipFile() throw()
  6322. {
  6323. for (int i = entries.size(); --i >= 0;)
  6324. {
  6325. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [i];
  6326. delete zei;
  6327. }
  6328. if (deleteStreamWhenDestroyed)
  6329. delete inputStream;
  6330. delete inputSource;
  6331. #ifdef JUCE_DEBUG
  6332. // If you hit this assertion, it means you've created a stream to read
  6333. // one of the items in the zipfile, but you've forgotten to delete that
  6334. // stream object before deleting the file.. Streams can't be kept open
  6335. // after the file is deleted because they need to share the input
  6336. // stream that the file uses to read itself.
  6337. jassert (numOpenStreams == 0);
  6338. #endif
  6339. }
  6340. int ZipFile::getNumEntries() const throw()
  6341. {
  6342. return entries.size();
  6343. }
  6344. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  6345. {
  6346. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [index];
  6347. return (zei != 0) ? &(zei->entry)
  6348. : 0;
  6349. }
  6350. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  6351. {
  6352. for (int i = 0; i < entries.size(); ++i)
  6353. if (((ZipEntryInfo*) entries.getUnchecked (i))->entry.filename == fileName)
  6354. return i;
  6355. return -1;
  6356. }
  6357. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  6358. {
  6359. return getEntry (getIndexOfFileName (fileName));
  6360. }
  6361. InputStream* ZipFile::createStreamForEntry (const int index)
  6362. {
  6363. ZipEntryInfo* const zei = (ZipEntryInfo*) entries[index];
  6364. InputStream* stream = 0;
  6365. if (zei != 0)
  6366. {
  6367. stream = new ZipInputStream (*this, *zei);
  6368. if (zei->compressed)
  6369. {
  6370. stream = new GZIPDecompressorInputStream (stream, true, true,
  6371. zei->entry.uncompressedSize);
  6372. // (much faster to unzip in big blocks using a buffer..)
  6373. stream = new BufferedInputStream (stream, 32768, true);
  6374. }
  6375. }
  6376. return stream;
  6377. }
  6378. class ZipFilenameComparator
  6379. {
  6380. public:
  6381. static int compareElements (const void* const first, const void* const second) throw()
  6382. {
  6383. return ((const ZipEntryInfo*) first)->entry.filename
  6384. .compare (((const ZipEntryInfo*) second)->entry.filename);
  6385. }
  6386. };
  6387. void ZipFile::sortEntriesByFilename()
  6388. {
  6389. ZipFilenameComparator sorter;
  6390. entries.sort (sorter);
  6391. }
  6392. void ZipFile::init()
  6393. {
  6394. InputStream* in = inputStream;
  6395. bool deleteInput = false;
  6396. if (inputSource != 0)
  6397. {
  6398. deleteInput = true;
  6399. in = inputSource->createInputStream();
  6400. }
  6401. if (in != 0)
  6402. {
  6403. numEntries = 0;
  6404. int pos = findEndOfZipEntryTable (in);
  6405. if (pos >= 0 && pos < in->getTotalLength())
  6406. {
  6407. const int size = (int) (in->getTotalLength() - pos);
  6408. in->setPosition (pos);
  6409. MemoryBlock headerData;
  6410. if (in->readIntoMemoryBlock (headerData, size) == size)
  6411. {
  6412. pos = 0;
  6413. for (int i = 0; i < numEntries; ++i)
  6414. {
  6415. if (pos + 46 > size)
  6416. break;
  6417. const char* const buffer = ((const char*) headerData.getData()) + pos;
  6418. const int fileNameLen = littleEndianShort (buffer + 28);
  6419. if (pos + 46 + fileNameLen > size)
  6420. break;
  6421. ZipEntryInfo* const zei = new ZipEntryInfo();
  6422. zei->entry.filename = String (buffer + 46, fileNameLen);
  6423. const int time = littleEndianShort (buffer + 12);
  6424. const int date = littleEndianShort (buffer + 14);
  6425. const int year = 1980 + (date >> 9);
  6426. const int month = ((date >> 5) & 15) - 1;
  6427. const int day = date & 31;
  6428. const int hours = time >> 11;
  6429. const int minutes = (time >> 5) & 63;
  6430. const int seconds = (time & 31) << 1;
  6431. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  6432. zei->compressed = littleEndianShort (buffer + 10) != 0;
  6433. zei->compressedSize = littleEndianInt (buffer + 20);
  6434. zei->entry.uncompressedSize = littleEndianInt (buffer + 24);
  6435. zei->streamOffset = littleEndianInt (buffer + 42);
  6436. entries.add (zei);
  6437. pos += 46 + fileNameLen
  6438. + littleEndianShort (buffer + 30)
  6439. + littleEndianShort (buffer + 32);
  6440. }
  6441. }
  6442. }
  6443. if (deleteInput)
  6444. delete in;
  6445. }
  6446. }
  6447. int ZipFile::findEndOfZipEntryTable (InputStream* input)
  6448. {
  6449. BufferedInputStream in (input, 8192, false);
  6450. in.setPosition (in.getTotalLength());
  6451. int64 pos = in.getPosition();
  6452. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  6453. char buffer [32];
  6454. zeromem (buffer, sizeof (buffer));
  6455. while (pos > lowestPos)
  6456. {
  6457. in.setPosition (pos - 22);
  6458. pos = in.getPosition();
  6459. memcpy (buffer + 22, buffer, 4);
  6460. if (in.read (buffer, 22) != 22)
  6461. return 0;
  6462. for (int i = 0; i < 22; ++i)
  6463. {
  6464. if (littleEndianInt (buffer + i) == 0x06054b50)
  6465. {
  6466. in.setPosition (pos + i);
  6467. in.read (buffer, 22);
  6468. numEntries = littleEndianShort (buffer + 10);
  6469. return littleEndianInt (buffer + 16);
  6470. }
  6471. }
  6472. }
  6473. return 0;
  6474. }
  6475. void ZipFile::uncompressTo (const File& targetDirectory,
  6476. const bool shouldOverwriteFiles)
  6477. {
  6478. for (int i = 0; i < entries.size(); ++i)
  6479. {
  6480. const ZipEntryInfo& zei = *(ZipEntryInfo*) entries[i];
  6481. const File targetFile (targetDirectory.getChildFile (zei.entry.filename));
  6482. if (zei.entry.filename.endsWithChar (T('/')))
  6483. {
  6484. targetFile.createDirectory(); // (entry is a directory, not a file)
  6485. }
  6486. else
  6487. {
  6488. InputStream* const in = createStreamForEntry (i);
  6489. if (in != 0)
  6490. {
  6491. if (shouldOverwriteFiles)
  6492. targetFile.deleteFile();
  6493. if ((! targetFile.exists())
  6494. && targetFile.getParentDirectory().createDirectory())
  6495. {
  6496. FileOutputStream* const out = targetFile.createOutputStream();
  6497. if (out != 0)
  6498. {
  6499. out->writeFromInputStream (*in, -1);
  6500. delete out;
  6501. targetFile.setCreationTime (zei.entry.fileTime);
  6502. targetFile.setLastModificationTime (zei.entry.fileTime);
  6503. targetFile.setLastAccessTime (zei.entry.fileTime);
  6504. }
  6505. }
  6506. delete in;
  6507. }
  6508. }
  6509. }
  6510. }
  6511. END_JUCE_NAMESPACE
  6512. /********* End of inlined file: juce_ZipFile.cpp *********/
  6513. /********* Start of inlined file: juce_CharacterFunctions.cpp *********/
  6514. #ifdef _MSC_VER
  6515. #pragma warning (disable: 4514 4996)
  6516. #pragma warning (push)
  6517. #endif
  6518. #include <cwctype>
  6519. #include <cctype>
  6520. #include <ctime>
  6521. #ifdef _MSC_VER
  6522. #pragma warning (pop)
  6523. #endif
  6524. BEGIN_JUCE_NAMESPACE
  6525. int CharacterFunctions::length (const char* const s) throw()
  6526. {
  6527. return (int) strlen (s);
  6528. }
  6529. int CharacterFunctions::length (const juce_wchar* const s) throw()
  6530. {
  6531. #if MACOS_10_2_OR_EARLIER
  6532. int n = 0;
  6533. while (s[n] != 0)
  6534. ++n;
  6535. return n;
  6536. #else
  6537. return (int) wcslen (s);
  6538. #endif
  6539. }
  6540. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  6541. {
  6542. strncpy (dest, src, maxChars);
  6543. }
  6544. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  6545. {
  6546. #if MACOS_10_2_OR_EARLIER
  6547. while (--maxChars >= 0 && *src != 0)
  6548. *dest++ = *src++;
  6549. *dest = 0;
  6550. #else
  6551. wcsncpy (dest, src, maxChars);
  6552. #endif
  6553. }
  6554. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  6555. {
  6556. mbstowcs (dest, src, maxChars);
  6557. }
  6558. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  6559. {
  6560. wcstombs (dest, src, maxChars);
  6561. }
  6562. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  6563. {
  6564. return (int) wcstombs (0, src, 0);
  6565. }
  6566. void CharacterFunctions::append (char* dest, const char* src) throw()
  6567. {
  6568. strcat (dest, src);
  6569. }
  6570. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  6571. {
  6572. #if MACOS_10_2_OR_EARLIER
  6573. while (*dest != 0)
  6574. ++dest;
  6575. while (*src != 0)
  6576. *dest++ = *src++;
  6577. *dest = 0;
  6578. #else
  6579. wcscat (dest, src);
  6580. #endif
  6581. }
  6582. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  6583. {
  6584. return strcmp (s1, s2);
  6585. }
  6586. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  6587. {
  6588. jassert (s1 != 0 && s2 != 0);
  6589. #if MACOS_10_2_OR_EARLIER
  6590. for (;;)
  6591. {
  6592. if (*s1 != *s2)
  6593. {
  6594. const int diff = *s1 - *s2;
  6595. if (diff != 0)
  6596. return diff < 0 ? -1 : 1;
  6597. }
  6598. else if (*s1 == 0)
  6599. break;
  6600. ++s1;
  6601. ++s2;
  6602. }
  6603. return 0;
  6604. #else
  6605. return wcscmp (s1, s2);
  6606. #endif
  6607. }
  6608. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  6609. {
  6610. jassert (s1 != 0 && s2 != 0);
  6611. return strncmp (s1, s2, maxChars);
  6612. }
  6613. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  6614. {
  6615. jassert (s1 != 0 && s2 != 0);
  6616. #if MACOS_10_2_OR_EARLIER
  6617. while (--maxChars >= 0)
  6618. {
  6619. if (*s1 != *s2)
  6620. return (*s1 < *s2) ? -1 : 1;
  6621. else if (*s1 == 0)
  6622. break;
  6623. ++s1;
  6624. ++s2;
  6625. }
  6626. return 0;
  6627. #else
  6628. return wcsncmp (s1, s2, maxChars);
  6629. #endif
  6630. }
  6631. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  6632. {
  6633. jassert (s1 != 0 && s2 != 0);
  6634. #if JUCE_WIN32
  6635. return stricmp (s1, s2);
  6636. #else
  6637. return strcasecmp (s1, s2);
  6638. #endif
  6639. }
  6640. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  6641. {
  6642. jassert (s1 != 0 && s2 != 0);
  6643. #if JUCE_WIN32
  6644. return _wcsicmp (s1, s2);
  6645. #else
  6646. for (;;)
  6647. {
  6648. if (*s1 != *s2)
  6649. {
  6650. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  6651. if (diff != 0)
  6652. return diff < 0 ? -1 : 1;
  6653. }
  6654. else if (*s1 == 0)
  6655. break;
  6656. ++s1;
  6657. ++s2;
  6658. }
  6659. return 0;
  6660. #endif
  6661. }
  6662. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  6663. {
  6664. jassert (s1 != 0 && s2 != 0);
  6665. #if JUCE_WIN32
  6666. return strnicmp (s1, s2, maxChars);
  6667. #else
  6668. return strncasecmp (s1, s2, maxChars);
  6669. #endif
  6670. }
  6671. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  6672. {
  6673. jassert (s1 != 0 && s2 != 0);
  6674. #if JUCE_WIN32
  6675. return _wcsnicmp (s1, s2, maxChars);
  6676. #else
  6677. while (--maxChars >= 0)
  6678. {
  6679. if (*s1 != *s2)
  6680. {
  6681. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  6682. if (diff != 0)
  6683. return diff < 0 ? -1 : 1;
  6684. }
  6685. else if (*s1 == 0)
  6686. break;
  6687. ++s1;
  6688. ++s2;
  6689. }
  6690. return 0;
  6691. #endif
  6692. }
  6693. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  6694. {
  6695. return strstr (haystack, needle);
  6696. }
  6697. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  6698. {
  6699. #if MACOS_10_2_OR_EARLIER
  6700. while (*haystack != 0)
  6701. {
  6702. const juce_wchar* s1 = haystack;
  6703. const juce_wchar* s2 = needle;
  6704. for (;;)
  6705. {
  6706. if (*s2 == 0)
  6707. return haystack;
  6708. if (*s1 != *s2 || *s2 == 0)
  6709. break;
  6710. ++s1;
  6711. ++s2;
  6712. }
  6713. ++haystack;
  6714. }
  6715. return 0;
  6716. #else
  6717. return wcsstr (haystack, needle);
  6718. #endif
  6719. }
  6720. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  6721. {
  6722. if (haystack != 0)
  6723. {
  6724. int i = 0;
  6725. if (ignoreCase)
  6726. {
  6727. const char n1 = toLowerCase (needle);
  6728. const char n2 = toUpperCase (needle);
  6729. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  6730. {
  6731. while (haystack[i] != 0)
  6732. {
  6733. if (haystack[i] == n1 || haystack[i] == n2)
  6734. return i;
  6735. ++i;
  6736. }
  6737. return -1;
  6738. }
  6739. jassert (n1 == needle);
  6740. }
  6741. while (haystack[i] != 0)
  6742. {
  6743. if (haystack[i] == needle)
  6744. return i;
  6745. ++i;
  6746. }
  6747. }
  6748. return -1;
  6749. }
  6750. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  6751. {
  6752. if (haystack != 0)
  6753. {
  6754. int i = 0;
  6755. if (ignoreCase)
  6756. {
  6757. const juce_wchar n1 = toLowerCase (needle);
  6758. const juce_wchar n2 = toUpperCase (needle);
  6759. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  6760. {
  6761. while (haystack[i] != 0)
  6762. {
  6763. if (haystack[i] == n1 || haystack[i] == n2)
  6764. return i;
  6765. ++i;
  6766. }
  6767. return -1;
  6768. }
  6769. jassert (n1 == needle);
  6770. }
  6771. while (haystack[i] != 0)
  6772. {
  6773. if (haystack[i] == needle)
  6774. return i;
  6775. ++i;
  6776. }
  6777. }
  6778. return -1;
  6779. }
  6780. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  6781. {
  6782. jassert (haystack != 0);
  6783. int i = 0;
  6784. while (haystack[i] != 0)
  6785. {
  6786. if (haystack[i] == needle)
  6787. return i;
  6788. ++i;
  6789. }
  6790. return -1;
  6791. }
  6792. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  6793. {
  6794. jassert (haystack != 0);
  6795. int i = 0;
  6796. while (haystack[i] != 0)
  6797. {
  6798. if (haystack[i] == needle)
  6799. return i;
  6800. ++i;
  6801. }
  6802. return -1;
  6803. }
  6804. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  6805. {
  6806. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  6807. }
  6808. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  6809. {
  6810. if (allowedChars == 0)
  6811. return 0;
  6812. int i = 0;
  6813. for (;;)
  6814. {
  6815. if (indexOfCharFast (allowedChars, text[i]) < 0)
  6816. break;
  6817. ++i;
  6818. }
  6819. return i;
  6820. }
  6821. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  6822. {
  6823. return (int) strftime (dest, maxChars, format, tm);
  6824. }
  6825. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  6826. {
  6827. #if MACOS_10_2_OR_EARLIER
  6828. const String formatTemp (format);
  6829. size_t num = strftime ((char*) dest, maxChars, (const char*) formatTemp, tm);
  6830. String temp ((char*) dest);
  6831. temp.copyToBuffer (dest, num);
  6832. dest [num] = 0;
  6833. return (int) num;
  6834. #else
  6835. return (int) wcsftime (dest, maxChars, format, tm);
  6836. #endif
  6837. }
  6838. int CharacterFunctions::getIntValue (const char* const s) throw()
  6839. {
  6840. return atoi (s);
  6841. }
  6842. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  6843. {
  6844. #if JUCE_WIN32
  6845. return _wtoi (s);
  6846. #else
  6847. int v = 0;
  6848. while (isWhitespace (*s))
  6849. ++s;
  6850. const bool isNeg = *s == T('-');
  6851. if (isNeg)
  6852. ++s;
  6853. for (;;)
  6854. {
  6855. const wchar_t c = *s++;
  6856. if (c >= T('0') && c <= T('9'))
  6857. v = v * 10 + (int) (c - T('0'));
  6858. else
  6859. break;
  6860. }
  6861. return isNeg ? -v : v;
  6862. #endif
  6863. }
  6864. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  6865. {
  6866. #if JUCE_LINUX
  6867. return atoll (s);
  6868. #elif defined (JUCE_WIN32)
  6869. return _atoi64 (s);
  6870. #else
  6871. int64 v = 0;
  6872. while (isWhitespace (*s))
  6873. ++s;
  6874. const bool isNeg = *s == T('-');
  6875. if (isNeg)
  6876. ++s;
  6877. for (;;)
  6878. {
  6879. const char c = *s++;
  6880. if (c >= '0' && c <= '9')
  6881. v = v * 10 + (int64) (c - '0');
  6882. else
  6883. break;
  6884. }
  6885. return isNeg ? -v : v;
  6886. #endif
  6887. }
  6888. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  6889. {
  6890. #if JUCE_WIN32
  6891. return _wtoi64 (s);
  6892. #else
  6893. int64 v = 0;
  6894. while (isWhitespace (*s))
  6895. ++s;
  6896. const bool isNeg = *s == T('-');
  6897. if (isNeg)
  6898. ++s;
  6899. for (;;)
  6900. {
  6901. const juce_wchar c = *s++;
  6902. if (c >= T('0') && c <= T('9'))
  6903. v = v * 10 + (int64) (c - T('0'));
  6904. else
  6905. break;
  6906. }
  6907. return isNeg ? -v : v;
  6908. #endif
  6909. }
  6910. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  6911. {
  6912. return atof (s);
  6913. }
  6914. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  6915. {
  6916. #if MACOS_10_2_OR_EARLIER
  6917. String temp (s);
  6918. return atof ((const char*) temp);
  6919. #else
  6920. wchar_t* endChar;
  6921. return wcstod (s, &endChar);
  6922. #endif
  6923. }
  6924. char CharacterFunctions::toUpperCase (const char character) throw()
  6925. {
  6926. return (char) toupper (character);
  6927. }
  6928. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  6929. {
  6930. #if MACOS_10_2_OR_EARLIER
  6931. return toupper ((char) character);
  6932. #else
  6933. return towupper (character);
  6934. #endif
  6935. }
  6936. void CharacterFunctions::toUpperCase (char* s) throw()
  6937. {
  6938. #if JUCE_WIN32
  6939. strupr (s);
  6940. #else
  6941. while (*s != 0)
  6942. {
  6943. *s = toUpperCase (*s);
  6944. ++s;
  6945. }
  6946. #endif
  6947. }
  6948. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  6949. {
  6950. #if JUCE_WIN32
  6951. _wcsupr (s);
  6952. #else
  6953. while (*s != 0)
  6954. {
  6955. *s = toUpperCase (*s);
  6956. ++s;
  6957. }
  6958. #endif
  6959. }
  6960. bool CharacterFunctions::isUpperCase (const char character) throw()
  6961. {
  6962. return isupper (character) != 0;
  6963. }
  6964. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  6965. {
  6966. #if JUCE_WIN32
  6967. return iswupper (character) != 0;
  6968. #else
  6969. return toLowerCase (character) != character;
  6970. #endif
  6971. }
  6972. char CharacterFunctions::toLowerCase (const char character) throw()
  6973. {
  6974. return (char) tolower (character);
  6975. }
  6976. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  6977. {
  6978. #if MACOS_10_2_OR_EARLIER
  6979. return tolower ((char) character);
  6980. #else
  6981. return towlower (character);
  6982. #endif
  6983. }
  6984. void CharacterFunctions::toLowerCase (char* s) throw()
  6985. {
  6986. #if JUCE_WIN32
  6987. strlwr (s);
  6988. #else
  6989. while (*s != 0)
  6990. {
  6991. *s = toLowerCase (*s);
  6992. ++s;
  6993. }
  6994. #endif
  6995. }
  6996. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  6997. {
  6998. #if JUCE_WIN32
  6999. _wcslwr (s);
  7000. #else
  7001. while (*s != 0)
  7002. {
  7003. *s = toLowerCase (*s);
  7004. ++s;
  7005. }
  7006. #endif
  7007. }
  7008. bool CharacterFunctions::isLowerCase (const char character) throw()
  7009. {
  7010. return islower (character) != 0;
  7011. }
  7012. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  7013. {
  7014. #if JUCE_WIN32
  7015. return iswlower (character) != 0;
  7016. #else
  7017. return toUpperCase (character) != character;
  7018. #endif
  7019. }
  7020. bool CharacterFunctions::isWhitespace (const char character) throw()
  7021. {
  7022. return character == T(' ') || (character <= 13 && character >= 9);
  7023. }
  7024. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  7025. {
  7026. #if MACOS_10_2_OR_EARLIER
  7027. return isWhitespace ((char) character);
  7028. #else
  7029. return iswspace (character) != 0;
  7030. #endif
  7031. }
  7032. bool CharacterFunctions::isDigit (const char character) throw()
  7033. {
  7034. return (character >= '0' && character <= '9');
  7035. }
  7036. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  7037. {
  7038. #if MACOS_10_2_OR_EARLIER
  7039. return isdigit ((char) character) != 0;
  7040. #else
  7041. return iswdigit (character) != 0;
  7042. #endif
  7043. }
  7044. bool CharacterFunctions::isLetter (const char character) throw()
  7045. {
  7046. return (character >= 'a' && character <= 'z')
  7047. || (character >= 'A' && character <= 'Z');
  7048. }
  7049. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  7050. {
  7051. #if MACOS_10_2_OR_EARLIER
  7052. return isLetter ((char) character);
  7053. #else
  7054. return iswalpha (character) != 0;
  7055. #endif
  7056. }
  7057. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  7058. {
  7059. return (character >= 'a' && character <= 'z')
  7060. || (character >= 'A' && character <= 'Z')
  7061. || (character >= '0' && character <= '9');
  7062. }
  7063. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  7064. {
  7065. #if MACOS_10_2_OR_EARLIER
  7066. return isLetterOrDigit ((char) character);
  7067. #else
  7068. return iswalnum (character) != 0;
  7069. #endif
  7070. }
  7071. int CharacterFunctions::getHexDigitValue (const tchar digit) throw()
  7072. {
  7073. if (digit >= T('0') && digit <= T('9'))
  7074. return digit - T('0');
  7075. else if (digit >= T('a') && digit <= T('f'))
  7076. return digit - (T('a') - 10);
  7077. else if (digit >= T('A') && digit <= T('F'))
  7078. return digit - (T('A') - 10);
  7079. return -1;
  7080. }
  7081. int CharacterFunctions::printf (char* const dest, const int maxLength, const char* const format, ...) throw()
  7082. {
  7083. va_list list;
  7084. va_start (list, format);
  7085. return vprintf (dest, maxLength, format, list);
  7086. }
  7087. int CharacterFunctions::printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw()
  7088. {
  7089. va_list list;
  7090. va_start (list, format);
  7091. return vprintf (dest, maxLength, format, list);
  7092. }
  7093. int CharacterFunctions::vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw()
  7094. {
  7095. #if JUCE_WIN32
  7096. return (int) _vsnprintf (dest, maxLength, format, args);
  7097. #else
  7098. return (int) vsnprintf (dest, maxLength, format, args);
  7099. #endif
  7100. }
  7101. int CharacterFunctions::vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw()
  7102. {
  7103. #if MACOS_10_3_OR_EARLIER
  7104. const String formatTemp (format);
  7105. size_t num = vprintf ((char*) dest, maxLength, formatTemp, args);
  7106. String temp ((char*) dest);
  7107. temp.copyToBuffer (dest, num);
  7108. dest [num] = 0;
  7109. return (int) num;
  7110. #elif defined (JUCE_WIN32)
  7111. return (int) _vsnwprintf (dest, maxLength, format, args);
  7112. #else
  7113. return (int) vswprintf (dest, maxLength, format, args);
  7114. #endif
  7115. }
  7116. END_JUCE_NAMESPACE
  7117. /********* End of inlined file: juce_CharacterFunctions.cpp *********/
  7118. /********* Start of inlined file: juce_LocalisedStrings.cpp *********/
  7119. BEGIN_JUCE_NAMESPACE
  7120. LocalisedStrings::LocalisedStrings (const String& fileContents) throw()
  7121. {
  7122. loadFromText (fileContents);
  7123. }
  7124. LocalisedStrings::LocalisedStrings (const File& fileToLoad) throw()
  7125. {
  7126. loadFromText (fileToLoad.loadFileAsString());
  7127. }
  7128. LocalisedStrings::~LocalisedStrings() throw()
  7129. {
  7130. }
  7131. const String LocalisedStrings::translate (const String& text) const throw()
  7132. {
  7133. return translations.getValue (text, text);
  7134. }
  7135. static int findCloseQuote (const String& text, int startPos) throw()
  7136. {
  7137. tchar lastChar = 0;
  7138. for (;;)
  7139. {
  7140. const tchar c = text [startPos];
  7141. if (c == 0 || (c == T('"') && lastChar != T('\\')))
  7142. break;
  7143. lastChar = c;
  7144. ++startPos;
  7145. }
  7146. return startPos;
  7147. }
  7148. static const String unescapeString (const String& s) throw()
  7149. {
  7150. return s.replace (T("\\\""), T("\""))
  7151. .replace (T("\\\'"), T("\'"))
  7152. .replace (T("\\t"), T("\t"))
  7153. .replace (T("\\r"), T("\r"))
  7154. .replace (T("\\n"), T("\n"));
  7155. }
  7156. void LocalisedStrings::loadFromText (const String& fileContents) throw()
  7157. {
  7158. StringArray lines;
  7159. lines.addLines (fileContents);
  7160. for (int i = 0; i < lines.size(); ++i)
  7161. {
  7162. String line (lines[i].trim());
  7163. if (line.startsWithChar (T('"')))
  7164. {
  7165. int closeQuote = findCloseQuote (line, 1);
  7166. const String originalText (unescapeString (line.substring (1, closeQuote)));
  7167. if (originalText.isNotEmpty())
  7168. {
  7169. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  7170. closeQuote = findCloseQuote (line, openingQuote + 1);
  7171. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  7172. if (newText.isNotEmpty())
  7173. translations.set (originalText, newText);
  7174. }
  7175. }
  7176. else if (line.startsWithIgnoreCase (T("language:")))
  7177. {
  7178. languageName = line.substring (9).trim();
  7179. }
  7180. else if (line.startsWithIgnoreCase (T("countries:")))
  7181. {
  7182. countryCodes.addTokens (line.substring (10).trim(), true);
  7183. countryCodes.trim();
  7184. countryCodes.removeEmptyStrings();
  7185. }
  7186. }
  7187. }
  7188. static CriticalSection currentMappingsLock;
  7189. static LocalisedStrings* currentMappings = 0;
  7190. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations) throw()
  7191. {
  7192. const ScopedLock sl (currentMappingsLock);
  7193. delete currentMappings;
  7194. currentMappings = newTranslations;
  7195. }
  7196. LocalisedStrings* LocalisedStrings::getCurrentMappings() throw()
  7197. {
  7198. return currentMappings;
  7199. }
  7200. const String LocalisedStrings::translateWithCurrentMappings (const String& text) throw()
  7201. {
  7202. const ScopedLock sl (currentMappingsLock);
  7203. if (currentMappings != 0)
  7204. return currentMappings->translate (text);
  7205. return text;
  7206. }
  7207. const String LocalisedStrings::translateWithCurrentMappings (const char* text) throw()
  7208. {
  7209. return translateWithCurrentMappings (String (text));
  7210. }
  7211. END_JUCE_NAMESPACE
  7212. /********* End of inlined file: juce_LocalisedStrings.cpp *********/
  7213. /********* Start of inlined file: juce_String.cpp *********/
  7214. #ifdef _MSC_VER
  7215. #pragma warning (disable: 4514)
  7216. #pragma warning (push)
  7217. #endif
  7218. #include <locale>
  7219. #if JUCE_MSVC
  7220. #include <float.h>
  7221. #endif
  7222. BEGIN_JUCE_NAMESPACE
  7223. #ifdef _MSC_VER
  7224. #pragma warning (pop)
  7225. #endif
  7226. static const char* const emptyCharString = "\0\0\0\0JUCE";
  7227. static const int safeEmptyStringRefCount = 0x3fffffff;
  7228. String::InternalRefCountedStringHolder String::emptyString = { safeEmptyStringRefCount, 0, { 0 } };
  7229. static tchar decimalPoint = T('.');
  7230. void juce_initialiseStrings()
  7231. {
  7232. decimalPoint = String::fromUTF8 ((const uint8*) localeconv()->decimal_point) [0];
  7233. }
  7234. void String::deleteInternal() throw()
  7235. {
  7236. if (atomicDecrementAndReturn (text->refCount) == 0)
  7237. juce_free (text);
  7238. }
  7239. void String::createInternal (const int numChars) throw()
  7240. {
  7241. jassert (numChars > 0);
  7242. text = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7243. + numChars * sizeof (tchar));
  7244. text->refCount = 1;
  7245. text->allocatedNumChars = numChars;
  7246. text->text[0] = 0;
  7247. }
  7248. void String::createInternal (const tchar* const t, const tchar* const textEnd) throw()
  7249. {
  7250. jassert (*(textEnd - 1) == 0); // must have a null terminator
  7251. const int numChars = (int) (textEnd - t);
  7252. createInternal (numChars - 1);
  7253. memcpy (text->text, t, numChars * sizeof (tchar));
  7254. }
  7255. void String::appendInternal (const tchar* const newText,
  7256. const int numExtraChars) throw()
  7257. {
  7258. if (numExtraChars > 0)
  7259. {
  7260. const int oldLen = CharacterFunctions::length (text->text);
  7261. const int newTotalLen = oldLen + numExtraChars;
  7262. if (text->refCount > 1)
  7263. {
  7264. // it's in use by other strings as well, so we need to make a private copy before messing with it..
  7265. InternalRefCountedStringHolder* const newTextHolder
  7266. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7267. + newTotalLen * sizeof (tchar));
  7268. newTextHolder->refCount = 1;
  7269. newTextHolder->allocatedNumChars = newTotalLen;
  7270. memcpy (newTextHolder->text, text->text, oldLen * sizeof (tchar));
  7271. memcpy (newTextHolder->text + oldLen, newText, numExtraChars * sizeof (tchar));
  7272. InternalRefCountedStringHolder* const old = text;
  7273. text = newTextHolder;
  7274. if (atomicDecrementAndReturn (old->refCount) == 0)
  7275. juce_free (old);
  7276. }
  7277. else
  7278. {
  7279. // no other strings using it, so just expand it if needed..
  7280. if (newTotalLen > text->allocatedNumChars)
  7281. {
  7282. text = (InternalRefCountedStringHolder*)
  7283. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7284. + newTotalLen * sizeof (tchar));
  7285. text->allocatedNumChars = newTotalLen;
  7286. }
  7287. memcpy (text->text + oldLen, newText, numExtraChars * sizeof (tchar));
  7288. }
  7289. text->text [newTotalLen] = 0;
  7290. }
  7291. }
  7292. void String::dupeInternalIfMultiplyReferenced() throw()
  7293. {
  7294. if (text->refCount > 1)
  7295. {
  7296. InternalRefCountedStringHolder* const old = text;
  7297. const int len = old->allocatedNumChars;
  7298. InternalRefCountedStringHolder* const newTextHolder
  7299. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7300. + len * sizeof (tchar));
  7301. newTextHolder->refCount = 1;
  7302. newTextHolder->allocatedNumChars = len;
  7303. memcpy (newTextHolder->text, old->text, (len + 1) * sizeof (tchar));
  7304. text = newTextHolder;
  7305. if (atomicDecrementAndReturn (old->refCount) == 0)
  7306. juce_free (old);
  7307. }
  7308. }
  7309. const String String::empty;
  7310. String::String() throw()
  7311. : text (&emptyString)
  7312. {
  7313. }
  7314. String::String (const String& other) throw()
  7315. : text (other.text)
  7316. {
  7317. atomicIncrement (text->refCount);
  7318. }
  7319. String::String (const int numChars,
  7320. const int /*dummyVariable*/) throw()
  7321. {
  7322. createInternal (numChars);
  7323. }
  7324. String::String (const char* const t) throw()
  7325. {
  7326. if (t != 0 && *t != 0)
  7327. {
  7328. const int len = CharacterFunctions::length (t);
  7329. createInternal (len);
  7330. #if JUCE_STRINGS_ARE_UNICODE
  7331. CharacterFunctions::copy (text->text, t, len + 1);
  7332. #else
  7333. memcpy (text->text, t, len + 1);
  7334. #endif
  7335. }
  7336. else
  7337. {
  7338. text = &emptyString;
  7339. emptyString.refCount = safeEmptyStringRefCount;
  7340. }
  7341. }
  7342. String::String (const juce_wchar* const t) throw()
  7343. {
  7344. if (t != 0 && *t != 0)
  7345. {
  7346. #if JUCE_STRINGS_ARE_UNICODE
  7347. const int len = CharacterFunctions::length (t);
  7348. createInternal (len);
  7349. memcpy (text->text, t, (len + 1) * sizeof (tchar));
  7350. #else
  7351. const int len = CharacterFunctions::bytesRequiredForCopy (t);
  7352. createInternal (len);
  7353. CharacterFunctions::copy (text->text, t, len + 1);
  7354. #endif
  7355. }
  7356. else
  7357. {
  7358. text = &emptyString;
  7359. emptyString.refCount = safeEmptyStringRefCount;
  7360. }
  7361. }
  7362. String::String (const char* const t,
  7363. const int maxChars) throw()
  7364. {
  7365. int i;
  7366. for (i = 0; i < maxChars; ++i)
  7367. if (t[i] == 0)
  7368. break;
  7369. if (i > 0)
  7370. {
  7371. createInternal (i);
  7372. #if JUCE_STRINGS_ARE_UNICODE
  7373. CharacterFunctions::copy (text->text, t, i);
  7374. #else
  7375. memcpy (text->text, t, i);
  7376. #endif
  7377. text->text [i] = 0;
  7378. }
  7379. else
  7380. {
  7381. text = &emptyString;
  7382. emptyString.refCount = safeEmptyStringRefCount;
  7383. }
  7384. }
  7385. String::String (const juce_wchar* const t,
  7386. const int maxChars) throw()
  7387. {
  7388. int i;
  7389. for (i = 0; i < maxChars; ++i)
  7390. if (t[i] == 0)
  7391. break;
  7392. if (i > 0)
  7393. {
  7394. createInternal (i);
  7395. #if JUCE_STRINGS_ARE_UNICODE
  7396. memcpy (text->text, t, i * sizeof (tchar));
  7397. #else
  7398. CharacterFunctions::copy (text->text, t, i);
  7399. #endif
  7400. text->text [i] = 0;
  7401. }
  7402. else
  7403. {
  7404. text = &emptyString;
  7405. emptyString.refCount = safeEmptyStringRefCount;
  7406. }
  7407. }
  7408. const String String::charToString (const tchar character) throw()
  7409. {
  7410. tchar temp[2];
  7411. temp[0] = character;
  7412. temp[1] = 0;
  7413. return String (temp);
  7414. }
  7415. // pass in a pointer to the END of a buffer..
  7416. static tchar* int64ToCharString (tchar* t, const int64 n) throw()
  7417. {
  7418. *--t = 0;
  7419. int64 v = (n >= 0) ? n : -n;
  7420. do
  7421. {
  7422. *--t = (tchar) (T('0') + (int) (v % 10));
  7423. v /= 10;
  7424. } while (v > 0);
  7425. if (n < 0)
  7426. *--t = T('-');
  7427. return t;
  7428. }
  7429. static tchar* intToCharString (tchar* t, const int n) throw()
  7430. {
  7431. if (n == (int) 0x80000000) // (would cause an overflow)
  7432. return int64ToCharString (t, n);
  7433. *--t = 0;
  7434. int v = abs (n);
  7435. do
  7436. {
  7437. *--t = (tchar) (T('0') + (v % 10));
  7438. v /= 10;
  7439. } while (v > 0);
  7440. if (n < 0)
  7441. *--t = T('-');
  7442. return t;
  7443. }
  7444. static tchar* uintToCharString (tchar* t, unsigned int v) throw()
  7445. {
  7446. *--t = 0;
  7447. do
  7448. {
  7449. *--t = (tchar) (T('0') + (v % 10));
  7450. v /= 10;
  7451. } while (v > 0);
  7452. return t;
  7453. }
  7454. String::String (const int number) throw()
  7455. {
  7456. tchar buffer [16];
  7457. tchar* const end = buffer + 16;
  7458. createInternal (intToCharString (end, number), end);
  7459. }
  7460. String::String (const unsigned int number) throw()
  7461. {
  7462. tchar buffer [16];
  7463. tchar* const end = buffer + 16;
  7464. createInternal (uintToCharString (end, number), end);
  7465. }
  7466. String::String (const short number) throw()
  7467. {
  7468. tchar buffer [16];
  7469. tchar* const end = buffer + 16;
  7470. createInternal (intToCharString (end, (int) number), end);
  7471. }
  7472. String::String (const unsigned short number) throw()
  7473. {
  7474. tchar buffer [16];
  7475. tchar* const end = buffer + 16;
  7476. createInternal (uintToCharString (end, (unsigned int) number), end);
  7477. }
  7478. String::String (const int64 number) throw()
  7479. {
  7480. tchar buffer [32];
  7481. tchar* const end = buffer + 32;
  7482. createInternal (int64ToCharString (end, number), end);
  7483. }
  7484. String::String (const uint64 number) throw()
  7485. {
  7486. tchar buffer [32];
  7487. tchar* const end = buffer + 32;
  7488. tchar* t = end;
  7489. *--t = 0;
  7490. int64 v = number;
  7491. do
  7492. {
  7493. *--t = (tchar) (T('0') + (int) (v % 10));
  7494. v /= 10;
  7495. } while (v > 0);
  7496. createInternal (t, end);
  7497. }
  7498. // a double-to-string routine that actually uses the number of dec. places you asked for
  7499. // without resorting to exponent notation if the number's too big or small (which is what printf does).
  7500. void String::doubleToStringWithDecPlaces (double n, int numDecPlaces) throw()
  7501. {
  7502. const int bufSize = 80;
  7503. tchar buffer [bufSize];
  7504. int len;
  7505. tchar* t;
  7506. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  7507. {
  7508. int64 v = (int64) (pow (10.0, numDecPlaces) * fabs (n) + 0.5);
  7509. t = buffer + bufSize;
  7510. *--t = (tchar) 0;
  7511. while (numDecPlaces >= 0 || v > 0)
  7512. {
  7513. if (numDecPlaces == 0)
  7514. *--t = decimalPoint;
  7515. *--t = (tchar) (T('0') + (v % 10));
  7516. v /= 10;
  7517. --numDecPlaces;
  7518. }
  7519. if (n < 0)
  7520. *--t = T('-');
  7521. len = (int) ((buffer + bufSize) - t);
  7522. }
  7523. else
  7524. {
  7525. len = CharacterFunctions::printf (buffer, bufSize, T("%.9g"), n) + 1;
  7526. t = buffer;
  7527. }
  7528. if (len > 1)
  7529. {
  7530. jassert (len < numElementsInArray (buffer));
  7531. createInternal (len - 1);
  7532. memcpy (text->text, t, len * sizeof (tchar));
  7533. }
  7534. else
  7535. {
  7536. jassert (*t == 0);
  7537. text = &emptyString;
  7538. emptyString.refCount = safeEmptyStringRefCount;
  7539. }
  7540. }
  7541. String::String (const float number,
  7542. const int numberOfDecimalPlaces) throw()
  7543. {
  7544. doubleToStringWithDecPlaces ((double) number,
  7545. numberOfDecimalPlaces);
  7546. }
  7547. String::String (const double number,
  7548. const int numberOfDecimalPlaces) throw()
  7549. {
  7550. doubleToStringWithDecPlaces (number,
  7551. numberOfDecimalPlaces);
  7552. }
  7553. String::~String() throw()
  7554. {
  7555. if (atomicDecrementAndReturn (text->refCount) == 0)
  7556. juce_free (text);
  7557. }
  7558. void String::preallocateStorage (const int numChars) throw()
  7559. {
  7560. if (numChars > text->allocatedNumChars)
  7561. {
  7562. dupeInternalIfMultiplyReferenced();
  7563. text = (InternalRefCountedStringHolder*) juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7564. + numChars * sizeof (tchar));
  7565. text->allocatedNumChars = numChars;
  7566. }
  7567. }
  7568. #if JUCE_STRINGS_ARE_UNICODE
  7569. String::operator const char*() const throw()
  7570. {
  7571. if (isEmpty())
  7572. {
  7573. return (const char*) emptyCharString;
  7574. }
  7575. else
  7576. {
  7577. String* const mutableThis = const_cast <String*> (this);
  7578. mutableThis->dupeInternalIfMultiplyReferenced();
  7579. int len = CharacterFunctions::bytesRequiredForCopy (text->text) + 1;
  7580. mutableThis->text = (InternalRefCountedStringHolder*)
  7581. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7582. + (len * sizeof (juce_wchar) + len));
  7583. char* otherCopy = (char*) (text->text + len);
  7584. --len;
  7585. CharacterFunctions::copy (otherCopy, text->text, len);
  7586. otherCopy [len] = 0;
  7587. return otherCopy;
  7588. }
  7589. }
  7590. #else
  7591. String::operator const juce_wchar*() const throw()
  7592. {
  7593. if (isEmpty())
  7594. {
  7595. return (const juce_wchar*) emptyCharString;
  7596. }
  7597. else
  7598. {
  7599. String* const mutableThis = const_cast <String*> (this);
  7600. mutableThis->dupeInternalIfMultiplyReferenced();
  7601. int len = CharacterFunctions::length (text->text) + 1;
  7602. mutableThis->text = (InternalRefCountedStringHolder*)
  7603. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7604. + (len * sizeof (juce_wchar) + len));
  7605. juce_wchar* otherCopy = (juce_wchar*) (text->text + len);
  7606. --len;
  7607. CharacterFunctions::copy (otherCopy, text->text, len);
  7608. otherCopy [len] = 0;
  7609. return otherCopy;
  7610. }
  7611. }
  7612. #endif
  7613. void String::copyToBuffer (char* const destBuffer,
  7614. const int bufferSizeBytes) const throw()
  7615. {
  7616. #if JUCE_STRINGS_ARE_UNICODE
  7617. const int len = jmin (bufferSizeBytes, CharacterFunctions::bytesRequiredForCopy (text->text));
  7618. CharacterFunctions::copy (destBuffer, text->text, len);
  7619. #else
  7620. const int len = jmin (bufferSizeBytes, length());
  7621. memcpy (destBuffer, text->text, len * sizeof (tchar));
  7622. #endif
  7623. destBuffer [len] = 0;
  7624. }
  7625. void String::copyToBuffer (juce_wchar* const destBuffer,
  7626. const int maxCharsToCopy) const throw()
  7627. {
  7628. const int len = jmin (maxCharsToCopy, length());
  7629. #if JUCE_STRINGS_ARE_UNICODE
  7630. memcpy (destBuffer, text->text, len * sizeof (juce_wchar));
  7631. #else
  7632. CharacterFunctions::copy (destBuffer, text->text, len);
  7633. #endif
  7634. destBuffer [len] = 0;
  7635. }
  7636. int String::length() const throw()
  7637. {
  7638. return CharacterFunctions::length (text->text);
  7639. }
  7640. int String::hashCode() const throw()
  7641. {
  7642. const tchar* t = text->text;
  7643. int result = 0;
  7644. while (*t != (tchar) 0)
  7645. result = 31 * result + *t++;
  7646. return result;
  7647. }
  7648. int64 String::hashCode64() const throw()
  7649. {
  7650. const tchar* t = text->text;
  7651. int64 result = 0;
  7652. while (*t != (tchar) 0)
  7653. result = 101 * result + *t++;
  7654. return result;
  7655. }
  7656. const String& String::operator= (const tchar* const otherText) throw()
  7657. {
  7658. if (otherText != 0 && *otherText != 0)
  7659. {
  7660. const int otherLen = CharacterFunctions::length (otherText);
  7661. if (otherLen > 0)
  7662. {
  7663. // avoid resizing the memory block if the string is
  7664. // shrinking..
  7665. if (text->refCount > 1
  7666. || otherLen > text->allocatedNumChars
  7667. || otherLen <= (text->allocatedNumChars >> 1))
  7668. {
  7669. deleteInternal();
  7670. createInternal (otherLen);
  7671. }
  7672. memcpy (text->text, otherText, (otherLen + 1) * sizeof (tchar));
  7673. return *this;
  7674. }
  7675. }
  7676. deleteInternal();
  7677. text = &emptyString;
  7678. emptyString.refCount = safeEmptyStringRefCount;
  7679. return *this;
  7680. }
  7681. const String& String::operator= (const String& other) throw()
  7682. {
  7683. if (this != &other)
  7684. {
  7685. atomicIncrement (other.text->refCount);
  7686. if (atomicDecrementAndReturn (text->refCount) == 0)
  7687. juce_free (text);
  7688. text = other.text;
  7689. }
  7690. return *this;
  7691. }
  7692. bool String::operator== (const String& other) const throw()
  7693. {
  7694. return text == other.text
  7695. || CharacterFunctions::compare (text->text, other.text->text) == 0;
  7696. }
  7697. bool String::operator== (const tchar* const t) const throw()
  7698. {
  7699. return t != 0 ? CharacterFunctions::compare (text->text, t) == 0
  7700. : isEmpty();
  7701. }
  7702. bool String::equalsIgnoreCase (const tchar* t) const throw()
  7703. {
  7704. return t != 0 ? CharacterFunctions::compareIgnoreCase (text->text, t) == 0
  7705. : isEmpty();
  7706. }
  7707. bool String::equalsIgnoreCase (const String& other) const throw()
  7708. {
  7709. return text == other.text
  7710. || CharacterFunctions::compareIgnoreCase (text->text, other.text->text) == 0;
  7711. }
  7712. bool String::operator!= (const String& other) const throw()
  7713. {
  7714. return text != other.text
  7715. && CharacterFunctions::compare (text->text, other.text->text) != 0;
  7716. }
  7717. bool String::operator!= (const tchar* const t) const throw()
  7718. {
  7719. return t != 0 ? (CharacterFunctions::compare (text->text, t) != 0)
  7720. : isNotEmpty();
  7721. }
  7722. bool String::operator> (const String& other) const throw()
  7723. {
  7724. return compare (other) > 0;
  7725. }
  7726. bool String::operator< (const tchar* const other) const throw()
  7727. {
  7728. return compare (other) < 0;
  7729. }
  7730. bool String::operator>= (const String& other) const throw()
  7731. {
  7732. return compare (other) >= 0;
  7733. }
  7734. bool String::operator<= (const tchar* const other) const throw()
  7735. {
  7736. return compare (other) <= 0;
  7737. }
  7738. int String::compare (const tchar* const other) const throw()
  7739. {
  7740. return other != 0 ? CharacterFunctions::compare (text->text, other)
  7741. : isEmpty();
  7742. }
  7743. int String::compareIgnoreCase (const tchar* const other) const throw()
  7744. {
  7745. return other != 0 ? CharacterFunctions::compareIgnoreCase (text->text, other)
  7746. : isEmpty();
  7747. }
  7748. int String::compareLexicographically (const tchar* other) const throw()
  7749. {
  7750. if (other == 0)
  7751. return isEmpty();
  7752. const tchar* s1 = text->text;
  7753. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  7754. ++s1;
  7755. while (*other != 0 && ! CharacterFunctions::isLetterOrDigit (*other))
  7756. ++other;
  7757. return CharacterFunctions::compareIgnoreCase (s1, other);
  7758. }
  7759. const String String::operator+ (const String& other) const throw()
  7760. {
  7761. if (*(other.text->text) == 0)
  7762. return *this;
  7763. if (isEmpty())
  7764. return other;
  7765. const int len = CharacterFunctions::length (text->text);
  7766. const int otherLen = CharacterFunctions::length (other.text->text);
  7767. String result (len + otherLen, (int) 0);
  7768. memcpy (result.text->text, text->text, len * sizeof (tchar));
  7769. memcpy (result.text->text + len, other.text->text, otherLen * sizeof (tchar));
  7770. result.text->text [len + otherLen] = 0;
  7771. return result;
  7772. }
  7773. const String String::operator+ (const tchar* const textToAppend) const throw()
  7774. {
  7775. if (textToAppend == 0 || *textToAppend == 0)
  7776. return *this;
  7777. const int len = CharacterFunctions::length (text->text);
  7778. const int otherLen = CharacterFunctions::length (textToAppend);
  7779. String result (len + otherLen, (int) 0);
  7780. memcpy (result.text->text, text->text, len * sizeof (tchar));
  7781. memcpy (result.text->text + len, textToAppend, otherLen * sizeof (tchar));
  7782. result.text->text [len + otherLen] = 0;
  7783. return result;
  7784. }
  7785. const String String::operator+ (const tchar characterToAppend) const throw()
  7786. {
  7787. if (characterToAppend == 0)
  7788. return *this;
  7789. const int len = CharacterFunctions::length (text->text);
  7790. String result ((int) (len + 1), (int) 0);
  7791. memcpy (result.text->text, text->text, len * sizeof (tchar));
  7792. result.text->text[len] = characterToAppend;
  7793. result.text->text[len + 1] = 0;
  7794. return result;
  7795. }
  7796. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  7797. const String& string2) throw()
  7798. {
  7799. String s (string1);
  7800. s += string2;
  7801. return s;
  7802. }
  7803. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  7804. const String& string2) throw()
  7805. {
  7806. String s (string1);
  7807. s += string2;
  7808. return s;
  7809. }
  7810. const String& String::operator+= (const tchar* const t) throw()
  7811. {
  7812. if (t != 0)
  7813. appendInternal (t, CharacterFunctions::length (t));
  7814. return *this;
  7815. }
  7816. const String& String::operator+= (const String& other) throw()
  7817. {
  7818. if (isEmpty())
  7819. operator= (other);
  7820. else
  7821. appendInternal (other.text->text,
  7822. CharacterFunctions::length (other.text->text));
  7823. return *this;
  7824. }
  7825. const String& String::operator+= (const char ch) throw()
  7826. {
  7827. char asString[2];
  7828. asString[0] = ch;
  7829. asString[1] = 0;
  7830. #if JUCE_STRINGS_ARE_UNICODE
  7831. operator+= (String (asString));
  7832. #else
  7833. appendInternal (asString, 1);
  7834. #endif
  7835. return *this;
  7836. }
  7837. const String& String::operator+= (const juce_wchar ch) throw()
  7838. {
  7839. juce_wchar asString[2];
  7840. asString[0] = ch;
  7841. asString[1] = 0;
  7842. #if JUCE_STRINGS_ARE_UNICODE
  7843. appendInternal (asString, 1);
  7844. #else
  7845. operator+= (String (asString));
  7846. #endif
  7847. return *this;
  7848. }
  7849. void String::append (const tchar* const other,
  7850. const int howMany) throw()
  7851. {
  7852. if (howMany > 0)
  7853. {
  7854. int i;
  7855. for (i = 0; i < howMany; ++i)
  7856. if (other[i] == 0)
  7857. break;
  7858. appendInternal (other, i);
  7859. }
  7860. }
  7861. String& String::operator<< (const int number) throw()
  7862. {
  7863. tchar buffer [64];
  7864. tchar* const end = buffer + 64;
  7865. const tchar* const t = intToCharString (end, number);
  7866. appendInternal (t, (int) (end - t) - 1);
  7867. return *this;
  7868. }
  7869. String& String::operator<< (const unsigned int number) throw()
  7870. {
  7871. tchar buffer [64];
  7872. tchar* const end = buffer + 64;
  7873. const tchar* const t = uintToCharString (end, number);
  7874. appendInternal (t, (int) (end - t) - 1);
  7875. return *this;
  7876. }
  7877. String& String::operator<< (const short number) throw()
  7878. {
  7879. tchar buffer [64];
  7880. tchar* const end = buffer + 64;
  7881. const tchar* const t = intToCharString (end, (int) number);
  7882. appendInternal (t, (int) (end - t) - 1);
  7883. return *this;
  7884. }
  7885. String& String::operator<< (const double number) throw()
  7886. {
  7887. operator+= (String (number));
  7888. return *this;
  7889. }
  7890. String& String::operator<< (const float number) throw()
  7891. {
  7892. operator+= (String (number));
  7893. return *this;
  7894. }
  7895. String& String::operator<< (const char character) throw()
  7896. {
  7897. operator+= (character);
  7898. return *this;
  7899. }
  7900. String& String::operator<< (const juce_wchar character) throw()
  7901. {
  7902. operator+= (character);
  7903. return *this;
  7904. }
  7905. String& String::operator<< (const char* const t) throw()
  7906. {
  7907. #if JUCE_STRINGS_ARE_UNICODE
  7908. operator+= (String (t));
  7909. #else
  7910. operator+= (t);
  7911. #endif
  7912. return *this;
  7913. }
  7914. String& String::operator<< (const juce_wchar* const t) throw()
  7915. {
  7916. #if JUCE_STRINGS_ARE_UNICODE
  7917. operator+= (t);
  7918. #else
  7919. operator+= (String (t));
  7920. #endif
  7921. return *this;
  7922. }
  7923. String& String::operator<< (const String& t) throw()
  7924. {
  7925. operator+= (t);
  7926. return *this;
  7927. }
  7928. int String::indexOfChar (const tchar character) const throw()
  7929. {
  7930. const tchar* t = text->text;
  7931. for (;;)
  7932. {
  7933. if (*t == character)
  7934. return (int) (t - text->text);
  7935. if (*t++ == 0)
  7936. return -1;
  7937. }
  7938. }
  7939. int String::lastIndexOfChar (const tchar character) const throw()
  7940. {
  7941. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  7942. if (text->text[i] == character)
  7943. return i;
  7944. return -1;
  7945. }
  7946. int String::indexOf (const tchar* const t) const throw()
  7947. {
  7948. const tchar* const r = CharacterFunctions::find (text->text, t);
  7949. return (r == 0) ? -1
  7950. : (int) (r - text->text);
  7951. }
  7952. int String::indexOfChar (const int startIndex,
  7953. const tchar character) const throw()
  7954. {
  7955. if (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text))
  7956. return -1;
  7957. const tchar* t = text->text + jmax (0, startIndex);
  7958. for (;;)
  7959. {
  7960. if (*t == character)
  7961. return (int) (t - text->text);
  7962. if (*t++ == 0)
  7963. return -1;
  7964. }
  7965. }
  7966. int String::indexOfAnyOf (const tchar* const charactersToLookFor,
  7967. const int startIndex,
  7968. const bool ignoreCase) const throw()
  7969. {
  7970. if (charactersToLookFor == 0
  7971. || (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text)))
  7972. return -1;
  7973. const tchar* t = text->text + jmax (0, startIndex);
  7974. while (*t != 0)
  7975. {
  7976. if (CharacterFunctions::indexOfChar (charactersToLookFor, *t, ignoreCase) >= 0)
  7977. return (int) (t - text->text);
  7978. ++t;
  7979. }
  7980. return -1;
  7981. }
  7982. int String::indexOf (const int startIndex,
  7983. const tchar* const other) const throw()
  7984. {
  7985. if (other == 0 || startIndex >= CharacterFunctions::length (text->text))
  7986. return -1;
  7987. const tchar* const found = CharacterFunctions::find (text->text + jmax (0, startIndex),
  7988. other);
  7989. return (found == 0) ? -1
  7990. : (int) (found - text->text);
  7991. }
  7992. int String::indexOfIgnoreCase (const tchar* const other) const throw()
  7993. {
  7994. if (other != 0 && *other != 0)
  7995. {
  7996. const int len = CharacterFunctions::length (other);
  7997. const int end = CharacterFunctions::length (text->text) - len;
  7998. for (int i = 0; i <= end; ++i)
  7999. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  8000. return i;
  8001. }
  8002. return -1;
  8003. }
  8004. int String::indexOfIgnoreCase (const int startIndex,
  8005. const tchar* const other) const throw()
  8006. {
  8007. if (other != 0 && *other != 0)
  8008. {
  8009. const int len = CharacterFunctions::length (other);
  8010. const int end = length() - len;
  8011. for (int i = jmax (0, startIndex); i <= end; ++i)
  8012. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  8013. return i;
  8014. }
  8015. return -1;
  8016. }
  8017. int String::lastIndexOf (const tchar* const other) const throw()
  8018. {
  8019. if (other != 0 && *other != 0)
  8020. {
  8021. const int len = CharacterFunctions::length (other);
  8022. int i = length() - len;
  8023. if (i >= 0)
  8024. {
  8025. const tchar* n = text->text + i;
  8026. while (i >= 0)
  8027. {
  8028. if (CharacterFunctions::compare (n--, other, len) == 0)
  8029. return i;
  8030. --i;
  8031. }
  8032. }
  8033. }
  8034. return -1;
  8035. }
  8036. int String::lastIndexOfIgnoreCase (const tchar* const other) const throw()
  8037. {
  8038. if (other != 0 && *other != 0)
  8039. {
  8040. const int len = CharacterFunctions::length (other);
  8041. int i = length() - len;
  8042. if (i >= 0)
  8043. {
  8044. const tchar* n = text->text + i;
  8045. while (i >= 0)
  8046. {
  8047. if (CharacterFunctions::compareIgnoreCase (n--, other, len) == 0)
  8048. return i;
  8049. --i;
  8050. }
  8051. }
  8052. }
  8053. return -1;
  8054. }
  8055. int String::lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  8056. const bool ignoreCase) const throw()
  8057. {
  8058. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  8059. if (CharacterFunctions::indexOfChar (charactersToLookFor, text->text [i], ignoreCase) >= 0)
  8060. return i;
  8061. return -1;
  8062. }
  8063. bool String::contains (const tchar* const other) const throw()
  8064. {
  8065. return indexOf (other) >= 0;
  8066. }
  8067. bool String::containsChar (const tchar character) const throw()
  8068. {
  8069. return indexOfChar (character) >= 0;
  8070. }
  8071. bool String::containsIgnoreCase (const tchar* const t) const throw()
  8072. {
  8073. return indexOfIgnoreCase (t) >= 0;
  8074. }
  8075. int String::indexOfWholeWord (const tchar* const word) const throw()
  8076. {
  8077. if (word != 0 && *word != 0)
  8078. {
  8079. const int wordLen = CharacterFunctions::length (word);
  8080. const int end = length() - wordLen;
  8081. const tchar* t = text->text;
  8082. for (int i = 0; i <= end; ++i)
  8083. {
  8084. if (CharacterFunctions::compare (t, word, wordLen) == 0
  8085. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  8086. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  8087. {
  8088. return i;
  8089. }
  8090. ++t;
  8091. }
  8092. }
  8093. return -1;
  8094. }
  8095. int String::indexOfWholeWordIgnoreCase (const tchar* const word) const throw()
  8096. {
  8097. if (word != 0 && *word != 0)
  8098. {
  8099. const int wordLen = CharacterFunctions::length (word);
  8100. const int end = length() - wordLen;
  8101. const tchar* t = text->text;
  8102. for (int i = 0; i <= end; ++i)
  8103. {
  8104. if (CharacterFunctions::compareIgnoreCase (t, word, wordLen) == 0
  8105. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  8106. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  8107. {
  8108. return i;
  8109. }
  8110. ++t;
  8111. }
  8112. }
  8113. return -1;
  8114. }
  8115. bool String::containsWholeWord (const tchar* const wordToLookFor) const throw()
  8116. {
  8117. return indexOfWholeWord (wordToLookFor) >= 0;
  8118. }
  8119. bool String::containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw()
  8120. {
  8121. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  8122. }
  8123. static int indexOfMatch (const tchar* const wildcard,
  8124. const tchar* const test,
  8125. const bool ignoreCase) throw()
  8126. {
  8127. int start = 0;
  8128. while (test [start] != 0)
  8129. {
  8130. int i = 0;
  8131. for (;;)
  8132. {
  8133. const tchar wc = wildcard [i];
  8134. const tchar c = test [i + start];
  8135. if (wc == c
  8136. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  8137. || (wc == T('?') && c != 0))
  8138. {
  8139. if (wc == 0)
  8140. return start;
  8141. ++i;
  8142. }
  8143. else
  8144. {
  8145. if (wc == T('*') && (wildcard [i + 1] == 0
  8146. || indexOfMatch (wildcard + i + 1,
  8147. test + start + i,
  8148. ignoreCase) >= 0))
  8149. {
  8150. return start;
  8151. }
  8152. break;
  8153. }
  8154. }
  8155. ++start;
  8156. }
  8157. return -1;
  8158. }
  8159. bool String::matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw()
  8160. {
  8161. int i = 0;
  8162. for (;;)
  8163. {
  8164. const tchar wc = wildcard [i];
  8165. const tchar c = text->text [i];
  8166. if (wc == c
  8167. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  8168. || (wc == T('?') && c != 0))
  8169. {
  8170. if (wc == 0)
  8171. return true;
  8172. ++i;
  8173. }
  8174. else
  8175. {
  8176. return wc == T('*') && (wildcard [i + 1] == 0
  8177. || indexOfMatch (wildcard + i + 1,
  8178. text->text + i,
  8179. ignoreCase) >= 0);
  8180. }
  8181. }
  8182. }
  8183. void String::printf (const tchar* const pf, ...) throw()
  8184. {
  8185. va_list list;
  8186. va_start (list, pf);
  8187. vprintf (pf, list);
  8188. }
  8189. const String String::formatted (const tchar* const pf, ...) throw()
  8190. {
  8191. va_list list;
  8192. va_start (list, pf);
  8193. String result;
  8194. result.vprintf (pf, list);
  8195. return result;
  8196. }
  8197. void String::vprintf (const tchar* const pf, va_list& args) throw()
  8198. {
  8199. tchar stackBuf [256];
  8200. unsigned int bufSize = 256;
  8201. tchar* buf = stackBuf;
  8202. deleteInternal();
  8203. do
  8204. {
  8205. #if JUCE_LINUX && JUCE_64BIT
  8206. va_list tempArgs;
  8207. va_copy (tempArgs, args);
  8208. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, tempArgs);
  8209. va_end (tempArgs);
  8210. #else
  8211. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, args);
  8212. #endif
  8213. if (num > 0)
  8214. {
  8215. createInternal (num);
  8216. memcpy (text->text, buf, (num + 1) * sizeof (tchar));
  8217. break;
  8218. }
  8219. else if (num == 0)
  8220. {
  8221. text = &emptyString;
  8222. emptyString.refCount = safeEmptyStringRefCount;
  8223. break;
  8224. }
  8225. if (buf != stackBuf)
  8226. juce_free (buf);
  8227. bufSize += 256;
  8228. buf = (tchar*) juce_malloc (bufSize * sizeof (tchar));
  8229. }
  8230. while (bufSize < 65536); // this is a sanity check to avoid situations where vprintf repeatedly
  8231. // returns -1 because of an error rather than because it needs more space.
  8232. if (buf != stackBuf)
  8233. juce_free (buf);
  8234. }
  8235. const String String::repeatedString (const tchar* const stringToRepeat,
  8236. int numberOfTimesToRepeat) throw()
  8237. {
  8238. const int len = CharacterFunctions::length (stringToRepeat);
  8239. String result ((int) (len * numberOfTimesToRepeat + 1), (int) 0);
  8240. tchar* n = result.text->text;
  8241. n[0] = 0;
  8242. while (--numberOfTimesToRepeat >= 0)
  8243. {
  8244. CharacterFunctions::append (n, stringToRepeat);
  8245. n += len;
  8246. }
  8247. return result;
  8248. }
  8249. const String String::replaceSection (int index,
  8250. int numCharsToReplace,
  8251. const tchar* const stringToInsert) const throw()
  8252. {
  8253. if (index < 0)
  8254. {
  8255. // a negative index to replace from?
  8256. jassertfalse
  8257. index = 0;
  8258. }
  8259. if (numCharsToReplace < 0)
  8260. {
  8261. // replacing a negative number of characters?
  8262. numCharsToReplace = 0;
  8263. jassertfalse;
  8264. }
  8265. const int len = length();
  8266. if (index + numCharsToReplace > len)
  8267. {
  8268. if (index > len)
  8269. {
  8270. // replacing beyond the end of the string?
  8271. index = len;
  8272. jassertfalse
  8273. }
  8274. numCharsToReplace = len - index;
  8275. }
  8276. const int newStringLen = (stringToInsert != 0) ? CharacterFunctions::length (stringToInsert) : 0;
  8277. const int newTotalLen = len + newStringLen - numCharsToReplace;
  8278. String result (newTotalLen, (int) 0);
  8279. memcpy (result.text->text,
  8280. text->text,
  8281. index * sizeof (tchar));
  8282. if (newStringLen > 0)
  8283. memcpy (result.text->text + index,
  8284. stringToInsert,
  8285. newStringLen * sizeof (tchar));
  8286. const int endStringLen = newTotalLen - (index + newStringLen);
  8287. if (endStringLen > 0)
  8288. memcpy (result.text->text + (index + newStringLen),
  8289. text->text + (index + numCharsToReplace),
  8290. endStringLen * sizeof (tchar));
  8291. result.text->text [newTotalLen] = 0;
  8292. return result;
  8293. }
  8294. const String String::replace (const tchar* const stringToReplace,
  8295. const tchar* const stringToInsert,
  8296. const bool ignoreCase) const throw()
  8297. {
  8298. const int stringToReplaceLen = CharacterFunctions::length (stringToReplace);
  8299. const int stringToInsertLen = CharacterFunctions::length (stringToInsert);
  8300. int i = 0;
  8301. String result (*this);
  8302. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  8303. : result.indexOf (i, stringToReplace))) >= 0)
  8304. {
  8305. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  8306. i += stringToInsertLen;
  8307. }
  8308. return result;
  8309. }
  8310. const String String::replaceCharacter (const tchar charToReplace,
  8311. const tchar charToInsert) const throw()
  8312. {
  8313. const int index = indexOfChar (charToReplace);
  8314. if (index < 0)
  8315. return *this;
  8316. String result (*this);
  8317. result.dupeInternalIfMultiplyReferenced();
  8318. tchar* t = result.text->text + index;
  8319. while (*t != 0)
  8320. {
  8321. if (*t == charToReplace)
  8322. *t = charToInsert;
  8323. ++t;
  8324. }
  8325. return result;
  8326. }
  8327. const String String::replaceCharacters (const String& charactersToReplace,
  8328. const tchar* const charactersToInsertInstead) const throw()
  8329. {
  8330. String result (*this);
  8331. result.dupeInternalIfMultiplyReferenced();
  8332. tchar* t = result.text->text;
  8333. const int len2 = CharacterFunctions::length (charactersToInsertInstead);
  8334. // the two strings passed in are supposed to be the same length!
  8335. jassert (len2 == charactersToReplace.length());
  8336. while (*t != 0)
  8337. {
  8338. const int index = charactersToReplace.indexOfChar (*t);
  8339. if (((unsigned int) index) < (unsigned int) len2)
  8340. *t = charactersToInsertInstead [index];
  8341. ++t;
  8342. }
  8343. return result;
  8344. }
  8345. bool String::startsWith (const tchar* const other) const throw()
  8346. {
  8347. return other != 0
  8348. && CharacterFunctions::compare (text->text, other, CharacterFunctions::length (other)) == 0;
  8349. }
  8350. bool String::startsWithIgnoreCase (const tchar* const other) const throw()
  8351. {
  8352. return other != 0
  8353. && CharacterFunctions::compareIgnoreCase (text->text, other, CharacterFunctions::length (other)) == 0;
  8354. }
  8355. bool String::startsWithChar (const tchar character) const throw()
  8356. {
  8357. return text->text[0] == character;
  8358. }
  8359. bool String::endsWithChar (const tchar character) const throw()
  8360. {
  8361. return text->text[0] != 0
  8362. && text->text [length() - 1] == character;
  8363. }
  8364. bool String::endsWith (const tchar* const other) const throw()
  8365. {
  8366. if (other == 0)
  8367. return false;
  8368. const int thisLen = length();
  8369. const int otherLen = CharacterFunctions::length (other);
  8370. return thisLen >= otherLen
  8371. && CharacterFunctions::compare (text->text + thisLen - otherLen, other) == 0;
  8372. }
  8373. bool String::endsWithIgnoreCase (const tchar* const other) const throw()
  8374. {
  8375. if (other == 0)
  8376. return false;
  8377. const int thisLen = length();
  8378. const int otherLen = CharacterFunctions::length (other);
  8379. return thisLen >= otherLen
  8380. && CharacterFunctions::compareIgnoreCase (text->text + thisLen - otherLen, other) == 0;
  8381. }
  8382. const String String::toUpperCase() const throw()
  8383. {
  8384. String result (*this);
  8385. result.dupeInternalIfMultiplyReferenced();
  8386. CharacterFunctions::toUpperCase (result.text->text);
  8387. return result;
  8388. }
  8389. const String String::toLowerCase() const throw()
  8390. {
  8391. String result (*this);
  8392. result.dupeInternalIfMultiplyReferenced();
  8393. CharacterFunctions::toLowerCase (result.text->text);
  8394. return result;
  8395. }
  8396. tchar& String::operator[] (const int index) throw()
  8397. {
  8398. jassert (((unsigned int) index) <= (unsigned int) length());
  8399. dupeInternalIfMultiplyReferenced();
  8400. return text->text [index];
  8401. }
  8402. tchar String::getLastCharacter() const throw()
  8403. {
  8404. return (isEmpty()) ? ((tchar) 0)
  8405. : text->text [CharacterFunctions::length (text->text) - 1];
  8406. }
  8407. const String String::substring (int start, int end) const throw()
  8408. {
  8409. if (start < 0)
  8410. start = 0;
  8411. else if (end <= start)
  8412. return empty;
  8413. int len = 0;
  8414. const tchar* const t = text->text;
  8415. while (len <= end && t [len] != 0)
  8416. ++len;
  8417. if (end >= len)
  8418. {
  8419. if (start == 0)
  8420. return *this;
  8421. end = len;
  8422. }
  8423. return String (text->text + start,
  8424. end - start);
  8425. }
  8426. const String String::substring (const int start) const throw()
  8427. {
  8428. if (start <= 0)
  8429. return *this;
  8430. const int len = CharacterFunctions::length (text->text);
  8431. if (start >= len)
  8432. return empty;
  8433. else
  8434. return String (text->text + start,
  8435. len - start);
  8436. }
  8437. const String String::dropLastCharacters (const int numberToDrop) const throw()
  8438. {
  8439. return String (text->text,
  8440. jmax (0, CharacterFunctions::length (text->text) - numberToDrop));
  8441. }
  8442. const String String::fromFirstOccurrenceOf (const tchar* const sub,
  8443. const bool includeSubString,
  8444. const bool ignoreCase) const throw()
  8445. {
  8446. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  8447. : indexOf (sub);
  8448. if (i < 0)
  8449. return empty;
  8450. else
  8451. return substring (includeSubString ? i : i + CharacterFunctions::length (sub));
  8452. }
  8453. const String String::fromLastOccurrenceOf (const tchar* const sub,
  8454. const bool includeSubString,
  8455. const bool ignoreCase) const throw()
  8456. {
  8457. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  8458. : lastIndexOf (sub);
  8459. if (i < 0)
  8460. return *this;
  8461. else
  8462. return substring (includeSubString ? i : i + CharacterFunctions::length (sub));
  8463. }
  8464. const String String::upToFirstOccurrenceOf (const tchar* const sub,
  8465. const bool includeSubString,
  8466. const bool ignoreCase) const throw()
  8467. {
  8468. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  8469. : indexOf (sub);
  8470. if (i < 0)
  8471. return *this;
  8472. else
  8473. return substring (0, includeSubString ? i + CharacterFunctions::length (sub) : i);
  8474. }
  8475. const String String::upToLastOccurrenceOf (const tchar* const sub,
  8476. const bool includeSubString,
  8477. const bool ignoreCase) const throw()
  8478. {
  8479. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  8480. : lastIndexOf (sub);
  8481. if (i < 0)
  8482. return *this;
  8483. return substring (0, includeSubString ? i + CharacterFunctions::length (sub) : i);
  8484. }
  8485. bool String::isQuotedString() const throw()
  8486. {
  8487. const String trimmed (trimStart());
  8488. return trimmed[0] == T('"')
  8489. || trimmed[0] == T('\'');
  8490. }
  8491. const String String::unquoted() const throw()
  8492. {
  8493. String s (*this);
  8494. if (s[0] == T('"') || s[0] == T('\''))
  8495. s = s.substring (1);
  8496. const int lastCharIndex = s.length() - 1;
  8497. if (lastCharIndex >= 0
  8498. && (s [lastCharIndex] == T('"') || s[lastCharIndex] == T('\'')))
  8499. s [lastCharIndex] = 0;
  8500. return s;
  8501. }
  8502. const String String::quoted (const tchar quoteCharacter) const throw()
  8503. {
  8504. if (isEmpty())
  8505. return charToString (quoteCharacter) + quoteCharacter;
  8506. String t (*this);
  8507. if (! t.startsWithChar (quoteCharacter))
  8508. t = charToString (quoteCharacter) + t;
  8509. if (! t.endsWithChar (quoteCharacter))
  8510. t += quoteCharacter;
  8511. return t;
  8512. }
  8513. const String String::trim() const throw()
  8514. {
  8515. if (isEmpty())
  8516. return empty;
  8517. int start = 0;
  8518. while (CharacterFunctions::isWhitespace (text->text [start]))
  8519. ++start;
  8520. const int len = CharacterFunctions::length (text->text);
  8521. int end = len - 1;
  8522. while ((end >= start) && CharacterFunctions::isWhitespace (text->text [end]))
  8523. --end;
  8524. ++end;
  8525. if (end <= start)
  8526. return empty;
  8527. else if (start > 0 || end < len)
  8528. return String (text->text + start, end - start);
  8529. else
  8530. return *this;
  8531. }
  8532. const String String::trimStart() const throw()
  8533. {
  8534. if (isEmpty())
  8535. return empty;
  8536. const tchar* t = text->text;
  8537. while (CharacterFunctions::isWhitespace (*t))
  8538. ++t;
  8539. if (t == text->text)
  8540. return *this;
  8541. else
  8542. return String (t);
  8543. }
  8544. const String String::trimEnd() const throw()
  8545. {
  8546. if (isEmpty())
  8547. return empty;
  8548. const tchar* endT = text->text + (CharacterFunctions::length (text->text) - 1);
  8549. while ((endT >= text->text) && CharacterFunctions::isWhitespace (*endT))
  8550. --endT;
  8551. return String (text->text, (int) (++endT - text->text));
  8552. }
  8553. const String String::retainCharacters (const tchar* const charactersToRetain) const throw()
  8554. {
  8555. jassert (charactersToRetain != 0);
  8556. if (isEmpty())
  8557. return empty;
  8558. String result (text->allocatedNumChars, (int) 0);
  8559. tchar* dst = result.text->text;
  8560. const tchar* src = text->text;
  8561. while (*src != 0)
  8562. {
  8563. if (CharacterFunctions::indexOfCharFast (charactersToRetain, *src) >= 0)
  8564. *dst++ = *src;
  8565. ++src;
  8566. }
  8567. *dst = 0;
  8568. return result;
  8569. }
  8570. const String String::removeCharacters (const tchar* const charactersToRemove) const throw()
  8571. {
  8572. jassert (charactersToRemove != 0);
  8573. if (isEmpty())
  8574. return empty;
  8575. String result (text->allocatedNumChars, (int) 0);
  8576. tchar* dst = result.text->text;
  8577. const tchar* src = text->text;
  8578. while (*src != 0)
  8579. {
  8580. if (CharacterFunctions::indexOfCharFast (charactersToRemove, *src) < 0)
  8581. *dst++ = *src;
  8582. ++src;
  8583. }
  8584. *dst = 0;
  8585. return result;
  8586. }
  8587. const String String::initialSectionContainingOnly (const tchar* const permittedCharacters) const throw()
  8588. {
  8589. return substring (0, CharacterFunctions::getIntialSectionContainingOnly (text->text, permittedCharacters));
  8590. }
  8591. const String String::initialSectionNotContaining (const tchar* const charactersToStopAt) const throw()
  8592. {
  8593. jassert (charactersToStopAt != 0);
  8594. const tchar* const t = text->text;
  8595. int i = 0;
  8596. while (t[i] != 0)
  8597. {
  8598. if (CharacterFunctions::indexOfCharFast (charactersToStopAt, t[i]) >= 0)
  8599. return String (text->text, i);
  8600. ++i;
  8601. }
  8602. return empty;
  8603. }
  8604. bool String::containsOnly (const tchar* const chars) const throw()
  8605. {
  8606. jassert (chars != 0);
  8607. const tchar* t = text->text;
  8608. while (*t != 0)
  8609. if (CharacterFunctions::indexOfCharFast (chars, *t++) < 0)
  8610. return false;
  8611. return true;
  8612. }
  8613. bool String::containsAnyOf (const tchar* const chars) const throw()
  8614. {
  8615. jassert (chars != 0);
  8616. const tchar* t = text->text;
  8617. while (*t != 0)
  8618. if (CharacterFunctions::indexOfCharFast (chars, *t++) >= 0)
  8619. return true;
  8620. return false;
  8621. }
  8622. int String::getIntValue() const throw()
  8623. {
  8624. return CharacterFunctions::getIntValue (text->text);
  8625. }
  8626. int String::getTrailingIntValue() const throw()
  8627. {
  8628. int n = 0;
  8629. int mult = 1;
  8630. const tchar* t = text->text + length();
  8631. while (--t >= text->text)
  8632. {
  8633. const tchar c = *t;
  8634. if (! CharacterFunctions::isDigit (c))
  8635. {
  8636. if (c == T('-'))
  8637. n = -n;
  8638. break;
  8639. }
  8640. n += mult * (c - T('0'));
  8641. mult *= 10;
  8642. }
  8643. return n;
  8644. }
  8645. int64 String::getLargeIntValue() const throw()
  8646. {
  8647. return CharacterFunctions::getInt64Value (text->text);
  8648. }
  8649. float String::getFloatValue() const throw()
  8650. {
  8651. return (float) CharacterFunctions::getDoubleValue (text->text);
  8652. }
  8653. double String::getDoubleValue() const throw()
  8654. {
  8655. return CharacterFunctions::getDoubleValue (text->text);
  8656. }
  8657. static const tchar* const hexDigits = T("0123456789abcdef");
  8658. const String String::toHexString (const int number) throw()
  8659. {
  8660. tchar buffer[32];
  8661. tchar* const end = buffer + 32;
  8662. tchar* t = end;
  8663. *--t = 0;
  8664. unsigned int v = (unsigned int) number;
  8665. do
  8666. {
  8667. *--t = hexDigits [v & 15];
  8668. v >>= 4;
  8669. } while (v != 0);
  8670. return String (t, (int) (((char*) end) - (char*) t) - 1);
  8671. }
  8672. const String String::toHexString (const int64 number) throw()
  8673. {
  8674. tchar buffer[32];
  8675. tchar* const end = buffer + 32;
  8676. tchar* t = end;
  8677. *--t = 0;
  8678. uint64 v = (uint64) number;
  8679. do
  8680. {
  8681. *--t = hexDigits [(int) (v & 15)];
  8682. v >>= 4;
  8683. } while (v != 0);
  8684. return String (t, (int) (((char*) end) - (char*) t));
  8685. }
  8686. const String String::toHexString (const short number) throw()
  8687. {
  8688. return toHexString ((int) (unsigned short) number);
  8689. }
  8690. const String String::toHexString (const unsigned char* data,
  8691. const int size,
  8692. const int groupSize) throw()
  8693. {
  8694. if (size <= 0)
  8695. return empty;
  8696. int numChars = (size * 2) + 2;
  8697. if (groupSize > 0)
  8698. numChars += size / groupSize;
  8699. String s (numChars, (int) 0);
  8700. tchar* d = s.text->text;
  8701. for (int i = 0; i < size; ++i)
  8702. {
  8703. *d++ = hexDigits [(*data) >> 4];
  8704. *d++ = hexDigits [(*data) & 0xf];
  8705. ++data;
  8706. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  8707. *d++ = T(' ');
  8708. }
  8709. *d = 0;
  8710. return s;
  8711. }
  8712. int String::getHexValue32() const throw()
  8713. {
  8714. int result = 0;
  8715. const tchar* c = text->text;
  8716. for (;;)
  8717. {
  8718. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  8719. if (hexValue >= 0)
  8720. result = (result << 4) | hexValue;
  8721. else if (*c == 0)
  8722. break;
  8723. ++c;
  8724. }
  8725. return result;
  8726. }
  8727. int64 String::getHexValue64() const throw()
  8728. {
  8729. int64 result = 0;
  8730. const tchar* c = text->text;
  8731. for (;;)
  8732. {
  8733. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  8734. if (hexValue >= 0)
  8735. result = (result << 4) | hexValue;
  8736. else if (*c == 0)
  8737. break;
  8738. ++c;
  8739. }
  8740. return result;
  8741. }
  8742. const String String::createStringFromData (const void* const data_,
  8743. const int size) throw()
  8744. {
  8745. const char* const data = (const char*) data_;
  8746. if (size <= 0 || data == 0)
  8747. {
  8748. return empty;
  8749. }
  8750. else if (size < 2)
  8751. {
  8752. return charToString (data[0]);
  8753. }
  8754. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  8755. || (data[0] == (char)-1 && data[1] == (char)-2))
  8756. {
  8757. // assume it's 16-bit unicode
  8758. const bool bigEndian = (data[0] == (char)-2);
  8759. const int numChars = size / 2 - 1;
  8760. String result;
  8761. result.preallocateStorage (numChars + 2);
  8762. const uint16* const src = (const uint16*) (data + 2);
  8763. tchar* const dst = const_cast <tchar*> ((const tchar*) result);
  8764. if (bigEndian)
  8765. {
  8766. for (int i = 0; i < numChars; ++i)
  8767. dst[i] = (tchar) swapIfLittleEndian (src[i]);
  8768. }
  8769. else
  8770. {
  8771. for (int i = 0; i < numChars; ++i)
  8772. dst[i] = (tchar) swapIfBigEndian (src[i]);
  8773. }
  8774. dst [numChars] = 0;
  8775. return result;
  8776. }
  8777. else
  8778. {
  8779. return String::fromUTF8 ((const uint8*) data, size);
  8780. }
  8781. }
  8782. const char* String::toUTF8() const throw()
  8783. {
  8784. if (isEmpty())
  8785. {
  8786. return (const char*) emptyCharString;
  8787. }
  8788. else
  8789. {
  8790. String* const mutableThis = const_cast <String*> (this);
  8791. mutableThis->dupeInternalIfMultiplyReferenced();
  8792. const int currentLen = CharacterFunctions::length (text->text) + 1;
  8793. const int utf8BytesNeeded = copyToUTF8 (0);
  8794. mutableThis->text = (InternalRefCountedStringHolder*)
  8795. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8796. + (currentLen * sizeof (juce_wchar) + utf8BytesNeeded));
  8797. char* const otherCopy = (char*) (text->text + currentLen);
  8798. copyToUTF8 ((uint8*) otherCopy);
  8799. return otherCopy;
  8800. }
  8801. }
  8802. int String::copyToUTF8 (uint8* const buffer) const throw()
  8803. {
  8804. #if JUCE_STRINGS_ARE_UNICODE
  8805. int num = 0, index = 0;
  8806. for (;;)
  8807. {
  8808. const uint32 c = (uint32) text->text [index++];
  8809. if (c >= 0x80)
  8810. {
  8811. int numExtraBytes = 1;
  8812. if (c >= 0x800)
  8813. {
  8814. ++numExtraBytes;
  8815. if (c >= 0x10000)
  8816. {
  8817. ++numExtraBytes;
  8818. if (c >= 0x200000)
  8819. {
  8820. ++numExtraBytes;
  8821. if (c >= 0x4000000)
  8822. ++numExtraBytes;
  8823. }
  8824. }
  8825. }
  8826. if (buffer != 0)
  8827. {
  8828. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  8829. while (--numExtraBytes >= 0)
  8830. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  8831. }
  8832. else
  8833. {
  8834. num += numExtraBytes + 1;
  8835. }
  8836. }
  8837. else
  8838. {
  8839. if (buffer != 0)
  8840. buffer [num] = (uint8) c;
  8841. ++num;
  8842. }
  8843. if (c == 0)
  8844. break;
  8845. }
  8846. return num;
  8847. #else
  8848. const int numBytes = length() + 1;
  8849. if (buffer != 0)
  8850. copyToBuffer ((char*) buffer, numBytes);
  8851. return numBytes;
  8852. #endif
  8853. }
  8854. const String String::fromUTF8 (const uint8* const buffer, int bufferSizeBytes) throw()
  8855. {
  8856. if (buffer == 0)
  8857. return empty;
  8858. if (bufferSizeBytes < 0)
  8859. bufferSizeBytes = INT_MAX;
  8860. int numBytes;
  8861. for (numBytes = 0; numBytes < bufferSizeBytes; ++numBytes)
  8862. if (buffer [numBytes] == 0)
  8863. break;
  8864. String result (numBytes + 1, 0);
  8865. tchar* dest = result.text->text;
  8866. int i = 0;
  8867. while (i < numBytes)
  8868. {
  8869. const uint8 c = buffer [i++];
  8870. if ((c & 0x80) != 0)
  8871. {
  8872. int mask = 0x7f;
  8873. int bit = 0x40;
  8874. int numExtraValues = 0;
  8875. while (bit != 0 && (c & bit) != 0)
  8876. {
  8877. bit >>= 1;
  8878. mask >>= 1;
  8879. ++numExtraValues;
  8880. }
  8881. int n = (c & mask);
  8882. while (--numExtraValues >= 0 && i < bufferSizeBytes)
  8883. {
  8884. const uint8 c = buffer[i];
  8885. if ((c & 0xc0) != 0x80)
  8886. break;
  8887. n <<= 6;
  8888. n |= (c & 0x3f);
  8889. ++i;
  8890. }
  8891. *dest++ = (tchar) n;
  8892. }
  8893. else
  8894. {
  8895. *dest++ = (tchar) c;
  8896. }
  8897. }
  8898. *dest = 0;
  8899. return result;
  8900. }
  8901. END_JUCE_NAMESPACE
  8902. /********* End of inlined file: juce_String.cpp *********/
  8903. /********* Start of inlined file: juce_StringArray.cpp *********/
  8904. BEGIN_JUCE_NAMESPACE
  8905. StringArray::StringArray() throw()
  8906. {
  8907. }
  8908. StringArray::StringArray (const StringArray& other) throw()
  8909. {
  8910. addArray (other);
  8911. }
  8912. StringArray::StringArray (const juce_wchar** const strings,
  8913. const int numberOfStrings) throw()
  8914. {
  8915. for (int i = 0; i < numberOfStrings; ++i)
  8916. add (strings [i]);
  8917. }
  8918. StringArray::StringArray (const char** const strings,
  8919. const int numberOfStrings) throw()
  8920. {
  8921. for (int i = 0; i < numberOfStrings; ++i)
  8922. add (strings [i]);
  8923. }
  8924. StringArray::StringArray (const juce_wchar** const strings) throw()
  8925. {
  8926. int i = 0;
  8927. while (strings[i] != 0)
  8928. add (strings [i++]);
  8929. }
  8930. StringArray::StringArray (const char** const strings) throw()
  8931. {
  8932. int i = 0;
  8933. while (strings[i] != 0)
  8934. add (strings [i++]);
  8935. }
  8936. const StringArray& StringArray::operator= (const StringArray& other) throw()
  8937. {
  8938. if (this != &other)
  8939. {
  8940. clear();
  8941. addArray (other);
  8942. }
  8943. return *this;
  8944. }
  8945. StringArray::~StringArray() throw()
  8946. {
  8947. clear();
  8948. }
  8949. bool StringArray::operator== (const StringArray& other) const throw()
  8950. {
  8951. if (other.size() != size())
  8952. return false;
  8953. for (int i = size(); --i >= 0;)
  8954. {
  8955. if (*(String*) other.strings.getUnchecked(i)
  8956. != *(String*) strings.getUnchecked(i))
  8957. {
  8958. return false;
  8959. }
  8960. }
  8961. return true;
  8962. }
  8963. bool StringArray::operator!= (const StringArray& other) const throw()
  8964. {
  8965. return ! operator== (other);
  8966. }
  8967. void StringArray::clear() throw()
  8968. {
  8969. for (int i = size(); --i >= 0;)
  8970. {
  8971. String* const s = (String*) strings.getUnchecked(i);
  8972. delete s;
  8973. }
  8974. strings.clear();
  8975. }
  8976. const String& StringArray::operator[] (const int index) const throw()
  8977. {
  8978. if (((unsigned int) index) < (unsigned int) strings.size())
  8979. return *(const String*) (strings.getUnchecked (index));
  8980. return String::empty;
  8981. }
  8982. void StringArray::add (const String& newString) throw()
  8983. {
  8984. strings.add (new String (newString));
  8985. }
  8986. void StringArray::insert (const int index,
  8987. const String& newString) throw()
  8988. {
  8989. strings.insert (index, new String (newString));
  8990. }
  8991. void StringArray::addIfNotAlreadyThere (const String& newString,
  8992. const bool ignoreCase) throw()
  8993. {
  8994. if (! contains (newString, ignoreCase))
  8995. add (newString);
  8996. }
  8997. void StringArray::addArray (const StringArray& otherArray,
  8998. int startIndex,
  8999. int numElementsToAdd) throw()
  9000. {
  9001. if (startIndex < 0)
  9002. {
  9003. jassertfalse
  9004. startIndex = 0;
  9005. }
  9006. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  9007. numElementsToAdd = otherArray.size() - startIndex;
  9008. while (--numElementsToAdd >= 0)
  9009. strings.add (new String (*(const String*) otherArray.strings.getUnchecked (startIndex++)));
  9010. }
  9011. void StringArray::set (const int index,
  9012. const String& newString) throw()
  9013. {
  9014. String* const s = (String*) strings [index];
  9015. if (s != 0)
  9016. {
  9017. *s = newString;
  9018. }
  9019. else if (index >= 0)
  9020. {
  9021. add (newString);
  9022. }
  9023. }
  9024. bool StringArray::contains (const String& stringToLookFor,
  9025. const bool ignoreCase) const throw()
  9026. {
  9027. if (ignoreCase)
  9028. {
  9029. for (int i = size(); --i >= 0;)
  9030. if (stringToLookFor.equalsIgnoreCase (*(const String*)(strings.getUnchecked(i))))
  9031. return true;
  9032. }
  9033. else
  9034. {
  9035. for (int i = size(); --i >= 0;)
  9036. if (stringToLookFor == *(const String*)(strings.getUnchecked(i)))
  9037. return true;
  9038. }
  9039. return false;
  9040. }
  9041. int StringArray::indexOf (const String& stringToLookFor,
  9042. const bool ignoreCase,
  9043. int i) const throw()
  9044. {
  9045. if (i < 0)
  9046. i = 0;
  9047. const int numElements = size();
  9048. if (ignoreCase)
  9049. {
  9050. while (i < numElements)
  9051. {
  9052. if (stringToLookFor.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  9053. return i;
  9054. ++i;
  9055. }
  9056. }
  9057. else
  9058. {
  9059. while (i < numElements)
  9060. {
  9061. if (stringToLookFor == *(const String*) strings.getUnchecked (i))
  9062. return i;
  9063. ++i;
  9064. }
  9065. }
  9066. return -1;
  9067. }
  9068. void StringArray::remove (const int index) throw()
  9069. {
  9070. String* const s = (String*) strings [index];
  9071. if (s != 0)
  9072. {
  9073. strings.remove (index);
  9074. delete s;
  9075. }
  9076. }
  9077. void StringArray::removeString (const String& stringToRemove,
  9078. const bool ignoreCase) throw()
  9079. {
  9080. if (ignoreCase)
  9081. {
  9082. for (int i = size(); --i >= 0;)
  9083. if (stringToRemove.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  9084. remove (i);
  9085. }
  9086. else
  9087. {
  9088. for (int i = size(); --i >= 0;)
  9089. if (stringToRemove == *(const String*) strings.getUnchecked (i))
  9090. remove (i);
  9091. }
  9092. }
  9093. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings) throw()
  9094. {
  9095. if (removeWhitespaceStrings)
  9096. {
  9097. for (int i = size(); --i >= 0;)
  9098. if (((const String*) strings.getUnchecked(i))->trim().isEmpty())
  9099. remove (i);
  9100. }
  9101. else
  9102. {
  9103. for (int i = size(); --i >= 0;)
  9104. if (((const String*) strings.getUnchecked(i))->isEmpty())
  9105. remove (i);
  9106. }
  9107. }
  9108. void StringArray::trim() throw()
  9109. {
  9110. for (int i = size(); --i >= 0;)
  9111. {
  9112. String& s = *(String*) strings.getUnchecked(i);
  9113. s = s.trim();
  9114. }
  9115. }
  9116. class InternalStringArrayComparator
  9117. {
  9118. public:
  9119. static int compareElements (void* const first, void* const second) throw()
  9120. {
  9121. return ((const String*) first)->compare (*(const String*) second);
  9122. }
  9123. };
  9124. class InsensitiveInternalStringArrayComparator
  9125. {
  9126. public:
  9127. static int compareElements (void* const first, void* const second) throw()
  9128. {
  9129. return ((const String*) first)->compareIgnoreCase (*(const String*) second);
  9130. }
  9131. };
  9132. void StringArray::sort (const bool ignoreCase) throw()
  9133. {
  9134. if (ignoreCase)
  9135. {
  9136. InsensitiveInternalStringArrayComparator comp;
  9137. strings.sort (comp);
  9138. }
  9139. else
  9140. {
  9141. InternalStringArrayComparator comp;
  9142. strings.sort (comp);
  9143. }
  9144. }
  9145. void StringArray::move (const int currentIndex, int newIndex) throw()
  9146. {
  9147. strings.move (currentIndex, newIndex);
  9148. }
  9149. const String StringArray::joinIntoString (const String& separator,
  9150. int start,
  9151. int numberToJoin) const throw()
  9152. {
  9153. const int last = (numberToJoin < 0) ? size()
  9154. : jmin (size(), start + numberToJoin);
  9155. if (start < 0)
  9156. start = 0;
  9157. if (start >= last)
  9158. return String::empty;
  9159. if (start == last - 1)
  9160. return *(const String*) strings.getUnchecked (start);
  9161. const int separatorLen = separator.length();
  9162. int charsNeeded = separatorLen * (last - start - 1);
  9163. for (int i = start; i < last; ++i)
  9164. charsNeeded += ((const String*) strings.getUnchecked(i))->length();
  9165. String result;
  9166. result.preallocateStorage (charsNeeded);
  9167. tchar* dest = (tchar*) (const tchar*) result;
  9168. while (start < last)
  9169. {
  9170. const String& s = *(const String*) strings.getUnchecked (start);
  9171. const int len = s.length();
  9172. if (len > 0)
  9173. {
  9174. s.copyToBuffer (dest, len);
  9175. dest += len;
  9176. }
  9177. if (++start < last && separatorLen > 0)
  9178. {
  9179. separator.copyToBuffer (dest, separatorLen);
  9180. dest += separatorLen;
  9181. }
  9182. }
  9183. *dest = 0;
  9184. return result;
  9185. }
  9186. int StringArray::addTokens (const tchar* const text,
  9187. const bool preserveQuotedStrings) throw()
  9188. {
  9189. return addTokens (text,
  9190. T(" \n\r\t"),
  9191. preserveQuotedStrings ? T("\"") : 0);
  9192. }
  9193. int StringArray::addTokens (const tchar* const text,
  9194. const tchar* breakCharacters,
  9195. const tchar* quoteCharacters) throw()
  9196. {
  9197. int num = 0;
  9198. if (text != 0 && *text != 0)
  9199. {
  9200. if (breakCharacters == 0)
  9201. breakCharacters = T("");
  9202. if (quoteCharacters == 0)
  9203. quoteCharacters = T("");
  9204. bool insideQuotes = false;
  9205. tchar currentQuoteChar = 0;
  9206. int i = 0;
  9207. int tokenStart = 0;
  9208. for (;;)
  9209. {
  9210. const tchar c = text[i];
  9211. bool isBreak = (c == 0);
  9212. if (! (insideQuotes || isBreak))
  9213. {
  9214. const tchar* b = breakCharacters;
  9215. while (*b != 0)
  9216. {
  9217. if (*b++ == c)
  9218. {
  9219. isBreak = true;
  9220. break;
  9221. }
  9222. }
  9223. }
  9224. if (! isBreak)
  9225. {
  9226. bool isQuote = false;
  9227. const tchar* q = quoteCharacters;
  9228. while (*q != 0)
  9229. {
  9230. if (*q++ == c)
  9231. {
  9232. isQuote = true;
  9233. break;
  9234. }
  9235. }
  9236. if (isQuote)
  9237. {
  9238. if (insideQuotes)
  9239. {
  9240. // only break out of quotes-mode if we find a matching quote to the
  9241. // one that we opened with..
  9242. if (currentQuoteChar == c)
  9243. insideQuotes = false;
  9244. }
  9245. else
  9246. {
  9247. insideQuotes = true;
  9248. currentQuoteChar = c;
  9249. }
  9250. }
  9251. }
  9252. else
  9253. {
  9254. add (String (text + tokenStart, i - tokenStart));
  9255. ++num;
  9256. tokenStart = i + 1;
  9257. }
  9258. if (c == 0)
  9259. break;
  9260. ++i;
  9261. }
  9262. }
  9263. return num;
  9264. }
  9265. int StringArray::addLines (const tchar* text) throw()
  9266. {
  9267. int numLines = 0;
  9268. if (text != 0)
  9269. {
  9270. while (*text != 0)
  9271. {
  9272. const tchar* const startOfLine = text;
  9273. while (*text != 0)
  9274. {
  9275. if (*text == T('\r'))
  9276. {
  9277. ++text;
  9278. if (*text == T('\n'))
  9279. ++text;
  9280. break;
  9281. }
  9282. if (*text == T('\n'))
  9283. {
  9284. ++text;
  9285. break;
  9286. }
  9287. ++text;
  9288. }
  9289. const tchar* endOfLine = text;
  9290. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  9291. --endOfLine;
  9292. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  9293. --endOfLine;
  9294. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  9295. ++numLines;
  9296. }
  9297. }
  9298. return numLines;
  9299. }
  9300. void StringArray::removeDuplicates (const bool ignoreCase) throw()
  9301. {
  9302. for (int i = 0; i < size() - 1; ++i)
  9303. {
  9304. const String& s = *(String*) strings.getUnchecked(i);
  9305. int nextIndex = i + 1;
  9306. for (;;)
  9307. {
  9308. nextIndex = indexOf (s, ignoreCase, nextIndex);
  9309. if (nextIndex < 0)
  9310. break;
  9311. remove (nextIndex);
  9312. }
  9313. }
  9314. }
  9315. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  9316. const bool appendNumberToFirstInstance,
  9317. const tchar* const preNumberString,
  9318. const tchar* const postNumberString) throw()
  9319. {
  9320. for (int i = 0; i < size() - 1; ++i)
  9321. {
  9322. String& s = *(String*) strings.getUnchecked(i);
  9323. int nextIndex = indexOf (s, ignoreCase, i + 1);
  9324. if (nextIndex >= 0)
  9325. {
  9326. const String original (s);
  9327. int number = 0;
  9328. if (appendNumberToFirstInstance)
  9329. s = original + preNumberString + String (++number) + postNumberString;
  9330. else
  9331. ++number;
  9332. while (nextIndex >= 0)
  9333. {
  9334. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  9335. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  9336. }
  9337. }
  9338. }
  9339. }
  9340. void StringArray::minimiseStorageOverheads() throw()
  9341. {
  9342. strings.minimiseStorageOverheads();
  9343. }
  9344. END_JUCE_NAMESPACE
  9345. /********* End of inlined file: juce_StringArray.cpp *********/
  9346. /********* Start of inlined file: juce_StringPairArray.cpp *********/
  9347. BEGIN_JUCE_NAMESPACE
  9348. StringPairArray::StringPairArray (const bool ignoreCase_) throw()
  9349. : ignoreCase (ignoreCase_)
  9350. {
  9351. }
  9352. StringPairArray::StringPairArray (const StringPairArray& other) throw()
  9353. : keys (other.keys),
  9354. values (other.values),
  9355. ignoreCase (other.ignoreCase)
  9356. {
  9357. }
  9358. StringPairArray::~StringPairArray() throw()
  9359. {
  9360. }
  9361. const StringPairArray& StringPairArray::operator= (const StringPairArray& other) throw()
  9362. {
  9363. keys = other.keys;
  9364. values = other.values;
  9365. return *this;
  9366. }
  9367. bool StringPairArray::operator== (const StringPairArray& other) const throw()
  9368. {
  9369. for (int i = keys.size(); --i >= 0;)
  9370. if (other [keys[i]] != values[i])
  9371. return false;
  9372. return true;
  9373. }
  9374. bool StringPairArray::operator!= (const StringPairArray& other) const throw()
  9375. {
  9376. return ! operator== (other);
  9377. }
  9378. const String& StringPairArray::operator[] (const String& key) const throw()
  9379. {
  9380. return values [keys.indexOf (key, ignoreCase)];
  9381. }
  9382. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  9383. {
  9384. const int i = keys.indexOf (key, ignoreCase);
  9385. if (i >= 0)
  9386. return values[i];
  9387. return defaultReturnValue;
  9388. }
  9389. void StringPairArray::set (const String& key,
  9390. const String& value) throw()
  9391. {
  9392. const int i = keys.indexOf (key, ignoreCase);
  9393. if (i >= 0)
  9394. {
  9395. values.set (i, value);
  9396. }
  9397. else
  9398. {
  9399. keys.add (key);
  9400. values.add (value);
  9401. }
  9402. }
  9403. void StringPairArray::addArray (const StringPairArray& other)
  9404. {
  9405. for (int i = 0; i < other.size(); ++i)
  9406. set (other.keys[i], other.values[i]);
  9407. }
  9408. void StringPairArray::clear() throw()
  9409. {
  9410. keys.clear();
  9411. values.clear();
  9412. }
  9413. void StringPairArray::remove (const String& key) throw()
  9414. {
  9415. remove (keys.indexOf (key, ignoreCase));
  9416. }
  9417. void StringPairArray::remove (const int index) throw()
  9418. {
  9419. keys.remove (index);
  9420. values.remove (index);
  9421. }
  9422. void StringPairArray::minimiseStorageOverheads() throw()
  9423. {
  9424. keys.minimiseStorageOverheads();
  9425. values.minimiseStorageOverheads();
  9426. }
  9427. END_JUCE_NAMESPACE
  9428. /********* End of inlined file: juce_StringPairArray.cpp *********/
  9429. /********* Start of inlined file: juce_XmlDocument.cpp *********/
  9430. BEGIN_JUCE_NAMESPACE
  9431. static bool isXmlIdentifierChar_Slow (const tchar c) throw()
  9432. {
  9433. return CharacterFunctions::isLetterOrDigit (c)
  9434. || c == T('_')
  9435. || c == T('-')
  9436. || c == T(':')
  9437. || c == T('.');
  9438. }
  9439. #define isXmlIdentifierChar(c) \
  9440. ((c > 0 && c <= 127) ? identifierLookupTable [(int) c] : isXmlIdentifierChar_Slow (c))
  9441. XmlDocument::XmlDocument (const String& documentText) throw()
  9442. : originalText (documentText),
  9443. inputSource (0)
  9444. {
  9445. }
  9446. XmlDocument::XmlDocument (const File& file)
  9447. {
  9448. inputSource = new FileInputSource (file);
  9449. }
  9450. XmlDocument::~XmlDocument() throw()
  9451. {
  9452. delete inputSource;
  9453. }
  9454. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  9455. {
  9456. if (inputSource != newSource)
  9457. {
  9458. delete inputSource;
  9459. inputSource = newSource;
  9460. }
  9461. }
  9462. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  9463. {
  9464. String textToParse (originalText);
  9465. if (textToParse.isEmpty() && inputSource != 0)
  9466. {
  9467. InputStream* const in = inputSource->createInputStream();
  9468. if (in != 0)
  9469. {
  9470. MemoryBlock data;
  9471. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  9472. delete in;
  9473. if (data.getSize() >= 2
  9474. && ((data[0] == (char)-2 && data[1] == (char)-1)
  9475. || (data[0] == (char)-1 && data[1] == (char)-2)))
  9476. {
  9477. textToParse = String::createStringFromData ((const char*) data.getData(), data.getSize());
  9478. }
  9479. else
  9480. {
  9481. textToParse = String::fromUTF8 ((const uint8*) data.getData(), data.getSize());
  9482. }
  9483. if (! onlyReadOuterDocumentElement)
  9484. originalText = textToParse;
  9485. }
  9486. }
  9487. input = textToParse;
  9488. lastError = String::empty;
  9489. errorOccurred = false;
  9490. outOfData = false;
  9491. needToLoadDTD = true;
  9492. for (int i = 0; i < 128; ++i)
  9493. identifierLookupTable[i] = isXmlIdentifierChar_Slow ((tchar) i);
  9494. if (textToParse.isEmpty())
  9495. {
  9496. lastError = "not enough input";
  9497. }
  9498. else
  9499. {
  9500. skipHeader();
  9501. if (input != 0)
  9502. {
  9503. XmlElement* const result = readNextElement (! onlyReadOuterDocumentElement);
  9504. if (errorOccurred)
  9505. delete result;
  9506. else
  9507. return result;
  9508. }
  9509. else
  9510. {
  9511. lastError = "incorrect xml header";
  9512. }
  9513. }
  9514. return 0;
  9515. }
  9516. const String& XmlDocument::getLastParseError() const throw()
  9517. {
  9518. return lastError;
  9519. }
  9520. void XmlDocument::setLastError (const String& desc, const bool carryOn) throw()
  9521. {
  9522. lastError = desc;
  9523. errorOccurred = ! carryOn;
  9524. }
  9525. const String XmlDocument::getFileContents (const String& filename) const
  9526. {
  9527. String result;
  9528. if (inputSource != 0)
  9529. {
  9530. InputStream* const in = inputSource->createInputStreamFor (filename.trim().unquoted());
  9531. if (in != 0)
  9532. {
  9533. result = in->readEntireStreamAsString();
  9534. delete in;
  9535. }
  9536. }
  9537. return result;
  9538. }
  9539. tchar XmlDocument::readNextChar() throw()
  9540. {
  9541. if (*input != 0)
  9542. {
  9543. return *input++;
  9544. }
  9545. else
  9546. {
  9547. outOfData = true;
  9548. return 0;
  9549. }
  9550. }
  9551. int XmlDocument::findNextTokenLength() throw()
  9552. {
  9553. int len = 0;
  9554. tchar c = *input;
  9555. while (isXmlIdentifierChar (c))
  9556. c = input [++len];
  9557. return len;
  9558. }
  9559. void XmlDocument::skipHeader() throw()
  9560. {
  9561. const tchar* const found = CharacterFunctions::find (input, T("<?xml"));
  9562. if (found != 0)
  9563. {
  9564. input = found;
  9565. input = CharacterFunctions::find (input, T("?>"));
  9566. if (input == 0)
  9567. return;
  9568. input += 2;
  9569. }
  9570. skipNextWhiteSpace();
  9571. const tchar* docType = CharacterFunctions::find (input, T("<!DOCTYPE"));
  9572. if (docType == 0)
  9573. return;
  9574. input = docType + 9;
  9575. int n = 1;
  9576. while (n > 0)
  9577. {
  9578. const tchar c = readNextChar();
  9579. if (outOfData)
  9580. return;
  9581. if (c == T('<'))
  9582. ++n;
  9583. else if (c == T('>'))
  9584. --n;
  9585. }
  9586. docType += 9;
  9587. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  9588. }
  9589. void XmlDocument::skipNextWhiteSpace() throw()
  9590. {
  9591. for (;;)
  9592. {
  9593. tchar c = *input;
  9594. while (CharacterFunctions::isWhitespace (c))
  9595. c = *++input;
  9596. if (c == 0)
  9597. {
  9598. outOfData = true;
  9599. break;
  9600. }
  9601. else if (c == T('<'))
  9602. {
  9603. if (input[1] == T('!')
  9604. && input[2] == T('-')
  9605. && input[3] == T('-'))
  9606. {
  9607. const tchar* const closeComment = CharacterFunctions::find (input, T("-->"));
  9608. if (closeComment == 0)
  9609. {
  9610. outOfData = true;
  9611. break;
  9612. }
  9613. input = closeComment + 3;
  9614. continue;
  9615. }
  9616. else if (input[1] == T('?'))
  9617. {
  9618. const tchar* const closeBracket = CharacterFunctions::find (input, T("?>"));
  9619. if (closeBracket == 0)
  9620. {
  9621. outOfData = true;
  9622. break;
  9623. }
  9624. input = closeBracket + 2;
  9625. continue;
  9626. }
  9627. }
  9628. break;
  9629. }
  9630. }
  9631. void XmlDocument::readQuotedString (String& result) throw()
  9632. {
  9633. const tchar quote = readNextChar();
  9634. while (! outOfData)
  9635. {
  9636. const tchar character = readNextChar();
  9637. if (character == quote)
  9638. break;
  9639. if (character == T('&'))
  9640. {
  9641. --input;
  9642. readEntity (result);
  9643. }
  9644. else
  9645. {
  9646. --input;
  9647. const tchar* const start = input;
  9648. for (;;)
  9649. {
  9650. const tchar character = *input;
  9651. if (character == quote)
  9652. {
  9653. result.append (start, (int) (input - start));
  9654. ++input;
  9655. return;
  9656. }
  9657. else if (character == T('&'))
  9658. {
  9659. result.append (start, (int) (input - start));
  9660. break;
  9661. }
  9662. else if (character == 0)
  9663. {
  9664. outOfData = true;
  9665. setLastError ("unmatched quotes", false);
  9666. break;
  9667. }
  9668. ++input;
  9669. }
  9670. }
  9671. }
  9672. }
  9673. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements) throw()
  9674. {
  9675. XmlElement* node = 0;
  9676. skipNextWhiteSpace();
  9677. if (outOfData)
  9678. return 0;
  9679. input = CharacterFunctions::find (input, T("<"));
  9680. if (input != 0)
  9681. {
  9682. ++input;
  9683. int tagLen = findNextTokenLength();
  9684. if (tagLen == 0)
  9685. {
  9686. // no tag name - but allow for a gap after the '<' before giving an error
  9687. skipNextWhiteSpace();
  9688. tagLen = findNextTokenLength();
  9689. if (tagLen == 0)
  9690. {
  9691. setLastError ("tag name missing", false);
  9692. return node;
  9693. }
  9694. }
  9695. node = new XmlElement (input, tagLen);
  9696. input += tagLen;
  9697. XmlElement::XmlAttributeNode* lastAttribute = 0;
  9698. // look for attributes
  9699. for (;;)
  9700. {
  9701. skipNextWhiteSpace();
  9702. const tchar c = *input;
  9703. // empty tag..
  9704. if (c == T('/') && input[1] == T('>'))
  9705. {
  9706. input += 2;
  9707. break;
  9708. }
  9709. // parse the guts of the element..
  9710. if (c == T('>'))
  9711. {
  9712. ++input;
  9713. skipNextWhiteSpace();
  9714. if (alsoParseSubElements)
  9715. readChildElements (node);
  9716. break;
  9717. }
  9718. // get an attribute..
  9719. if (isXmlIdentifierChar (c))
  9720. {
  9721. const int attNameLen = findNextTokenLength();
  9722. if (attNameLen > 0)
  9723. {
  9724. const tchar* attNameStart = input;
  9725. input += attNameLen;
  9726. skipNextWhiteSpace();
  9727. if (readNextChar() == T('='))
  9728. {
  9729. skipNextWhiteSpace();
  9730. const tchar c = *input;
  9731. if (c == T('"') || c == T('\''))
  9732. {
  9733. XmlElement::XmlAttributeNode* const newAtt
  9734. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  9735. String::empty);
  9736. readQuotedString (newAtt->value);
  9737. if (lastAttribute == 0)
  9738. node->attributes = newAtt;
  9739. else
  9740. lastAttribute->next = newAtt;
  9741. lastAttribute = newAtt;
  9742. continue;
  9743. }
  9744. }
  9745. }
  9746. }
  9747. else
  9748. {
  9749. if (! outOfData)
  9750. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  9751. }
  9752. break;
  9753. }
  9754. }
  9755. return node;
  9756. }
  9757. void XmlDocument::readChildElements (XmlElement* parent) throw()
  9758. {
  9759. XmlElement* lastChildNode = 0;
  9760. for (;;)
  9761. {
  9762. skipNextWhiteSpace();
  9763. if (outOfData)
  9764. {
  9765. setLastError ("unmatched tags", false);
  9766. break;
  9767. }
  9768. if (*input == T('<'))
  9769. {
  9770. if (input[1] == T('/'))
  9771. {
  9772. // our close tag..
  9773. input = CharacterFunctions::find (input, T(">"));
  9774. ++input;
  9775. break;
  9776. }
  9777. else if (input[1] == T('!')
  9778. && input[2] == T('[')
  9779. && input[3] == T('C')
  9780. && input[4] == T('D')
  9781. && input[5] == T('A')
  9782. && input[6] == T('T')
  9783. && input[7] == T('A')
  9784. && input[8] == T('['))
  9785. {
  9786. input += 9;
  9787. const tchar* const inputStart = input;
  9788. int len = 0;
  9789. for (;;)
  9790. {
  9791. if (*input == 0)
  9792. {
  9793. setLastError ("unterminated CDATA section", false);
  9794. outOfData = true;
  9795. break;
  9796. }
  9797. else if (input[0] == T(']')
  9798. && input[1] == T(']')
  9799. && input[2] == T('>'))
  9800. {
  9801. input += 3;
  9802. break;
  9803. }
  9804. ++input;
  9805. ++len;
  9806. }
  9807. XmlElement* const e = new XmlElement ((int) 0);
  9808. e->setText (String (inputStart, len));
  9809. if (lastChildNode != 0)
  9810. lastChildNode->nextElement = e;
  9811. else
  9812. parent->addChildElement (e);
  9813. lastChildNode = e;
  9814. }
  9815. else
  9816. {
  9817. // this is some other element, so parse and add it..
  9818. XmlElement* const n = readNextElement (true);
  9819. if (n != 0)
  9820. {
  9821. if (lastChildNode == 0)
  9822. parent->addChildElement (n);
  9823. else
  9824. lastChildNode->nextElement = n;
  9825. lastChildNode = n;
  9826. }
  9827. else
  9828. {
  9829. return;
  9830. }
  9831. }
  9832. }
  9833. else
  9834. {
  9835. // read character block..
  9836. XmlElement* const e = new XmlElement ((int)0);
  9837. if (lastChildNode != 0)
  9838. lastChildNode->nextElement = e;
  9839. else
  9840. parent->addChildElement (e);
  9841. lastChildNode = e;
  9842. String textElementContent;
  9843. for (;;)
  9844. {
  9845. const tchar c = *input;
  9846. if (c == T('<'))
  9847. break;
  9848. if (c == 0)
  9849. {
  9850. setLastError ("unmatched tags", false);
  9851. outOfData = true;
  9852. return;
  9853. }
  9854. if (c == T('&'))
  9855. {
  9856. String entity;
  9857. readEntity (entity);
  9858. if (entity.startsWithChar (T('<')) && entity [1] != 0)
  9859. {
  9860. const tchar* const oldInput = input;
  9861. const bool oldOutOfData = outOfData;
  9862. input = (const tchar*) entity;
  9863. outOfData = false;
  9864. for (;;)
  9865. {
  9866. XmlElement* const n = readNextElement (true);
  9867. if (n == 0)
  9868. break;
  9869. if (lastChildNode == 0)
  9870. parent->addChildElement (n);
  9871. else
  9872. lastChildNode->nextElement = n;
  9873. lastChildNode = n;
  9874. }
  9875. input = oldInput;
  9876. outOfData = oldOutOfData;
  9877. }
  9878. else
  9879. {
  9880. textElementContent += entity;
  9881. }
  9882. }
  9883. else
  9884. {
  9885. const tchar* start = input;
  9886. int len = 0;
  9887. for (;;)
  9888. {
  9889. const tchar c = *input;
  9890. if (c == T('<') || c == T('&'))
  9891. {
  9892. break;
  9893. }
  9894. else if (c == 0)
  9895. {
  9896. setLastError ("unmatched tags", false);
  9897. outOfData = true;
  9898. return;
  9899. }
  9900. ++input;
  9901. ++len;
  9902. }
  9903. textElementContent.append (start, len);
  9904. }
  9905. }
  9906. textElementContent = textElementContent.trim();
  9907. if (textElementContent.isNotEmpty())
  9908. e->setText (textElementContent);
  9909. }
  9910. }
  9911. }
  9912. void XmlDocument::readEntity (String& result) throw()
  9913. {
  9914. // skip over the ampersand
  9915. ++input;
  9916. if (CharacterFunctions::compareIgnoreCase (input, T("amp;"), 4) == 0)
  9917. {
  9918. input += 4;
  9919. result += T("&");
  9920. }
  9921. else if (CharacterFunctions::compareIgnoreCase (input, T("quot;"), 5) == 0)
  9922. {
  9923. input += 5;
  9924. result += T("\"");
  9925. }
  9926. else if (CharacterFunctions::compareIgnoreCase (input, T("apos;"), 5) == 0)
  9927. {
  9928. input += 5;
  9929. result += T("\'");
  9930. }
  9931. else if (CharacterFunctions::compareIgnoreCase (input, T("lt;"), 3) == 0)
  9932. {
  9933. input += 3;
  9934. result += T("<");
  9935. }
  9936. else if (CharacterFunctions::compareIgnoreCase (input, T("gt;"), 3) == 0)
  9937. {
  9938. input += 3;
  9939. result += T(">");
  9940. }
  9941. else if (*input == T('#'))
  9942. {
  9943. int charCode = 0;
  9944. ++input;
  9945. if (*input == T('x') || *input == T('X'))
  9946. {
  9947. ++input;
  9948. int numChars = 0;
  9949. while (input[0] != T(';'))
  9950. {
  9951. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  9952. if (hexValue < 0 || ++numChars > 8)
  9953. {
  9954. setLastError ("illegal escape sequence", true);
  9955. break;
  9956. }
  9957. charCode = (charCode << 4) | hexValue;
  9958. ++input;
  9959. }
  9960. ++input;
  9961. }
  9962. else if (input[0] >= T('0') && input[0] <= T('9'))
  9963. {
  9964. int numChars = 0;
  9965. while (input[0] != T(';'))
  9966. {
  9967. if (++numChars > 12)
  9968. {
  9969. setLastError ("illegal escape sequence", true);
  9970. break;
  9971. }
  9972. charCode = charCode * 10 + (input[0] - T('0'));
  9973. ++input;
  9974. }
  9975. ++input;
  9976. }
  9977. else
  9978. {
  9979. setLastError ("illegal escape sequence", true);
  9980. result += T("&");
  9981. return;
  9982. }
  9983. result << (tchar) charCode;
  9984. }
  9985. else
  9986. {
  9987. const tchar* const entityNameStart = input;
  9988. const tchar* const closingSemiColon = CharacterFunctions::find (input, T(";"));
  9989. if (closingSemiColon == 0)
  9990. {
  9991. outOfData = true;
  9992. result += T("&");
  9993. }
  9994. else
  9995. {
  9996. input = closingSemiColon + 1;
  9997. result += expandExternalEntity (String (entityNameStart,
  9998. (int) (closingSemiColon - entityNameStart)));
  9999. }
  10000. }
  10001. }
  10002. const String XmlDocument::expandEntity (const String& ent)
  10003. {
  10004. if (ent.equalsIgnoreCase (T("amp")))
  10005. {
  10006. return T("&");
  10007. }
  10008. else if (ent.equalsIgnoreCase (T("quot")))
  10009. {
  10010. return T("\"");
  10011. }
  10012. else if (ent.equalsIgnoreCase (T("apos")))
  10013. {
  10014. return T("\'");
  10015. }
  10016. else if (ent.equalsIgnoreCase (T("lt")))
  10017. {
  10018. return T("<");
  10019. }
  10020. else if (ent.equalsIgnoreCase (T("gt")))
  10021. {
  10022. return T(">");
  10023. }
  10024. else if (ent[0] == T('#'))
  10025. {
  10026. if (ent[1] == T('x') || ent[1] == T('X'))
  10027. {
  10028. return String::charToString ((tchar) ent.substring (2).getHexValue32());
  10029. }
  10030. else if (ent[1] >= T('0') && ent[1] <= T('9'))
  10031. {
  10032. return String::charToString ((tchar) ent.substring (1).getIntValue());
  10033. }
  10034. setLastError ("illegal escape sequence", false);
  10035. return T("&");
  10036. }
  10037. else
  10038. {
  10039. return expandExternalEntity (ent);
  10040. }
  10041. }
  10042. const String XmlDocument::expandExternalEntity (const String& entity)
  10043. {
  10044. if (needToLoadDTD)
  10045. {
  10046. if (dtdText.isNotEmpty())
  10047. {
  10048. while (dtdText.endsWithChar (T('>')))
  10049. dtdText = dtdText.dropLastCharacters (1);
  10050. tokenisedDTD.addTokens (dtdText, true);
  10051. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase (T("system"))
  10052. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  10053. {
  10054. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  10055. tokenisedDTD.clear();
  10056. tokenisedDTD.addTokens (getFileContents (fn), true);
  10057. }
  10058. else
  10059. {
  10060. tokenisedDTD.clear();
  10061. const int openBracket = dtdText.indexOfChar (T('['));
  10062. if (openBracket > 0)
  10063. {
  10064. const int closeBracket = dtdText.lastIndexOfChar (T(']'));
  10065. if (closeBracket > openBracket)
  10066. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  10067. closeBracket), true);
  10068. }
  10069. }
  10070. for (int i = tokenisedDTD.size(); --i >= 0;)
  10071. {
  10072. if (tokenisedDTD[i].startsWithChar (T('%'))
  10073. && tokenisedDTD[i].endsWithChar (T(';')))
  10074. {
  10075. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  10076. StringArray newToks;
  10077. newToks.addTokens (parsed, true);
  10078. tokenisedDTD.remove (i);
  10079. for (int j = newToks.size(); --j >= 0;)
  10080. tokenisedDTD.insert (i, newToks[j]);
  10081. }
  10082. }
  10083. }
  10084. needToLoadDTD = false;
  10085. }
  10086. for (int i = 0; i < tokenisedDTD.size(); ++i)
  10087. {
  10088. if (tokenisedDTD[i] == entity)
  10089. {
  10090. if (tokenisedDTD[i - 1].equalsIgnoreCase (T("<!entity")))
  10091. {
  10092. String ent (tokenisedDTD [i + 1]);
  10093. while (ent.endsWithChar (T('>')))
  10094. ent = ent.dropLastCharacters (1);
  10095. ent = ent.trim().unquoted();
  10096. // check for sub-entities..
  10097. int ampersand = ent.indexOfChar (T('&'));
  10098. while (ampersand >= 0)
  10099. {
  10100. const int semiColon = ent.indexOf (i + 1, T(";"));
  10101. if (semiColon < 0)
  10102. {
  10103. setLastError ("entity without terminating semi-colon", false);
  10104. break;
  10105. }
  10106. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  10107. ent = ent.substring (0, ampersand)
  10108. + resolved
  10109. + ent.substring (semiColon + 1);
  10110. ampersand = ent.indexOfChar (semiColon + 1, T('&'));
  10111. }
  10112. return ent;
  10113. }
  10114. }
  10115. }
  10116. setLastError ("unknown entity", true);
  10117. return entity;
  10118. }
  10119. const String XmlDocument::getParameterEntity (const String& entity)
  10120. {
  10121. for (int i = 0; i < tokenisedDTD.size(); ++i)
  10122. {
  10123. if (tokenisedDTD[i] == entity)
  10124. {
  10125. if (tokenisedDTD [i - 1] == T("%")
  10126. && tokenisedDTD [i - 2].equalsIgnoreCase (T("<!entity")))
  10127. {
  10128. String ent (tokenisedDTD [i + 1]);
  10129. while (ent.endsWithChar (T('>')))
  10130. ent = ent.dropLastCharacters (1);
  10131. if (ent.equalsIgnoreCase (T("system")))
  10132. {
  10133. String filename (tokenisedDTD [i + 2]);
  10134. while (filename.endsWithChar (T('>')))
  10135. filename = filename.dropLastCharacters (1);
  10136. return getFileContents (filename);
  10137. }
  10138. else
  10139. {
  10140. return ent.trim().unquoted();
  10141. }
  10142. }
  10143. }
  10144. }
  10145. return entity;
  10146. }
  10147. END_JUCE_NAMESPACE
  10148. /********* End of inlined file: juce_XmlDocument.cpp *********/
  10149. /********* Start of inlined file: juce_XmlElement.cpp *********/
  10150. BEGIN_JUCE_NAMESPACE
  10151. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  10152. : name (other.name),
  10153. value (other.value),
  10154. next (0)
  10155. {
  10156. }
  10157. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_,
  10158. const String& value_) throw()
  10159. : name (name_),
  10160. value (value_),
  10161. next (0)
  10162. {
  10163. }
  10164. XmlElement::XmlElement (const String& tagName_) throw()
  10165. : tagName (tagName_),
  10166. firstChildElement (0),
  10167. nextElement (0),
  10168. attributes (0)
  10169. {
  10170. // the tag name mustn't be empty, or it'll look like a text element!
  10171. jassert (tagName_.trim().isNotEmpty())
  10172. }
  10173. XmlElement::XmlElement (int /*dummy*/) throw()
  10174. : firstChildElement (0),
  10175. nextElement (0),
  10176. attributes (0)
  10177. {
  10178. }
  10179. XmlElement::XmlElement (const tchar* const tagName_,
  10180. const int nameLen) throw()
  10181. : tagName (tagName_, nameLen),
  10182. firstChildElement (0),
  10183. nextElement (0),
  10184. attributes (0)
  10185. {
  10186. }
  10187. XmlElement::XmlElement (const XmlElement& other) throw()
  10188. : tagName (other.tagName),
  10189. firstChildElement (0),
  10190. nextElement (0),
  10191. attributes (0)
  10192. {
  10193. copyChildrenAndAttributesFrom (other);
  10194. }
  10195. const XmlElement& XmlElement::operator= (const XmlElement& other) throw()
  10196. {
  10197. if (this != &other)
  10198. {
  10199. removeAllAttributes();
  10200. deleteAllChildElements();
  10201. tagName = other.tagName;
  10202. copyChildrenAndAttributesFrom (other);
  10203. }
  10204. return *this;
  10205. }
  10206. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other) throw()
  10207. {
  10208. XmlElement* child = other.firstChildElement;
  10209. XmlElement* lastChild = 0;
  10210. while (child != 0)
  10211. {
  10212. XmlElement* const copiedChild = new XmlElement (*child);
  10213. if (lastChild != 0)
  10214. lastChild->nextElement = copiedChild;
  10215. else
  10216. firstChildElement = copiedChild;
  10217. lastChild = copiedChild;
  10218. child = child->nextElement;
  10219. }
  10220. const XmlAttributeNode* att = other.attributes;
  10221. XmlAttributeNode* lastAtt = 0;
  10222. while (att != 0)
  10223. {
  10224. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  10225. if (lastAtt != 0)
  10226. lastAtt->next = newAtt;
  10227. else
  10228. attributes = newAtt;
  10229. lastAtt = newAtt;
  10230. att = att->next;
  10231. }
  10232. }
  10233. XmlElement::~XmlElement() throw()
  10234. {
  10235. XmlElement* child = firstChildElement;
  10236. while (child != 0)
  10237. {
  10238. XmlElement* const nextChild = child->nextElement;
  10239. delete child;
  10240. child = nextChild;
  10241. }
  10242. XmlAttributeNode* att = attributes;
  10243. while (att != 0)
  10244. {
  10245. XmlAttributeNode* const nextAtt = att->next;
  10246. delete att;
  10247. att = nextAtt;
  10248. }
  10249. }
  10250. static bool isLegalXmlChar (const juce_wchar character)
  10251. {
  10252. if ((character >= 'a' && character <= 'z')
  10253. || (character >= 'A' && character <= 'Z')
  10254. || (character >= '0' && character <= '9'))
  10255. return true;
  10256. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  10257. do
  10258. {
  10259. if (((juce_wchar) (uint8) *t) == character)
  10260. return true;
  10261. }
  10262. while (*++t != 0);
  10263. return false;
  10264. }
  10265. static void escapeIllegalXmlChars (OutputStream& outputStream,
  10266. const String& text,
  10267. const bool changeNewLines) throw()
  10268. {
  10269. const juce_wchar* t = (const juce_wchar*) text;
  10270. for (;;)
  10271. {
  10272. const juce_wchar character = *t++;
  10273. if (character == 0)
  10274. {
  10275. break;
  10276. }
  10277. else if (isLegalXmlChar (character))
  10278. {
  10279. outputStream.writeByte ((char) character);
  10280. }
  10281. else
  10282. {
  10283. switch (character)
  10284. {
  10285. case '&':
  10286. outputStream.write ("&amp;", 5);
  10287. break;
  10288. case '"':
  10289. outputStream.write ("&quot;", 6);
  10290. break;
  10291. case '>':
  10292. outputStream.write ("&gt;", 4);
  10293. break;
  10294. case '<':
  10295. outputStream.write ("&lt;", 4);
  10296. break;
  10297. case '\n':
  10298. if (changeNewLines)
  10299. outputStream.write ("&#10;", 5);
  10300. else
  10301. outputStream.writeByte ((char) character);
  10302. break;
  10303. case '\r':
  10304. if (changeNewLines)
  10305. outputStream.write ("&#13;", 5);
  10306. else
  10307. outputStream.writeByte ((char) character);
  10308. break;
  10309. default:
  10310. {
  10311. String encoded (T("&#"));
  10312. encoded << String ((int) (unsigned int) character).trim()
  10313. << T(';');
  10314. outputStream.write ((const char*) encoded, encoded.length());
  10315. }
  10316. }
  10317. }
  10318. }
  10319. }
  10320. static void writeSpaces (OutputStream& out, int numSpaces) throw()
  10321. {
  10322. if (numSpaces > 0)
  10323. {
  10324. const char* const blanks = " ";
  10325. const int blankSize = (int) sizeof (blanks) - 1;
  10326. while (numSpaces > blankSize)
  10327. {
  10328. out.write (blanks, blankSize);
  10329. numSpaces -= blankSize;
  10330. }
  10331. out.write (blanks, numSpaces);
  10332. }
  10333. }
  10334. void XmlElement::writeElementAsText (OutputStream& outputStream,
  10335. const int indentationLevel) const throw()
  10336. {
  10337. writeSpaces (outputStream, indentationLevel);
  10338. if (! isTextElement())
  10339. {
  10340. outputStream.writeByte ('<');
  10341. const int nameLen = tagName.length();
  10342. outputStream.write ((const char*) tagName, nameLen);
  10343. const int attIndent = indentationLevel + nameLen + 1;
  10344. int lineLen = 0;
  10345. const XmlAttributeNode* att = attributes;
  10346. while (att != 0)
  10347. {
  10348. if (lineLen > 60 && indentationLevel >= 0)
  10349. {
  10350. outputStream.write ("\r\n", 2);
  10351. writeSpaces (outputStream, attIndent);
  10352. lineLen = 0;
  10353. }
  10354. const int attNameLen = att->name.length();
  10355. outputStream.writeByte (' ');
  10356. outputStream.write ((const char*) (att->name), attNameLen);
  10357. outputStream.write ("=\"", 2);
  10358. escapeIllegalXmlChars (outputStream, att->value, true);
  10359. outputStream.writeByte ('"');
  10360. lineLen += 4 + attNameLen + att->value.length();
  10361. att = att->next;
  10362. }
  10363. if (firstChildElement != 0)
  10364. {
  10365. XmlElement* child = firstChildElement;
  10366. if (child->nextElement == 0 && child->isTextElement())
  10367. {
  10368. outputStream.writeByte ('>');
  10369. escapeIllegalXmlChars (outputStream, child->getText(), false);
  10370. }
  10371. else
  10372. {
  10373. if (indentationLevel >= 0)
  10374. outputStream.write (">\r\n", 3);
  10375. else
  10376. outputStream.writeByte ('>');
  10377. bool lastWasTextNode = false;
  10378. while (child != 0)
  10379. {
  10380. if (child->isTextElement())
  10381. {
  10382. if ((! lastWasTextNode) && (indentationLevel >= 0))
  10383. writeSpaces (outputStream, indentationLevel + 2);
  10384. escapeIllegalXmlChars (outputStream, child->getText(), false);
  10385. lastWasTextNode = true;
  10386. }
  10387. else
  10388. {
  10389. if (indentationLevel >= 0)
  10390. {
  10391. if (lastWasTextNode)
  10392. outputStream.write ("\r\n", 2);
  10393. child->writeElementAsText (outputStream, indentationLevel + 2);
  10394. }
  10395. else
  10396. {
  10397. child->writeElementAsText (outputStream, indentationLevel);
  10398. }
  10399. lastWasTextNode = false;
  10400. }
  10401. child = child->nextElement;
  10402. }
  10403. if (indentationLevel >= 0)
  10404. {
  10405. if (lastWasTextNode)
  10406. outputStream.write ("\r\n", 2);
  10407. writeSpaces (outputStream, indentationLevel);
  10408. }
  10409. }
  10410. outputStream.write ("</", 2);
  10411. outputStream.write ((const char*) tagName, nameLen);
  10412. if (indentationLevel >= 0)
  10413. outputStream.write (">\r\n", 3);
  10414. else
  10415. outputStream.writeByte ('>');
  10416. }
  10417. else
  10418. {
  10419. if (indentationLevel >= 0)
  10420. outputStream.write ("/>\r\n", 4);
  10421. else
  10422. outputStream.write ("/>", 2);
  10423. }
  10424. }
  10425. else
  10426. {
  10427. if (indentationLevel >= 0)
  10428. writeSpaces (outputStream, indentationLevel + 2);
  10429. escapeIllegalXmlChars (outputStream, getText(), false);
  10430. }
  10431. }
  10432. const String XmlElement::createDocument (const String& dtd,
  10433. const bool allOnOneLine,
  10434. const bool includeXmlHeader,
  10435. const tchar* const encoding) const throw()
  10436. {
  10437. String doc;
  10438. doc.preallocateStorage (1024);
  10439. if (includeXmlHeader)
  10440. {
  10441. doc << "<?xml version=\"1.0\" encoding=\""
  10442. << encoding;
  10443. if (allOnOneLine)
  10444. doc += "\"?> ";
  10445. else
  10446. doc += "\"?>\n\n";
  10447. }
  10448. if (dtd.isNotEmpty())
  10449. {
  10450. if (allOnOneLine)
  10451. doc << dtd << " ";
  10452. else
  10453. doc << dtd << "\r\n";
  10454. }
  10455. MemoryOutputStream mem (2048, 4096);
  10456. writeElementAsText (mem, allOnOneLine ? -1 : 0);
  10457. return doc + String (mem.getData(),
  10458. mem.getDataSize());
  10459. }
  10460. bool XmlElement::writeToFile (const File& f,
  10461. const String& dtd,
  10462. const tchar* const encoding) const throw()
  10463. {
  10464. if (f.hasWriteAccess())
  10465. {
  10466. const File tempFile (f.getNonexistentSibling());
  10467. FileOutputStream* const out = tempFile.createOutputStream();
  10468. if (out != 0)
  10469. {
  10470. *out << "<?xml version=\"1.0\" encoding=\"" << encoding << "\"?>\r\n\r\n"
  10471. << dtd << "\r\n";
  10472. writeElementAsText (*out, 0);
  10473. delete out;
  10474. if (tempFile.moveFileTo (f))
  10475. return true;
  10476. tempFile.deleteFile();
  10477. }
  10478. }
  10479. return false;
  10480. }
  10481. bool XmlElement::hasTagName (const tchar* const tagNameWanted) const throw()
  10482. {
  10483. #ifdef JUCE_DEBUG
  10484. // if debugging, check that the case is actually the same, because
  10485. // valid xml is case-sensitive, and although this lets it pass, it's
  10486. // better not to..
  10487. if (tagName.equalsIgnoreCase (tagNameWanted))
  10488. {
  10489. jassert (tagName == tagNameWanted);
  10490. return true;
  10491. }
  10492. else
  10493. {
  10494. return false;
  10495. }
  10496. #else
  10497. return tagName.equalsIgnoreCase (tagNameWanted);
  10498. #endif
  10499. }
  10500. XmlElement* XmlElement::getNextElementWithTagName (const tchar* const requiredTagName) const
  10501. {
  10502. XmlElement* e = nextElement;
  10503. while (e != 0 && ! e->hasTagName (requiredTagName))
  10504. e = e->nextElement;
  10505. return e;
  10506. }
  10507. int XmlElement::getNumAttributes() const throw()
  10508. {
  10509. const XmlAttributeNode* att = attributes;
  10510. int count = 0;
  10511. while (att != 0)
  10512. {
  10513. att = att->next;
  10514. ++count;
  10515. }
  10516. return count;
  10517. }
  10518. const String& XmlElement::getAttributeName (const int index) const throw()
  10519. {
  10520. const XmlAttributeNode* att = attributes;
  10521. int count = 0;
  10522. while (att != 0)
  10523. {
  10524. if (count == index)
  10525. return att->name;
  10526. att = att->next;
  10527. ++count;
  10528. }
  10529. return String::empty;
  10530. }
  10531. const String& XmlElement::getAttributeValue (const int index) const throw()
  10532. {
  10533. const XmlAttributeNode* att = attributes;
  10534. int count = 0;
  10535. while (att != 0)
  10536. {
  10537. if (count == index)
  10538. return att->value;
  10539. att = att->next;
  10540. ++count;
  10541. }
  10542. return String::empty;
  10543. }
  10544. bool XmlElement::hasAttribute (const tchar* const attributeName) const throw()
  10545. {
  10546. const XmlAttributeNode* att = attributes;
  10547. while (att != 0)
  10548. {
  10549. if (att->name.equalsIgnoreCase (attributeName))
  10550. return true;
  10551. att = att->next;
  10552. }
  10553. return false;
  10554. }
  10555. const String XmlElement::getStringAttribute (const tchar* const attributeName,
  10556. const tchar* const defaultReturnValue) const throw()
  10557. {
  10558. const XmlAttributeNode* att = attributes;
  10559. while (att != 0)
  10560. {
  10561. if (att->name.equalsIgnoreCase (attributeName))
  10562. return att->value;
  10563. att = att->next;
  10564. }
  10565. return defaultReturnValue;
  10566. }
  10567. int XmlElement::getIntAttribute (const tchar* const attributeName,
  10568. const int defaultReturnValue) const throw()
  10569. {
  10570. const XmlAttributeNode* att = attributes;
  10571. while (att != 0)
  10572. {
  10573. if (att->name.equalsIgnoreCase (attributeName))
  10574. return att->value.getIntValue();
  10575. att = att->next;
  10576. }
  10577. return defaultReturnValue;
  10578. }
  10579. double XmlElement::getDoubleAttribute (const tchar* const attributeName,
  10580. const double defaultReturnValue) const throw()
  10581. {
  10582. const XmlAttributeNode* att = attributes;
  10583. while (att != 0)
  10584. {
  10585. if (att->name.equalsIgnoreCase (attributeName))
  10586. return att->value.getDoubleValue();
  10587. att = att->next;
  10588. }
  10589. return defaultReturnValue;
  10590. }
  10591. bool XmlElement::getBoolAttribute (const tchar* const attributeName,
  10592. const bool defaultReturnValue) const throw()
  10593. {
  10594. const XmlAttributeNode* att = attributes;
  10595. while (att != 0)
  10596. {
  10597. if (att->name.equalsIgnoreCase (attributeName))
  10598. {
  10599. tchar firstChar = att->value[0];
  10600. if (CharacterFunctions::isWhitespace (firstChar))
  10601. firstChar = att->value.trimStart() [0];
  10602. return firstChar == T('1')
  10603. || firstChar == T('t')
  10604. || firstChar == T('y')
  10605. || firstChar == T('T')
  10606. || firstChar == T('Y');
  10607. }
  10608. att = att->next;
  10609. }
  10610. return defaultReturnValue;
  10611. }
  10612. bool XmlElement::compareAttribute (const tchar* const attributeName,
  10613. const tchar* const stringToCompareAgainst,
  10614. const bool ignoreCase) const throw()
  10615. {
  10616. const XmlAttributeNode* att = attributes;
  10617. while (att != 0)
  10618. {
  10619. if (att->name.equalsIgnoreCase (attributeName))
  10620. {
  10621. if (ignoreCase)
  10622. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  10623. else
  10624. return att->value == stringToCompareAgainst;
  10625. }
  10626. att = att->next;
  10627. }
  10628. return false;
  10629. }
  10630. void XmlElement::setAttribute (const tchar* const attributeName,
  10631. const String& value) throw()
  10632. {
  10633. #ifdef JUCE_DEBUG
  10634. // check the identifier being passed in is legal..
  10635. const tchar* t = attributeName;
  10636. while (*t != 0)
  10637. {
  10638. jassert (CharacterFunctions::isLetterOrDigit (*t)
  10639. || *t == T('_')
  10640. || *t == T('-')
  10641. || *t == T(':'));
  10642. ++t;
  10643. }
  10644. #endif
  10645. if (attributes == 0)
  10646. {
  10647. attributes = new XmlAttributeNode (attributeName, value);
  10648. }
  10649. else
  10650. {
  10651. XmlAttributeNode* att = attributes;
  10652. for (;;)
  10653. {
  10654. if (att->name.equalsIgnoreCase (attributeName))
  10655. {
  10656. att->value = value;
  10657. break;
  10658. }
  10659. else if (att->next == 0)
  10660. {
  10661. att->next = new XmlAttributeNode (attributeName, value);
  10662. break;
  10663. }
  10664. att = att->next;
  10665. }
  10666. }
  10667. }
  10668. void XmlElement::setAttribute (const tchar* const attributeName,
  10669. const tchar* const text) throw()
  10670. {
  10671. setAttribute (attributeName, String (text));
  10672. }
  10673. void XmlElement::setAttribute (const tchar* const attributeName,
  10674. const int number) throw()
  10675. {
  10676. setAttribute (attributeName, String (number));
  10677. }
  10678. void XmlElement::setAttribute (const tchar* const attributeName,
  10679. const double number) throw()
  10680. {
  10681. tchar buffer [40];
  10682. CharacterFunctions::printf (buffer, numElementsInArray (buffer), T("%.9g"), number);
  10683. setAttribute (attributeName, buffer);
  10684. }
  10685. void XmlElement::removeAttribute (const tchar* const attributeName) throw()
  10686. {
  10687. XmlAttributeNode* att = attributes;
  10688. XmlAttributeNode* lastAtt = 0;
  10689. while (att != 0)
  10690. {
  10691. if (att->name.equalsIgnoreCase (attributeName))
  10692. {
  10693. if (lastAtt == 0)
  10694. attributes = att->next;
  10695. else
  10696. lastAtt->next = att->next;
  10697. delete att;
  10698. break;
  10699. }
  10700. lastAtt = att;
  10701. att = att->next;
  10702. }
  10703. }
  10704. void XmlElement::removeAllAttributes() throw()
  10705. {
  10706. while (attributes != 0)
  10707. {
  10708. XmlAttributeNode* const nextAtt = attributes->next;
  10709. delete attributes;
  10710. attributes = nextAtt;
  10711. }
  10712. }
  10713. int XmlElement::getNumChildElements() const throw()
  10714. {
  10715. int count = 0;
  10716. const XmlElement* child = firstChildElement;
  10717. while (child != 0)
  10718. {
  10719. ++count;
  10720. child = child->nextElement;
  10721. }
  10722. return count;
  10723. }
  10724. XmlElement* XmlElement::getChildElement (const int index) const throw()
  10725. {
  10726. int count = 0;
  10727. XmlElement* child = firstChildElement;
  10728. while (child != 0 && count < index)
  10729. {
  10730. child = child->nextElement;
  10731. ++count;
  10732. }
  10733. return child;
  10734. }
  10735. XmlElement* XmlElement::getChildByName (const tchar* const childName) const throw()
  10736. {
  10737. XmlElement* child = firstChildElement;
  10738. while (child != 0)
  10739. {
  10740. if (child->hasTagName (childName))
  10741. break;
  10742. child = child->nextElement;
  10743. }
  10744. return child;
  10745. }
  10746. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  10747. {
  10748. if (newNode != 0)
  10749. {
  10750. if (firstChildElement == 0)
  10751. {
  10752. firstChildElement = newNode;
  10753. }
  10754. else
  10755. {
  10756. XmlElement* child = firstChildElement;
  10757. while (child->nextElement != 0)
  10758. child = child->nextElement;
  10759. child->nextElement = newNode;
  10760. // if this is non-zero, then something's probably
  10761. // gone wrong..
  10762. jassert (newNode->nextElement == 0);
  10763. }
  10764. }
  10765. }
  10766. void XmlElement::insertChildElement (XmlElement* const newNode,
  10767. int indexToInsertAt) throw()
  10768. {
  10769. if (newNode != 0)
  10770. {
  10771. removeChildElement (newNode, false);
  10772. if (indexToInsertAt == 0)
  10773. {
  10774. newNode->nextElement = firstChildElement;
  10775. firstChildElement = newNode;
  10776. }
  10777. else
  10778. {
  10779. if (firstChildElement == 0)
  10780. {
  10781. firstChildElement = newNode;
  10782. }
  10783. else
  10784. {
  10785. if (indexToInsertAt < 0)
  10786. indexToInsertAt = INT_MAX;
  10787. XmlElement* child = firstChildElement;
  10788. while (child->nextElement != 0 && --indexToInsertAt > 0)
  10789. child = child->nextElement;
  10790. newNode->nextElement = child->nextElement;
  10791. child->nextElement = newNode;
  10792. }
  10793. }
  10794. }
  10795. }
  10796. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  10797. XmlElement* const newNode) throw()
  10798. {
  10799. if (newNode != 0)
  10800. {
  10801. XmlElement* child = firstChildElement;
  10802. XmlElement* previousNode = 0;
  10803. while (child != 0)
  10804. {
  10805. if (child == currentChildElement)
  10806. {
  10807. if (child != newNode)
  10808. {
  10809. if (previousNode == 0)
  10810. firstChildElement = newNode;
  10811. else
  10812. previousNode->nextElement = newNode;
  10813. newNode->nextElement = child->nextElement;
  10814. delete child;
  10815. }
  10816. return true;
  10817. }
  10818. previousNode = child;
  10819. child = child->nextElement;
  10820. }
  10821. }
  10822. return false;
  10823. }
  10824. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  10825. const bool shouldDeleteTheChild) throw()
  10826. {
  10827. if (childToRemove != 0)
  10828. {
  10829. if (firstChildElement == childToRemove)
  10830. {
  10831. firstChildElement = childToRemove->nextElement;
  10832. childToRemove->nextElement = 0;
  10833. }
  10834. else
  10835. {
  10836. XmlElement* child = firstChildElement;
  10837. XmlElement* last = 0;
  10838. while (child != 0)
  10839. {
  10840. if (child == childToRemove)
  10841. {
  10842. if (last == 0)
  10843. firstChildElement = child->nextElement;
  10844. else
  10845. last->nextElement = child->nextElement;
  10846. childToRemove->nextElement = 0;
  10847. break;
  10848. }
  10849. last = child;
  10850. child = child->nextElement;
  10851. }
  10852. }
  10853. if (shouldDeleteTheChild)
  10854. delete childToRemove;
  10855. }
  10856. }
  10857. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  10858. const bool ignoreOrderOfAttributes) const throw()
  10859. {
  10860. if (this != other)
  10861. {
  10862. if (other == 0 || tagName != other->tagName)
  10863. {
  10864. return false;
  10865. }
  10866. if (ignoreOrderOfAttributes)
  10867. {
  10868. int totalAtts = 0;
  10869. const XmlAttributeNode* att = attributes;
  10870. while (att != 0)
  10871. {
  10872. if (! other->compareAttribute (att->name, att->value))
  10873. return false;
  10874. att = att->next;
  10875. ++totalAtts;
  10876. }
  10877. if (totalAtts != other->getNumAttributes())
  10878. return false;
  10879. }
  10880. else
  10881. {
  10882. const XmlAttributeNode* thisAtt = attributes;
  10883. const XmlAttributeNode* otherAtt = other->attributes;
  10884. for (;;)
  10885. {
  10886. if (thisAtt == 0 || otherAtt == 0)
  10887. {
  10888. if (thisAtt == otherAtt) // both 0, so it's a match
  10889. break;
  10890. return false;
  10891. }
  10892. if (thisAtt->name != otherAtt->name
  10893. || thisAtt->value != otherAtt->value)
  10894. {
  10895. return false;
  10896. }
  10897. thisAtt = thisAtt->next;
  10898. otherAtt = otherAtt->next;
  10899. }
  10900. }
  10901. const XmlElement* thisChild = firstChildElement;
  10902. const XmlElement* otherChild = other->firstChildElement;
  10903. for (;;)
  10904. {
  10905. if (thisChild == 0 || otherChild == 0)
  10906. {
  10907. if (thisChild == otherChild) // both 0, so it's a match
  10908. break;
  10909. return false;
  10910. }
  10911. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  10912. return false;
  10913. thisChild = thisChild->nextElement;
  10914. otherChild = otherChild->nextElement;
  10915. }
  10916. }
  10917. return true;
  10918. }
  10919. void XmlElement::deleteAllChildElements() throw()
  10920. {
  10921. while (firstChildElement != 0)
  10922. {
  10923. XmlElement* const nextChild = firstChildElement->nextElement;
  10924. delete firstChildElement;
  10925. firstChildElement = nextChild;
  10926. }
  10927. }
  10928. void XmlElement::deleteAllChildElementsWithTagName (const tchar* const name) throw()
  10929. {
  10930. XmlElement* child = firstChildElement;
  10931. while (child != 0)
  10932. {
  10933. if (child->hasTagName (name))
  10934. {
  10935. XmlElement* const nextChild = child->nextElement;
  10936. removeChildElement (child, true);
  10937. child = nextChild;
  10938. }
  10939. else
  10940. {
  10941. child = child->nextElement;
  10942. }
  10943. }
  10944. }
  10945. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  10946. {
  10947. const XmlElement* child = firstChildElement;
  10948. while (child != 0)
  10949. {
  10950. if (child == possibleChild)
  10951. return true;
  10952. child = child->nextElement;
  10953. }
  10954. return false;
  10955. }
  10956. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  10957. {
  10958. if (this == elementToLookFor || elementToLookFor == 0)
  10959. return 0;
  10960. XmlElement* child = firstChildElement;
  10961. while (child != 0)
  10962. {
  10963. if (elementToLookFor == child)
  10964. return this;
  10965. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  10966. if (found != 0)
  10967. return found;
  10968. child = child->nextElement;
  10969. }
  10970. return 0;
  10971. }
  10972. XmlElement** XmlElement::getChildElementsAsArray (const int num) const throw()
  10973. {
  10974. XmlElement** const elems = new XmlElement* [num];
  10975. XmlElement* e = firstChildElement;
  10976. int i = 0;
  10977. while (e != 0)
  10978. {
  10979. elems [i++] = e;
  10980. e = e->nextElement;
  10981. }
  10982. return elems;
  10983. }
  10984. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  10985. {
  10986. XmlElement* e = firstChildElement = elems[0];
  10987. for (int i = 1; i < num; ++i)
  10988. {
  10989. e->nextElement = elems[i];
  10990. e = e->nextElement;
  10991. }
  10992. e->nextElement = 0;
  10993. }
  10994. bool XmlElement::isTextElement() const throw()
  10995. {
  10996. return tagName.isEmpty();
  10997. }
  10998. static const tchar* const juce_xmltextContentAttributeName = T("text");
  10999. const String XmlElement::getText() const throw()
  11000. {
  11001. jassert (isTextElement()); // you're trying to get the text from an element that
  11002. // isn't actually a text element.. If this contains text sub-nodes, you
  11003. // can use getAllSubText instead to
  11004. return getStringAttribute (juce_xmltextContentAttributeName);
  11005. }
  11006. void XmlElement::setText (const String& newText) throw()
  11007. {
  11008. if (isTextElement())
  11009. {
  11010. setAttribute (juce_xmltextContentAttributeName, newText);
  11011. }
  11012. else
  11013. {
  11014. jassertfalse // you can only change the text in a text element, not a normal one.
  11015. }
  11016. }
  11017. const String XmlElement::getAllSubText() const throw()
  11018. {
  11019. String result;
  11020. const XmlElement* child = firstChildElement;
  11021. while (child != 0)
  11022. {
  11023. if (child->isTextElement())
  11024. result += child->getText();
  11025. child = child->nextElement;
  11026. }
  11027. return result;
  11028. }
  11029. const String XmlElement::getChildElementAllSubText (const tchar* const childTagName,
  11030. const String& defaultReturnValue) const throw()
  11031. {
  11032. const XmlElement* const child = getChildByName (childTagName);
  11033. if (child != 0)
  11034. return child->getAllSubText();
  11035. return defaultReturnValue;
  11036. }
  11037. XmlElement* XmlElement::createTextElement (const String& text) throw()
  11038. {
  11039. XmlElement* const e = new XmlElement ((int) 0);
  11040. e->setAttribute (juce_xmltextContentAttributeName, text);
  11041. return e;
  11042. }
  11043. void XmlElement::addTextElement (const String& text) throw()
  11044. {
  11045. addChildElement (createTextElement (text));
  11046. }
  11047. void XmlElement::deleteAllTextElements() throw()
  11048. {
  11049. XmlElement* child = firstChildElement;
  11050. while (child != 0)
  11051. {
  11052. XmlElement* const next = child->nextElement;
  11053. if (child->isTextElement())
  11054. removeChildElement (child, true);
  11055. child = next;
  11056. }
  11057. }
  11058. END_JUCE_NAMESPACE
  11059. /********* End of inlined file: juce_XmlElement.cpp *********/
  11060. /********* Start of inlined file: juce_InterProcessLock.cpp *********/
  11061. BEGIN_JUCE_NAMESPACE
  11062. // (implemented in the platform-specific code files)
  11063. END_JUCE_NAMESPACE
  11064. /********* End of inlined file: juce_InterProcessLock.cpp *********/
  11065. /********* Start of inlined file: juce_ReadWriteLock.cpp *********/
  11066. BEGIN_JUCE_NAMESPACE
  11067. ReadWriteLock::ReadWriteLock() throw()
  11068. : numWaitingWriters (0),
  11069. numWriters (0),
  11070. writerThreadId (0)
  11071. {
  11072. }
  11073. ReadWriteLock::~ReadWriteLock() throw()
  11074. {
  11075. jassert (readerThreads.size() == 0);
  11076. jassert (numWriters == 0);
  11077. }
  11078. void ReadWriteLock::enterRead() const throw()
  11079. {
  11080. const int threadId = Thread::getCurrentThreadId();
  11081. const ScopedLock sl (accessLock);
  11082. for (;;)
  11083. {
  11084. jassert (readerThreads.size() % 2 == 0);
  11085. int i;
  11086. for (i = 0; i < readerThreads.size(); i += 2)
  11087. if (readerThreads.getUnchecked(i) == threadId)
  11088. break;
  11089. if (i < readerThreads.size()
  11090. || numWriters + numWaitingWriters == 0
  11091. || (threadId == writerThreadId && numWriters > 0))
  11092. {
  11093. if (i < readerThreads.size())
  11094. {
  11095. readerThreads.set (i + 1, readerThreads.getUnchecked (i + 1) + 1);
  11096. }
  11097. else
  11098. {
  11099. readerThreads.add (threadId);
  11100. readerThreads.add (1);
  11101. }
  11102. return;
  11103. }
  11104. const ScopedUnlock ul (accessLock);
  11105. waitEvent.wait (100);
  11106. }
  11107. }
  11108. void ReadWriteLock::exitRead() const throw()
  11109. {
  11110. const int threadId = Thread::getCurrentThreadId();
  11111. const ScopedLock sl (accessLock);
  11112. for (int i = 0; i < readerThreads.size(); i += 2)
  11113. {
  11114. if (readerThreads.getUnchecked(i) == threadId)
  11115. {
  11116. const int newCount = readerThreads.getUnchecked (i + 1) - 1;
  11117. if (newCount == 0)
  11118. {
  11119. readerThreads.removeRange (i, 2);
  11120. waitEvent.signal();
  11121. }
  11122. else
  11123. {
  11124. readerThreads.set (i + 1, newCount);
  11125. }
  11126. return;
  11127. }
  11128. }
  11129. jassertfalse // unlocking a lock that wasn't locked..
  11130. }
  11131. void ReadWriteLock::enterWrite() const throw()
  11132. {
  11133. const int threadId = Thread::getCurrentThreadId();
  11134. const ScopedLock sl (accessLock);
  11135. for (;;)
  11136. {
  11137. if (readerThreads.size() + numWriters == 0
  11138. || threadId == writerThreadId
  11139. || (readerThreads.size() == 2
  11140. && readerThreads.getUnchecked(0) == threadId))
  11141. {
  11142. writerThreadId = threadId;
  11143. ++numWriters;
  11144. break;
  11145. }
  11146. ++numWaitingWriters;
  11147. accessLock.exit();
  11148. waitEvent.wait (100);
  11149. accessLock.enter();
  11150. --numWaitingWriters;
  11151. }
  11152. }
  11153. bool ReadWriteLock::tryEnterWrite() const throw()
  11154. {
  11155. const int threadId = Thread::getCurrentThreadId();
  11156. const ScopedLock sl (accessLock);
  11157. if (readerThreads.size() + numWriters == 0
  11158. || threadId == writerThreadId
  11159. || (readerThreads.size() == 2
  11160. && readerThreads.getUnchecked(0) == threadId))
  11161. {
  11162. writerThreadId = threadId;
  11163. ++numWriters;
  11164. return true;
  11165. }
  11166. return false;
  11167. }
  11168. void ReadWriteLock::exitWrite() const throw()
  11169. {
  11170. const ScopedLock sl (accessLock);
  11171. // check this thread actually had the lock..
  11172. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  11173. if (--numWriters == 0)
  11174. {
  11175. writerThreadId = 0;
  11176. waitEvent.signal();
  11177. }
  11178. }
  11179. END_JUCE_NAMESPACE
  11180. /********* End of inlined file: juce_ReadWriteLock.cpp *********/
  11181. /********* Start of inlined file: juce_Thread.cpp *********/
  11182. BEGIN_JUCE_NAMESPACE
  11183. // these functions are implemented in the platform-specific code.
  11184. void* juce_createThread (void* userData) throw();
  11185. void juce_killThread (void* handle) throw();
  11186. void juce_setThreadPriority (void* handle, int priority) throw();
  11187. void juce_setCurrentThreadName (const String& name) throw();
  11188. #if JUCE_WIN32
  11189. void juce_CloseThreadHandle (void* handle) throw();
  11190. #endif
  11191. static VoidArray runningThreads (4);
  11192. static CriticalSection runningThreadsLock;
  11193. void Thread::threadEntryPoint (Thread* const thread) throw()
  11194. {
  11195. runningThreadsLock.enter();
  11196. runningThreads.add (thread);
  11197. runningThreadsLock.exit();
  11198. JUCE_TRY
  11199. {
  11200. thread->threadId_ = Thread::getCurrentThreadId();
  11201. if (thread->threadName_.isNotEmpty())
  11202. juce_setCurrentThreadName (thread->threadName_);
  11203. if (thread->startSuspensionEvent_.wait (10000))
  11204. {
  11205. if (thread->affinityMask_ != 0)
  11206. setCurrentThreadAffinityMask (thread->affinityMask_);
  11207. thread->run();
  11208. }
  11209. }
  11210. JUCE_CATCH_ALL_ASSERT
  11211. runningThreadsLock.enter();
  11212. jassert (runningThreads.contains (thread));
  11213. runningThreads.removeValue (thread);
  11214. runningThreadsLock.exit();
  11215. #if JUCE_WIN32
  11216. juce_CloseThreadHandle (thread->threadHandle_);
  11217. #endif
  11218. thread->threadHandle_ = 0;
  11219. thread->threadId_ = 0;
  11220. }
  11221. // used to wrap the incoming call from the platform-specific code
  11222. void JUCE_API juce_threadEntryPoint (void* userData)
  11223. {
  11224. Thread::threadEntryPoint ((Thread*) userData);
  11225. }
  11226. Thread::Thread (const String& threadName)
  11227. : threadName_ (threadName),
  11228. threadHandle_ (0),
  11229. threadPriority_ (5),
  11230. threadId_ (0),
  11231. affinityMask_ (0),
  11232. threadShouldExit_ (false)
  11233. {
  11234. }
  11235. Thread::~Thread()
  11236. {
  11237. stopThread (100);
  11238. }
  11239. void Thread::startThread() throw()
  11240. {
  11241. const ScopedLock sl (startStopLock);
  11242. threadShouldExit_ = false;
  11243. if (threadHandle_ == 0)
  11244. {
  11245. threadHandle_ = juce_createThread ((void*) this);
  11246. juce_setThreadPriority (threadHandle_, threadPriority_);
  11247. startSuspensionEvent_.signal();
  11248. }
  11249. }
  11250. void Thread::startThread (const int priority) throw()
  11251. {
  11252. const ScopedLock sl (startStopLock);
  11253. if (threadHandle_ == 0)
  11254. {
  11255. threadPriority_ = priority;
  11256. startThread();
  11257. }
  11258. else
  11259. {
  11260. setPriority (priority);
  11261. }
  11262. }
  11263. bool Thread::isThreadRunning() const throw()
  11264. {
  11265. return threadHandle_ != 0;
  11266. }
  11267. void Thread::signalThreadShouldExit() throw()
  11268. {
  11269. threadShouldExit_ = true;
  11270. }
  11271. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const throw()
  11272. {
  11273. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  11274. jassert (getThreadId() != getCurrentThreadId());
  11275. const int sleepMsPerIteration = 5;
  11276. int count = timeOutMilliseconds / sleepMsPerIteration;
  11277. while (isThreadRunning())
  11278. {
  11279. if (timeOutMilliseconds > 0 && --count < 0)
  11280. return false;
  11281. sleep (sleepMsPerIteration);
  11282. }
  11283. return true;
  11284. }
  11285. void Thread::stopThread (const int timeOutMilliseconds) throw()
  11286. {
  11287. // agh! You can't stop the thread that's calling this method! How on earth
  11288. // would that work??
  11289. jassert (getCurrentThreadId() != getThreadId());
  11290. const ScopedLock sl (startStopLock);
  11291. if (isThreadRunning())
  11292. {
  11293. signalThreadShouldExit();
  11294. notify();
  11295. if (timeOutMilliseconds != 0)
  11296. waitForThreadToExit (timeOutMilliseconds);
  11297. if (isThreadRunning())
  11298. {
  11299. // very bad karma if this point is reached, as
  11300. // there are bound to be locks and events left in
  11301. // silly states when a thread is killed by force..
  11302. jassertfalse
  11303. Logger::writeToLog ("!! killing thread by force !!");
  11304. juce_killThread (threadHandle_);
  11305. threadHandle_ = 0;
  11306. threadId_ = 0;
  11307. const ScopedLock sl (runningThreadsLock);
  11308. runningThreads.removeValue (this);
  11309. }
  11310. }
  11311. }
  11312. void Thread::setPriority (const int priority) throw()
  11313. {
  11314. const ScopedLock sl (startStopLock);
  11315. threadPriority_ = priority;
  11316. juce_setThreadPriority (threadHandle_, priority);
  11317. }
  11318. void Thread::setCurrentThreadPriority (const int priority) throw()
  11319. {
  11320. juce_setThreadPriority (0, priority);
  11321. }
  11322. void Thread::setAffinityMask (const uint32 affinityMask) throw()
  11323. {
  11324. affinityMask_ = affinityMask;
  11325. }
  11326. int Thread::getThreadId() const throw()
  11327. {
  11328. return threadId_;
  11329. }
  11330. bool Thread::wait (const int timeOutMilliseconds) const throw()
  11331. {
  11332. return defaultEvent_.wait (timeOutMilliseconds);
  11333. }
  11334. void Thread::notify() const throw()
  11335. {
  11336. defaultEvent_.signal();
  11337. }
  11338. int Thread::getNumRunningThreads() throw()
  11339. {
  11340. return runningThreads.size();
  11341. }
  11342. Thread* Thread::getCurrentThread() throw()
  11343. {
  11344. const int thisId = getCurrentThreadId();
  11345. Thread* result = 0;
  11346. runningThreadsLock.enter();
  11347. for (int i = runningThreads.size(); --i >= 0;)
  11348. {
  11349. Thread* const t = (Thread*) (runningThreads.getUnchecked(i));
  11350. if (t->threadId_ == thisId)
  11351. {
  11352. result = t;
  11353. break;
  11354. }
  11355. }
  11356. runningThreadsLock.exit();
  11357. return result;
  11358. }
  11359. void Thread::stopAllThreads (const int timeOutMilliseconds) throw()
  11360. {
  11361. runningThreadsLock.enter();
  11362. for (int i = runningThreads.size(); --i >= 0;)
  11363. ((Thread*) runningThreads.getUnchecked(i))->signalThreadShouldExit();
  11364. runningThreadsLock.exit();
  11365. for (;;)
  11366. {
  11367. runningThreadsLock.enter();
  11368. Thread* const t = (Thread*) runningThreads[0];
  11369. runningThreadsLock.exit();
  11370. if (t == 0)
  11371. break;
  11372. t->stopThread (timeOutMilliseconds);
  11373. }
  11374. }
  11375. END_JUCE_NAMESPACE
  11376. /********* End of inlined file: juce_Thread.cpp *********/
  11377. /********* Start of inlined file: juce_ThreadPool.cpp *********/
  11378. BEGIN_JUCE_NAMESPACE
  11379. ThreadPoolJob::ThreadPoolJob (const String& name)
  11380. : jobName (name),
  11381. pool (0),
  11382. shouldStop (false),
  11383. isActive (false),
  11384. shouldBeDeleted (false)
  11385. {
  11386. }
  11387. ThreadPoolJob::~ThreadPoolJob()
  11388. {
  11389. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  11390. // to remove it first!
  11391. jassert (pool == 0 || ! pool->contains (this));
  11392. }
  11393. const String ThreadPoolJob::getJobName() const
  11394. {
  11395. return jobName;
  11396. }
  11397. void ThreadPoolJob::setJobName (const String& newName)
  11398. {
  11399. jobName = newName;
  11400. }
  11401. void ThreadPoolJob::signalJobShouldExit()
  11402. {
  11403. shouldStop = true;
  11404. }
  11405. class ThreadPoolThread : public Thread
  11406. {
  11407. ThreadPool& pool;
  11408. bool volatile busy;
  11409. ThreadPoolThread (const ThreadPoolThread&);
  11410. const ThreadPoolThread& operator= (const ThreadPoolThread&);
  11411. public:
  11412. ThreadPoolThread (ThreadPool& pool_)
  11413. : Thread (T("Pool")),
  11414. pool (pool_),
  11415. busy (false)
  11416. {
  11417. }
  11418. ~ThreadPoolThread()
  11419. {
  11420. }
  11421. void run()
  11422. {
  11423. while (! threadShouldExit())
  11424. {
  11425. if (! pool.runNextJob())
  11426. wait (500);
  11427. }
  11428. }
  11429. };
  11430. ThreadPool::ThreadPool (const int numThreads_,
  11431. const bool startThreadsOnlyWhenNeeded,
  11432. const int stopThreadsWhenNotUsedTimeoutMs)
  11433. : numThreads (jmax (1, numThreads_)),
  11434. threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  11435. priority (5)
  11436. {
  11437. jassert (numThreads_ > 0); // not much point having one of these with no threads in it.
  11438. threads = (Thread**) juce_calloc (sizeof (Thread*) * numThreads);
  11439. for (int i = numThreads; --i >= 0;)
  11440. {
  11441. threads[i] = new ThreadPoolThread (*this);
  11442. if (! startThreadsOnlyWhenNeeded)
  11443. threads[i]->startThread();
  11444. }
  11445. }
  11446. ThreadPool::~ThreadPool()
  11447. {
  11448. removeAllJobs (true, 4000);
  11449. int i;
  11450. for (i = numThreads; --i >= 0;)
  11451. threads[i]->signalThreadShouldExit();
  11452. for (i = numThreads; --i >= 0;)
  11453. {
  11454. threads[i]->stopThread (500);
  11455. delete threads[i];
  11456. }
  11457. juce_free (threads);
  11458. }
  11459. void ThreadPool::addJob (ThreadPoolJob* const job)
  11460. {
  11461. jassert (job->pool == 0);
  11462. if (job->pool == 0)
  11463. {
  11464. job->pool = this;
  11465. job->shouldStop = false;
  11466. job->isActive = false;
  11467. lock.enter();
  11468. jobs.add (job);
  11469. int numRunning = 0;
  11470. int i;
  11471. for (i = numThreads; --i >= 0;)
  11472. if (threads[i]->isThreadRunning() && ! threads[i]->threadShouldExit())
  11473. ++numRunning;
  11474. if (numRunning < numThreads)
  11475. {
  11476. bool startedOne = false;
  11477. int n = 1000;
  11478. while (--n >= 0 && ! startedOne)
  11479. {
  11480. for (int i = numThreads; --i >= 0;)
  11481. {
  11482. if (! threads[i]->isThreadRunning())
  11483. {
  11484. threads[i]->startThread();
  11485. startedOne = true;
  11486. }
  11487. }
  11488. if (! startedOne)
  11489. Thread::sleep (5);
  11490. }
  11491. }
  11492. lock.exit();
  11493. for (i = numThreads; --i >= 0;)
  11494. threads[i]->notify();
  11495. }
  11496. }
  11497. int ThreadPool::getNumJobs() const throw()
  11498. {
  11499. return jobs.size();
  11500. }
  11501. ThreadPoolJob* ThreadPool::getJob (const int index) const
  11502. {
  11503. const ScopedLock sl (lock);
  11504. return (ThreadPoolJob*) jobs [index];
  11505. }
  11506. bool ThreadPool::contains (const ThreadPoolJob* const job) const throw()
  11507. {
  11508. const ScopedLock sl (lock);
  11509. return jobs.contains ((void*) job);
  11510. }
  11511. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  11512. {
  11513. const ScopedLock sl (lock);
  11514. return jobs.contains ((void*) job) && job->isActive;
  11515. }
  11516. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  11517. const int timeOutMs) const
  11518. {
  11519. if (job != 0)
  11520. {
  11521. const uint32 start = Time::getMillisecondCounter();
  11522. while (contains (job))
  11523. {
  11524. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  11525. return false;
  11526. Thread::sleep (2);
  11527. }
  11528. }
  11529. return true;
  11530. }
  11531. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  11532. const bool interruptIfRunning,
  11533. const int timeOutMs)
  11534. {
  11535. if (job != 0)
  11536. {
  11537. lock.enter();
  11538. if (jobs.contains (job))
  11539. {
  11540. if (job->isActive)
  11541. {
  11542. if (interruptIfRunning)
  11543. job->signalJobShouldExit();
  11544. lock.exit();
  11545. return waitForJobToFinish (job, timeOutMs);
  11546. }
  11547. else
  11548. {
  11549. jobs.removeValue (job);
  11550. }
  11551. }
  11552. lock.exit();
  11553. }
  11554. return true;
  11555. }
  11556. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  11557. const int timeOutMs)
  11558. {
  11559. lock.enter();
  11560. for (int i = jobs.size(); --i >= 0;)
  11561. {
  11562. ThreadPoolJob* const job = (ThreadPoolJob*) jobs.getUnchecked(i);
  11563. if (job->isActive)
  11564. {
  11565. if (interruptRunningJobs)
  11566. job->signalJobShouldExit();
  11567. }
  11568. else
  11569. {
  11570. jobs.remove (i);
  11571. }
  11572. }
  11573. lock.exit();
  11574. const uint32 start = Time::getMillisecondCounter();
  11575. while (jobs.size() > 0)
  11576. {
  11577. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  11578. return false;
  11579. Thread::sleep (2);
  11580. }
  11581. return true;
  11582. }
  11583. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  11584. {
  11585. StringArray s;
  11586. const ScopedLock sl (lock);
  11587. for (int i = 0; i < jobs.size(); ++i)
  11588. {
  11589. const ThreadPoolJob* const job = (const ThreadPoolJob*) jobs.getUnchecked(i);
  11590. if (job->isActive || ! onlyReturnActiveJobs)
  11591. s.add (job->getJobName());
  11592. }
  11593. return s;
  11594. }
  11595. void ThreadPool::setThreadPriorities (const int newPriority)
  11596. {
  11597. if (priority != newPriority)
  11598. {
  11599. priority = newPriority;
  11600. for (int i = numThreads; --i >= 0;)
  11601. threads[i]->setPriority (newPriority);
  11602. }
  11603. }
  11604. bool ThreadPool::runNextJob()
  11605. {
  11606. lock.enter();
  11607. ThreadPoolJob* job = 0;
  11608. for (int i = 0; i < jobs.size(); ++i)
  11609. {
  11610. job = (ThreadPoolJob*) jobs [i];
  11611. if (job != 0 && ! (job->isActive || job->shouldStop))
  11612. break;
  11613. job = 0;
  11614. }
  11615. if (job != 0)
  11616. {
  11617. job->isActive = true;
  11618. lock.exit();
  11619. JUCE_TRY
  11620. {
  11621. ThreadPoolJob::JobStatus result = job->runJob();
  11622. lastJobEndTime = Time::getApproximateMillisecondCounter();
  11623. const ScopedLock sl (lock);
  11624. if (jobs.contains (job))
  11625. {
  11626. job->isActive = false;
  11627. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  11628. {
  11629. job->pool = 0;
  11630. job->shouldStop = true;
  11631. jobs.removeValue (job);
  11632. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  11633. delete job;
  11634. }
  11635. else
  11636. {
  11637. // move the job to the end of the queue if it wants another go
  11638. jobs.move (jobs.indexOf (job), -1);
  11639. }
  11640. }
  11641. }
  11642. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  11643. catch (...)
  11644. {
  11645. lock.enter();
  11646. jobs.removeValue (job);
  11647. lock.exit();
  11648. }
  11649. #endif
  11650. }
  11651. else
  11652. {
  11653. lock.exit();
  11654. if (threadStopTimeout > 0
  11655. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  11656. {
  11657. lock.enter();
  11658. if (jobs.size() == 0)
  11659. {
  11660. for (int i = numThreads; --i >= 0;)
  11661. threads[i]->signalThreadShouldExit();
  11662. }
  11663. lock.exit();
  11664. }
  11665. else
  11666. {
  11667. return false;
  11668. }
  11669. }
  11670. return true;
  11671. }
  11672. END_JUCE_NAMESPACE
  11673. /********* End of inlined file: juce_ThreadPool.cpp *********/
  11674. /********* Start of inlined file: juce_TimeSliceThread.cpp *********/
  11675. BEGIN_JUCE_NAMESPACE
  11676. TimeSliceThread::TimeSliceThread (const String& threadName)
  11677. : Thread (threadName),
  11678. index (0),
  11679. clientBeingCalled (0),
  11680. clientsChanged (false)
  11681. {
  11682. }
  11683. TimeSliceThread::~TimeSliceThread()
  11684. {
  11685. stopThread (2000);
  11686. }
  11687. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  11688. {
  11689. const ScopedLock sl (listLock);
  11690. clients.addIfNotAlreadyThere (client);
  11691. clientsChanged = true;
  11692. notify();
  11693. }
  11694. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  11695. {
  11696. const ScopedLock sl1 (listLock);
  11697. clientsChanged = true;
  11698. // if there's a chance we're in the middle of calling this client, we need to
  11699. // also lock the outer lock..
  11700. if (clientBeingCalled == client)
  11701. {
  11702. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  11703. const ScopedLock sl1 (callbackLock);
  11704. const ScopedLock sl2 (listLock);
  11705. clients.removeValue (client);
  11706. }
  11707. else
  11708. {
  11709. clients.removeValue (client);
  11710. }
  11711. }
  11712. int TimeSliceThread::getNumClients() const throw()
  11713. {
  11714. return clients.size();
  11715. }
  11716. TimeSliceClient* TimeSliceThread::getClient (const int index) const throw()
  11717. {
  11718. const ScopedLock sl (listLock);
  11719. return clients [index];
  11720. }
  11721. void TimeSliceThread::run()
  11722. {
  11723. int numCallsSinceBusy = 0;
  11724. while (! threadShouldExit())
  11725. {
  11726. int timeToWait = 500;
  11727. {
  11728. const ScopedLock sl (callbackLock);
  11729. {
  11730. const ScopedLock sl (listLock);
  11731. if (clients.size() > 0)
  11732. {
  11733. index = (index + 1) % clients.size();
  11734. clientBeingCalled = clients [index];
  11735. }
  11736. else
  11737. {
  11738. index = 0;
  11739. clientBeingCalled = 0;
  11740. }
  11741. if (clientsChanged)
  11742. {
  11743. clientsChanged = false;
  11744. numCallsSinceBusy = 0;
  11745. }
  11746. }
  11747. if (clientBeingCalled != 0)
  11748. {
  11749. if (clientBeingCalled->useTimeSlice())
  11750. numCallsSinceBusy = 0;
  11751. else
  11752. ++numCallsSinceBusy;
  11753. if (numCallsSinceBusy >= clients.size())
  11754. timeToWait = 500;
  11755. else if (index == 0)
  11756. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  11757. else
  11758. timeToWait = 0;
  11759. }
  11760. }
  11761. if (timeToWait > 0)
  11762. wait (timeToWait);
  11763. }
  11764. }
  11765. END_JUCE_NAMESPACE
  11766. /********* End of inlined file: juce_TimeSliceThread.cpp *********/
  11767. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  11768. /********* Start of inlined file: juce_Application.cpp *********/
  11769. #if JUCE_MSVC
  11770. #pragma warning (push)
  11771. #pragma warning (disable: 4245 4514 4100)
  11772. #include <crtdbg.h>
  11773. #pragma warning (pop)
  11774. #endif
  11775. BEGIN_JUCE_NAMESPACE
  11776. void juce_setCurrentExecutableFileName (const String& filename) throw();
  11777. void juce_setCurrentThreadName (const String& name) throw();
  11778. static JUCEApplication* appInstance = 0;
  11779. JUCEApplication::JUCEApplication()
  11780. : appReturnValue (0),
  11781. stillInitialising (true)
  11782. {
  11783. }
  11784. JUCEApplication::~JUCEApplication()
  11785. {
  11786. }
  11787. JUCEApplication* JUCEApplication::getInstance() throw()
  11788. {
  11789. return appInstance;
  11790. }
  11791. bool JUCEApplication::isInitialising() const throw()
  11792. {
  11793. return stillInitialising;
  11794. }
  11795. const String JUCEApplication::getApplicationVersion()
  11796. {
  11797. return String::empty;
  11798. }
  11799. bool JUCEApplication::moreThanOneInstanceAllowed()
  11800. {
  11801. return true;
  11802. }
  11803. void JUCEApplication::anotherInstanceStarted (const String&)
  11804. {
  11805. }
  11806. void JUCEApplication::systemRequestedQuit()
  11807. {
  11808. quit();
  11809. }
  11810. void JUCEApplication::quit (const bool useMaximumForce)
  11811. {
  11812. MessageManager::getInstance()->postQuitMessage (useMaximumForce);
  11813. }
  11814. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  11815. {
  11816. appReturnValue = newReturnValue;
  11817. }
  11818. void JUCEApplication::unhandledException (const std::exception*,
  11819. const String&,
  11820. const int)
  11821. {
  11822. jassertfalse
  11823. }
  11824. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  11825. const char* const sourceFile,
  11826. const int lineNumber)
  11827. {
  11828. if (appInstance != 0)
  11829. appInstance->unhandledException (e, sourceFile, lineNumber);
  11830. }
  11831. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  11832. {
  11833. return 0;
  11834. }
  11835. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  11836. {
  11837. commands.add (StandardApplicationCommandIDs::quit);
  11838. }
  11839. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  11840. {
  11841. if (commandID == StandardApplicationCommandIDs::quit)
  11842. {
  11843. result.setInfo ("Quit",
  11844. "Quits the application",
  11845. "Application",
  11846. 0);
  11847. result.defaultKeypresses.add (KeyPress (T('q'), ModifierKeys::commandModifier, 0));
  11848. }
  11849. }
  11850. bool JUCEApplication::perform (const InvocationInfo& info)
  11851. {
  11852. if (info.commandID == StandardApplicationCommandIDs::quit)
  11853. {
  11854. systemRequestedQuit();
  11855. return true;
  11856. }
  11857. return false;
  11858. }
  11859. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  11860. {
  11861. jassert (appInstance == 0);
  11862. appInstance = app;
  11863. bool useForce = true;
  11864. initialiseJuce_GUI();
  11865. InterProcessLock* appLock = 0;
  11866. if (! app->moreThanOneInstanceAllowed())
  11867. {
  11868. appLock = new InterProcessLock ("juceAppLock_" + app->getApplicationName());
  11869. if (! appLock->enter(0))
  11870. {
  11871. MessageManager::broadcastMessage (app->getApplicationName() + "/" + commandLine);
  11872. delete appInstance;
  11873. appInstance = 0;
  11874. commandLine = String::empty;
  11875. DBG ("Another instance is running - quitting...");
  11876. return 0;
  11877. }
  11878. }
  11879. JUCE_TRY
  11880. {
  11881. juce_setCurrentThreadName ("Juce Message Thread");
  11882. // let the app do its setting-up..
  11883. app->initialise (commandLine.trim());
  11884. commandLine = String::empty;
  11885. // register for broadcast new app messages
  11886. MessageManager::getInstance()->registerBroadcastListener (app);
  11887. app->stillInitialising = false;
  11888. // now loop until a quit message is received..
  11889. useForce = MessageManager::getInstance()->runDispatchLoop();
  11890. MessageManager::getInstance()->deregisterBroadcastListener (app);
  11891. if (appLock != 0)
  11892. {
  11893. appLock->exit();
  11894. delete appLock;
  11895. }
  11896. }
  11897. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  11898. catch (const std::exception& e)
  11899. {
  11900. app->unhandledException (&e, __FILE__, __LINE__);
  11901. }
  11902. catch (...)
  11903. {
  11904. app->unhandledException (0, __FILE__, __LINE__);
  11905. }
  11906. #endif
  11907. return shutdownAppAndClearUp (useForce);
  11908. }
  11909. int JUCEApplication::shutdownAppAndClearUp (const bool useMaximumForce)
  11910. {
  11911. jassert (appInstance != 0);
  11912. JUCEApplication* const app = appInstance;
  11913. int returnValue = 0;
  11914. static bool reentrancyCheck = false;
  11915. if (! reentrancyCheck)
  11916. {
  11917. reentrancyCheck = true;
  11918. JUCE_TRY
  11919. {
  11920. // give the app a chance to clean up..
  11921. app->shutdown();
  11922. }
  11923. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  11924. catch (const std::exception& e)
  11925. {
  11926. app->unhandledException (&e, __FILE__, __LINE__);
  11927. }
  11928. catch (...)
  11929. {
  11930. app->unhandledException (0, __FILE__, __LINE__);
  11931. }
  11932. #endif
  11933. JUCE_TRY
  11934. {
  11935. shutdownJuce_GUI();
  11936. returnValue = app->getApplicationReturnValue();
  11937. appInstance = 0;
  11938. delete app;
  11939. }
  11940. JUCE_CATCH_ALL_ASSERT
  11941. if (useMaximumForce)
  11942. {
  11943. Process::terminate();
  11944. }
  11945. reentrancyCheck = false;
  11946. }
  11947. return returnValue;
  11948. }
  11949. int JUCEApplication::main (int argc, char* argv[],
  11950. JUCEApplication* const newApp)
  11951. {
  11952. juce_setCurrentExecutableFileName (String::fromUTF8 ((const uint8*) argv[0]));
  11953. String cmd;
  11954. for (int i = 1; i < argc; ++i)
  11955. cmd << String::fromUTF8 ((const uint8*) argv[i]) << T(' ');
  11956. return JUCEApplication::main (cmd, newApp);
  11957. }
  11958. void JUCEApplication::actionListenerCallback (const String& message)
  11959. {
  11960. if (message.startsWith (getApplicationName() + "/"))
  11961. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  11962. }
  11963. static bool juceInitialisedGUI = false;
  11964. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  11965. {
  11966. if (! juceInitialisedGUI)
  11967. {
  11968. juceInitialisedGUI = true;
  11969. initialiseJuce_NonGUI();
  11970. MessageManager::getInstance();
  11971. Font::initialiseDefaultFontNames();
  11972. LookAndFeel::setDefaultLookAndFeel (0);
  11973. #if JUCE_WIN32 && JUCE_DEBUG
  11974. // This section is just for catching people who mess up their project settings and
  11975. // turn RTTI off..
  11976. try
  11977. {
  11978. TextButton tb (String::empty);
  11979. Component* c = &tb;
  11980. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  11981. c = dynamic_cast <Button*> (c);
  11982. }
  11983. catch (...)
  11984. {
  11985. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  11986. // got as far as this catch statement, then why haven't you got exception catching
  11987. // turned on in the debugger???
  11988. jassertfalse
  11989. }
  11990. #endif
  11991. }
  11992. }
  11993. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  11994. {
  11995. if (juceInitialisedGUI)
  11996. {
  11997. DeletedAtShutdown::deleteAll();
  11998. LookAndFeel::clearDefaultLookAndFeel();
  11999. shutdownJuce_NonGUI();
  12000. juceInitialisedGUI = false;
  12001. }
  12002. }
  12003. END_JUCE_NAMESPACE
  12004. /********* End of inlined file: juce_Application.cpp *********/
  12005. /********* Start of inlined file: juce_ApplicationCommandInfo.cpp *********/
  12006. BEGIN_JUCE_NAMESPACE
  12007. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  12008. : commandID (commandID_),
  12009. flags (0)
  12010. {
  12011. }
  12012. void ApplicationCommandInfo::setInfo (const String& shortName_,
  12013. const String& description_,
  12014. const String& categoryName_,
  12015. const int flags_) throw()
  12016. {
  12017. shortName = shortName_;
  12018. description = description_;
  12019. categoryName = categoryName_;
  12020. flags = flags_;
  12021. }
  12022. void ApplicationCommandInfo::setActive (const bool b) throw()
  12023. {
  12024. if (b)
  12025. flags &= ~isDisabled;
  12026. else
  12027. flags |= isDisabled;
  12028. }
  12029. void ApplicationCommandInfo::setTicked (const bool b) throw()
  12030. {
  12031. if (b)
  12032. flags |= isTicked;
  12033. else
  12034. flags &= ~isTicked;
  12035. }
  12036. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  12037. {
  12038. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  12039. }
  12040. END_JUCE_NAMESPACE
  12041. /********* End of inlined file: juce_ApplicationCommandInfo.cpp *********/
  12042. /********* Start of inlined file: juce_ApplicationCommandManager.cpp *********/
  12043. BEGIN_JUCE_NAMESPACE
  12044. ApplicationCommandManager::ApplicationCommandManager()
  12045. : listeners (8),
  12046. firstTarget (0)
  12047. {
  12048. keyMappings = new KeyPressMappingSet (this);
  12049. Desktop::getInstance().addFocusChangeListener (this);
  12050. }
  12051. ApplicationCommandManager::~ApplicationCommandManager()
  12052. {
  12053. Desktop::getInstance().removeFocusChangeListener (this);
  12054. deleteAndZero (keyMappings);
  12055. }
  12056. void ApplicationCommandManager::clearCommands()
  12057. {
  12058. commands.clear();
  12059. keyMappings->clearAllKeyPresses();
  12060. triggerAsyncUpdate();
  12061. }
  12062. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  12063. {
  12064. // zero isn't a valid command ID!
  12065. jassert (newCommand.commandID != 0);
  12066. // the name isn't optional!
  12067. jassert (newCommand.shortName.isNotEmpty());
  12068. if (getCommandForID (newCommand.commandID) == 0)
  12069. {
  12070. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  12071. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  12072. commands.add (newInfo);
  12073. keyMappings->resetToDefaultMapping (newCommand.commandID);
  12074. triggerAsyncUpdate();
  12075. }
  12076. else
  12077. {
  12078. // trying to re-register the same command with different parameters?
  12079. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  12080. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  12081. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  12082. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  12083. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  12084. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  12085. }
  12086. }
  12087. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  12088. {
  12089. if (target != 0)
  12090. {
  12091. Array <CommandID> commandIDs;
  12092. target->getAllCommands (commandIDs);
  12093. for (int i = 0; i < commandIDs.size(); ++i)
  12094. {
  12095. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  12096. target->getCommandInfo (info.commandID, info);
  12097. registerCommand (info);
  12098. }
  12099. }
  12100. }
  12101. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  12102. {
  12103. for (int i = commands.size(); --i >= 0;)
  12104. {
  12105. if (commands.getUnchecked (i)->commandID == commandID)
  12106. {
  12107. commands.remove (i);
  12108. triggerAsyncUpdate();
  12109. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  12110. for (int j = keys.size(); --j >= 0;)
  12111. keyMappings->removeKeyPress (keys.getReference (j));
  12112. }
  12113. }
  12114. }
  12115. void ApplicationCommandManager::commandStatusChanged()
  12116. {
  12117. triggerAsyncUpdate();
  12118. }
  12119. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  12120. {
  12121. for (int i = commands.size(); --i >= 0;)
  12122. if (commands.getUnchecked(i)->commandID == commandID)
  12123. return commands.getUnchecked(i);
  12124. return 0;
  12125. }
  12126. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  12127. {
  12128. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  12129. return (ci != 0) ? ci->shortName : String::empty;
  12130. }
  12131. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  12132. {
  12133. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  12134. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  12135. : String::empty;
  12136. }
  12137. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  12138. {
  12139. StringArray s;
  12140. for (int i = 0; i < commands.size(); ++i)
  12141. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  12142. return s;
  12143. }
  12144. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  12145. {
  12146. Array <CommandID> results (4);
  12147. for (int i = 0; i < commands.size(); ++i)
  12148. if (commands.getUnchecked(i)->categoryName == categoryName)
  12149. results.add (commands.getUnchecked(i)->commandID);
  12150. return results;
  12151. }
  12152. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  12153. {
  12154. ApplicationCommandTarget::InvocationInfo info (commandID);
  12155. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  12156. return invoke (info, asynchronously);
  12157. }
  12158. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  12159. {
  12160. // This call isn't thread-safe for use from a non-UI thread without locking the message
  12161. // manager first..
  12162. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  12163. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  12164. if (target == 0)
  12165. return false;
  12166. ApplicationCommandInfo commandInfo (0);
  12167. target->getCommandInfo (info_.commandID, commandInfo);
  12168. ApplicationCommandTarget::InvocationInfo info (info_);
  12169. info.commandFlags = commandInfo.flags;
  12170. sendListenerInvokeCallback (info);
  12171. const bool ok = target->invoke (info, asynchronously);
  12172. commandStatusChanged();
  12173. return ok;
  12174. }
  12175. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  12176. {
  12177. return firstTarget != 0 ? firstTarget
  12178. : findDefaultComponentTarget();
  12179. }
  12180. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  12181. {
  12182. firstTarget = newTarget;
  12183. }
  12184. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  12185. ApplicationCommandInfo& upToDateInfo)
  12186. {
  12187. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  12188. if (target == 0)
  12189. target = JUCEApplication::getInstance();
  12190. if (target != 0)
  12191. target = target->getTargetForCommand (commandID);
  12192. if (target != 0)
  12193. target->getCommandInfo (commandID, upToDateInfo);
  12194. return target;
  12195. }
  12196. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  12197. {
  12198. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  12199. if (target == 0 && c != 0)
  12200. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  12201. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  12202. return target;
  12203. }
  12204. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  12205. {
  12206. Component* c = Component::getCurrentlyFocusedComponent();
  12207. if (c == 0)
  12208. {
  12209. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  12210. if (activeWindow != 0)
  12211. {
  12212. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  12213. if (c == 0)
  12214. c = activeWindow;
  12215. }
  12216. }
  12217. if (c == 0)
  12218. {
  12219. // getting a bit desperate now - try all desktop comps..
  12220. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  12221. {
  12222. ApplicationCommandTarget* const target
  12223. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  12224. ->getPeer()->getLastFocusedSubcomponent());
  12225. if (target != 0)
  12226. return target;
  12227. }
  12228. }
  12229. if (c != 0)
  12230. {
  12231. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  12232. // if we're focused on a ResizableWindow, chances are that it's the content
  12233. // component that really should get the event. And if not, the event will
  12234. // still be passed up to the top level window anyway, so let's send it to the
  12235. // content comp.
  12236. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  12237. c = resizableWindow->getContentComponent();
  12238. ApplicationCommandTarget* const target = findTargetForComponent (c);
  12239. if (target != 0)
  12240. return target;
  12241. }
  12242. return JUCEApplication::getInstance();
  12243. }
  12244. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  12245. {
  12246. jassert (listener != 0);
  12247. if (listener != 0)
  12248. listeners.add (listener);
  12249. }
  12250. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  12251. {
  12252. listeners.removeValue (listener);
  12253. }
  12254. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const
  12255. {
  12256. for (int i = listeners.size(); --i >= 0;)
  12257. {
  12258. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandInvoked (info);
  12259. i = jmin (i, listeners.size());
  12260. }
  12261. }
  12262. void ApplicationCommandManager::handleAsyncUpdate()
  12263. {
  12264. for (int i = listeners.size(); --i >= 0;)
  12265. {
  12266. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandListChanged();
  12267. i = jmin (i, listeners.size());
  12268. }
  12269. }
  12270. void ApplicationCommandManager::globalFocusChanged (Component*)
  12271. {
  12272. commandStatusChanged();
  12273. }
  12274. END_JUCE_NAMESPACE
  12275. /********* End of inlined file: juce_ApplicationCommandManager.cpp *********/
  12276. /********* Start of inlined file: juce_ApplicationCommandTarget.cpp *********/
  12277. BEGIN_JUCE_NAMESPACE
  12278. ApplicationCommandTarget::ApplicationCommandTarget()
  12279. : messageInvoker (0)
  12280. {
  12281. }
  12282. ApplicationCommandTarget::~ApplicationCommandTarget()
  12283. {
  12284. deleteAndZero (messageInvoker);
  12285. }
  12286. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  12287. {
  12288. if (isCommandActive (info.commandID))
  12289. {
  12290. if (async)
  12291. {
  12292. if (messageInvoker == 0)
  12293. messageInvoker = new CommandTargetMessageInvoker (this);
  12294. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  12295. return true;
  12296. }
  12297. else
  12298. {
  12299. const bool success = perform (info);
  12300. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  12301. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  12302. // returns the command's info.
  12303. return success;
  12304. }
  12305. }
  12306. return false;
  12307. }
  12308. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  12309. {
  12310. Component* c = dynamic_cast <Component*> (this);
  12311. if (c != 0)
  12312. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  12313. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  12314. return 0;
  12315. }
  12316. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  12317. {
  12318. ApplicationCommandTarget* target = this;
  12319. int depth = 0;
  12320. while (target != 0)
  12321. {
  12322. Array <CommandID> commandIDs;
  12323. target->getAllCommands (commandIDs);
  12324. if (commandIDs.contains (commandID))
  12325. return target;
  12326. target = target->getNextCommandTarget();
  12327. ++depth;
  12328. jassert (depth < 100); // could be a recursive command chain??
  12329. jassert (target != this); // definitely a recursive command chain!
  12330. if (depth > 100 || target == this)
  12331. break;
  12332. }
  12333. if (target == 0)
  12334. {
  12335. target = JUCEApplication::getInstance();
  12336. if (target != 0)
  12337. {
  12338. Array <CommandID> commandIDs;
  12339. target->getAllCommands (commandIDs);
  12340. if (commandIDs.contains (commandID))
  12341. return target;
  12342. }
  12343. }
  12344. return 0;
  12345. }
  12346. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  12347. {
  12348. ApplicationCommandInfo info (commandID);
  12349. info.flags = ApplicationCommandInfo::isDisabled;
  12350. getCommandInfo (commandID, info);
  12351. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  12352. }
  12353. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  12354. {
  12355. ApplicationCommandTarget* target = this;
  12356. int depth = 0;
  12357. while (target != 0)
  12358. {
  12359. if (target->tryToInvoke (info, async))
  12360. return true;
  12361. target = target->getNextCommandTarget();
  12362. ++depth;
  12363. jassert (depth < 100); // could be a recursive command chain??
  12364. jassert (target != this); // definitely a recursive command chain!
  12365. if (depth > 100 || target == this)
  12366. break;
  12367. }
  12368. if (target == 0)
  12369. {
  12370. target = JUCEApplication::getInstance();
  12371. if (target != 0)
  12372. return target->tryToInvoke (info, async);
  12373. }
  12374. return false;
  12375. }
  12376. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  12377. {
  12378. ApplicationCommandTarget::InvocationInfo info (commandID);
  12379. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  12380. return invoke (info, asynchronously);
  12381. }
  12382. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  12383. : commandID (commandID_),
  12384. commandFlags (0),
  12385. invocationMethod (direct),
  12386. originatingComponent (0),
  12387. isKeyDown (false),
  12388. millisecsSinceKeyPressed (0)
  12389. {
  12390. }
  12391. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  12392. : owner (owner_)
  12393. {
  12394. }
  12395. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  12396. {
  12397. }
  12398. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  12399. {
  12400. InvocationInfo* const info = (InvocationInfo*) message.pointerParameter;
  12401. owner->tryToInvoke (*info, false);
  12402. delete info;
  12403. }
  12404. END_JUCE_NAMESPACE
  12405. /********* End of inlined file: juce_ApplicationCommandTarget.cpp *********/
  12406. /********* Start of inlined file: juce_ApplicationProperties.cpp *********/
  12407. BEGIN_JUCE_NAMESPACE
  12408. juce_ImplementSingleton (ApplicationProperties)
  12409. ApplicationProperties::ApplicationProperties() throw()
  12410. : userProps (0),
  12411. commonProps (0),
  12412. msBeforeSaving (3000),
  12413. options (PropertiesFile::storeAsBinary),
  12414. commonSettingsAreReadOnly (0)
  12415. {
  12416. }
  12417. ApplicationProperties::~ApplicationProperties()
  12418. {
  12419. closeFiles();
  12420. clearSingletonInstance();
  12421. }
  12422. void ApplicationProperties::setStorageParameters (const String& applicationName,
  12423. const String& fileNameSuffix,
  12424. const String& folderName_,
  12425. const int millisecondsBeforeSaving,
  12426. const int propertiesFileOptions) throw()
  12427. {
  12428. appName = applicationName;
  12429. fileSuffix = fileNameSuffix;
  12430. folderName = folderName_;
  12431. msBeforeSaving = millisecondsBeforeSaving;
  12432. options = propertiesFileOptions;
  12433. }
  12434. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  12435. const bool testCommonSettings,
  12436. const bool showWarningDialogOnFailure)
  12437. {
  12438. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  12439. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  12440. if (! (userOk && commonOk))
  12441. {
  12442. if (showWarningDialogOnFailure)
  12443. {
  12444. String filenames;
  12445. if (userProps != 0 && ! userOk)
  12446. filenames << '\n' << userProps->getFile().getFullPathName();
  12447. if (commonProps != 0 && ! commonOk)
  12448. filenames << '\n' << commonProps->getFile().getFullPathName();
  12449. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  12450. appName + TRANS(" - Unable to save settings"),
  12451. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  12452. + appName + TRANS(" needs to be able to write to the following files:\n")
  12453. + filenames
  12454. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  12455. }
  12456. return false;
  12457. }
  12458. return true;
  12459. }
  12460. void ApplicationProperties::openFiles() throw()
  12461. {
  12462. // You need to call setStorageParameters() before trying to get hold of the
  12463. // properties!
  12464. jassert (appName.isNotEmpty());
  12465. if (appName.isNotEmpty())
  12466. {
  12467. if (userProps == 0)
  12468. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  12469. false, msBeforeSaving, options);
  12470. if (commonProps == 0)
  12471. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  12472. true, msBeforeSaving, options);
  12473. userProps->setFallbackPropertySet (commonProps);
  12474. }
  12475. }
  12476. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  12477. {
  12478. if (userProps == 0)
  12479. openFiles();
  12480. return userProps;
  12481. }
  12482. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  12483. {
  12484. if (commonProps == 0)
  12485. openFiles();
  12486. if (returnUserPropsIfReadOnly)
  12487. {
  12488. if (commonSettingsAreReadOnly == 0)
  12489. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  12490. if (commonSettingsAreReadOnly > 0)
  12491. return userProps;
  12492. }
  12493. return commonProps;
  12494. }
  12495. bool ApplicationProperties::saveIfNeeded()
  12496. {
  12497. return (userProps == 0 || userProps->saveIfNeeded())
  12498. && (commonProps == 0 || commonProps->saveIfNeeded());
  12499. }
  12500. void ApplicationProperties::closeFiles()
  12501. {
  12502. deleteAndZero (userProps);
  12503. deleteAndZero (commonProps);
  12504. }
  12505. END_JUCE_NAMESPACE
  12506. /********* End of inlined file: juce_ApplicationProperties.cpp *********/
  12507. /********* Start of inlined file: juce_DeletedAtShutdown.cpp *********/
  12508. BEGIN_JUCE_NAMESPACE
  12509. static VoidArray objectsToDelete (16);
  12510. static CriticalSection lock;
  12511. DeletedAtShutdown::DeletedAtShutdown() throw()
  12512. {
  12513. const ScopedLock sl (lock);
  12514. objectsToDelete.add (this);
  12515. }
  12516. DeletedAtShutdown::~DeletedAtShutdown()
  12517. {
  12518. const ScopedLock sl (lock);
  12519. objectsToDelete.removeValue (this);
  12520. }
  12521. void DeletedAtShutdown::deleteAll()
  12522. {
  12523. // make a local copy of the array, so it can't get into a loop if something
  12524. // creates another DeletedAtShutdown object during its destructor.
  12525. lock.enter();
  12526. const VoidArray localCopy (objectsToDelete);
  12527. lock.exit();
  12528. for (int i = localCopy.size(); --i >= 0;)
  12529. {
  12530. JUCE_TRY
  12531. {
  12532. DeletedAtShutdown* const deletee = (DeletedAtShutdown*) localCopy.getUnchecked(i);
  12533. // double-check that it's not already been deleted during another object's destructor.
  12534. lock.enter();
  12535. const bool okToDelete = objectsToDelete.contains (deletee);
  12536. lock.exit();
  12537. if (okToDelete)
  12538. delete deletee;
  12539. }
  12540. JUCE_CATCH_EXCEPTION
  12541. }
  12542. // if no objects got re-created during shutdown, this should have been emptied by their
  12543. // destructors
  12544. jassert (objectsToDelete.size() == 0);
  12545. objectsToDelete.clear(); // just to make sure the array doesn't have any memory still allocated
  12546. }
  12547. END_JUCE_NAMESPACE
  12548. /********* End of inlined file: juce_DeletedAtShutdown.cpp *********/
  12549. /********* Start of inlined file: juce_PropertiesFile.cpp *********/
  12550. BEGIN_JUCE_NAMESPACE
  12551. static const int propFileMagicNumber = ((int) littleEndianInt ("PROP"));
  12552. static const int propFileMagicNumberCompressed = ((int) littleEndianInt ("CPRP"));
  12553. static const tchar* const propertyFileXmlTag = T("PROPERTIES");
  12554. static const tchar* const propertyTagName = T("VALUE");
  12555. PropertiesFile::PropertiesFile (const File& f,
  12556. const int millisecondsBeforeSaving,
  12557. const int options_) throw()
  12558. : PropertySet (ignoreCaseOfKeyNames),
  12559. file (f),
  12560. timerInterval (millisecondsBeforeSaving),
  12561. options (options_),
  12562. needsWriting (false)
  12563. {
  12564. // You need to correctly specify just one storage format for the file
  12565. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  12566. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  12567. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  12568. InputStream* fileStream = f.createInputStream();
  12569. if (fileStream != 0)
  12570. {
  12571. int magicNumber = fileStream->readInt();
  12572. if (magicNumber == propFileMagicNumberCompressed)
  12573. {
  12574. fileStream = new SubregionStream (fileStream, 4, -1, true);
  12575. fileStream = new GZIPDecompressorInputStream (fileStream, true);
  12576. magicNumber = propFileMagicNumber;
  12577. }
  12578. if (magicNumber == propFileMagicNumber)
  12579. {
  12580. BufferedInputStream in (fileStream, 2048, true);
  12581. int numValues = in.readInt();
  12582. while (--numValues >= 0 && ! in.isExhausted())
  12583. {
  12584. const String key (in.readString());
  12585. const String value (in.readString());
  12586. jassert (key.isNotEmpty());
  12587. if (key.isNotEmpty())
  12588. getAllProperties().set (key, value);
  12589. }
  12590. }
  12591. else
  12592. {
  12593. // Not a binary props file - let's see if it's XML..
  12594. delete fileStream;
  12595. XmlDocument parser (f);
  12596. XmlElement* doc = parser.getDocumentElement (true);
  12597. if (doc != 0 && doc->hasTagName (propertyFileXmlTag))
  12598. {
  12599. delete doc;
  12600. doc = parser.getDocumentElement();
  12601. if (doc != 0)
  12602. {
  12603. forEachXmlChildElementWithTagName (*doc, e, propertyTagName)
  12604. {
  12605. const String name (e->getStringAttribute (T("name")));
  12606. if (name.isNotEmpty())
  12607. {
  12608. getAllProperties().set (name,
  12609. e->getFirstChildElement() != 0
  12610. ? e->getFirstChildElement()->createDocument (String::empty, true)
  12611. : e->getStringAttribute (T("val")));
  12612. }
  12613. }
  12614. }
  12615. else
  12616. {
  12617. // must be a pretty broken XML file we're trying to parse here!
  12618. jassertfalse
  12619. }
  12620. delete doc;
  12621. }
  12622. }
  12623. }
  12624. }
  12625. PropertiesFile::~PropertiesFile()
  12626. {
  12627. saveIfNeeded();
  12628. }
  12629. bool PropertiesFile::saveIfNeeded()
  12630. {
  12631. const ScopedLock sl (getLock());
  12632. return (! needsWriting) || save();
  12633. }
  12634. bool PropertiesFile::needsToBeSaved() const throw()
  12635. {
  12636. const ScopedLock sl (getLock());
  12637. return needsWriting;
  12638. }
  12639. bool PropertiesFile::save()
  12640. {
  12641. const ScopedLock sl (getLock());
  12642. stopTimer();
  12643. if (file == File::nonexistent
  12644. || file.isDirectory()
  12645. || ! file.getParentDirectory().createDirectory())
  12646. return false;
  12647. if ((options & storeAsXML) != 0)
  12648. {
  12649. XmlElement* const doc = new XmlElement (propertyFileXmlTag);
  12650. for (int i = 0; i < getAllProperties().size(); ++i)
  12651. {
  12652. XmlElement* const e = new XmlElement (propertyTagName);
  12653. e->setAttribute (T("name"), getAllProperties().getAllKeys() [i]);
  12654. // if the value seems to contain xml, store it as such..
  12655. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  12656. XmlElement* const childElement = xmlContent.getDocumentElement();
  12657. if (childElement != 0)
  12658. e->addChildElement (childElement);
  12659. else
  12660. e->setAttribute (T("val"), getAllProperties().getAllValues() [i]);
  12661. doc->addChildElement (e);
  12662. }
  12663. const bool ok = doc->writeToFile (file, String::empty);
  12664. delete doc;
  12665. return ok;
  12666. }
  12667. else
  12668. {
  12669. const File tempFile (file.getNonexistentSibling (false));
  12670. OutputStream* out = tempFile.createOutputStream();
  12671. if (out != 0)
  12672. {
  12673. if ((options & storeAsCompressedBinary) != 0)
  12674. {
  12675. out->writeInt (propFileMagicNumberCompressed);
  12676. out->flush();
  12677. out = new GZIPCompressorOutputStream (out, 9, true);
  12678. }
  12679. else
  12680. {
  12681. // have you set up the storage option flags correctly?
  12682. jassert ((options & storeAsBinary) != 0);
  12683. out->writeInt (propFileMagicNumber);
  12684. }
  12685. const int numProperties = getAllProperties().size();
  12686. out->writeInt (numProperties);
  12687. for (int i = 0; i < numProperties; ++i)
  12688. {
  12689. out->writeString (getAllProperties().getAllKeys() [i]);
  12690. out->writeString (getAllProperties().getAllValues() [i]);
  12691. }
  12692. out->flush();
  12693. delete out;
  12694. if (tempFile.moveFileTo (file))
  12695. {
  12696. needsWriting = false;
  12697. return true;
  12698. }
  12699. tempFile.deleteFile();
  12700. }
  12701. }
  12702. return false;
  12703. }
  12704. void PropertiesFile::timerCallback()
  12705. {
  12706. saveIfNeeded();
  12707. }
  12708. void PropertiesFile::propertyChanged()
  12709. {
  12710. sendChangeMessage (this);
  12711. needsWriting = true;
  12712. if (timerInterval > 0)
  12713. startTimer (timerInterval);
  12714. else if (timerInterval == 0)
  12715. saveIfNeeded();
  12716. }
  12717. const File PropertiesFile::getFile() const throw()
  12718. {
  12719. return file;
  12720. }
  12721. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  12722. const String& fileNameSuffix,
  12723. const String& folderName,
  12724. const bool commonToAllUsers)
  12725. {
  12726. // mustn't have illegal characters in this name..
  12727. jassert (applicationName == File::createLegalFileName (applicationName));
  12728. #if JUCE_MAC
  12729. File dir (commonToAllUsers ? "/Library/Preferences"
  12730. : "~/Library/Preferences");
  12731. if (folderName.isNotEmpty())
  12732. dir = dir.getChildFile (folderName);
  12733. #endif
  12734. #ifdef JUCE_LINUX
  12735. const File dir ((commonToAllUsers ? T("/var/") : T("~/"))
  12736. + (folderName.isNotEmpty() ? folderName
  12737. : (T(".") + applicationName)));
  12738. #endif
  12739. #if JUCE_WIN32
  12740. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  12741. : File::userApplicationDataDirectory));
  12742. if (dir == File::nonexistent)
  12743. return File::nonexistent;
  12744. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  12745. : applicationName);
  12746. #endif
  12747. return dir.getChildFile (applicationName)
  12748. .withFileExtension (fileNameSuffix);
  12749. }
  12750. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  12751. const String& fileNameSuffix,
  12752. const String& folderName,
  12753. const bool commonToAllUsers,
  12754. const int millisecondsBeforeSaving,
  12755. const int propertiesFileOptions)
  12756. {
  12757. const File file (getDefaultAppSettingsFile (applicationName,
  12758. fileNameSuffix,
  12759. folderName,
  12760. commonToAllUsers));
  12761. jassert (file != File::nonexistent);
  12762. if (file == File::nonexistent)
  12763. return 0;
  12764. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions);
  12765. }
  12766. END_JUCE_NAMESPACE
  12767. /********* End of inlined file: juce_PropertiesFile.cpp *********/
  12768. /********* Start of inlined file: juce_AiffAudioFormat.cpp *********/
  12769. BEGIN_JUCE_NAMESPACE
  12770. #undef chunkName
  12771. #define chunkName(a) (int)littleEndianInt(a)
  12772. #define aiffFormatName TRANS("AIFF file")
  12773. static const tchar* const aiffExtensions[] = { T(".aiff"), T(".aif"), 0 };
  12774. class AiffAudioFormatReader : public AudioFormatReader
  12775. {
  12776. public:
  12777. int bytesPerFrame;
  12778. int64 dataChunkStart;
  12779. bool littleEndian;
  12780. AiffAudioFormatReader (InputStream* in)
  12781. : AudioFormatReader (in, aiffFormatName)
  12782. {
  12783. if (input->readInt() == chunkName ("FORM"))
  12784. {
  12785. const int len = input->readIntBigEndian();
  12786. const int64 end = input->getPosition() + len;
  12787. const int nextType = input->readInt();
  12788. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  12789. {
  12790. bool hasGotVer = false;
  12791. bool hasGotData = false;
  12792. bool hasGotType = false;
  12793. while (input->getPosition() < end)
  12794. {
  12795. const int type = input->readInt();
  12796. const uint32 length = (uint32) input->readIntBigEndian();
  12797. const int64 chunkEnd = input->getPosition() + length;
  12798. if (type == chunkName ("FVER"))
  12799. {
  12800. hasGotVer = true;
  12801. const int ver = input->readIntBigEndian();
  12802. if (ver != 0 && ver != (int)0xa2805140)
  12803. break;
  12804. }
  12805. else if (type == chunkName ("COMM"))
  12806. {
  12807. hasGotType = true;
  12808. numChannels = (unsigned int)input->readShortBigEndian();
  12809. lengthInSamples = input->readIntBigEndian();
  12810. bitsPerSample = input->readShortBigEndian();
  12811. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  12812. unsigned char sampleRateBytes[10];
  12813. input->read (sampleRateBytes, 10);
  12814. const int byte0 = sampleRateBytes[0];
  12815. if ((byte0 & 0x80) != 0
  12816. || byte0 <= 0x3F || byte0 > 0x40
  12817. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  12818. break;
  12819. unsigned int sampRate = bigEndianInt ((char*) sampleRateBytes + 2);
  12820. sampRate >>= (16414 - bigEndianShort ((char*) sampleRateBytes));
  12821. sampleRate = (int)sampRate;
  12822. if (length <= 18)
  12823. {
  12824. // some types don't have a chunk large enough to include a compression
  12825. // type, so assume it's just big-endian pcm
  12826. littleEndian = false;
  12827. }
  12828. else
  12829. {
  12830. const int compType = input->readInt();
  12831. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  12832. {
  12833. littleEndian = false;
  12834. }
  12835. else if (compType == chunkName ("sowt"))
  12836. {
  12837. littleEndian = true;
  12838. }
  12839. else
  12840. {
  12841. sampleRate = 0;
  12842. break;
  12843. }
  12844. }
  12845. }
  12846. else if (type == chunkName ("SSND"))
  12847. {
  12848. hasGotData = true;
  12849. const int offset = input->readIntBigEndian();
  12850. dataChunkStart = input->getPosition() + 4 + offset;
  12851. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  12852. }
  12853. else if ((hasGotVer && hasGotData && hasGotType)
  12854. || chunkEnd < input->getPosition()
  12855. || input->isExhausted())
  12856. {
  12857. break;
  12858. }
  12859. input->setPosition (chunkEnd);
  12860. }
  12861. }
  12862. }
  12863. }
  12864. ~AiffAudioFormatReader()
  12865. {
  12866. }
  12867. bool read (int** destSamples,
  12868. int64 startSampleInFile,
  12869. int numSamples)
  12870. {
  12871. int64 start = startSampleInFile;
  12872. int startOffsetInDestBuffer = 0;
  12873. if (startSampleInFile < 0)
  12874. {
  12875. const int silence = (int) jmin (-startSampleInFile, (int64) numSamples);
  12876. int** destChan = destSamples;
  12877. for (int i = 2; --i >= 0;)
  12878. {
  12879. if (*destChan != 0)
  12880. {
  12881. zeromem (*destChan, sizeof (int) * silence);
  12882. ++destChan;
  12883. }
  12884. }
  12885. startOffsetInDestBuffer += silence;
  12886. numSamples -= silence;
  12887. start = 0;
  12888. }
  12889. int numToDo = jlimit (0, numSamples, (int) (lengthInSamples - start));
  12890. if (numToDo > 0)
  12891. {
  12892. input->setPosition (dataChunkStart + start * bytesPerFrame);
  12893. int num = numToDo;
  12894. int* left = destSamples[0];
  12895. if (left != 0)
  12896. left += startOffsetInDestBuffer;
  12897. int* right = destSamples[1];
  12898. if (right != 0)
  12899. right += startOffsetInDestBuffer;
  12900. // (keep this a multiple of 3)
  12901. const int tempBufSize = 1440 * 4;
  12902. char tempBuffer [tempBufSize];
  12903. while (num > 0)
  12904. {
  12905. const int numThisTime = jmin (tempBufSize / bytesPerFrame, num);
  12906. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  12907. if (bytesRead < numThisTime * bytesPerFrame)
  12908. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  12909. if (bitsPerSample == 16)
  12910. {
  12911. if (littleEndian)
  12912. {
  12913. const short* src = (const short*) tempBuffer;
  12914. if (numChannels > 1)
  12915. {
  12916. if (left == 0)
  12917. {
  12918. for (int i = numThisTime; --i >= 0;)
  12919. {
  12920. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12921. ++src;
  12922. }
  12923. }
  12924. else if (right == 0)
  12925. {
  12926. for (int i = numThisTime; --i >= 0;)
  12927. {
  12928. ++src;
  12929. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12930. }
  12931. }
  12932. else
  12933. {
  12934. for (int i = numThisTime; --i >= 0;)
  12935. {
  12936. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12937. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12938. }
  12939. }
  12940. }
  12941. else
  12942. {
  12943. for (int i = numThisTime; --i >= 0;)
  12944. {
  12945. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12946. }
  12947. }
  12948. }
  12949. else
  12950. {
  12951. const char* src = (const char*) tempBuffer;
  12952. if (numChannels > 1)
  12953. {
  12954. if (left == 0)
  12955. {
  12956. for (int i = numThisTime; --i >= 0;)
  12957. {
  12958. *right++ = bigEndianShort (src) << 16;
  12959. src += 4;
  12960. }
  12961. }
  12962. else if (right == 0)
  12963. {
  12964. for (int i = numThisTime; --i >= 0;)
  12965. {
  12966. src += 2;
  12967. *left++ = bigEndianShort (src) << 16;
  12968. src += 2;
  12969. }
  12970. }
  12971. else
  12972. {
  12973. for (int i = numThisTime; --i >= 0;)
  12974. {
  12975. *left++ = bigEndianShort (src) << 16;
  12976. src += 2;
  12977. *right++ = bigEndianShort (src) << 16;
  12978. src += 2;
  12979. }
  12980. }
  12981. }
  12982. else
  12983. {
  12984. for (int i = numThisTime; --i >= 0;)
  12985. {
  12986. *left++ = bigEndianShort (src) << 16;
  12987. src += 2;
  12988. }
  12989. }
  12990. }
  12991. }
  12992. else if (bitsPerSample == 24)
  12993. {
  12994. const char* src = (const char*)tempBuffer;
  12995. if (littleEndian)
  12996. {
  12997. if (numChannels > 1)
  12998. {
  12999. if (left == 0)
  13000. {
  13001. for (int i = numThisTime; --i >= 0;)
  13002. {
  13003. *right++ = littleEndian24Bit (src) << 8;
  13004. src += 6;
  13005. }
  13006. }
  13007. else if (right == 0)
  13008. {
  13009. for (int i = numThisTime; --i >= 0;)
  13010. {
  13011. src += 3;
  13012. *left++ = littleEndian24Bit (src) << 8;
  13013. src += 3;
  13014. }
  13015. }
  13016. else
  13017. {
  13018. for (int i = numThisTime; --i >= 0;)
  13019. {
  13020. *left++ = littleEndian24Bit (src) << 8;
  13021. src += 3;
  13022. *right++ = littleEndian24Bit (src) << 8;
  13023. src += 3;
  13024. }
  13025. }
  13026. }
  13027. else
  13028. {
  13029. for (int i = numThisTime; --i >= 0;)
  13030. {
  13031. *left++ = littleEndian24Bit (src) << 8;
  13032. src += 3;
  13033. }
  13034. }
  13035. }
  13036. else
  13037. {
  13038. if (numChannels > 1)
  13039. {
  13040. if (left == 0)
  13041. {
  13042. for (int i = numThisTime; --i >= 0;)
  13043. {
  13044. *right++ = bigEndian24Bit (src) << 8;
  13045. src += 6;
  13046. }
  13047. }
  13048. else if (right == 0)
  13049. {
  13050. for (int i = numThisTime; --i >= 0;)
  13051. {
  13052. src += 3;
  13053. *left++ = bigEndian24Bit (src) << 8;
  13054. src += 3;
  13055. }
  13056. }
  13057. else
  13058. {
  13059. for (int i = numThisTime; --i >= 0;)
  13060. {
  13061. *left++ = bigEndian24Bit (src) << 8;
  13062. src += 3;
  13063. *right++ = bigEndian24Bit (src) << 8;
  13064. src += 3;
  13065. }
  13066. }
  13067. }
  13068. else
  13069. {
  13070. for (int i = numThisTime; --i >= 0;)
  13071. {
  13072. *left++ = bigEndian24Bit (src) << 8;
  13073. src += 3;
  13074. }
  13075. }
  13076. }
  13077. }
  13078. else if (bitsPerSample == 32)
  13079. {
  13080. const unsigned int* src = (const unsigned int*) tempBuffer;
  13081. unsigned int* l = (unsigned int*) left;
  13082. unsigned int* r = (unsigned int*) right;
  13083. if (littleEndian)
  13084. {
  13085. if (numChannels > 1)
  13086. {
  13087. if (l == 0)
  13088. {
  13089. for (int i = numThisTime; --i >= 0;)
  13090. {
  13091. ++src;
  13092. *r++ = swapIfBigEndian (*src++);
  13093. }
  13094. }
  13095. else if (r == 0)
  13096. {
  13097. for (int i = numThisTime; --i >= 0;)
  13098. {
  13099. *l++ = swapIfBigEndian (*src++);
  13100. ++src;
  13101. }
  13102. }
  13103. else
  13104. {
  13105. for (int i = numThisTime; --i >= 0;)
  13106. {
  13107. *l++ = swapIfBigEndian (*src++);
  13108. *r++ = swapIfBigEndian (*src++);
  13109. }
  13110. }
  13111. }
  13112. else
  13113. {
  13114. for (int i = numThisTime; --i >= 0;)
  13115. {
  13116. *l++ = swapIfBigEndian (*src++);
  13117. }
  13118. }
  13119. }
  13120. else
  13121. {
  13122. if (numChannels > 1)
  13123. {
  13124. if (l == 0)
  13125. {
  13126. for (int i = numThisTime; --i >= 0;)
  13127. {
  13128. ++src;
  13129. *r++ = swapIfLittleEndian (*src++);
  13130. }
  13131. }
  13132. else if (r == 0)
  13133. {
  13134. for (int i = numThisTime; --i >= 0;)
  13135. {
  13136. *l++ = swapIfLittleEndian (*src++);
  13137. ++src;
  13138. }
  13139. }
  13140. else
  13141. {
  13142. for (int i = numThisTime; --i >= 0;)
  13143. {
  13144. *l++ = swapIfLittleEndian (*src++);
  13145. *r++ = swapIfLittleEndian (*src++);
  13146. }
  13147. }
  13148. }
  13149. else
  13150. {
  13151. for (int i = numThisTime; --i >= 0;)
  13152. {
  13153. *l++ = swapIfLittleEndian (*src++);
  13154. }
  13155. }
  13156. }
  13157. left = (int*) l;
  13158. right = (int*) r;
  13159. }
  13160. else if (bitsPerSample == 8)
  13161. {
  13162. const char* src = (const char*) tempBuffer;
  13163. if (numChannels > 1)
  13164. {
  13165. if (left == 0)
  13166. {
  13167. for (int i = numThisTime; --i >= 0;)
  13168. {
  13169. *right++ = ((int) *src++) << 24;
  13170. ++src;
  13171. }
  13172. }
  13173. else if (right == 0)
  13174. {
  13175. for (int i = numThisTime; --i >= 0;)
  13176. {
  13177. ++src;
  13178. *left++ = ((int) *src++) << 24;
  13179. }
  13180. }
  13181. else
  13182. {
  13183. for (int i = numThisTime; --i >= 0;)
  13184. {
  13185. *left++ = ((int) *src++) << 24;
  13186. *right++ = ((int) *src++) << 24;
  13187. }
  13188. }
  13189. }
  13190. else
  13191. {
  13192. for (int i = numThisTime; --i >= 0;)
  13193. {
  13194. *left++ = ((int) *src++) << 24;
  13195. }
  13196. }
  13197. }
  13198. num -= numThisTime;
  13199. }
  13200. }
  13201. if (numToDo < numSamples)
  13202. {
  13203. int** destChan = destSamples;
  13204. while (*destChan != 0)
  13205. {
  13206. zeromem ((*destChan) + (startOffsetInDestBuffer + numToDo),
  13207. sizeof (int) * (numSamples - numToDo));
  13208. ++destChan;
  13209. }
  13210. }
  13211. return true;
  13212. }
  13213. juce_UseDebuggingNewOperator
  13214. private:
  13215. AiffAudioFormatReader (const AiffAudioFormatReader&);
  13216. const AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  13217. };
  13218. class AiffAudioFormatWriter : public AudioFormatWriter
  13219. {
  13220. MemoryBlock tempBlock;
  13221. uint32 lengthInSamples, bytesWritten;
  13222. int64 headerPosition;
  13223. bool writeFailed;
  13224. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  13225. const AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  13226. void writeHeader()
  13227. {
  13228. const bool couldSeekOk = output->setPosition (headerPosition);
  13229. (void) couldSeekOk;
  13230. // if this fails, you've given it an output stream that can't seek! It needs
  13231. // to be able to seek back to write the header
  13232. jassert (couldSeekOk);
  13233. const int headerLen = 54;
  13234. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  13235. audioBytes += (audioBytes & 1);
  13236. output->writeInt (chunkName ("FORM"));
  13237. output->writeIntBigEndian (headerLen + audioBytes - 8);
  13238. output->writeInt (chunkName ("AIFF"));
  13239. output->writeInt (chunkName ("COMM"));
  13240. output->writeIntBigEndian (18);
  13241. output->writeShortBigEndian ((short) numChannels);
  13242. output->writeIntBigEndian (lengthInSamples);
  13243. output->writeShortBigEndian ((short) bitsPerSample);
  13244. uint8 sampleRateBytes[10];
  13245. zeromem (sampleRateBytes, 10);
  13246. if (sampleRate <= 1)
  13247. {
  13248. sampleRateBytes[0] = 0x3f;
  13249. sampleRateBytes[1] = 0xff;
  13250. sampleRateBytes[2] = 0x80;
  13251. }
  13252. else
  13253. {
  13254. int mask = 0x40000000;
  13255. sampleRateBytes[0] = 0x40;
  13256. if (sampleRate >= mask)
  13257. {
  13258. jassertfalse
  13259. sampleRateBytes[1] = 0x1d;
  13260. }
  13261. else
  13262. {
  13263. int n = (int) sampleRate;
  13264. int i;
  13265. for (i = 0; i <= 32 ; ++i)
  13266. {
  13267. if ((n & mask) != 0)
  13268. break;
  13269. mask >>= 1;
  13270. }
  13271. n = n << (i + 1);
  13272. sampleRateBytes[1] = (uint8) (29 - i);
  13273. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  13274. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  13275. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  13276. sampleRateBytes[5] = (uint8) (n & 0xff);
  13277. }
  13278. }
  13279. output->write (sampleRateBytes, 10);
  13280. output->writeInt (chunkName ("SSND"));
  13281. output->writeIntBigEndian (audioBytes + 8);
  13282. output->writeInt (0);
  13283. output->writeInt (0);
  13284. jassert (output->getPosition() == headerLen);
  13285. }
  13286. public:
  13287. AiffAudioFormatWriter (OutputStream* out,
  13288. const double sampleRate,
  13289. const unsigned int chans,
  13290. const int bits)
  13291. : AudioFormatWriter (out,
  13292. aiffFormatName,
  13293. sampleRate,
  13294. chans,
  13295. bits),
  13296. lengthInSamples (0),
  13297. bytesWritten (0),
  13298. writeFailed (false)
  13299. {
  13300. headerPosition = out->getPosition();
  13301. writeHeader();
  13302. }
  13303. ~AiffAudioFormatWriter()
  13304. {
  13305. if ((bytesWritten & 1) != 0)
  13306. output->writeByte (0);
  13307. writeHeader();
  13308. }
  13309. bool write (const int** data, int numSamples)
  13310. {
  13311. if (writeFailed)
  13312. return false;
  13313. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  13314. tempBlock.ensureSize (bytes, false);
  13315. char* buffer = (char*) tempBlock.getData();
  13316. const int* left = data[0];
  13317. const int* right = data[1];
  13318. if (right == 0)
  13319. right = left;
  13320. if (bitsPerSample == 16)
  13321. {
  13322. short* b = (short*) buffer;
  13323. if (numChannels > 1)
  13324. {
  13325. for (int i = numSamples; --i >= 0;)
  13326. {
  13327. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  13328. *b++ = (short) swapIfLittleEndian ((unsigned short) (*right++ >> 16));
  13329. }
  13330. }
  13331. else
  13332. {
  13333. for (int i = numSamples; --i >= 0;)
  13334. {
  13335. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  13336. }
  13337. }
  13338. }
  13339. else if (bitsPerSample == 24)
  13340. {
  13341. char* b = (char*) buffer;
  13342. if (numChannels > 1)
  13343. {
  13344. for (int i = numSamples; --i >= 0;)
  13345. {
  13346. bigEndian24BitToChars (*left++ >> 8, b);
  13347. b += 3;
  13348. bigEndian24BitToChars (*right++ >> 8, b);
  13349. b += 3;
  13350. }
  13351. }
  13352. else
  13353. {
  13354. for (int i = numSamples; --i >= 0;)
  13355. {
  13356. bigEndian24BitToChars (*left++ >> 8, b);
  13357. b += 3;
  13358. }
  13359. }
  13360. }
  13361. else if (bitsPerSample == 32)
  13362. {
  13363. unsigned int* b = (unsigned int*) buffer;
  13364. if (numChannels > 1)
  13365. {
  13366. for (int i = numSamples; --i >= 0;)
  13367. {
  13368. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  13369. *b++ = swapIfLittleEndian ((unsigned int) *right++);
  13370. }
  13371. }
  13372. else
  13373. {
  13374. for (int i = numSamples; --i >= 0;)
  13375. {
  13376. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  13377. }
  13378. }
  13379. }
  13380. else if (bitsPerSample == 8)
  13381. {
  13382. char* b = (char*)buffer;
  13383. if (numChannels > 1)
  13384. {
  13385. for (int i = numSamples; --i >= 0;)
  13386. {
  13387. *b++ = (char) (*left++ >> 24);
  13388. *b++ = (char) (*right++ >> 24);
  13389. }
  13390. }
  13391. else
  13392. {
  13393. for (int i = numSamples; --i >= 0;)
  13394. {
  13395. *b++ = (char) (*left++ >> 24);
  13396. }
  13397. }
  13398. }
  13399. if (bytesWritten + bytes >= (uint32) 0xfff00000
  13400. || ! output->write (buffer, bytes))
  13401. {
  13402. // failed to write to disk, so let's try writing the header.
  13403. // If it's just run out of disk space, then if it does manage
  13404. // to write the header, we'll still have a useable file..
  13405. writeHeader();
  13406. writeFailed = true;
  13407. return false;
  13408. }
  13409. else
  13410. {
  13411. bytesWritten += bytes;
  13412. lengthInSamples += numSamples;
  13413. return true;
  13414. }
  13415. }
  13416. juce_UseDebuggingNewOperator
  13417. };
  13418. AiffAudioFormat::AiffAudioFormat()
  13419. : AudioFormat (aiffFormatName, (const tchar**) aiffExtensions)
  13420. {
  13421. }
  13422. AiffAudioFormat::~AiffAudioFormat()
  13423. {
  13424. }
  13425. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  13426. {
  13427. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  13428. return Array <int> (rates);
  13429. }
  13430. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  13431. {
  13432. const int depths[] = { 8, 16, 24, 0 };
  13433. return Array <int> (depths);
  13434. }
  13435. bool AiffAudioFormat::canDoStereo()
  13436. {
  13437. return true;
  13438. }
  13439. bool AiffAudioFormat::canDoMono()
  13440. {
  13441. return true;
  13442. }
  13443. #if JUCE_MAC
  13444. bool AiffAudioFormat::canHandleFile (const File& f)
  13445. {
  13446. if (AudioFormat::canHandleFile (f))
  13447. return true;
  13448. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  13449. return type == 'AIFF' || type == 'AIFC'
  13450. || type == 'aiff' || type == 'aifc';
  13451. }
  13452. #endif
  13453. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  13454. const bool deleteStreamIfOpeningFails)
  13455. {
  13456. AiffAudioFormatReader* w = new AiffAudioFormatReader (sourceStream);
  13457. if (w->sampleRate == 0)
  13458. {
  13459. if (! deleteStreamIfOpeningFails)
  13460. w->input = 0;
  13461. deleteAndZero (w);
  13462. }
  13463. return w;
  13464. }
  13465. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  13466. double sampleRate,
  13467. unsigned int chans,
  13468. int bitsPerSample,
  13469. const StringPairArray& /*metadataValues*/,
  13470. int /*qualityOptionIndex*/)
  13471. {
  13472. if (getPossibleBitDepths().contains (bitsPerSample))
  13473. {
  13474. return new AiffAudioFormatWriter (out,
  13475. sampleRate,
  13476. chans,
  13477. bitsPerSample);
  13478. }
  13479. return 0;
  13480. }
  13481. END_JUCE_NAMESPACE
  13482. /********* End of inlined file: juce_AiffAudioFormat.cpp *********/
  13483. /********* Start of inlined file: juce_AudioCDReader.cpp *********/
  13484. BEGIN_JUCE_NAMESPACE
  13485. #if JUCE_MAC
  13486. // Mac version doesn't need any native code because it's all done with files..
  13487. // Windows + Linux versions are in the platform-dependent code sections.
  13488. static void findCDs (OwnedArray<File>& cds)
  13489. {
  13490. File volumes ("/Volumes");
  13491. volumes.findChildFiles (cds, File::findDirectories, false);
  13492. for (int i = cds.size(); --i >= 0;)
  13493. if (! cds[i]->getChildFile (".TOC.plist").exists())
  13494. cds.remove (i);
  13495. }
  13496. const StringArray AudioCDReader::getAvailableCDNames()
  13497. {
  13498. OwnedArray<File> cds;
  13499. findCDs (cds);
  13500. StringArray names;
  13501. for (int i = 0; i < cds.size(); ++i)
  13502. names.add (cds[i]->getFileName());
  13503. return names;
  13504. }
  13505. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  13506. {
  13507. OwnedArray<File> cds;
  13508. findCDs (cds);
  13509. if (cds[index] != 0)
  13510. return new AudioCDReader (*cds[index]);
  13511. else
  13512. return 0;
  13513. }
  13514. AudioCDReader::AudioCDReader (const File& volume)
  13515. : AudioFormatReader (0, "CD Audio"),
  13516. volumeDir (volume),
  13517. currentReaderTrack (-1),
  13518. reader (0)
  13519. {
  13520. sampleRate = 44100.0;
  13521. bitsPerSample = 16;
  13522. numChannels = 2;
  13523. usesFloatingPointData = false;
  13524. refreshTrackLengths();
  13525. }
  13526. AudioCDReader::~AudioCDReader()
  13527. {
  13528. if (reader != 0)
  13529. delete reader;
  13530. }
  13531. static int getTrackNumber (const File& file)
  13532. {
  13533. return file.getFileName()
  13534. .initialSectionContainingOnly (T("0123456789"))
  13535. .getIntValue();
  13536. }
  13537. int AudioCDReader::compareElements (const File* const first, const File* const second) throw()
  13538. {
  13539. const int firstTrack = getTrackNumber (*first);
  13540. const int secondTrack = getTrackNumber (*second);
  13541. jassert (firstTrack > 0 && secondTrack > 0);
  13542. return firstTrack - secondTrack;
  13543. }
  13544. void AudioCDReader::refreshTrackLengths()
  13545. {
  13546. tracks.clear();
  13547. trackStartSamples.clear();
  13548. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, T("*.aiff"));
  13549. tracks.sort (*this);
  13550. AiffAudioFormat format;
  13551. int sample = 0;
  13552. for (int i = 0; i < tracks.size(); ++i)
  13553. {
  13554. trackStartSamples.add (sample);
  13555. FileInputStream* const in = tracks[i]->createInputStream();
  13556. if (in != 0)
  13557. {
  13558. AudioFormatReader* const r = format.createReaderFor (in, true);
  13559. if (r != 0)
  13560. {
  13561. sample += r->lengthInSamples;
  13562. delete r;
  13563. }
  13564. }
  13565. }
  13566. trackStartSamples.add (sample);
  13567. lengthInSamples = sample;
  13568. }
  13569. bool AudioCDReader::read (int** destSamples,
  13570. int64 startSampleInFile,
  13571. int numSamples)
  13572. {
  13573. while (numSamples > 0)
  13574. {
  13575. int track = -1;
  13576. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  13577. {
  13578. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  13579. {
  13580. track = i;
  13581. break;
  13582. }
  13583. }
  13584. if (track < 0)
  13585. return false;
  13586. if (track != currentReaderTrack)
  13587. {
  13588. deleteAndZero (reader);
  13589. if (tracks [track] != 0)
  13590. {
  13591. FileInputStream* const in = tracks [track]->createInputStream();
  13592. if (in != 0)
  13593. {
  13594. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  13595. AiffAudioFormat format;
  13596. reader = format.createReaderFor (bin, true);
  13597. if (reader == 0)
  13598. currentReaderTrack = -1;
  13599. else
  13600. currentReaderTrack = track;
  13601. }
  13602. }
  13603. }
  13604. if (reader == 0)
  13605. return false;
  13606. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  13607. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  13608. reader->read (destSamples, startPos, numAvailable);
  13609. numSamples -= numAvailable;
  13610. startSampleInFile += numAvailable;
  13611. }
  13612. return true;
  13613. }
  13614. bool AudioCDReader::isCDStillPresent() const
  13615. {
  13616. return volumeDir.exists();
  13617. }
  13618. int AudioCDReader::getNumTracks() const
  13619. {
  13620. return tracks.size();
  13621. }
  13622. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  13623. {
  13624. return trackStartSamples [trackNum];
  13625. }
  13626. bool AudioCDReader::isTrackAudio (int trackNum) const
  13627. {
  13628. return tracks [trackNum] != 0;
  13629. }
  13630. void AudioCDReader::enableIndexScanning (bool b)
  13631. {
  13632. // any way to do this on a Mac??
  13633. }
  13634. int AudioCDReader::getLastIndex() const
  13635. {
  13636. return 0;
  13637. }
  13638. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  13639. {
  13640. return Array <int>();
  13641. }
  13642. int AudioCDReader::getCDDBId()
  13643. {
  13644. return 0; //xxx
  13645. }
  13646. #endif
  13647. END_JUCE_NAMESPACE
  13648. /********* End of inlined file: juce_AudioCDReader.cpp *********/
  13649. /********* Start of inlined file: juce_AudioFormat.cpp *********/
  13650. BEGIN_JUCE_NAMESPACE
  13651. AudioFormatReader::AudioFormatReader (InputStream* const in,
  13652. const String& formatName_)
  13653. : sampleRate (0),
  13654. bitsPerSample (0),
  13655. lengthInSamples (0),
  13656. numChannels (0),
  13657. usesFloatingPointData (false),
  13658. input (in),
  13659. formatName (formatName_)
  13660. {
  13661. }
  13662. AudioFormatReader::~AudioFormatReader()
  13663. {
  13664. delete input;
  13665. }
  13666. static void findMaxMin (const float* src, const int num,
  13667. float& maxVal, float& minVal)
  13668. {
  13669. float mn = src[0];
  13670. float mx = mn;
  13671. for (int i = 1; i < num; ++i)
  13672. {
  13673. const float s = src[i];
  13674. if (s > mx)
  13675. mx = s;
  13676. if (s < mn)
  13677. mn = s;
  13678. }
  13679. maxVal = mx;
  13680. minVal = mn;
  13681. }
  13682. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  13683. int64 numSamples,
  13684. float& lowestLeft, float& highestLeft,
  13685. float& lowestRight, float& highestRight)
  13686. {
  13687. if (numSamples <= 0)
  13688. {
  13689. lowestLeft = 0;
  13690. lowestRight = 0;
  13691. highestLeft = 0;
  13692. highestRight = 0;
  13693. return;
  13694. }
  13695. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  13696. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  13697. int* tempBuffer[3];
  13698. tempBuffer[0] = (int*) tempSpace.getData();
  13699. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  13700. tempBuffer[2] = 0;
  13701. if (usesFloatingPointData)
  13702. {
  13703. float lmin = 1.0e6;
  13704. float lmax = -lmin;
  13705. float rmin = lmin;
  13706. float rmax = lmax;
  13707. while (numSamples > 0)
  13708. {
  13709. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  13710. read ((int**) tempBuffer, startSampleInFile, numToDo);
  13711. numSamples -= numToDo;
  13712. float bufmin, bufmax;
  13713. findMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  13714. lmin = jmin (lmin, bufmin);
  13715. lmax = jmax (lmax, bufmax);
  13716. if (numChannels > 1)
  13717. {
  13718. findMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  13719. rmin = jmin (rmin, bufmin);
  13720. rmax = jmax (rmax, bufmax);
  13721. }
  13722. }
  13723. if (numChannels <= 1)
  13724. {
  13725. rmax = lmax;
  13726. rmin = lmin;
  13727. }
  13728. lowestLeft = lmin;
  13729. highestLeft = lmax;
  13730. lowestRight = rmin;
  13731. highestRight = rmax;
  13732. }
  13733. else
  13734. {
  13735. int lmax = INT_MIN;
  13736. int lmin = INT_MAX;
  13737. int rmax = INT_MIN;
  13738. int rmin = INT_MAX;
  13739. while (numSamples > 0)
  13740. {
  13741. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  13742. read ((int**) tempBuffer, startSampleInFile, numToDo);
  13743. numSamples -= numToDo;
  13744. for (int j = numChannels; --j >= 0;)
  13745. {
  13746. int bufMax = INT_MIN;
  13747. int bufMin = INT_MAX;
  13748. const int* const b = tempBuffer[j];
  13749. for (int i = 0; i < numToDo; ++i)
  13750. {
  13751. const int samp = b[i];
  13752. if (samp < bufMin)
  13753. bufMin = samp;
  13754. if (samp > bufMax)
  13755. bufMax = samp;
  13756. }
  13757. if (j == 0)
  13758. {
  13759. lmax = jmax (lmax, bufMax);
  13760. lmin = jmin (lmin, bufMin);
  13761. }
  13762. else
  13763. {
  13764. rmax = jmax (rmax, bufMax);
  13765. rmin = jmin (rmin, bufMin);
  13766. }
  13767. }
  13768. }
  13769. if (numChannels <= 1)
  13770. {
  13771. rmax = lmax;
  13772. rmin = lmin;
  13773. }
  13774. lowestLeft = lmin / (float)INT_MAX;
  13775. highestLeft = lmax / (float)INT_MAX;
  13776. lowestRight = rmin / (float)INT_MAX;
  13777. highestRight = rmax / (float)INT_MAX;
  13778. }
  13779. }
  13780. int64 AudioFormatReader::searchForLevel (int64 startSample,
  13781. int64 numSamplesToSearch,
  13782. const double magnitudeRangeMinimum,
  13783. const double magnitudeRangeMaximum,
  13784. const int minimumConsecutiveSamples)
  13785. {
  13786. if (numSamplesToSearch == 0)
  13787. return -1;
  13788. const int bufferSize = 4096;
  13789. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  13790. int* tempBuffer[3];
  13791. tempBuffer[0] = (int*) tempSpace.getData();
  13792. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  13793. tempBuffer[2] = 0;
  13794. int consecutive = 0;
  13795. int64 firstMatchPos = -1;
  13796. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  13797. const double doubleMin = jlimit (0.0, (double) INT_MAX, magnitudeRangeMinimum * INT_MAX);
  13798. const double doubleMax = jlimit (doubleMin, (double) INT_MAX, magnitudeRangeMaximum * INT_MAX);
  13799. const int intMagnitudeRangeMinimum = roundDoubleToInt (doubleMin);
  13800. const int intMagnitudeRangeMaximum = roundDoubleToInt (doubleMax);
  13801. while (numSamplesToSearch != 0)
  13802. {
  13803. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  13804. int64 bufferStart = startSample;
  13805. if (numSamplesToSearch < 0)
  13806. bufferStart -= numThisTime;
  13807. if (bufferStart >= (int) lengthInSamples)
  13808. break;
  13809. read ((int**) tempBuffer, bufferStart, numThisTime);
  13810. int num = numThisTime;
  13811. while (--num >= 0)
  13812. {
  13813. if (numSamplesToSearch < 0)
  13814. --startSample;
  13815. bool matches = false;
  13816. const int index = (int) (startSample - bufferStart);
  13817. if (usesFloatingPointData)
  13818. {
  13819. const float sample1 = fabsf (((float*) tempBuffer[0]) [index]);
  13820. if (sample1 >= magnitudeRangeMinimum
  13821. && sample1 <= magnitudeRangeMaximum)
  13822. {
  13823. matches = true;
  13824. }
  13825. else if (numChannels > 1)
  13826. {
  13827. const float sample2 = fabsf (((float*) tempBuffer[1]) [index]);
  13828. matches = (sample2 >= magnitudeRangeMinimum
  13829. && sample2 <= magnitudeRangeMaximum);
  13830. }
  13831. }
  13832. else
  13833. {
  13834. const int sample1 = abs (tempBuffer[0] [index]);
  13835. if (sample1 >= intMagnitudeRangeMinimum
  13836. && sample1 <= intMagnitudeRangeMaximum)
  13837. {
  13838. matches = true;
  13839. }
  13840. else if (numChannels > 1)
  13841. {
  13842. const int sample2 = abs (tempBuffer[1][index]);
  13843. matches = (sample2 >= intMagnitudeRangeMinimum
  13844. && sample2 <= intMagnitudeRangeMaximum);
  13845. }
  13846. }
  13847. if (matches)
  13848. {
  13849. if (firstMatchPos < 0)
  13850. firstMatchPos = startSample;
  13851. if (++consecutive >= minimumConsecutiveSamples)
  13852. {
  13853. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  13854. return -1;
  13855. return firstMatchPos;
  13856. }
  13857. }
  13858. else
  13859. {
  13860. consecutive = 0;
  13861. firstMatchPos = -1;
  13862. }
  13863. if (numSamplesToSearch > 0)
  13864. ++startSample;
  13865. }
  13866. if (numSamplesToSearch > 0)
  13867. numSamplesToSearch -= numThisTime;
  13868. else
  13869. numSamplesToSearch += numThisTime;
  13870. }
  13871. return -1;
  13872. }
  13873. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  13874. const String& formatName_,
  13875. const double rate,
  13876. const unsigned int numChannels_,
  13877. const unsigned int bitsPerSample_)
  13878. : sampleRate (rate),
  13879. numChannels (numChannels_),
  13880. bitsPerSample (bitsPerSample_),
  13881. usesFloatingPointData (false),
  13882. output (out),
  13883. formatName (formatName_)
  13884. {
  13885. }
  13886. AudioFormatWriter::~AudioFormatWriter()
  13887. {
  13888. delete output;
  13889. }
  13890. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  13891. int64 startSample,
  13892. int numSamplesToRead)
  13893. {
  13894. const int bufferSize = 16384;
  13895. const int maxChans = 128;
  13896. AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
  13897. int* buffers [maxChans];
  13898. for (int i = maxChans; --i >= 0;)
  13899. buffers[i] = 0;
  13900. while (numSamplesToRead > 0)
  13901. {
  13902. const int numToDo = jmin (numSamplesToRead, bufferSize);
  13903. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  13904. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  13905. if (! reader.read (buffers, startSample, numToDo))
  13906. return false;
  13907. if (reader.usesFloatingPointData != isFloatingPoint())
  13908. {
  13909. int** bufferChan = buffers;
  13910. while (*bufferChan != 0)
  13911. {
  13912. int* b = *bufferChan++;
  13913. if (isFloatingPoint())
  13914. {
  13915. // int -> float
  13916. const double factor = 1.0 / INT_MAX;
  13917. for (int i = 0; i < numToDo; ++i)
  13918. ((float*)b)[i] = (float) (factor * b[i]);
  13919. }
  13920. else
  13921. {
  13922. // float -> int
  13923. for (int i = 0; i < numToDo; ++i)
  13924. {
  13925. const double samp = *(const float*) b;
  13926. if (samp <= -1.0)
  13927. *b++ = INT_MIN;
  13928. else if (samp >= 1.0)
  13929. *b++ = INT_MAX;
  13930. else
  13931. *b++ = roundDoubleToInt (INT_MAX * samp);
  13932. }
  13933. }
  13934. }
  13935. }
  13936. if (! write ((const int**) buffers, numToDo))
  13937. return false;
  13938. numSamplesToRead -= numToDo;
  13939. startSample += numToDo;
  13940. }
  13941. return true;
  13942. }
  13943. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  13944. int numSamplesToRead,
  13945. const int samplesPerBlock)
  13946. {
  13947. const int maxChans = 128;
  13948. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  13949. int* buffers [maxChans];
  13950. while (numSamplesToRead > 0)
  13951. {
  13952. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  13953. AudioSourceChannelInfo info;
  13954. info.buffer = &tempBuffer;
  13955. info.startSample = 0;
  13956. info.numSamples = numToDo;
  13957. info.clearActiveBufferRegion();
  13958. source.getNextAudioBlock (info);
  13959. int i;
  13960. for (i = maxChans; --i >= 0;)
  13961. buffers[i] = 0;
  13962. for (i = tempBuffer.getNumChannels(); --i >= 0;)
  13963. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  13964. if (! isFloatingPoint())
  13965. {
  13966. int** bufferChan = buffers;
  13967. while (*bufferChan != 0)
  13968. {
  13969. int* b = *bufferChan++;
  13970. // float -> int
  13971. for (int j = numToDo; --j >= 0;)
  13972. {
  13973. const double samp = *(const float*) b;
  13974. if (samp <= -1.0)
  13975. *b++ = INT_MIN;
  13976. else if (samp >= 1.0)
  13977. *b++ = INT_MAX;
  13978. else
  13979. *b++ = roundDoubleToInt (INT_MAX * samp);
  13980. }
  13981. }
  13982. }
  13983. if (! write ((const int**) buffers, numToDo))
  13984. return false;
  13985. numSamplesToRead -= numToDo;
  13986. }
  13987. return true;
  13988. }
  13989. AudioFormat::AudioFormat (const String& name,
  13990. const tchar** const extensions)
  13991. : formatName (name),
  13992. fileExtensions (extensions)
  13993. {
  13994. }
  13995. AudioFormat::~AudioFormat()
  13996. {
  13997. }
  13998. const String& AudioFormat::getFormatName() const
  13999. {
  14000. return formatName;
  14001. }
  14002. const StringArray& AudioFormat::getFileExtensions() const
  14003. {
  14004. return fileExtensions;
  14005. }
  14006. bool AudioFormat::canHandleFile (const File& f)
  14007. {
  14008. for (int i = 0; i < fileExtensions.size(); ++i)
  14009. if (f.hasFileExtension (fileExtensions[i]))
  14010. return true;
  14011. return false;
  14012. }
  14013. bool AudioFormat::isCompressed()
  14014. {
  14015. return false;
  14016. }
  14017. const StringArray AudioFormat::getQualityOptions()
  14018. {
  14019. return StringArray();
  14020. }
  14021. END_JUCE_NAMESPACE
  14022. /********* End of inlined file: juce_AudioFormat.cpp *********/
  14023. /********* Start of inlined file: juce_AudioFormatManager.cpp *********/
  14024. BEGIN_JUCE_NAMESPACE
  14025. AudioFormatManager::AudioFormatManager()
  14026. : knownFormats (4),
  14027. defaultFormatIndex (0)
  14028. {
  14029. }
  14030. AudioFormatManager::~AudioFormatManager()
  14031. {
  14032. clearFormats();
  14033. clearSingletonInstance();
  14034. }
  14035. juce_ImplementSingleton (AudioFormatManager);
  14036. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  14037. const bool makeThisTheDefaultFormat)
  14038. {
  14039. jassert (newFormat != 0);
  14040. if (newFormat != 0)
  14041. {
  14042. #ifdef JUCE_DEBUG
  14043. for (int i = getNumKnownFormats(); --i >= 0;)
  14044. {
  14045. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  14046. {
  14047. jassertfalse // trying to add the same format twice!
  14048. }
  14049. }
  14050. #endif
  14051. if (makeThisTheDefaultFormat)
  14052. defaultFormatIndex = knownFormats.size();
  14053. knownFormats.add (newFormat);
  14054. }
  14055. }
  14056. void AudioFormatManager::registerBasicFormats()
  14057. {
  14058. #if JUCE_MAC
  14059. registerFormat (new AiffAudioFormat(), true);
  14060. registerFormat (new WavAudioFormat(), false);
  14061. #else
  14062. registerFormat (new WavAudioFormat(), true);
  14063. registerFormat (new AiffAudioFormat(), false);
  14064. #endif
  14065. #if JUCE_USE_FLAC
  14066. registerFormat (new FlacAudioFormat(), false);
  14067. #endif
  14068. #if JUCE_USE_OGGVORBIS
  14069. registerFormat (new OggVorbisAudioFormat(), false);
  14070. #endif
  14071. }
  14072. void AudioFormatManager::clearFormats()
  14073. {
  14074. for (int i = getNumKnownFormats(); --i >= 0;)
  14075. {
  14076. AudioFormat* const af = getKnownFormat(i);
  14077. delete af;
  14078. }
  14079. knownFormats.clear();
  14080. defaultFormatIndex = 0;
  14081. }
  14082. int AudioFormatManager::getNumKnownFormats() const
  14083. {
  14084. return knownFormats.size();
  14085. }
  14086. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  14087. {
  14088. return (AudioFormat*) knownFormats [index];
  14089. }
  14090. AudioFormat* AudioFormatManager::getDefaultFormat() const
  14091. {
  14092. return getKnownFormat (defaultFormatIndex);
  14093. }
  14094. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  14095. {
  14096. String e (fileExtension);
  14097. if (! e.startsWithChar (T('.')))
  14098. e = T(".") + e;
  14099. for (int i = 0; i < getNumKnownFormats(); ++i)
  14100. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  14101. return getKnownFormat(i);
  14102. return 0;
  14103. }
  14104. const String AudioFormatManager::getWildcardForAllFormats() const
  14105. {
  14106. StringArray allExtensions;
  14107. int i;
  14108. for (i = 0; i < getNumKnownFormats(); ++i)
  14109. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  14110. allExtensions.trim();
  14111. allExtensions.removeEmptyStrings();
  14112. String s;
  14113. for (i = 0; i < allExtensions.size(); ++i)
  14114. {
  14115. s << T('*');
  14116. if (! allExtensions[i].startsWithChar (T('.')))
  14117. s << T('.');
  14118. s << allExtensions[i];
  14119. if (i < allExtensions.size() - 1)
  14120. s << T(';');
  14121. }
  14122. return s;
  14123. }
  14124. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  14125. {
  14126. // you need to actually register some formats before the manager can
  14127. // use them to open a file!
  14128. jassert (knownFormats.size() > 0);
  14129. for (int i = 0; i < getNumKnownFormats(); ++i)
  14130. {
  14131. AudioFormat* const af = getKnownFormat(i);
  14132. if (af->canHandleFile (file))
  14133. {
  14134. InputStream* const in = file.createInputStream();
  14135. if (in != 0)
  14136. {
  14137. AudioFormatReader* const r = af->createReaderFor (in, true);
  14138. if (r != 0)
  14139. return r;
  14140. }
  14141. }
  14142. }
  14143. return 0;
  14144. }
  14145. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* in)
  14146. {
  14147. // you need to actually register some formats before the manager can
  14148. // use them to open a file!
  14149. jassert (knownFormats.size() > 0);
  14150. if (in != 0)
  14151. {
  14152. const int64 originalStreamPos = in->getPosition();
  14153. for (int i = 0; i < getNumKnownFormats(); ++i)
  14154. {
  14155. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  14156. if (r != 0)
  14157. return r;
  14158. in->setPosition (originalStreamPos);
  14159. // the stream that is passed-in must be capable of being repositioned so
  14160. // that all the formats can have a go at opening it.
  14161. jassert (in->getPosition() == originalStreamPos);
  14162. }
  14163. delete in;
  14164. }
  14165. return 0;
  14166. }
  14167. END_JUCE_NAMESPACE
  14168. /********* End of inlined file: juce_AudioFormatManager.cpp *********/
  14169. /********* Start of inlined file: juce_AudioSubsectionReader.cpp *********/
  14170. BEGIN_JUCE_NAMESPACE
  14171. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  14172. const int64 startSample_,
  14173. const int64 length_,
  14174. const bool deleteSourceWhenDeleted_)
  14175. : AudioFormatReader (0, source_->getFormatName()),
  14176. source (source_),
  14177. startSample (startSample_),
  14178. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  14179. {
  14180. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  14181. sampleRate = source->sampleRate;
  14182. bitsPerSample = source->bitsPerSample;
  14183. lengthInSamples = length;
  14184. numChannels = source->numChannels;
  14185. usesFloatingPointData = source->usesFloatingPointData;
  14186. }
  14187. AudioSubsectionReader::~AudioSubsectionReader()
  14188. {
  14189. if (deleteSourceWhenDeleted)
  14190. delete source;
  14191. }
  14192. bool AudioSubsectionReader::read (int** destSamples,
  14193. int64 startSampleInFile,
  14194. int numSamples)
  14195. {
  14196. if (startSampleInFile < 0 || startSampleInFile + numSamples > length)
  14197. {
  14198. int** d = destSamples;
  14199. while (*d != 0)
  14200. {
  14201. zeromem (*d, sizeof (int) * numSamples);
  14202. ++d;
  14203. }
  14204. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  14205. numSamples = jmax (0, jmin (numSamples, (int) (length - startSampleInFile)));
  14206. }
  14207. return source->read (destSamples,
  14208. startSampleInFile + startSample,
  14209. numSamples);
  14210. }
  14211. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  14212. int64 numSamples,
  14213. float& lowestLeft,
  14214. float& highestLeft,
  14215. float& lowestRight,
  14216. float& highestRight)
  14217. {
  14218. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  14219. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  14220. source->readMaxLevels (startSampleInFile + startSample,
  14221. numSamples,
  14222. lowestLeft,
  14223. highestLeft,
  14224. lowestRight,
  14225. highestRight);
  14226. }
  14227. END_JUCE_NAMESPACE
  14228. /********* End of inlined file: juce_AudioSubsectionReader.cpp *********/
  14229. /********* Start of inlined file: juce_AudioThumbnail.cpp *********/
  14230. BEGIN_JUCE_NAMESPACE
  14231. const int timeBeforeDeletingReader = 2000;
  14232. struct AudioThumbnailDataFormat
  14233. {
  14234. char thumbnailMagic[4];
  14235. int samplesPerThumbSample;
  14236. int64 totalSamples; // source samples
  14237. int64 numFinishedSamples; // source samples
  14238. int numThumbnailSamples;
  14239. int numChannels;
  14240. int sampleRate;
  14241. char future[16];
  14242. char data[1];
  14243. };
  14244. #if JUCE_BIG_ENDIAN
  14245. static void swap (int& n) { n = (int) swapByteOrder ((uint32) n); }
  14246. static void swap (int64& n) { n = (int64) swapByteOrder ((uint64) n); }
  14247. #endif
  14248. static void swapEndiannessIfNeeded (AudioThumbnailDataFormat* const d)
  14249. {
  14250. (void) d;
  14251. #if JUCE_BIG_ENDIAN
  14252. swap (d->samplesPerThumbSample);
  14253. swap (d->totalSamples);
  14254. swap (d->numFinishedSamples);
  14255. swap (d->numThumbnailSamples);
  14256. swap (d->numChannels);
  14257. swap (d->sampleRate);
  14258. #endif
  14259. }
  14260. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  14261. AudioFormatManager& formatManagerToUse_,
  14262. AudioThumbnailCache& cacheToUse)
  14263. : formatManagerToUse (formatManagerToUse_),
  14264. cache (cacheToUse),
  14265. source (0),
  14266. reader (0),
  14267. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  14268. {
  14269. clear();
  14270. }
  14271. AudioThumbnail::~AudioThumbnail()
  14272. {
  14273. cache.removeThumbnail (this);
  14274. const ScopedLock sl (readerLock);
  14275. deleteAndZero (reader);
  14276. delete source;
  14277. }
  14278. void AudioThumbnail::setSource (InputSource* const newSource)
  14279. {
  14280. cache.removeThumbnail (this);
  14281. timerCallback(); // stops the timer and deletes the reader
  14282. delete source;
  14283. source = newSource;
  14284. clear();
  14285. if (! (cache.loadThumb (*this, newSource->hashCode())
  14286. && isFullyLoaded()))
  14287. {
  14288. {
  14289. const ScopedLock sl (readerLock);
  14290. reader = createReader();
  14291. }
  14292. if (reader != 0)
  14293. {
  14294. initialiseFromAudioFile (*reader);
  14295. cache.addThumbnail (this);
  14296. }
  14297. }
  14298. sendChangeMessage (this);
  14299. }
  14300. bool AudioThumbnail::useTimeSlice()
  14301. {
  14302. const ScopedLock sl (readerLock);
  14303. if (isFullyLoaded())
  14304. {
  14305. if (reader != 0)
  14306. startTimer (timeBeforeDeletingReader);
  14307. cache.removeThumbnail (this);
  14308. return false;
  14309. }
  14310. if (reader == 0)
  14311. reader = createReader();
  14312. if (reader != 0)
  14313. {
  14314. readNextBlockFromAudioFile (*reader);
  14315. stopTimer();
  14316. sendChangeMessage (this);
  14317. const bool justFinished = isFullyLoaded();
  14318. if (justFinished)
  14319. cache.storeThumb (*this, source->hashCode());
  14320. return ! justFinished;
  14321. }
  14322. return false;
  14323. }
  14324. AudioFormatReader* AudioThumbnail::createReader() const
  14325. {
  14326. if (source != 0)
  14327. {
  14328. InputStream* const audioFileStream = source->createInputStream();
  14329. if (audioFileStream != 0)
  14330. return formatManagerToUse.createReaderFor (audioFileStream);
  14331. }
  14332. return 0;
  14333. }
  14334. void AudioThumbnail::timerCallback()
  14335. {
  14336. stopTimer();
  14337. const ScopedLock sl (readerLock);
  14338. deleteAndZero (reader);
  14339. }
  14340. void AudioThumbnail::clear()
  14341. {
  14342. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  14343. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14344. d->thumbnailMagic[0] = 'j';
  14345. d->thumbnailMagic[1] = 'a';
  14346. d->thumbnailMagic[2] = 't';
  14347. d->thumbnailMagic[3] = 'm';
  14348. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  14349. d->totalSamples = 0;
  14350. d->numFinishedSamples = 0;
  14351. d->numThumbnailSamples = 0;
  14352. d->numChannels = 0;
  14353. d->sampleRate = 0;
  14354. numSamplesCached = 0;
  14355. cacheNeedsRefilling = true;
  14356. }
  14357. void AudioThumbnail::loadFrom (InputStream& input)
  14358. {
  14359. data.setSize (0);
  14360. input.readIntoMemoryBlock (data);
  14361. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14362. swapEndiannessIfNeeded (d);
  14363. if (! (d->thumbnailMagic[0] == 'j'
  14364. && d->thumbnailMagic[1] == 'a'
  14365. && d->thumbnailMagic[2] == 't'
  14366. && d->thumbnailMagic[3] == 'm'))
  14367. {
  14368. clear();
  14369. }
  14370. numSamplesCached = 0;
  14371. cacheNeedsRefilling = true;
  14372. }
  14373. void AudioThumbnail::saveTo (OutputStream& output) const
  14374. {
  14375. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14376. swapEndiannessIfNeeded (d);
  14377. output.write (data.getData(), data.getSize());
  14378. swapEndiannessIfNeeded (d);
  14379. }
  14380. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& reader)
  14381. {
  14382. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  14383. d->totalSamples = reader.lengthInSamples;
  14384. d->numChannels = jmin (2, reader.numChannels);
  14385. d->numFinishedSamples = 0;
  14386. d->sampleRate = roundDoubleToInt (reader.sampleRate);
  14387. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  14388. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  14389. d = (AudioThumbnailDataFormat*) data.getData();
  14390. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  14391. return d->totalSamples > 0;
  14392. }
  14393. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& reader)
  14394. {
  14395. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14396. if (d->numFinishedSamples < d->totalSamples)
  14397. {
  14398. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  14399. generateSection (reader,
  14400. d->numFinishedSamples,
  14401. numToDo);
  14402. d->numFinishedSamples += numToDo;
  14403. }
  14404. cacheNeedsRefilling = true;
  14405. return (d->numFinishedSamples < d->totalSamples);
  14406. }
  14407. int AudioThumbnail::getNumChannels() const throw()
  14408. {
  14409. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14410. jassert (d != 0);
  14411. return d->numChannels;
  14412. }
  14413. double AudioThumbnail::getTotalLength() const throw()
  14414. {
  14415. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14416. jassert (d != 0);
  14417. if (d->sampleRate > 0)
  14418. return d->totalSamples / (double)d->sampleRate;
  14419. else
  14420. return 0.0;
  14421. }
  14422. void AudioThumbnail::generateSection (AudioFormatReader& reader,
  14423. int64 startSample,
  14424. int numSamples)
  14425. {
  14426. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14427. jassert (d != 0);
  14428. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  14429. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  14430. char* l = getChannelData (0);
  14431. char* r = getChannelData (1);
  14432. for (int i = firstDataPos; i < lastDataPos; ++i)
  14433. {
  14434. const int sourceStart = i * d->samplesPerThumbSample;
  14435. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  14436. float lowestLeft, highestLeft, lowestRight, highestRight;
  14437. reader.readMaxLevels (sourceStart,
  14438. sourceEnd - sourceStart,
  14439. lowestLeft,
  14440. highestLeft,
  14441. lowestRight,
  14442. highestRight);
  14443. int n = i * 2;
  14444. if (r != 0)
  14445. {
  14446. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  14447. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  14448. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  14449. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  14450. }
  14451. else
  14452. {
  14453. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  14454. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  14455. }
  14456. }
  14457. }
  14458. char* AudioThumbnail::getChannelData (int channel) const
  14459. {
  14460. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14461. jassert (d != 0);
  14462. if (channel >= 0 && channel < d->numChannels)
  14463. return d->data + (channel * 2 * d->numThumbnailSamples);
  14464. return 0;
  14465. }
  14466. bool AudioThumbnail::isFullyLoaded() const throw()
  14467. {
  14468. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14469. jassert (d != 0);
  14470. return d->numFinishedSamples >= d->totalSamples;
  14471. }
  14472. void AudioThumbnail::refillCache (const int numSamples,
  14473. double startTime,
  14474. const double timePerPixel)
  14475. {
  14476. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14477. jassert (d != 0);
  14478. if (numSamples <= 0
  14479. || timePerPixel <= 0.0
  14480. || d->sampleRate <= 0)
  14481. {
  14482. numSamplesCached = 0;
  14483. cacheNeedsRefilling = true;
  14484. return;
  14485. }
  14486. if (numSamples == numSamplesCached
  14487. && numChannelsCached == d->numChannels
  14488. && startTime == cachedStart
  14489. && timePerPixel == cachedTimePerPixel
  14490. && ! cacheNeedsRefilling)
  14491. {
  14492. return;
  14493. }
  14494. numSamplesCached = numSamples;
  14495. numChannelsCached = d->numChannels;
  14496. cachedStart = startTime;
  14497. cachedTimePerPixel = timePerPixel;
  14498. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  14499. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  14500. const ScopedLock sl (readerLock);
  14501. cacheNeedsRefilling = false;
  14502. if (needExtraDetail && reader == 0)
  14503. reader = createReader();
  14504. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  14505. {
  14506. startTimer (timeBeforeDeletingReader);
  14507. char* cacheData = (char*) cachedLevels.getData();
  14508. int sample = roundDoubleToInt (startTime * d->sampleRate);
  14509. for (int i = numSamples; --i >= 0;)
  14510. {
  14511. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * d->sampleRate);
  14512. if (sample >= 0)
  14513. {
  14514. if (sample >= reader->lengthInSamples)
  14515. break;
  14516. float lmin, lmax, rmin, rmax;
  14517. reader->readMaxLevels (sample,
  14518. jmax (1, nextSample - sample),
  14519. lmin, lmax, rmin, rmax);
  14520. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  14521. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  14522. if (numChannelsCached > 1)
  14523. {
  14524. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  14525. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  14526. }
  14527. cacheData += 2 * numChannelsCached;
  14528. }
  14529. startTime += timePerPixel;
  14530. sample = nextSample;
  14531. }
  14532. }
  14533. else
  14534. {
  14535. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  14536. {
  14537. char* const data = getChannelData (channelNum);
  14538. char* cacheData = ((char*) cachedLevels.getData()) + channelNum * 2;
  14539. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  14540. startTime = cachedStart;
  14541. int sample = roundDoubleToInt (startTime * timeToThumbSampleFactor);
  14542. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  14543. for (int i = numSamples; --i >= 0;)
  14544. {
  14545. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  14546. if (sample >= 0 && data != 0)
  14547. {
  14548. char mx = -128;
  14549. char mn = 127;
  14550. while (sample <= nextSample)
  14551. {
  14552. if (sample >= numFinished)
  14553. break;
  14554. const int n = sample << 1;
  14555. const char sampMin = data [n];
  14556. const char sampMax = data [n + 1];
  14557. if (sampMin < mn)
  14558. mn = sampMin;
  14559. if (sampMax > mx)
  14560. mx = sampMax;
  14561. ++sample;
  14562. }
  14563. if (mn <= mx)
  14564. {
  14565. cacheData[0] = mn;
  14566. cacheData[1] = mx;
  14567. }
  14568. else
  14569. {
  14570. cacheData[0] = 1;
  14571. cacheData[1] = 0;
  14572. }
  14573. }
  14574. else
  14575. {
  14576. cacheData[0] = 1;
  14577. cacheData[1] = 0;
  14578. }
  14579. cacheData += numChannelsCached * 2;
  14580. startTime += timePerPixel;
  14581. sample = nextSample;
  14582. }
  14583. }
  14584. }
  14585. }
  14586. void AudioThumbnail::drawChannel (Graphics& g,
  14587. int x, int y, int w, int h,
  14588. double startTime,
  14589. double endTime,
  14590. int channelNum,
  14591. const float verticalZoomFactor)
  14592. {
  14593. refillCache (w, startTime, (endTime - startTime) / w);
  14594. if (numSamplesCached >= w
  14595. && channelNum >= 0
  14596. && channelNum < numChannelsCached)
  14597. {
  14598. const float topY = (float) y;
  14599. const float bottomY = topY + h;
  14600. const float midY = topY + h * 0.5f;
  14601. const float vscale = verticalZoomFactor * h / 256.0f;
  14602. const Rectangle clip (g.getClipBounds());
  14603. const int skipLeft = clip.getX() - x;
  14604. w -= skipLeft;
  14605. x += skipLeft;
  14606. const char* cacheData = ((const char*) cachedLevels.getData())
  14607. + (channelNum << 1)
  14608. + skipLeft * (numChannelsCached << 1);
  14609. while (--w >= 0)
  14610. {
  14611. const char mn = cacheData[0];
  14612. const char mx = cacheData[1];
  14613. cacheData += numChannelsCached << 1;
  14614. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  14615. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  14616. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  14617. ++x;
  14618. if (x >= clip.getRight())
  14619. break;
  14620. }
  14621. }
  14622. }
  14623. END_JUCE_NAMESPACE
  14624. /********* End of inlined file: juce_AudioThumbnail.cpp *********/
  14625. /********* Start of inlined file: juce_AudioThumbnailCache.cpp *********/
  14626. BEGIN_JUCE_NAMESPACE
  14627. struct ThumbnailCacheEntry
  14628. {
  14629. int64 hash;
  14630. uint32 lastUsed;
  14631. MemoryBlock data;
  14632. juce_UseDebuggingNewOperator
  14633. };
  14634. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  14635. : TimeSliceThread (T("thumb cache")),
  14636. maxNumThumbsToStore (maxNumThumbsToStore_)
  14637. {
  14638. startThread (2);
  14639. }
  14640. AudioThumbnailCache::~AudioThumbnailCache()
  14641. {
  14642. }
  14643. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  14644. {
  14645. for (int i = thumbs.size(); --i >= 0;)
  14646. {
  14647. if (thumbs[i]->hash == hashCode)
  14648. {
  14649. MemoryInputStream in ((const char*) thumbs[i]->data.getData(),
  14650. thumbs[i]->data.getSize(),
  14651. false);
  14652. thumb.loadFrom (in);
  14653. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  14654. return true;
  14655. }
  14656. }
  14657. return false;
  14658. }
  14659. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  14660. const int64 hashCode)
  14661. {
  14662. MemoryOutputStream out;
  14663. thumb.saveTo (out);
  14664. ThumbnailCacheEntry* te = 0;
  14665. for (int i = thumbs.size(); --i >= 0;)
  14666. {
  14667. if (thumbs[i]->hash == hashCode)
  14668. {
  14669. te = thumbs[i];
  14670. break;
  14671. }
  14672. }
  14673. if (te == 0)
  14674. {
  14675. te = new ThumbnailCacheEntry();
  14676. te->hash = hashCode;
  14677. if (thumbs.size() < maxNumThumbsToStore)
  14678. {
  14679. thumbs.add (te);
  14680. }
  14681. else
  14682. {
  14683. int oldest = 0;
  14684. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  14685. int i;
  14686. for (i = thumbs.size(); --i >= 0;)
  14687. if (thumbs[i]->lastUsed < oldestTime)
  14688. oldest = i;
  14689. thumbs.set (i, te);
  14690. }
  14691. }
  14692. te->lastUsed = Time::getMillisecondCounter();
  14693. te->data.setSize (0);
  14694. te->data.append (out.getData(), out.getDataSize());
  14695. }
  14696. void AudioThumbnailCache::clear()
  14697. {
  14698. thumbs.clear();
  14699. }
  14700. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  14701. {
  14702. addTimeSliceClient (thumb);
  14703. }
  14704. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  14705. {
  14706. removeTimeSliceClient (thumb);
  14707. }
  14708. END_JUCE_NAMESPACE
  14709. /********* End of inlined file: juce_AudioThumbnailCache.cpp *********/
  14710. /********* Start of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  14711. #if JUCE_QUICKTIME
  14712. #if ! defined (_WIN32)
  14713. #include <Quicktime/Movies.h>
  14714. #include <Quicktime/QTML.h>
  14715. #include <Quicktime/QuickTimeComponents.h>
  14716. #include <Quicktime/MediaHandlers.h>
  14717. #include <Quicktime/ImageCodec.h>
  14718. #else
  14719. #ifdef _MSC_VER
  14720. #pragma warning (push)
  14721. #pragma warning (disable : 4100)
  14722. #endif
  14723. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  14724. add its header directory to your include path.
  14725. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  14726. flag in juce_Config.h
  14727. */
  14728. #include <Movies.h>
  14729. #include <QTML.h>
  14730. #include <QuickTimeComponents.h>
  14731. #include <MediaHandlers.h>
  14732. #include <ImageCodec.h>
  14733. #ifdef _MSC_VER
  14734. #pragma warning (pop)
  14735. #endif
  14736. #endif
  14737. BEGIN_JUCE_NAMESPACE
  14738. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  14739. #define quickTimeFormatName TRANS("QuickTime file")
  14740. static const tchar* const quickTimeExtensions[] = { T(".mov"), T(".mp3"), T(".mp4"), 0 };
  14741. class QTAudioReader : public AudioFormatReader
  14742. {
  14743. public:
  14744. QTAudioReader (InputStream* const input_, const int trackNum_)
  14745. : AudioFormatReader (input_, quickTimeFormatName),
  14746. ok (false),
  14747. movie (0),
  14748. trackNum (trackNum_),
  14749. extractor (0),
  14750. lastSampleRead (0),
  14751. lastThreadId (0),
  14752. dataHandle (0)
  14753. {
  14754. bufferList = (AudioBufferList*) juce_calloc (256);
  14755. #ifdef WIN32
  14756. if (InitializeQTML (0) != noErr)
  14757. return;
  14758. #elif JUCE_MAC
  14759. EnterMoviesOnThread (0);
  14760. #endif
  14761. if (EnterMovies() != noErr)
  14762. return;
  14763. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  14764. if (! opened)
  14765. return;
  14766. {
  14767. const int numTracks = GetMovieTrackCount (movie);
  14768. int trackCount = 0;
  14769. for (int i = 1; i <= numTracks; ++i)
  14770. {
  14771. track = GetMovieIndTrack (movie, i);
  14772. media = GetTrackMedia (track);
  14773. OSType mediaType;
  14774. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  14775. if (mediaType == SoundMediaType
  14776. && trackCount++ == trackNum_)
  14777. {
  14778. ok = true;
  14779. break;
  14780. }
  14781. }
  14782. }
  14783. if (! ok)
  14784. return;
  14785. ok = false;
  14786. lengthInSamples = GetMediaDecodeDuration (media);
  14787. usesFloatingPointData = false;
  14788. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  14789. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  14790. / GetMediaTimeScale (media);
  14791. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  14792. unsigned long output_layout_size;
  14793. err = MovieAudioExtractionGetPropertyInfo (extractor,
  14794. kQTPropertyClass_MovieAudioExtraction_Audio,
  14795. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  14796. 0, &output_layout_size, 0);
  14797. if (err != noErr)
  14798. return;
  14799. AudioChannelLayout* const qt_audio_channel_layout
  14800. = (AudioChannelLayout*) juce_calloc (output_layout_size);
  14801. err = MovieAudioExtractionGetProperty (extractor,
  14802. kQTPropertyClass_MovieAudioExtraction_Audio,
  14803. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  14804. output_layout_size, qt_audio_channel_layout, 0);
  14805. qt_audio_channel_layout->mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  14806. err = MovieAudioExtractionSetProperty (extractor,
  14807. kQTPropertyClass_MovieAudioExtraction_Audio,
  14808. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  14809. sizeof (qt_audio_channel_layout),
  14810. qt_audio_channel_layout);
  14811. juce_free (qt_audio_channel_layout);
  14812. err = MovieAudioExtractionGetProperty (extractor,
  14813. kQTPropertyClass_MovieAudioExtraction_Audio,
  14814. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  14815. sizeof (inputStreamDesc),
  14816. &inputStreamDesc, 0);
  14817. if (err != noErr)
  14818. return;
  14819. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  14820. | kAudioFormatFlagIsPacked
  14821. | kAudioFormatFlagsNativeEndian;
  14822. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  14823. inputStreamDesc.mChannelsPerFrame = jmin (2, inputStreamDesc.mChannelsPerFrame);
  14824. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  14825. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  14826. err = MovieAudioExtractionSetProperty (extractor,
  14827. kQTPropertyClass_MovieAudioExtraction_Audio,
  14828. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  14829. sizeof (inputStreamDesc),
  14830. &inputStreamDesc);
  14831. if (err != noErr)
  14832. return;
  14833. Boolean allChannelsDiscrete = false;
  14834. err = MovieAudioExtractionSetProperty (extractor,
  14835. kQTPropertyClass_MovieAudioExtraction_Movie,
  14836. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  14837. sizeof (allChannelsDiscrete),
  14838. &allChannelsDiscrete);
  14839. if (err != noErr)
  14840. return;
  14841. bufferList->mNumberBuffers = 1;
  14842. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  14843. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  14844. bufferList->mBuffers[0].mData = malloc (bufferList->mBuffers[0].mDataByteSize);
  14845. sampleRate = inputStreamDesc.mSampleRate;
  14846. bitsPerSample = 16;
  14847. numChannels = inputStreamDesc.mChannelsPerFrame;
  14848. detachThread();
  14849. ok = true;
  14850. }
  14851. ~QTAudioReader()
  14852. {
  14853. if (dataHandle != 0)
  14854. DisposeHandle (dataHandle);
  14855. if (extractor != 0)
  14856. {
  14857. MovieAudioExtractionEnd (extractor);
  14858. extractor = 0;
  14859. }
  14860. checkThreadIsAttached();
  14861. DisposeMovie (movie);
  14862. juce_free (bufferList->mBuffers[0].mData);
  14863. juce_free (bufferList);
  14864. #if JUCE_MAC
  14865. ExitMoviesOnThread ();
  14866. #endif
  14867. }
  14868. bool read (int** destSamples,
  14869. int64 startSample,
  14870. int numSamples)
  14871. {
  14872. checkThreadIsAttached();
  14873. int done = 0;
  14874. while (numSamples > 0)
  14875. {
  14876. if (! loadFrame ((int) startSample))
  14877. return false;
  14878. const int numToDo = jmin (numSamples, samplesPerFrame);
  14879. for (unsigned int j = 0; j < inputStreamDesc.mChannelsPerFrame; ++j)
  14880. {
  14881. if (destSamples[j] != 0)
  14882. {
  14883. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  14884. for (int i = 0; i < numToDo; ++i)
  14885. destSamples[j][done + i] = src [i << 1] << 16;
  14886. }
  14887. }
  14888. done += numToDo;
  14889. startSample += numToDo;
  14890. numSamples -= numToDo;
  14891. }
  14892. detachThread();
  14893. return true;
  14894. }
  14895. bool loadFrame (const int sampleNum)
  14896. {
  14897. if (lastSampleRead != sampleNum)
  14898. {
  14899. TimeRecord time;
  14900. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  14901. time.base = 0;
  14902. time.value.hi = 0;
  14903. time.value.lo = (UInt32) sampleNum;
  14904. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  14905. kQTPropertyClass_MovieAudioExtraction_Movie,
  14906. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  14907. sizeof (time), &time);
  14908. if (err != noErr)
  14909. return false;
  14910. }
  14911. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  14912. UInt32 outFlags = 0;
  14913. UInt32 actualNumSamples = samplesPerFrame;
  14914. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  14915. bufferList, &outFlags);
  14916. lastSampleRead = sampleNum + samplesPerFrame;
  14917. return err == noErr;
  14918. }
  14919. juce_UseDebuggingNewOperator
  14920. bool ok;
  14921. private:
  14922. Movie movie;
  14923. Media media;
  14924. Track track;
  14925. const int trackNum;
  14926. double trackUnitsPerFrame;
  14927. int samplesPerFrame;
  14928. int lastSampleRead, lastThreadId;
  14929. MovieAudioExtractionRef extractor;
  14930. AudioStreamBasicDescription inputStreamDesc;
  14931. AudioBufferList* bufferList;
  14932. Handle dataHandle;
  14933. /*OSErr readMovieStream (long offset, long size, void* dataPtr)
  14934. {
  14935. input->setPosition (offset);
  14936. input->read (dataPtr, size);
  14937. return noErr;
  14938. }
  14939. static OSErr readMovieStreamProc (long offset, long size, void* dataPtr, void* userRef)
  14940. {
  14941. return ((QTAudioReader*) userRef)->readMovieStream (offset, size, dataPtr);
  14942. }*/
  14943. void checkThreadIsAttached()
  14944. {
  14945. #if JUCE_MAC
  14946. if (Thread::getCurrentThreadId() != lastThreadId)
  14947. EnterMoviesOnThread (0);
  14948. AttachMovieToCurrentThread (movie);
  14949. #endif
  14950. }
  14951. void detachThread()
  14952. {
  14953. #if JUCE_MAC
  14954. DetachMovieFromCurrentThread (movie);
  14955. #endif
  14956. }
  14957. };
  14958. QuickTimeAudioFormat::QuickTimeAudioFormat()
  14959. : AudioFormat (quickTimeFormatName, (const tchar**) quickTimeExtensions)
  14960. {
  14961. }
  14962. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  14963. {
  14964. }
  14965. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  14966. {
  14967. return Array<int>();
  14968. }
  14969. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  14970. {
  14971. return Array<int>();
  14972. }
  14973. bool QuickTimeAudioFormat::canDoStereo()
  14974. {
  14975. return true;
  14976. }
  14977. bool QuickTimeAudioFormat::canDoMono()
  14978. {
  14979. return true;
  14980. }
  14981. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  14982. const bool deleteStreamIfOpeningFails)
  14983. {
  14984. QTAudioReader* r = new QTAudioReader (sourceStream, 0);
  14985. if (! r->ok)
  14986. {
  14987. if (! deleteStreamIfOpeningFails)
  14988. r->input = 0;
  14989. deleteAndZero (r);
  14990. }
  14991. return r;
  14992. }
  14993. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  14994. double /*sampleRateToUse*/,
  14995. unsigned int /*numberOfChannels*/,
  14996. int /*bitsPerSample*/,
  14997. const StringPairArray& /*metadataValues*/,
  14998. int /*qualityOptionIndex*/)
  14999. {
  15000. jassertfalse // not yet implemented!
  15001. return 0;
  15002. }
  15003. END_JUCE_NAMESPACE
  15004. #endif
  15005. /********* End of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  15006. /********* Start of inlined file: juce_WavAudioFormat.cpp *********/
  15007. BEGIN_JUCE_NAMESPACE
  15008. #define wavFormatName TRANS("WAV file")
  15009. static const tchar* const wavExtensions[] = { T(".wav"), T(".bwf"), 0 };
  15010. const tchar* const WavAudioFormat::bwavDescription = T("bwav description");
  15011. const tchar* const WavAudioFormat::bwavOriginator = T("bwav originator");
  15012. const tchar* const WavAudioFormat::bwavOriginatorRef = T("bwav originator ref");
  15013. const tchar* const WavAudioFormat::bwavOriginationDate = T("bwav origination date");
  15014. const tchar* const WavAudioFormat::bwavOriginationTime = T("bwav origination time");
  15015. const tchar* const WavAudioFormat::bwavTimeReference = T("bwav time reference");
  15016. const tchar* const WavAudioFormat::bwavCodingHistory = T("bwav coding history");
  15017. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  15018. const String& originator,
  15019. const String& originatorRef,
  15020. const Time& date,
  15021. const int64 timeReferenceSamples,
  15022. const String& codingHistory)
  15023. {
  15024. StringPairArray m;
  15025. m.set (bwavDescription, description);
  15026. m.set (bwavOriginator, originator);
  15027. m.set (bwavOriginatorRef, originatorRef);
  15028. m.set (bwavOriginationDate, date.formatted (T("%Y-%m-%d")));
  15029. m.set (bwavOriginationTime, date.formatted (T("%H:%M:%S")));
  15030. m.set (bwavTimeReference, String (timeReferenceSamples));
  15031. m.set (bwavCodingHistory, codingHistory);
  15032. return m;
  15033. }
  15034. #if JUCE_MSVC
  15035. #pragma pack (push, 1)
  15036. #define PACKED
  15037. #elif defined (JUCE_GCC)
  15038. #define PACKED __attribute__((packed))
  15039. #else
  15040. #define PACKED
  15041. #endif
  15042. struct BWAVChunk
  15043. {
  15044. char description [256];
  15045. char originator [32];
  15046. char originatorRef [32];
  15047. char originationDate [10];
  15048. char originationTime [8];
  15049. uint32 timeRefLow;
  15050. uint32 timeRefHigh;
  15051. uint16 version;
  15052. uint8 umid[64];
  15053. uint8 reserved[190];
  15054. char codingHistory[1];
  15055. void copyTo (StringPairArray& values) const
  15056. {
  15057. values.set (WavAudioFormat::bwavDescription, String (description, 256));
  15058. values.set (WavAudioFormat::bwavOriginator, String (originator, 32));
  15059. values.set (WavAudioFormat::bwavOriginatorRef, String (originatorRef, 32));
  15060. values.set (WavAudioFormat::bwavOriginationDate, String (originationDate, 10));
  15061. values.set (WavAudioFormat::bwavOriginationTime, String (originationTime, 8));
  15062. const uint32 timeLow = swapIfBigEndian (timeRefLow);
  15063. const uint32 timeHigh = swapIfBigEndian (timeRefHigh);
  15064. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  15065. values.set (WavAudioFormat::bwavTimeReference, String (time));
  15066. values.set (WavAudioFormat::bwavCodingHistory, String (codingHistory));
  15067. }
  15068. static MemoryBlock createFrom (const StringPairArray& values)
  15069. {
  15070. const int sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].length();
  15071. MemoryBlock data ((sizeNeeded + 3) & ~3);
  15072. data.fillWith (0);
  15073. BWAVChunk* b = (BWAVChunk*) data.getData();
  15074. // although copyToBuffer may overrun by one byte, that's ok as long as these
  15075. // operations get done in the right order
  15076. values [WavAudioFormat::bwavDescription].copyToBuffer (b->description, 256);
  15077. values [WavAudioFormat::bwavOriginator].copyToBuffer (b->originator, 32);
  15078. values [WavAudioFormat::bwavOriginatorRef].copyToBuffer (b->originatorRef, 32);
  15079. values [WavAudioFormat::bwavOriginationDate].copyToBuffer (b->originationDate, 10);
  15080. values [WavAudioFormat::bwavOriginationTime].copyToBuffer (b->originationTime, 8);
  15081. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  15082. b->timeRefLow = swapIfBigEndian ((uint32) (time & 0xffffffff));
  15083. b->timeRefHigh = swapIfBigEndian ((uint32) (time >> 32));
  15084. values [WavAudioFormat::bwavCodingHistory].copyToBuffer (b->codingHistory, 256 * 1024);
  15085. if (b->description[0] != 0
  15086. || b->originator[0] != 0
  15087. || b->originationDate[0] != 0
  15088. || b->originationTime[0] != 0
  15089. || b->codingHistory[0] != 0
  15090. || time != 0)
  15091. {
  15092. return data;
  15093. }
  15094. return MemoryBlock();
  15095. }
  15096. } PACKED;
  15097. #if JUCE_MSVC
  15098. #pragma pack (pop)
  15099. #endif
  15100. #undef PACKED
  15101. #undef chunkName
  15102. #define chunkName(a) ((int) littleEndianInt(a))
  15103. class WavAudioFormatReader : public AudioFormatReader
  15104. {
  15105. int bytesPerFrame;
  15106. int64 dataChunkStart, dataLength;
  15107. WavAudioFormatReader (const WavAudioFormatReader&);
  15108. const WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  15109. public:
  15110. WavAudioFormatReader (InputStream* const in)
  15111. : AudioFormatReader (in, wavFormatName),
  15112. dataLength (0)
  15113. {
  15114. if (input->readInt() == chunkName ("RIFF"))
  15115. {
  15116. const uint32 len = (uint32) input->readInt();
  15117. const int64 end = input->getPosition() + len;
  15118. bool hasGotType = false;
  15119. bool hasGotData = false;
  15120. if (input->readInt() == chunkName ("WAVE"))
  15121. {
  15122. while (input->getPosition() < end
  15123. && ! input->isExhausted())
  15124. {
  15125. const int chunkType = input->readInt();
  15126. uint32 length = (uint32) input->readInt();
  15127. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  15128. if (chunkType == chunkName ("fmt "))
  15129. {
  15130. // read the format chunk
  15131. const short format = input->readShort();
  15132. const short numChans = input->readShort();
  15133. sampleRate = input->readInt();
  15134. const int bytesPerSec = input->readInt();
  15135. numChannels = numChans;
  15136. bytesPerFrame = bytesPerSec / (int)sampleRate;
  15137. bitsPerSample = 8 * bytesPerFrame / numChans;
  15138. if (format == 3)
  15139. usesFloatingPointData = true;
  15140. else if (format != 1)
  15141. bytesPerFrame = 0;
  15142. hasGotType = true;
  15143. }
  15144. else if (chunkType == chunkName ("data"))
  15145. {
  15146. // get the data chunk's position
  15147. dataLength = length;
  15148. dataChunkStart = input->getPosition();
  15149. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  15150. hasGotData = true;
  15151. }
  15152. else if (chunkType == chunkName ("bext"))
  15153. {
  15154. // Broadcast-wav extension chunk..
  15155. BWAVChunk* const bwav = (BWAVChunk*) juce_calloc (jmax (length + 1, (int) sizeof (BWAVChunk)));
  15156. if (bwav != 0)
  15157. {
  15158. input->read (bwav, length);
  15159. bwav->copyTo (metadataValues);
  15160. juce_free (bwav);
  15161. }
  15162. }
  15163. else if ((hasGotType && hasGotData) || chunkEnd <= input->getPosition())
  15164. {
  15165. break;
  15166. }
  15167. input->setPosition (chunkEnd);
  15168. }
  15169. }
  15170. }
  15171. }
  15172. ~WavAudioFormatReader()
  15173. {
  15174. }
  15175. bool read (int** destSamples,
  15176. int64 startSampleInFile,
  15177. int numSamples)
  15178. {
  15179. int64 start = startSampleInFile;
  15180. int startOffsetInDestBuffer = 0;
  15181. if (startSampleInFile < 0)
  15182. {
  15183. const int silence = (int) jmin (-startSampleInFile, (int64) numSamples);
  15184. int** destChan = destSamples;
  15185. for (int i = 2; --i >= 0;)
  15186. {
  15187. if (*destChan != 0)
  15188. {
  15189. zeromem (*destChan, sizeof (int) * silence);
  15190. ++destChan;
  15191. }
  15192. }
  15193. startOffsetInDestBuffer += silence;
  15194. numSamples -= silence;
  15195. start = 0;
  15196. }
  15197. const int numToDo = (int) jlimit ((int64) 0, (int64) numSamples, lengthInSamples - start);
  15198. if (numToDo > 0)
  15199. {
  15200. input->setPosition (dataChunkStart + start * bytesPerFrame);
  15201. int num = numToDo;
  15202. int* left = destSamples[0];
  15203. if (left != 0)
  15204. left += startOffsetInDestBuffer;
  15205. int* right = destSamples[1];
  15206. if (right != 0)
  15207. right += startOffsetInDestBuffer;
  15208. // (keep this a multiple of 3)
  15209. const int tempBufSize = 1440 * 4;
  15210. char tempBuffer [tempBufSize];
  15211. while (num > 0)
  15212. {
  15213. const int numThisTime = jmin (tempBufSize / bytesPerFrame, num);
  15214. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15215. if (bytesRead < numThisTime * bytesPerFrame)
  15216. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15217. if (bitsPerSample == 16)
  15218. {
  15219. const short* src = (const short*) tempBuffer;
  15220. if (numChannels > 1)
  15221. {
  15222. if (left == 0)
  15223. {
  15224. for (int i = numThisTime; --i >= 0;)
  15225. {
  15226. ++src;
  15227. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15228. }
  15229. }
  15230. else if (right == 0)
  15231. {
  15232. for (int i = numThisTime; --i >= 0;)
  15233. {
  15234. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15235. ++src;
  15236. }
  15237. }
  15238. else
  15239. {
  15240. for (int i = numThisTime; --i >= 0;)
  15241. {
  15242. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15243. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15244. }
  15245. }
  15246. }
  15247. else
  15248. {
  15249. for (int i = numThisTime; --i >= 0;)
  15250. {
  15251. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15252. }
  15253. }
  15254. }
  15255. else if (bitsPerSample == 24)
  15256. {
  15257. const char* src = (const char*) tempBuffer;
  15258. if (numChannels > 1)
  15259. {
  15260. if (left == 0)
  15261. {
  15262. for (int i = numThisTime; --i >= 0;)
  15263. {
  15264. src += 6;
  15265. *right++ = littleEndian24Bit (src) << 8;
  15266. }
  15267. }
  15268. else if (right == 0)
  15269. {
  15270. for (int i = numThisTime; --i >= 0;)
  15271. {
  15272. *left++ = littleEndian24Bit (src) << 8;
  15273. src += 6;
  15274. }
  15275. }
  15276. else
  15277. {
  15278. for (int i = 0; i < numThisTime; ++i)
  15279. {
  15280. *left++ = littleEndian24Bit (src) << 8;
  15281. src += 3;
  15282. *right++ = littleEndian24Bit (src) << 8;
  15283. src += 3;
  15284. }
  15285. }
  15286. }
  15287. else
  15288. {
  15289. for (int i = 0; i < numThisTime; ++i)
  15290. {
  15291. *left++ = littleEndian24Bit (src) << 8;
  15292. src += 3;
  15293. }
  15294. }
  15295. }
  15296. else if (bitsPerSample == 32)
  15297. {
  15298. const unsigned int* src = (const unsigned int*) tempBuffer;
  15299. unsigned int* l = (unsigned int*) left;
  15300. unsigned int* r = (unsigned int*) right;
  15301. if (numChannels > 1)
  15302. {
  15303. if (l == 0)
  15304. {
  15305. for (int i = numThisTime; --i >= 0;)
  15306. {
  15307. ++src;
  15308. *r++ = swapIfBigEndian (*src++);
  15309. }
  15310. }
  15311. else if (r == 0)
  15312. {
  15313. for (int i = numThisTime; --i >= 0;)
  15314. {
  15315. *l++ = swapIfBigEndian (*src++);
  15316. ++src;
  15317. }
  15318. }
  15319. else
  15320. {
  15321. for (int i = numThisTime; --i >= 0;)
  15322. {
  15323. *l++ = swapIfBigEndian (*src++);
  15324. *r++ = swapIfBigEndian (*src++);
  15325. }
  15326. }
  15327. }
  15328. else
  15329. {
  15330. for (int i = numThisTime; --i >= 0;)
  15331. {
  15332. *l++ = swapIfBigEndian (*src++);
  15333. }
  15334. }
  15335. left = (int*)l;
  15336. right = (int*)r;
  15337. }
  15338. else if (bitsPerSample == 8)
  15339. {
  15340. const unsigned char* src = (const unsigned char*) tempBuffer;
  15341. if (numChannels > 1)
  15342. {
  15343. if (left == 0)
  15344. {
  15345. for (int i = numThisTime; --i >= 0;)
  15346. {
  15347. ++src;
  15348. *right++ = ((int) *src++ - 128) << 24;
  15349. }
  15350. }
  15351. else if (right == 0)
  15352. {
  15353. for (int i = numThisTime; --i >= 0;)
  15354. {
  15355. *left++ = ((int) *src++ - 128) << 24;
  15356. ++src;
  15357. }
  15358. }
  15359. else
  15360. {
  15361. for (int i = numThisTime; --i >= 0;)
  15362. {
  15363. *left++ = ((int) *src++ - 128) << 24;
  15364. *right++ = ((int) *src++ - 128) << 24;
  15365. }
  15366. }
  15367. }
  15368. else
  15369. {
  15370. for (int i = numThisTime; --i >= 0;)
  15371. {
  15372. *left++ = ((int)*src++ - 128) << 24;
  15373. }
  15374. }
  15375. }
  15376. num -= numThisTime;
  15377. }
  15378. }
  15379. if (numToDo < numSamples)
  15380. {
  15381. int** destChan = destSamples;
  15382. while (*destChan != 0)
  15383. {
  15384. zeromem ((*destChan) + (startOffsetInDestBuffer + numToDo),
  15385. sizeof (int) * (numSamples - numToDo));
  15386. ++destChan;
  15387. }
  15388. }
  15389. return true;
  15390. }
  15391. juce_UseDebuggingNewOperator
  15392. };
  15393. class WavAudioFormatWriter : public AudioFormatWriter
  15394. {
  15395. MemoryBlock tempBlock, bwavChunk;
  15396. uint32 lengthInSamples, bytesWritten;
  15397. int64 headerPosition;
  15398. bool writeFailed;
  15399. WavAudioFormatWriter (const WavAudioFormatWriter&);
  15400. const WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  15401. void writeHeader()
  15402. {
  15403. const bool seekedOk = output->setPosition (headerPosition);
  15404. (void) seekedOk;
  15405. // if this fails, you've given it an output stream that can't seek! It needs
  15406. // to be able to seek back to write the header
  15407. jassert (seekedOk);
  15408. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  15409. output->writeInt (chunkName ("RIFF"));
  15410. output->writeInt (lengthInSamples * bytesPerFrame
  15411. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36));
  15412. output->writeInt (chunkName ("WAVE"));
  15413. output->writeInt (chunkName ("fmt "));
  15414. output->writeInt (16);
  15415. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  15416. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  15417. output->writeShort ((short) numChannels);
  15418. output->writeInt ((int) sampleRate);
  15419. output->writeInt (bytesPerFrame * (int) sampleRate);
  15420. output->writeShort ((short) bytesPerFrame);
  15421. output->writeShort ((short) bitsPerSample);
  15422. if (bwavChunk.getSize() > 0)
  15423. {
  15424. output->writeInt (chunkName ("bext"));
  15425. output->writeInt (bwavChunk.getSize());
  15426. output->write (bwavChunk.getData(), bwavChunk.getSize());
  15427. }
  15428. output->writeInt (chunkName ("data"));
  15429. output->writeInt (lengthInSamples * bytesPerFrame);
  15430. usesFloatingPointData = (bitsPerSample == 32);
  15431. }
  15432. public:
  15433. WavAudioFormatWriter (OutputStream* const out,
  15434. const double sampleRate,
  15435. const unsigned int numChannels_,
  15436. const int bits,
  15437. const StringPairArray& metadataValues)
  15438. : AudioFormatWriter (out,
  15439. wavFormatName,
  15440. sampleRate,
  15441. numChannels_,
  15442. bits),
  15443. lengthInSamples (0),
  15444. bytesWritten (0),
  15445. writeFailed (false)
  15446. {
  15447. if (metadataValues.size() > 0)
  15448. bwavChunk = BWAVChunk::createFrom (metadataValues);
  15449. headerPosition = out->getPosition();
  15450. writeHeader();
  15451. }
  15452. ~WavAudioFormatWriter()
  15453. {
  15454. writeHeader();
  15455. }
  15456. bool write (const int** data, int numSamples)
  15457. {
  15458. if (writeFailed)
  15459. return false;
  15460. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15461. tempBlock.ensureSize (bytes, false);
  15462. char* buffer = (char*) tempBlock.getData();
  15463. const int* left = data[0];
  15464. const int* right = data[1];
  15465. if (right == 0)
  15466. right = left;
  15467. if (bitsPerSample == 16)
  15468. {
  15469. short* b = (short*) buffer;
  15470. if (numChannels > 1)
  15471. {
  15472. for (int i = numSamples; --i >= 0;)
  15473. {
  15474. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  15475. *b++ = (short) swapIfBigEndian ((unsigned short) (*right++ >> 16));
  15476. }
  15477. }
  15478. else
  15479. {
  15480. for (int i = numSamples; --i >= 0;)
  15481. {
  15482. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  15483. }
  15484. }
  15485. }
  15486. else if (bitsPerSample == 24)
  15487. {
  15488. char* b = (char*) buffer;
  15489. if (numChannels > 1)
  15490. {
  15491. for (int i = numSamples; --i >= 0;)
  15492. {
  15493. littleEndian24BitToChars ((*left++) >> 8, b);
  15494. b += 3;
  15495. littleEndian24BitToChars ((*right++) >> 8, b);
  15496. b += 3;
  15497. }
  15498. }
  15499. else
  15500. {
  15501. for (int i = numSamples; --i >= 0;)
  15502. {
  15503. littleEndian24BitToChars ((*left++) >> 8, b);
  15504. b += 3;
  15505. }
  15506. }
  15507. }
  15508. else if (bitsPerSample == 32)
  15509. {
  15510. unsigned int* b = (unsigned int*) buffer;
  15511. if (numChannels > 1)
  15512. {
  15513. for (int i = numSamples; --i >= 0;)
  15514. {
  15515. *b++ = swapIfBigEndian ((unsigned int) *left++);
  15516. *b++ = swapIfBigEndian ((unsigned int) *right++);
  15517. }
  15518. }
  15519. else
  15520. {
  15521. for (int i = numSamples; --i >= 0;)
  15522. {
  15523. *b++ = swapIfBigEndian ((unsigned int) *left++);
  15524. }
  15525. }
  15526. }
  15527. else if (bitsPerSample == 8)
  15528. {
  15529. unsigned char* b = (unsigned char*) buffer;
  15530. if (numChannels > 1)
  15531. {
  15532. for (int i = numSamples; --i >= 0;)
  15533. {
  15534. *b++ = (unsigned char) (128 + (*left++ >> 24));
  15535. *b++ = (unsigned char) (128 + (*right++ >> 24));
  15536. }
  15537. }
  15538. else
  15539. {
  15540. for (int i = numSamples; --i >= 0;)
  15541. {
  15542. *b++ = (unsigned char) (128 + (*left++ >> 24));
  15543. }
  15544. }
  15545. }
  15546. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15547. || ! output->write (buffer, bytes))
  15548. {
  15549. // failed to write to disk, so let's try writing the header.
  15550. // If it's just run out of disk space, then if it does manage
  15551. // to write the header, we'll still have a useable file..
  15552. writeHeader();
  15553. writeFailed = true;
  15554. return false;
  15555. }
  15556. else
  15557. {
  15558. bytesWritten += bytes;
  15559. lengthInSamples += numSamples;
  15560. return true;
  15561. }
  15562. }
  15563. juce_UseDebuggingNewOperator
  15564. };
  15565. WavAudioFormat::WavAudioFormat()
  15566. : AudioFormat (wavFormatName, (const tchar**) wavExtensions)
  15567. {
  15568. }
  15569. WavAudioFormat::~WavAudioFormat()
  15570. {
  15571. }
  15572. const Array <int> WavAudioFormat::getPossibleSampleRates()
  15573. {
  15574. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15575. return Array <int> (rates);
  15576. }
  15577. const Array <int> WavAudioFormat::getPossibleBitDepths()
  15578. {
  15579. const int depths[] = { 8, 16, 24, 32, 0 };
  15580. return Array <int> (depths);
  15581. }
  15582. bool WavAudioFormat::canDoStereo()
  15583. {
  15584. return true;
  15585. }
  15586. bool WavAudioFormat::canDoMono()
  15587. {
  15588. return true;
  15589. }
  15590. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  15591. const bool deleteStreamIfOpeningFails)
  15592. {
  15593. WavAudioFormatReader* r = new WavAudioFormatReader (sourceStream);
  15594. if (r->sampleRate == 0)
  15595. {
  15596. if (! deleteStreamIfOpeningFails)
  15597. r->input = 0;
  15598. deleteAndZero (r);
  15599. }
  15600. return r;
  15601. }
  15602. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  15603. double sampleRate,
  15604. unsigned int numChannels,
  15605. int bitsPerSample,
  15606. const StringPairArray& metadataValues,
  15607. int /*qualityOptionIndex*/)
  15608. {
  15609. if (getPossibleBitDepths().contains (bitsPerSample))
  15610. {
  15611. return new WavAudioFormatWriter (out,
  15612. sampleRate,
  15613. numChannels,
  15614. bitsPerSample,
  15615. metadataValues);
  15616. }
  15617. return 0;
  15618. }
  15619. END_JUCE_NAMESPACE
  15620. /********* End of inlined file: juce_WavAudioFormat.cpp *********/
  15621. /********* Start of inlined file: juce_AudioFormatReaderSource.cpp *********/
  15622. BEGIN_JUCE_NAMESPACE
  15623. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  15624. const bool deleteReaderWhenThisIsDeleted)
  15625. : reader (reader_),
  15626. deleteReader (deleteReaderWhenThisIsDeleted),
  15627. nextPlayPos (0),
  15628. looping (false)
  15629. {
  15630. jassert (reader != 0);
  15631. }
  15632. AudioFormatReaderSource::~AudioFormatReaderSource()
  15633. {
  15634. releaseResources();
  15635. if (deleteReader)
  15636. delete reader;
  15637. }
  15638. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  15639. {
  15640. nextPlayPos = newPosition;
  15641. }
  15642. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  15643. {
  15644. looping = shouldLoop;
  15645. }
  15646. int AudioFormatReaderSource::getNextReadPosition() const
  15647. {
  15648. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  15649. : nextPlayPos;
  15650. }
  15651. int AudioFormatReaderSource::getTotalLength() const
  15652. {
  15653. return (int) reader->lengthInSamples;
  15654. }
  15655. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  15656. double /*sampleRate*/)
  15657. {
  15658. }
  15659. void AudioFormatReaderSource::releaseResources()
  15660. {
  15661. }
  15662. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  15663. {
  15664. if (info.numSamples > 0)
  15665. {
  15666. const int start = nextPlayPos;
  15667. if (looping)
  15668. {
  15669. const int newStart = start % (int) reader->lengthInSamples;
  15670. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  15671. if (newEnd > newStart)
  15672. {
  15673. info.buffer->readFromAudioReader (reader,
  15674. info.startSample,
  15675. newEnd - newStart,
  15676. newStart,
  15677. true, true);
  15678. }
  15679. else
  15680. {
  15681. const int endSamps = (int) reader->lengthInSamples - newStart;
  15682. info.buffer->readFromAudioReader (reader,
  15683. info.startSample,
  15684. endSamps,
  15685. newStart,
  15686. true, true);
  15687. info.buffer->readFromAudioReader (reader,
  15688. info.startSample + endSamps,
  15689. newEnd,
  15690. 0,
  15691. true, true);
  15692. }
  15693. nextPlayPos = newEnd;
  15694. }
  15695. else
  15696. {
  15697. info.buffer->readFromAudioReader (reader,
  15698. info.startSample,
  15699. info.numSamples,
  15700. start,
  15701. true, true);
  15702. nextPlayPos += info.numSamples;
  15703. }
  15704. }
  15705. }
  15706. END_JUCE_NAMESPACE
  15707. /********* End of inlined file: juce_AudioFormatReaderSource.cpp *********/
  15708. /********* Start of inlined file: juce_AudioSourcePlayer.cpp *********/
  15709. BEGIN_JUCE_NAMESPACE
  15710. AudioSourcePlayer::AudioSourcePlayer()
  15711. : source (0),
  15712. sampleRate (0),
  15713. bufferSize (0),
  15714. tempBuffer (2, 8),
  15715. lastGain (1.0f),
  15716. gain (1.0f)
  15717. {
  15718. }
  15719. AudioSourcePlayer::~AudioSourcePlayer()
  15720. {
  15721. setSource (0);
  15722. }
  15723. void AudioSourcePlayer::setSource (AudioSource* newSource)
  15724. {
  15725. if (source != newSource)
  15726. {
  15727. AudioSource* const oldSource = source;
  15728. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  15729. newSource->prepareToPlay (bufferSize, sampleRate);
  15730. {
  15731. const ScopedLock sl (readLock);
  15732. source = newSource;
  15733. }
  15734. if (oldSource != 0)
  15735. oldSource->releaseResources();
  15736. }
  15737. }
  15738. void AudioSourcePlayer::setGain (const float newGain) throw()
  15739. {
  15740. gain = newGain;
  15741. }
  15742. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  15743. int totalNumInputChannels,
  15744. float** outputChannelData,
  15745. int totalNumOutputChannels,
  15746. int numSamples)
  15747. {
  15748. // these should have been prepared by audioDeviceAboutToStart()...
  15749. jassert (sampleRate > 0 && bufferSize > 0);
  15750. const ScopedLock sl (readLock);
  15751. if (source != 0)
  15752. {
  15753. AudioSourceChannelInfo info;
  15754. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  15755. // messy stuff needed to compact the channels down into an array
  15756. // of non-zero pointers..
  15757. for (i = 0; i < totalNumInputChannels; ++i)
  15758. {
  15759. if (inputChannelData[i] != 0)
  15760. {
  15761. inputChans [numInputs++] = inputChannelData[i];
  15762. if (numInputs >= numElementsInArray (inputChans))
  15763. break;
  15764. }
  15765. }
  15766. for (i = 0; i < totalNumOutputChannels; ++i)
  15767. {
  15768. if (outputChannelData[i] != 0)
  15769. {
  15770. outputChans [numOutputs++] = outputChannelData[i];
  15771. if (numOutputs >= numElementsInArray (outputChans))
  15772. break;
  15773. }
  15774. }
  15775. if (numInputs > numOutputs)
  15776. {
  15777. // if there aren't enough output channels for the number of
  15778. // inputs, we need to create some temporary extra ones (can't
  15779. // use the input data in case it gets written to)
  15780. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  15781. false, false, true);
  15782. for (i = 0; i < numOutputs; ++i)
  15783. {
  15784. channels[numActiveChans] = outputChans[i];
  15785. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  15786. ++numActiveChans;
  15787. }
  15788. for (i = numOutputs; i < numInputs; ++i)
  15789. {
  15790. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  15791. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  15792. ++numActiveChans;
  15793. }
  15794. }
  15795. else
  15796. {
  15797. for (i = 0; i < numInputs; ++i)
  15798. {
  15799. channels[numActiveChans] = outputChans[i];
  15800. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  15801. ++numActiveChans;
  15802. }
  15803. for (i = numInputs; i < numOutputs; ++i)
  15804. {
  15805. channels[numActiveChans] = outputChans[i];
  15806. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  15807. ++numActiveChans;
  15808. }
  15809. }
  15810. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  15811. info.buffer = &buffer;
  15812. info.startSample = 0;
  15813. info.numSamples = numSamples;
  15814. source->getNextAudioBlock (info);
  15815. for (i = info.buffer->getNumChannels(); --i >= 0;)
  15816. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  15817. lastGain = gain;
  15818. }
  15819. else
  15820. {
  15821. for (int i = 0; i < totalNumOutputChannels; ++i)
  15822. if (outputChannelData[i] != 0)
  15823. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  15824. }
  15825. }
  15826. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  15827. {
  15828. sampleRate = device->getCurrentSampleRate();
  15829. bufferSize = device->getCurrentBufferSizeSamples();
  15830. zeromem (channels, sizeof (channels));
  15831. if (source != 0)
  15832. source->prepareToPlay (bufferSize, sampleRate);
  15833. }
  15834. void AudioSourcePlayer::audioDeviceStopped()
  15835. {
  15836. if (source != 0)
  15837. source->releaseResources();
  15838. sampleRate = 0.0;
  15839. bufferSize = 0;
  15840. tempBuffer.setSize (2, 8);
  15841. }
  15842. END_JUCE_NAMESPACE
  15843. /********* End of inlined file: juce_AudioSourcePlayer.cpp *********/
  15844. /********* Start of inlined file: juce_AudioTransportSource.cpp *********/
  15845. BEGIN_JUCE_NAMESPACE
  15846. AudioTransportSource::AudioTransportSource()
  15847. : source (0),
  15848. resamplerSource (0),
  15849. bufferingSource (0),
  15850. positionableSource (0),
  15851. masterSource (0),
  15852. gain (1.0f),
  15853. lastGain (1.0f),
  15854. playing (false),
  15855. stopped (true),
  15856. sampleRate (44100.0),
  15857. sourceSampleRate (0.0),
  15858. blockSize (128),
  15859. readAheadBufferSize (0),
  15860. isPrepared (false),
  15861. inputStreamEOF (false)
  15862. {
  15863. }
  15864. AudioTransportSource::~AudioTransportSource()
  15865. {
  15866. setSource (0);
  15867. releaseResources();
  15868. }
  15869. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  15870. int readAheadBufferSize_,
  15871. double sourceSampleRateToCorrectFor)
  15872. {
  15873. if (source == newSource)
  15874. {
  15875. if (source == 0)
  15876. return;
  15877. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  15878. }
  15879. readAheadBufferSize = readAheadBufferSize_;
  15880. sourceSampleRate = sourceSampleRateToCorrectFor;
  15881. ResamplingAudioSource* newResamplerSource = 0;
  15882. BufferingAudioSource* newBufferingSource = 0;
  15883. PositionableAudioSource* newPositionableSource = 0;
  15884. AudioSource* newMasterSource = 0;
  15885. ResamplingAudioSource* oldResamplerSource = resamplerSource;
  15886. BufferingAudioSource* oldBufferingSource = bufferingSource;
  15887. AudioSource* oldMasterSource = masterSource;
  15888. if (newSource != 0)
  15889. {
  15890. newPositionableSource = newSource;
  15891. if (readAheadBufferSize_ > 0)
  15892. newPositionableSource = newBufferingSource
  15893. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  15894. newPositionableSource->setNextReadPosition (0);
  15895. if (sourceSampleRateToCorrectFor != 0)
  15896. newMasterSource = newResamplerSource
  15897. = new ResamplingAudioSource (newPositionableSource, false);
  15898. else
  15899. newMasterSource = newPositionableSource;
  15900. if (isPrepared)
  15901. {
  15902. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  15903. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  15904. newMasterSource->prepareToPlay (blockSize, sampleRate);
  15905. }
  15906. }
  15907. {
  15908. const ScopedLock sl (callbackLock);
  15909. source = newSource;
  15910. resamplerSource = newResamplerSource;
  15911. bufferingSource = newBufferingSource;
  15912. masterSource = newMasterSource;
  15913. positionableSource = newPositionableSource;
  15914. playing = false;
  15915. }
  15916. if (oldMasterSource != 0)
  15917. oldMasterSource->releaseResources();
  15918. if (oldResamplerSource != 0)
  15919. delete oldResamplerSource;
  15920. if (oldBufferingSource != 0)
  15921. delete oldBufferingSource;
  15922. }
  15923. void AudioTransportSource::start()
  15924. {
  15925. if ((! playing) && masterSource != 0)
  15926. {
  15927. callbackLock.enter();
  15928. playing = true;
  15929. stopped = false;
  15930. inputStreamEOF = false;
  15931. callbackLock.exit();
  15932. sendChangeMessage (this);
  15933. }
  15934. }
  15935. void AudioTransportSource::stop()
  15936. {
  15937. if (playing)
  15938. {
  15939. callbackLock.enter();
  15940. playing = false;
  15941. callbackLock.exit();
  15942. int n = 500;
  15943. while (--n >= 0 && ! stopped)
  15944. Thread::sleep (2);
  15945. sendChangeMessage (this);
  15946. }
  15947. }
  15948. void AudioTransportSource::setPosition (double newPosition)
  15949. {
  15950. if (sampleRate > 0.0)
  15951. setNextReadPosition (roundDoubleToInt (newPosition * sampleRate));
  15952. }
  15953. double AudioTransportSource::getCurrentPosition() const
  15954. {
  15955. if (sampleRate > 0.0)
  15956. return getNextReadPosition() / sampleRate;
  15957. else
  15958. return 0.0;
  15959. }
  15960. void AudioTransportSource::setNextReadPosition (int newPosition)
  15961. {
  15962. if (positionableSource != 0)
  15963. {
  15964. if (sampleRate > 0 && sourceSampleRate > 0)
  15965. newPosition = roundDoubleToInt (newPosition * sourceSampleRate / sampleRate);
  15966. positionableSource->setNextReadPosition (newPosition);
  15967. }
  15968. }
  15969. int AudioTransportSource::getNextReadPosition() const
  15970. {
  15971. if (positionableSource != 0)
  15972. {
  15973. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  15974. return roundDoubleToInt (positionableSource->getNextReadPosition() * ratio);
  15975. }
  15976. return 0;
  15977. }
  15978. int AudioTransportSource::getTotalLength() const
  15979. {
  15980. const ScopedLock sl (callbackLock);
  15981. if (positionableSource != 0)
  15982. {
  15983. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  15984. return roundDoubleToInt (positionableSource->getTotalLength() * ratio);
  15985. }
  15986. return 0;
  15987. }
  15988. bool AudioTransportSource::isLooping() const
  15989. {
  15990. const ScopedLock sl (callbackLock);
  15991. return positionableSource != 0
  15992. && positionableSource->isLooping();
  15993. }
  15994. void AudioTransportSource::setGain (const float newGain) throw()
  15995. {
  15996. gain = newGain;
  15997. }
  15998. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  15999. double sampleRate_)
  16000. {
  16001. const ScopedLock sl (callbackLock);
  16002. sampleRate = sampleRate_;
  16003. blockSize = samplesPerBlockExpected;
  16004. if (masterSource != 0)
  16005. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16006. if (resamplerSource != 0 && sourceSampleRate != 0)
  16007. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  16008. isPrepared = true;
  16009. }
  16010. void AudioTransportSource::releaseResources()
  16011. {
  16012. const ScopedLock sl (callbackLock);
  16013. if (masterSource != 0)
  16014. masterSource->releaseResources();
  16015. isPrepared = false;
  16016. }
  16017. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16018. {
  16019. const ScopedLock sl (callbackLock);
  16020. inputStreamEOF = false;
  16021. if (masterSource != 0 && ! stopped)
  16022. {
  16023. masterSource->getNextAudioBlock (info);
  16024. if (! playing)
  16025. {
  16026. // just stopped playing, so fade out the last block..
  16027. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  16028. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  16029. if (info.numSamples > 256)
  16030. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  16031. }
  16032. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  16033. && ! positionableSource->isLooping())
  16034. {
  16035. playing = false;
  16036. inputStreamEOF = true;
  16037. sendChangeMessage (this);
  16038. }
  16039. stopped = ! playing;
  16040. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  16041. {
  16042. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  16043. lastGain, gain);
  16044. }
  16045. }
  16046. else
  16047. {
  16048. info.clearActiveBufferRegion();
  16049. stopped = true;
  16050. }
  16051. lastGain = gain;
  16052. }
  16053. END_JUCE_NAMESPACE
  16054. /********* End of inlined file: juce_AudioTransportSource.cpp *********/
  16055. /********* Start of inlined file: juce_BufferingAudioSource.cpp *********/
  16056. BEGIN_JUCE_NAMESPACE
  16057. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  16058. public Thread,
  16059. private Timer
  16060. {
  16061. public:
  16062. SharedBufferingAudioSourceThread()
  16063. : Thread ("Audio Buffer"),
  16064. sources (8)
  16065. {
  16066. }
  16067. ~SharedBufferingAudioSourceThread()
  16068. {
  16069. stopThread (10000);
  16070. clearSingletonInstance();
  16071. }
  16072. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  16073. void addSource (BufferingAudioSource* source)
  16074. {
  16075. const ScopedLock sl (lock);
  16076. if (! sources.contains ((void*) source))
  16077. {
  16078. sources.add ((void*) source);
  16079. startThread();
  16080. stopTimer();
  16081. }
  16082. notify();
  16083. }
  16084. void removeSource (BufferingAudioSource* source)
  16085. {
  16086. const ScopedLock sl (lock);
  16087. sources.removeValue ((void*) source);
  16088. if (sources.size() == 0)
  16089. startTimer (5000);
  16090. }
  16091. private:
  16092. VoidArray sources;
  16093. CriticalSection lock;
  16094. void run()
  16095. {
  16096. while (! threadShouldExit())
  16097. {
  16098. bool busy = false;
  16099. for (int i = sources.size(); --i >= 0;)
  16100. {
  16101. if (threadShouldExit())
  16102. return;
  16103. const ScopedLock sl (lock);
  16104. BufferingAudioSource* const b = (BufferingAudioSource*) sources[i];
  16105. if (b != 0 && b->readNextBufferChunk())
  16106. busy = true;
  16107. }
  16108. if (! busy)
  16109. wait (500);
  16110. }
  16111. }
  16112. void timerCallback()
  16113. {
  16114. stopTimer();
  16115. if (sources.size() == 0)
  16116. deleteInstance();
  16117. }
  16118. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  16119. const SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  16120. };
  16121. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  16122. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  16123. const bool deleteSourceWhenDeleted_,
  16124. int numberOfSamplesToBuffer_)
  16125. : source (source_),
  16126. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  16127. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  16128. buffer (2, 0),
  16129. bufferValidStart (0),
  16130. bufferValidEnd (0),
  16131. nextPlayPos (0),
  16132. wasSourceLooping (false)
  16133. {
  16134. jassert (source_ != 0);
  16135. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  16136. // not using a larger buffer..
  16137. }
  16138. BufferingAudioSource::~BufferingAudioSource()
  16139. {
  16140. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16141. if (thread != 0)
  16142. thread->removeSource (this);
  16143. if (deleteSourceWhenDeleted)
  16144. delete source;
  16145. }
  16146. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  16147. {
  16148. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  16149. sampleRate = sampleRate_;
  16150. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  16151. buffer.clear();
  16152. bufferValidStart = 0;
  16153. bufferValidEnd = 0;
  16154. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  16155. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  16156. buffer.getNumSamples() / 2))
  16157. {
  16158. SharedBufferingAudioSourceThread::getInstance()->notify();
  16159. Thread::sleep (5);
  16160. }
  16161. }
  16162. void BufferingAudioSource::releaseResources()
  16163. {
  16164. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16165. if (thread != 0)
  16166. thread->removeSource (this);
  16167. buffer.setSize (2, 0);
  16168. source->releaseResources();
  16169. }
  16170. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16171. {
  16172. const ScopedLock sl (bufferStartPosLock);
  16173. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  16174. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  16175. if (validStart == validEnd)
  16176. {
  16177. // total cache miss
  16178. info.clearActiveBufferRegion();
  16179. }
  16180. else
  16181. {
  16182. if (validStart > 0)
  16183. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  16184. if (validEnd < info.numSamples)
  16185. info.buffer->clear (info.startSample + validEnd,
  16186. info.numSamples - validEnd); // partial cache miss at end
  16187. if (validStart < validEnd)
  16188. {
  16189. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  16190. {
  16191. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  16192. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  16193. if (startBufferIndex < endBufferIndex)
  16194. {
  16195. info.buffer->copyFrom (chan, info.startSample + validStart,
  16196. buffer,
  16197. chan, startBufferIndex,
  16198. validEnd - validStart);
  16199. }
  16200. else
  16201. {
  16202. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  16203. info.buffer->copyFrom (chan, info.startSample + validStart,
  16204. buffer,
  16205. chan, startBufferIndex,
  16206. initialSize);
  16207. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  16208. buffer,
  16209. chan, 0,
  16210. (validEnd - validStart) - initialSize);
  16211. }
  16212. }
  16213. }
  16214. nextPlayPos += info.numSamples;
  16215. }
  16216. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16217. if (thread != 0)
  16218. thread->notify();
  16219. }
  16220. int BufferingAudioSource::getNextReadPosition() const
  16221. {
  16222. return (source->isLooping() && nextPlayPos > 0)
  16223. ? nextPlayPos % source->getTotalLength()
  16224. : nextPlayPos;
  16225. }
  16226. void BufferingAudioSource::setNextReadPosition (int newPosition)
  16227. {
  16228. const ScopedLock sl (bufferStartPosLock);
  16229. nextPlayPos = newPosition;
  16230. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16231. if (thread != 0)
  16232. thread->notify();
  16233. }
  16234. bool BufferingAudioSource::readNextBufferChunk()
  16235. {
  16236. bufferStartPosLock.enter();
  16237. if (wasSourceLooping != isLooping())
  16238. {
  16239. wasSourceLooping = isLooping();
  16240. bufferValidStart = 0;
  16241. bufferValidEnd = 0;
  16242. }
  16243. int newBVS = jmax (0, nextPlayPos);
  16244. int newBVE = newBVS + buffer.getNumSamples() - 4;
  16245. int sectionToReadStart = 0;
  16246. int sectionToReadEnd = 0;
  16247. const int maxChunkSize = 2048;
  16248. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  16249. {
  16250. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  16251. sectionToReadStart = newBVS;
  16252. sectionToReadEnd = newBVE;
  16253. bufferValidStart = 0;
  16254. bufferValidEnd = 0;
  16255. }
  16256. else if (abs (newBVS - bufferValidStart) > 512
  16257. || abs (newBVE - bufferValidEnd) > 512)
  16258. {
  16259. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  16260. sectionToReadStart = bufferValidEnd;
  16261. sectionToReadEnd = newBVE;
  16262. bufferValidStart = newBVS;
  16263. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  16264. }
  16265. bufferStartPosLock.exit();
  16266. if (sectionToReadStart != sectionToReadEnd)
  16267. {
  16268. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  16269. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  16270. if (bufferIndexStart < bufferIndexEnd)
  16271. {
  16272. readBufferSection (sectionToReadStart,
  16273. sectionToReadEnd - sectionToReadStart,
  16274. bufferIndexStart);
  16275. }
  16276. else
  16277. {
  16278. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  16279. readBufferSection (sectionToReadStart,
  16280. initialSize,
  16281. bufferIndexStart);
  16282. readBufferSection (sectionToReadStart + initialSize,
  16283. (sectionToReadEnd - sectionToReadStart) - initialSize,
  16284. 0);
  16285. }
  16286. const ScopedLock sl2 (bufferStartPosLock);
  16287. bufferValidStart = newBVS;
  16288. bufferValidEnd = newBVE;
  16289. return true;
  16290. }
  16291. else
  16292. {
  16293. return false;
  16294. }
  16295. }
  16296. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  16297. {
  16298. if (source->getNextReadPosition() != start)
  16299. source->setNextReadPosition (start);
  16300. AudioSourceChannelInfo info;
  16301. info.buffer = &buffer;
  16302. info.startSample = bufferOffset;
  16303. info.numSamples = length;
  16304. source->getNextAudioBlock (info);
  16305. }
  16306. END_JUCE_NAMESPACE
  16307. /********* End of inlined file: juce_BufferingAudioSource.cpp *********/
  16308. /********* Start of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  16309. BEGIN_JUCE_NAMESPACE
  16310. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  16311. const bool deleteSourceWhenDeleted_)
  16312. : requiredNumberOfChannels (2),
  16313. source (source_),
  16314. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  16315. buffer (2, 16)
  16316. {
  16317. remappedInfo.buffer = &buffer;
  16318. remappedInfo.startSample = 0;
  16319. }
  16320. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  16321. {
  16322. if (deleteSourceWhenDeleted)
  16323. delete source;
  16324. }
  16325. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  16326. {
  16327. const ScopedLock sl (lock);
  16328. requiredNumberOfChannels = requiredNumberOfChannels_;
  16329. }
  16330. void ChannelRemappingAudioSource::clearAllMappings() throw()
  16331. {
  16332. const ScopedLock sl (lock);
  16333. remappedInputs.clear();
  16334. remappedOutputs.clear();
  16335. }
  16336. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  16337. {
  16338. const ScopedLock sl (lock);
  16339. while (remappedInputs.size() < destIndex)
  16340. remappedInputs.add (-1);
  16341. remappedInputs.set (destIndex, sourceIndex);
  16342. }
  16343. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  16344. {
  16345. const ScopedLock sl (lock);
  16346. while (remappedOutputs.size() < sourceIndex)
  16347. remappedOutputs.add (-1);
  16348. remappedOutputs.set (sourceIndex, destIndex);
  16349. }
  16350. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  16351. {
  16352. const ScopedLock sl (lock);
  16353. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  16354. return remappedInputs.getUnchecked (inputChannelIndex);
  16355. return -1;
  16356. }
  16357. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  16358. {
  16359. const ScopedLock sl (lock);
  16360. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  16361. return remappedOutputs .getUnchecked (outputChannelIndex);
  16362. return -1;
  16363. }
  16364. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  16365. {
  16366. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16367. }
  16368. void ChannelRemappingAudioSource::releaseResources()
  16369. {
  16370. source->releaseResources();
  16371. }
  16372. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  16373. {
  16374. const ScopedLock sl (lock);
  16375. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  16376. const int numChans = bufferToFill.buffer->getNumChannels();
  16377. int i;
  16378. for (i = 0; i < buffer.getNumChannels(); ++i)
  16379. {
  16380. const int remappedChan = getRemappedInputChannel (i);
  16381. if (remappedChan >= 0 && remappedChan < numChans)
  16382. {
  16383. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  16384. remappedChan,
  16385. bufferToFill.startSample,
  16386. bufferToFill.numSamples);
  16387. }
  16388. else
  16389. {
  16390. buffer.clear (i, 0, bufferToFill.numSamples);
  16391. }
  16392. }
  16393. remappedInfo.numSamples = bufferToFill.numSamples;
  16394. source->getNextAudioBlock (remappedInfo);
  16395. bufferToFill.clearActiveBufferRegion();
  16396. for (i = 0; i < requiredNumberOfChannels; ++i)
  16397. {
  16398. const int remappedChan = getRemappedOutputChannel (i);
  16399. if (remappedChan >= 0 && remappedChan < numChans)
  16400. {
  16401. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  16402. buffer, i, 0, bufferToFill.numSamples);
  16403. }
  16404. }
  16405. }
  16406. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  16407. {
  16408. XmlElement* e = new XmlElement (T("MAPPINGS"));
  16409. String ins, outs;
  16410. int i;
  16411. const ScopedLock sl (lock);
  16412. for (i = 0; i < remappedInputs.size(); ++i)
  16413. ins << remappedInputs.getUnchecked(i) << T(' ');
  16414. for (i = 0; i < remappedOutputs.size(); ++i)
  16415. outs << remappedOutputs.getUnchecked(i) << T(' ');
  16416. e->setAttribute (T("inputs"), ins.trimEnd());
  16417. e->setAttribute (T("outputs"), outs.trimEnd());
  16418. return e;
  16419. }
  16420. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  16421. {
  16422. if (e.hasTagName (T("MAPPINGS")))
  16423. {
  16424. const ScopedLock sl (lock);
  16425. clearAllMappings();
  16426. StringArray ins, outs;
  16427. ins.addTokens (e.getStringAttribute (T("inputs")), false);
  16428. outs.addTokens (e.getStringAttribute (T("outputs")), false);
  16429. int i;
  16430. for (i = 0; i < ins.size(); ++i)
  16431. remappedInputs.add (ins[i].getIntValue());
  16432. for (i = 0; i < outs.size(); ++i)
  16433. remappedOutputs.add (outs[i].getIntValue());
  16434. }
  16435. }
  16436. END_JUCE_NAMESPACE
  16437. /********* End of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  16438. /********* Start of inlined file: juce_IIRFilterAudioSource.cpp *********/
  16439. BEGIN_JUCE_NAMESPACE
  16440. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  16441. const bool deleteInputWhenDeleted_)
  16442. : input (inputSource),
  16443. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  16444. {
  16445. jassert (inputSource != 0);
  16446. for (int i = 2; --i >= 0;)
  16447. iirFilters.add (new IIRFilter());
  16448. }
  16449. IIRFilterAudioSource::~IIRFilterAudioSource()
  16450. {
  16451. if (deleteInputWhenDeleted)
  16452. delete input;
  16453. }
  16454. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  16455. {
  16456. for (int i = iirFilters.size(); --i >= 0;)
  16457. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  16458. }
  16459. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  16460. {
  16461. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16462. for (int i = iirFilters.size(); --i >= 0;)
  16463. iirFilters.getUnchecked(i)->reset();
  16464. }
  16465. void IIRFilterAudioSource::releaseResources()
  16466. {
  16467. input->releaseResources();
  16468. }
  16469. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  16470. {
  16471. input->getNextAudioBlock (bufferToFill);
  16472. const int numChannels = bufferToFill.buffer->getNumChannels();
  16473. while (numChannels > iirFilters.size())
  16474. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  16475. for (int i = 0; i < numChannels; ++i)
  16476. iirFilters.getUnchecked(i)
  16477. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  16478. bufferToFill.numSamples);
  16479. }
  16480. END_JUCE_NAMESPACE
  16481. /********* End of inlined file: juce_IIRFilterAudioSource.cpp *********/
  16482. /********* Start of inlined file: juce_MixerAudioSource.cpp *********/
  16483. BEGIN_JUCE_NAMESPACE
  16484. MixerAudioSource::MixerAudioSource()
  16485. : tempBuffer (2, 0),
  16486. currentSampleRate (0.0),
  16487. bufferSizeExpected (0)
  16488. {
  16489. }
  16490. MixerAudioSource::~MixerAudioSource()
  16491. {
  16492. removeAllInputs();
  16493. }
  16494. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  16495. {
  16496. if (input != 0 && ! inputs.contains (input))
  16497. {
  16498. lock.enter();
  16499. double localRate = currentSampleRate;
  16500. int localBufferSize = bufferSizeExpected;
  16501. lock.exit();
  16502. if (localRate != 0.0)
  16503. input->prepareToPlay (localBufferSize, localRate);
  16504. const ScopedLock sl (lock);
  16505. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  16506. inputs.add (input);
  16507. }
  16508. }
  16509. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  16510. {
  16511. if (input != 0)
  16512. {
  16513. lock.enter();
  16514. const int index = inputs.indexOf ((void*) input);
  16515. if (index >= 0)
  16516. {
  16517. inputsToDelete.shiftBits (index, 1);
  16518. inputs.remove (index);
  16519. }
  16520. lock.exit();
  16521. if (index >= 0)
  16522. {
  16523. input->releaseResources();
  16524. if (deleteInput)
  16525. delete input;
  16526. }
  16527. }
  16528. }
  16529. void MixerAudioSource::removeAllInputs()
  16530. {
  16531. lock.enter();
  16532. VoidArray inputsCopy (inputs);
  16533. BitArray inputsToDeleteCopy (inputsToDelete);
  16534. inputs.clear();
  16535. lock.exit();
  16536. for (int i = inputsCopy.size(); --i >= 0;)
  16537. if (inputsToDeleteCopy[i])
  16538. delete (AudioSource*) inputsCopy[i];
  16539. }
  16540. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  16541. {
  16542. tempBuffer.setSize (2, samplesPerBlockExpected);
  16543. const ScopedLock sl (lock);
  16544. currentSampleRate = sampleRate;
  16545. bufferSizeExpected = samplesPerBlockExpected;
  16546. for (int i = inputs.size(); --i >= 0;)
  16547. ((AudioSource*) inputs.getUnchecked(i))->prepareToPlay (samplesPerBlockExpected,
  16548. sampleRate);
  16549. }
  16550. void MixerAudioSource::releaseResources()
  16551. {
  16552. const ScopedLock sl (lock);
  16553. for (int i = inputs.size(); --i >= 0;)
  16554. ((AudioSource*) inputs.getUnchecked(i))->releaseResources();
  16555. tempBuffer.setSize (2, 0);
  16556. currentSampleRate = 0;
  16557. bufferSizeExpected = 0;
  16558. }
  16559. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16560. {
  16561. const ScopedLock sl (lock);
  16562. if (inputs.size() > 0)
  16563. {
  16564. ((AudioSource*) inputs.getUnchecked(0))->getNextAudioBlock (info);
  16565. if (inputs.size() > 1)
  16566. {
  16567. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  16568. info.buffer->getNumSamples());
  16569. AudioSourceChannelInfo info2;
  16570. info2.buffer = &tempBuffer;
  16571. info2.numSamples = info.numSamples;
  16572. info2.startSample = 0;
  16573. for (int i = 1; i < inputs.size(); ++i)
  16574. {
  16575. ((AudioSource*) inputs.getUnchecked(i))->getNextAudioBlock (info2);
  16576. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  16577. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  16578. }
  16579. }
  16580. }
  16581. else
  16582. {
  16583. info.clearActiveBufferRegion();
  16584. }
  16585. }
  16586. END_JUCE_NAMESPACE
  16587. /********* End of inlined file: juce_MixerAudioSource.cpp *********/
  16588. /********* Start of inlined file: juce_ResamplingAudioSource.cpp *********/
  16589. BEGIN_JUCE_NAMESPACE
  16590. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  16591. const bool deleteInputWhenDeleted_)
  16592. : input (inputSource),
  16593. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  16594. ratio (1.0),
  16595. lastRatio (1.0),
  16596. buffer (2, 0),
  16597. sampsInBuffer (0)
  16598. {
  16599. jassert (input != 0);
  16600. }
  16601. ResamplingAudioSource::~ResamplingAudioSource()
  16602. {
  16603. if (deleteInputWhenDeleted)
  16604. delete input;
  16605. }
  16606. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  16607. {
  16608. jassert (samplesInPerOutputSample > 0);
  16609. const ScopedLock sl (ratioLock);
  16610. ratio = jmax (0.0, samplesInPerOutputSample);
  16611. }
  16612. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  16613. double sampleRate)
  16614. {
  16615. const ScopedLock sl (ratioLock);
  16616. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16617. buffer.setSize (2, roundDoubleToInt (samplesPerBlockExpected * ratio) + 32);
  16618. buffer.clear();
  16619. sampsInBuffer = 0;
  16620. bufferPos = 0;
  16621. subSampleOffset = 0.0;
  16622. createLowPass (ratio);
  16623. resetFilters();
  16624. }
  16625. void ResamplingAudioSource::releaseResources()
  16626. {
  16627. input->releaseResources();
  16628. buffer.setSize (2, 0);
  16629. }
  16630. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16631. {
  16632. const ScopedLock sl (ratioLock);
  16633. if (lastRatio != ratio)
  16634. {
  16635. createLowPass (ratio);
  16636. lastRatio = ratio;
  16637. }
  16638. const int sampsNeeded = roundDoubleToInt (info.numSamples * ratio) + 2;
  16639. int bufferSize = buffer.getNumSamples();
  16640. if (bufferSize < sampsNeeded + 8)
  16641. {
  16642. bufferPos %= bufferSize;
  16643. bufferSize = sampsNeeded + 32;
  16644. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  16645. }
  16646. bufferPos %= bufferSize;
  16647. int endOfBufferPos = bufferPos + sampsInBuffer;
  16648. while (sampsNeeded > sampsInBuffer)
  16649. {
  16650. endOfBufferPos %= bufferSize;
  16651. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  16652. bufferSize - endOfBufferPos);
  16653. AudioSourceChannelInfo readInfo;
  16654. readInfo.buffer = &buffer;
  16655. readInfo.numSamples = numToDo;
  16656. readInfo.startSample = endOfBufferPos;
  16657. input->getNextAudioBlock (readInfo);
  16658. if (ratio > 1.0)
  16659. {
  16660. // for down-sampling, pre-apply the filter..
  16661. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  16662. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  16663. }
  16664. sampsInBuffer += numToDo;
  16665. endOfBufferPos += numToDo;
  16666. }
  16667. float* dl = info.buffer->getSampleData (0, info.startSample);
  16668. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  16669. const float* const bl = buffer.getSampleData (0, 0);
  16670. const float* const br = buffer.getSampleData (1, 0);
  16671. int nextPos = (bufferPos + 1) % bufferSize;
  16672. for (int m = info.numSamples; --m >= 0;)
  16673. {
  16674. const float alpha = (float) subSampleOffset;
  16675. const float invAlpha = 1.0f - alpha;
  16676. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  16677. if (dr != 0)
  16678. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  16679. subSampleOffset += ratio;
  16680. jassert (sampsInBuffer > 0);
  16681. while (subSampleOffset >= 1.0)
  16682. {
  16683. if (++bufferPos >= bufferSize)
  16684. bufferPos = 0;
  16685. --sampsInBuffer;
  16686. nextPos = (bufferPos + 1) % bufferSize;
  16687. subSampleOffset -= 1.0;
  16688. }
  16689. }
  16690. if (ratio < 1.0)
  16691. {
  16692. // for up-sampling, apply the filter after transposing..
  16693. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  16694. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  16695. }
  16696. jassert (sampsInBuffer >= 0);
  16697. }
  16698. void ResamplingAudioSource::createLowPass (const double ratio)
  16699. {
  16700. const double proportionalRate = (ratio > 1.0) ? 0.5 / ratio
  16701. : 0.5 * ratio;
  16702. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  16703. const double nSquared = n * n;
  16704. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  16705. setFilterCoefficients (c1,
  16706. c1 * 2.0f,
  16707. c1,
  16708. 1.0,
  16709. c1 * 2.0 * (1.0 - nSquared),
  16710. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  16711. }
  16712. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  16713. {
  16714. const double a = 1.0 / c4;
  16715. c1 *= a;
  16716. c2 *= a;
  16717. c3 *= a;
  16718. c5 *= a;
  16719. c6 *= a;
  16720. coefficients[0] = c1;
  16721. coefficients[1] = c2;
  16722. coefficients[2] = c3;
  16723. coefficients[3] = c4;
  16724. coefficients[4] = c5;
  16725. coefficients[5] = c6;
  16726. }
  16727. void ResamplingAudioSource::resetFilters()
  16728. {
  16729. zeromem (filterStates, sizeof (filterStates));
  16730. }
  16731. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  16732. {
  16733. while (--num >= 0)
  16734. {
  16735. const double in = *samples;
  16736. double out = coefficients[0] * in
  16737. + coefficients[1] * fs.x1
  16738. + coefficients[2] * fs.x2
  16739. - coefficients[4] * fs.y1
  16740. - coefficients[5] * fs.y2;
  16741. #if JUCE_INTEL
  16742. if (! (out < -1.0e-8 || out > 1.0e-8))
  16743. out = 0;
  16744. #endif
  16745. fs.x2 = fs.x1;
  16746. fs.x1 = in;
  16747. fs.y2 = fs.y1;
  16748. fs.y1 = out;
  16749. *samples++ = (float) out;
  16750. }
  16751. }
  16752. END_JUCE_NAMESPACE
  16753. /********* End of inlined file: juce_ResamplingAudioSource.cpp *********/
  16754. /********* Start of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  16755. BEGIN_JUCE_NAMESPACE
  16756. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  16757. : frequency (1000.0),
  16758. sampleRate (44100.0),
  16759. currentPhase (0.0),
  16760. phasePerSample (0.0),
  16761. amplitude (0.5f)
  16762. {
  16763. }
  16764. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  16765. {
  16766. }
  16767. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  16768. {
  16769. amplitude = newAmplitude;
  16770. }
  16771. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  16772. {
  16773. frequency = newFrequencyHz;
  16774. phasePerSample = 0.0;
  16775. }
  16776. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  16777. double sampleRate_)
  16778. {
  16779. currentPhase = 0.0;
  16780. phasePerSample = 0.0;
  16781. sampleRate = sampleRate_;
  16782. }
  16783. void ToneGeneratorAudioSource::releaseResources()
  16784. {
  16785. }
  16786. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16787. {
  16788. if (phasePerSample == 0.0)
  16789. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  16790. for (int i = 0; i < info.numSamples; ++i)
  16791. {
  16792. const float sample = amplitude * (float) sin (currentPhase);
  16793. currentPhase += phasePerSample;
  16794. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  16795. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  16796. }
  16797. }
  16798. END_JUCE_NAMESPACE
  16799. /********* End of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  16800. /********* Start of inlined file: juce_AudioDeviceManager.cpp *********/
  16801. BEGIN_JUCE_NAMESPACE
  16802. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  16803. : sampleRate (0),
  16804. bufferSize (0),
  16805. useDefaultInputChannels (true),
  16806. useDefaultOutputChannels (true)
  16807. {
  16808. }
  16809. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  16810. {
  16811. return outputDeviceName == other.outputDeviceName
  16812. && inputDeviceName == other.inputDeviceName
  16813. && sampleRate == other.sampleRate
  16814. && bufferSize == other.bufferSize
  16815. && inputChannels == other.inputChannels
  16816. && useDefaultInputChannels == other.useDefaultInputChannels
  16817. && outputChannels == other.outputChannels
  16818. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  16819. }
  16820. AudioDeviceManager::AudioDeviceManager()
  16821. : currentAudioDevice (0),
  16822. currentCallback (0),
  16823. numInputChansNeeded (0),
  16824. numOutputChansNeeded (2),
  16825. lastExplicitSettings (0),
  16826. listNeedsScanning (true),
  16827. useInputNames (false),
  16828. inputLevelMeasurementEnabled (false),
  16829. inputLevel (0),
  16830. testSound (0),
  16831. enabledMidiInputs (4),
  16832. midiCallbacks (4),
  16833. midiCallbackDevices (4),
  16834. defaultMidiOutput (0),
  16835. cpuUsageMs (0),
  16836. timeToCpuScale (0)
  16837. {
  16838. callbackHandler.owner = this;
  16839. }
  16840. AudioDeviceManager::~AudioDeviceManager()
  16841. {
  16842. deleteAndZero (currentAudioDevice);
  16843. deleteAndZero (defaultMidiOutput);
  16844. delete lastExplicitSettings;
  16845. delete testSound;
  16846. }
  16847. void AudioDeviceManager::createDeviceTypesIfNeeded()
  16848. {
  16849. if (availableDeviceTypes.size() == 0)
  16850. {
  16851. createAudioDeviceTypes (availableDeviceTypes);
  16852. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  16853. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  16854. if (availableDeviceTypes.size() > 0)
  16855. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  16856. }
  16857. }
  16858. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  16859. {
  16860. scanDevicesIfNeeded();
  16861. return availableDeviceTypes;
  16862. }
  16863. extern AudioIODeviceType* juce_createDefaultAudioIODeviceType();
  16864. #if JUCE_WIN32 && JUCE_ASIO
  16865. extern AudioIODeviceType* juce_createASIOAudioIODeviceType();
  16866. #endif
  16867. #if JUCE_WIN32 && JUCE_WDM_AUDIO
  16868. extern AudioIODeviceType* juce_createWDMAudioIODeviceType();
  16869. #endif
  16870. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  16871. {
  16872. AudioIODeviceType* const defaultDeviceType = juce_createDefaultAudioIODeviceType();
  16873. if (defaultDeviceType != 0)
  16874. list.add (defaultDeviceType);
  16875. #if JUCE_WIN32 && JUCE_ASIO
  16876. list.add (juce_createASIOAudioIODeviceType());
  16877. #endif
  16878. #if JUCE_WIN32 && JUCE_WDM_AUDIO
  16879. list.add (juce_createWDMAudioIODeviceType());
  16880. #endif
  16881. }
  16882. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  16883. const int numOutputChannelsNeeded,
  16884. const XmlElement* const e,
  16885. const bool selectDefaultDeviceOnFailure,
  16886. const String& preferredDefaultDeviceName)
  16887. {
  16888. scanDevicesIfNeeded();
  16889. numInputChansNeeded = numInputChannelsNeeded;
  16890. numOutputChansNeeded = numOutputChannelsNeeded;
  16891. if (e != 0 && e->hasTagName (T("DEVICESETUP")))
  16892. {
  16893. delete lastExplicitSettings;
  16894. lastExplicitSettings = new XmlElement (*e);
  16895. String error;
  16896. AudioDeviceSetup setup;
  16897. if (e->getStringAttribute (T("audioDeviceName")).isNotEmpty())
  16898. {
  16899. setup.inputDeviceName = setup.outputDeviceName
  16900. = e->getStringAttribute (T("audioDeviceName"));
  16901. }
  16902. else
  16903. {
  16904. setup.inputDeviceName = e->getStringAttribute (T("audioInputDeviceName"));
  16905. setup.outputDeviceName = e->getStringAttribute (T("audioOutputDeviceName"));
  16906. }
  16907. currentDeviceType = e->getStringAttribute (T("deviceType"));
  16908. if (currentDeviceType.isEmpty())
  16909. {
  16910. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  16911. if (type != 0)
  16912. currentDeviceType = type->getTypeName();
  16913. else if (availableDeviceTypes.size() > 0)
  16914. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  16915. }
  16916. setup.bufferSize = e->getIntAttribute (T("audioDeviceBufferSize"));
  16917. setup.sampleRate = e->getDoubleAttribute (T("audioDeviceRate"));
  16918. setup.inputChannels.parseString (e->getStringAttribute (T("audioDeviceInChans"), T("11")), 2);
  16919. setup.outputChannels.parseString (e->getStringAttribute (T("audioDeviceOutChans"), T("11")), 2);
  16920. setup.useDefaultInputChannels = ! e->hasAttribute (T("audioDeviceInChans"));
  16921. setup.useDefaultOutputChannels = ! e->hasAttribute (T("audioDeviceOutChans"));
  16922. error = setAudioDeviceSetup (setup, true);
  16923. midiInsFromXml.clear();
  16924. forEachXmlChildElementWithTagName (*e, c, T("MIDIINPUT"))
  16925. midiInsFromXml.add (c->getStringAttribute (T("name")));
  16926. const StringArray allMidiIns (MidiInput::getDevices());
  16927. for (int i = allMidiIns.size(); --i >= 0;)
  16928. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  16929. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  16930. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  16931. false, preferredDefaultDeviceName);
  16932. setDefaultMidiOutput (e->getStringAttribute (T("defaultMidiOutput")));
  16933. return error;
  16934. }
  16935. else
  16936. {
  16937. AudioDeviceSetup setup;
  16938. if (preferredDefaultDeviceName.isNotEmpty())
  16939. {
  16940. for (int j = availableDeviceTypes.size(); --j >= 0;)
  16941. {
  16942. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  16943. StringArray outs (type->getDeviceNames (false));
  16944. int i;
  16945. for (i = 0; i < outs.size(); ++i)
  16946. {
  16947. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  16948. {
  16949. setup.outputDeviceName = outs[i];
  16950. break;
  16951. }
  16952. }
  16953. StringArray ins (type->getDeviceNames (true));
  16954. for (i = 0; i < ins.size(); ++i)
  16955. {
  16956. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  16957. {
  16958. setup.inputDeviceName = ins[i];
  16959. break;
  16960. }
  16961. }
  16962. }
  16963. }
  16964. insertDefaultDeviceNames (setup);
  16965. return setAudioDeviceSetup (setup, false);
  16966. }
  16967. }
  16968. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  16969. {
  16970. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  16971. if (type != 0)
  16972. {
  16973. if (setup.outputDeviceName.isEmpty())
  16974. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  16975. if (setup.inputDeviceName.isEmpty())
  16976. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  16977. }
  16978. }
  16979. XmlElement* AudioDeviceManager::createStateXml() const
  16980. {
  16981. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  16982. }
  16983. void AudioDeviceManager::scanDevicesIfNeeded()
  16984. {
  16985. if (listNeedsScanning)
  16986. {
  16987. listNeedsScanning = false;
  16988. createDeviceTypesIfNeeded();
  16989. for (int i = availableDeviceTypes.size(); --i >= 0;)
  16990. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  16991. }
  16992. }
  16993. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  16994. {
  16995. scanDevicesIfNeeded();
  16996. for (int i = availableDeviceTypes.size(); --i >= 0;)
  16997. {
  16998. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  16999. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  17000. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  17001. {
  17002. return type;
  17003. }
  17004. }
  17005. return 0;
  17006. }
  17007. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  17008. {
  17009. setup = currentSetup;
  17010. }
  17011. void AudioDeviceManager::deleteCurrentDevice()
  17012. {
  17013. deleteAndZero (currentAudioDevice);
  17014. currentSetup.inputDeviceName = String::empty;
  17015. currentSetup.outputDeviceName = String::empty;
  17016. }
  17017. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  17018. const bool treatAsChosenDevice)
  17019. {
  17020. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  17021. {
  17022. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  17023. && currentDeviceType != type)
  17024. {
  17025. currentDeviceType = type;
  17026. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  17027. insertDefaultDeviceNames (s);
  17028. setAudioDeviceSetup (s, treatAsChosenDevice);
  17029. sendChangeMessage (this);
  17030. break;
  17031. }
  17032. }
  17033. }
  17034. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  17035. {
  17036. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  17037. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  17038. return availableDeviceTypes[i];
  17039. return availableDeviceTypes[0];
  17040. }
  17041. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  17042. const bool treatAsChosenDevice)
  17043. {
  17044. jassert (&newSetup != &currentSetup); // this will have no effect
  17045. if (newSetup == currentSetup && currentAudioDevice != 0)
  17046. return String::empty;
  17047. if (! (newSetup == currentSetup))
  17048. sendChangeMessage (this);
  17049. stopDevice();
  17050. String error;
  17051. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  17052. if (type == 0 || (newSetup.inputDeviceName.isEmpty()
  17053. && newSetup.outputDeviceName.isEmpty()))
  17054. {
  17055. deleteCurrentDevice();
  17056. if (treatAsChosenDevice)
  17057. updateXml();
  17058. return String::empty;
  17059. }
  17060. if (currentSetup.inputDeviceName != newSetup.inputDeviceName
  17061. || currentSetup.outputDeviceName != newSetup.outputDeviceName
  17062. || currentAudioDevice == 0)
  17063. {
  17064. deleteCurrentDevice();
  17065. scanDevicesIfNeeded();
  17066. if (newSetup.outputDeviceName.isNotEmpty()
  17067. && ! type->getDeviceNames (false).contains (newSetup.outputDeviceName))
  17068. {
  17069. return "No such device: " + newSetup.outputDeviceName;
  17070. }
  17071. if (newSetup.inputDeviceName.isNotEmpty()
  17072. && ! type->getDeviceNames (true).contains (newSetup.inputDeviceName))
  17073. {
  17074. return "No such device: " + newSetup.outputDeviceName;
  17075. }
  17076. currentAudioDevice = type->createDevice (newSetup.outputDeviceName,
  17077. newSetup.inputDeviceName);
  17078. if (currentAudioDevice == 0)
  17079. error = "Can't open device";
  17080. else
  17081. error = currentAudioDevice->getLastError();
  17082. if (error.isNotEmpty())
  17083. {
  17084. deleteCurrentDevice();
  17085. return error;
  17086. }
  17087. if (newSetup.useDefaultInputChannels)
  17088. {
  17089. inputChannels.clear();
  17090. inputChannels.setRange (0, numInputChansNeeded, true);
  17091. }
  17092. if (newSetup.useDefaultOutputChannels)
  17093. {
  17094. outputChannels.clear();
  17095. outputChannels.setRange (0, numOutputChansNeeded, true);
  17096. }
  17097. }
  17098. if (! newSetup.useDefaultInputChannels)
  17099. inputChannels = newSetup.inputChannels;
  17100. if (! newSetup.useDefaultOutputChannels)
  17101. outputChannels = newSetup.outputChannels;
  17102. currentSetup = newSetup;
  17103. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  17104. error = currentAudioDevice->open (inputChannels,
  17105. outputChannels,
  17106. currentSetup.sampleRate,
  17107. currentSetup.bufferSize);
  17108. if (error.isEmpty())
  17109. {
  17110. currentDeviceType = currentAudioDevice->getTypeName();
  17111. currentAudioDevice->start (&callbackHandler);
  17112. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  17113. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  17114. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  17115. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  17116. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  17117. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  17118. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  17119. if (treatAsChosenDevice)
  17120. updateXml();
  17121. }
  17122. else
  17123. {
  17124. deleteCurrentDevice();
  17125. }
  17126. return error;
  17127. }
  17128. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  17129. {
  17130. jassert (currentAudioDevice != 0);
  17131. if (rate > 0)
  17132. {
  17133. bool ok = false;
  17134. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  17135. {
  17136. const double sr = currentAudioDevice->getSampleRate (i);
  17137. if (sr == rate)
  17138. ok = true;
  17139. }
  17140. if (! ok)
  17141. rate = 0;
  17142. }
  17143. if (rate == 0)
  17144. {
  17145. double lowestAbove44 = 0.0;
  17146. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  17147. {
  17148. const double sr = currentAudioDevice->getSampleRate (i);
  17149. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  17150. lowestAbove44 = sr;
  17151. }
  17152. if (lowestAbove44 == 0.0)
  17153. rate = currentAudioDevice->getSampleRate (0);
  17154. else
  17155. rate = lowestAbove44;
  17156. }
  17157. return rate;
  17158. }
  17159. void AudioDeviceManager::stopDevice()
  17160. {
  17161. if (currentAudioDevice != 0)
  17162. currentAudioDevice->stop();
  17163. }
  17164. void AudioDeviceManager::closeAudioDevice()
  17165. {
  17166. stopDevice();
  17167. deleteAndZero (currentAudioDevice);
  17168. }
  17169. void AudioDeviceManager::restartLastAudioDevice()
  17170. {
  17171. if (currentAudioDevice == 0)
  17172. {
  17173. if (currentSetup.inputDeviceName.isEmpty()
  17174. && currentSetup.outputDeviceName.isEmpty())
  17175. {
  17176. // This method will only reload the last device that was running
  17177. // before closeAudioDevice() was called - you need to actually open
  17178. // one first, with setAudioDevice().
  17179. jassertfalse
  17180. return;
  17181. }
  17182. AudioDeviceSetup s (currentSetup);
  17183. setAudioDeviceSetup (s, false);
  17184. }
  17185. }
  17186. void AudioDeviceManager::updateXml()
  17187. {
  17188. delete lastExplicitSettings;
  17189. lastExplicitSettings = new XmlElement (T("DEVICESETUP"));
  17190. lastExplicitSettings->setAttribute (T("deviceType"), currentDeviceType);
  17191. lastExplicitSettings->setAttribute (T("audioOutputDeviceName"), currentSetup.outputDeviceName);
  17192. lastExplicitSettings->setAttribute (T("audioInputDeviceName"), currentSetup.inputDeviceName);
  17193. if (currentAudioDevice != 0)
  17194. {
  17195. lastExplicitSettings->setAttribute (T("audioDeviceRate"), currentAudioDevice->getCurrentSampleRate());
  17196. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  17197. lastExplicitSettings->setAttribute (T("audioDeviceBufferSize"), currentAudioDevice->getCurrentBufferSizeSamples());
  17198. if (! currentSetup.useDefaultInputChannels)
  17199. lastExplicitSettings->setAttribute (T("audioDeviceInChans"), currentSetup.inputChannels.toString (2));
  17200. if (! currentSetup.useDefaultOutputChannels)
  17201. lastExplicitSettings->setAttribute (T("audioDeviceOutChans"), currentSetup.outputChannels.toString (2));
  17202. }
  17203. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  17204. {
  17205. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  17206. m->setAttribute (T("name"), enabledMidiInputs[i]->getName());
  17207. lastExplicitSettings->addChildElement (m);
  17208. }
  17209. if (midiInsFromXml.size() > 0)
  17210. {
  17211. // Add any midi devices that have been enabled before, but which aren't currently
  17212. // open because the device has been disconnected.
  17213. const StringArray availableMidiDevices (MidiInput::getDevices());
  17214. for (int i = 0; i < midiInsFromXml.size(); ++i)
  17215. {
  17216. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  17217. {
  17218. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  17219. m->setAttribute (T("name"), midiInsFromXml[i]);
  17220. lastExplicitSettings->addChildElement (m);
  17221. }
  17222. }
  17223. }
  17224. if (defaultMidiOutputName.isNotEmpty())
  17225. lastExplicitSettings->setAttribute (T("defaultMidiOutput"), defaultMidiOutputName);
  17226. }
  17227. void AudioDeviceManager::setAudioCallback (AudioIODeviceCallback* newCallback)
  17228. {
  17229. if (newCallback != currentCallback)
  17230. {
  17231. AudioIODeviceCallback* lastCallback = currentCallback;
  17232. audioCallbackLock.enter();
  17233. currentCallback = 0;
  17234. audioCallbackLock.exit();
  17235. if (currentAudioDevice != 0)
  17236. {
  17237. if (lastCallback != 0)
  17238. lastCallback->audioDeviceStopped();
  17239. if (newCallback != 0)
  17240. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  17241. }
  17242. currentCallback = newCallback;
  17243. }
  17244. }
  17245. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  17246. int numInputChannels,
  17247. float** outputChannelData,
  17248. int numOutputChannels,
  17249. int numSamples)
  17250. {
  17251. const ScopedLock sl (audioCallbackLock);
  17252. if (inputLevelMeasurementEnabled)
  17253. {
  17254. for (int j = 0; j < numSamples; ++j)
  17255. {
  17256. float s = 0;
  17257. for (int i = 0; i < numInputChannels; ++i)
  17258. s += fabsf (inputChannelData[i][j]);
  17259. s /= numInputChannels;
  17260. const double decayFactor = 0.99992;
  17261. if (s > inputLevel)
  17262. inputLevel = s;
  17263. else if (inputLevel > 0.001f)
  17264. inputLevel *= decayFactor;
  17265. else
  17266. inputLevel = 0;
  17267. }
  17268. }
  17269. if (currentCallback != 0)
  17270. {
  17271. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  17272. currentCallback->audioDeviceIOCallback (inputChannelData,
  17273. numInputChannels,
  17274. outputChannelData,
  17275. numOutputChannels,
  17276. numSamples);
  17277. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  17278. const double filterAmount = 0.2;
  17279. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  17280. }
  17281. else
  17282. {
  17283. for (int i = 0; i < numOutputChannels; ++i)
  17284. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  17285. }
  17286. if (testSound != 0)
  17287. {
  17288. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  17289. const float* const src = testSound->getSampleData (0, testSoundPosition);
  17290. for (int i = 0; i < numOutputChannels; ++i)
  17291. for (int j = 0; j < numSamps; ++j)
  17292. outputChannelData [i][j] += src[j];
  17293. testSoundPosition += numSamps;
  17294. if (testSoundPosition >= testSound->getNumSamples())
  17295. {
  17296. delete testSound;
  17297. testSound = 0;
  17298. }
  17299. }
  17300. }
  17301. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  17302. {
  17303. cpuUsageMs = 0;
  17304. const double sampleRate = device->getCurrentSampleRate();
  17305. const int blockSize = device->getCurrentBufferSizeSamples();
  17306. if (sampleRate > 0.0 && blockSize > 0)
  17307. {
  17308. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  17309. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  17310. }
  17311. if (currentCallback != 0)
  17312. currentCallback->audioDeviceAboutToStart (device);
  17313. sendChangeMessage (this);
  17314. }
  17315. void AudioDeviceManager::audioDeviceStoppedInt()
  17316. {
  17317. cpuUsageMs = 0;
  17318. timeToCpuScale = 0;
  17319. sendChangeMessage (this);
  17320. if (currentCallback != 0)
  17321. currentCallback->audioDeviceStopped();
  17322. }
  17323. double AudioDeviceManager::getCpuUsage() const
  17324. {
  17325. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  17326. }
  17327. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  17328. const bool enabled)
  17329. {
  17330. if (enabled != isMidiInputEnabled (name))
  17331. {
  17332. if (enabled)
  17333. {
  17334. const int index = MidiInput::getDevices().indexOf (name);
  17335. if (index >= 0)
  17336. {
  17337. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  17338. if (min != 0)
  17339. {
  17340. enabledMidiInputs.add (min);
  17341. min->start();
  17342. }
  17343. }
  17344. }
  17345. else
  17346. {
  17347. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17348. if (enabledMidiInputs[i]->getName() == name)
  17349. enabledMidiInputs.remove (i);
  17350. }
  17351. updateXml();
  17352. sendChangeMessage (this);
  17353. }
  17354. }
  17355. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  17356. {
  17357. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17358. if (enabledMidiInputs[i]->getName() == name)
  17359. return true;
  17360. return false;
  17361. }
  17362. void AudioDeviceManager::addMidiInputCallback (const String& name,
  17363. MidiInputCallback* callback)
  17364. {
  17365. removeMidiInputCallback (name, callback);
  17366. if (name.isEmpty())
  17367. {
  17368. midiCallbacks.add (callback);
  17369. midiCallbackDevices.add (0);
  17370. }
  17371. else
  17372. {
  17373. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17374. {
  17375. if (enabledMidiInputs[i]->getName() == name)
  17376. {
  17377. const ScopedLock sl (midiCallbackLock);
  17378. midiCallbacks.add (callback);
  17379. midiCallbackDevices.add (enabledMidiInputs[i]);
  17380. break;
  17381. }
  17382. }
  17383. }
  17384. }
  17385. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  17386. MidiInputCallback* /*callback*/)
  17387. {
  17388. const ScopedLock sl (midiCallbackLock);
  17389. for (int i = midiCallbacks.size(); --i >= 0;)
  17390. {
  17391. String devName;
  17392. if (midiCallbackDevices.getUnchecked(i) != 0)
  17393. devName = midiCallbackDevices.getUnchecked(i)->getName();
  17394. if (devName == name)
  17395. {
  17396. midiCallbacks.remove (i);
  17397. midiCallbackDevices.remove (i);
  17398. }
  17399. }
  17400. }
  17401. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  17402. const MidiMessage& message)
  17403. {
  17404. if (! message.isActiveSense())
  17405. {
  17406. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  17407. const ScopedLock sl (midiCallbackLock);
  17408. for (int i = midiCallbackDevices.size(); --i >= 0;)
  17409. {
  17410. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  17411. if (md == source || (md == 0 && isDefaultSource))
  17412. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  17413. }
  17414. }
  17415. }
  17416. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  17417. {
  17418. if (defaultMidiOutputName != deviceName)
  17419. {
  17420. deleteAndZero (defaultMidiOutput);
  17421. defaultMidiOutputName = deviceName;
  17422. if (deviceName.isNotEmpty())
  17423. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  17424. updateXml();
  17425. sendChangeMessage (this);
  17426. }
  17427. }
  17428. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  17429. int numInputChannels,
  17430. float** outputChannelData,
  17431. int numOutputChannels,
  17432. int numSamples)
  17433. {
  17434. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  17435. }
  17436. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  17437. {
  17438. owner->audioDeviceAboutToStartInt (device);
  17439. }
  17440. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  17441. {
  17442. owner->audioDeviceStoppedInt();
  17443. }
  17444. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  17445. {
  17446. owner->handleIncomingMidiMessageInt (source, message);
  17447. }
  17448. void AudioDeviceManager::playTestSound()
  17449. {
  17450. audioCallbackLock.enter();
  17451. AudioSampleBuffer* oldSound = testSound;
  17452. testSound = 0;
  17453. audioCallbackLock.exit();
  17454. delete oldSound;
  17455. testSoundPosition = 0;
  17456. if (currentAudioDevice != 0)
  17457. {
  17458. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  17459. const int soundLength = (int) sampleRate;
  17460. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  17461. float* samples = newSound->getSampleData (0);
  17462. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  17463. const float amplitude = 0.5f;
  17464. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  17465. for (int i = 0; i < soundLength; ++i)
  17466. samples[i] = amplitude * (float) sin (i * phasePerSample);
  17467. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  17468. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  17469. const ScopedLock sl (audioCallbackLock);
  17470. testSound = newSound;
  17471. }
  17472. }
  17473. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  17474. {
  17475. if (inputLevelMeasurementEnabled != enableMeasurement)
  17476. {
  17477. const ScopedLock sl (audioCallbackLock);
  17478. inputLevelMeasurementEnabled = enableMeasurement;
  17479. inputLevel = 0;
  17480. }
  17481. }
  17482. double AudioDeviceManager::getCurrentInputLevel() const
  17483. {
  17484. jassert (inputLevelMeasurementEnabled); // you need to call enableInputLevelMeasurement() before using this!
  17485. return inputLevel;
  17486. }
  17487. END_JUCE_NAMESPACE
  17488. /********* End of inlined file: juce_AudioDeviceManager.cpp *********/
  17489. /********* Start of inlined file: juce_AudioIODevice.cpp *********/
  17490. BEGIN_JUCE_NAMESPACE
  17491. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  17492. : name (deviceName),
  17493. typeName (typeName_)
  17494. {
  17495. }
  17496. AudioIODevice::~AudioIODevice()
  17497. {
  17498. }
  17499. bool AudioIODevice::hasControlPanel() const
  17500. {
  17501. return false;
  17502. }
  17503. bool AudioIODevice::showControlPanel()
  17504. {
  17505. jassertfalse // this should only be called for devices which return true from
  17506. // their hasControlPanel() method.
  17507. return false;
  17508. }
  17509. END_JUCE_NAMESPACE
  17510. /********* End of inlined file: juce_AudioIODevice.cpp *********/
  17511. /********* Start of inlined file: juce_AudioIODeviceType.cpp *********/
  17512. BEGIN_JUCE_NAMESPACE
  17513. AudioIODeviceType::AudioIODeviceType (const tchar* const name)
  17514. : typeName (name)
  17515. {
  17516. }
  17517. AudioIODeviceType::~AudioIODeviceType()
  17518. {
  17519. }
  17520. END_JUCE_NAMESPACE
  17521. /********* End of inlined file: juce_AudioIODeviceType.cpp *********/
  17522. /********* Start of inlined file: juce_MidiOutput.cpp *********/
  17523. BEGIN_JUCE_NAMESPACE
  17524. MidiOutput::MidiOutput() throw()
  17525. : Thread ("midi out"),
  17526. internal (0),
  17527. firstMessage (0)
  17528. {
  17529. }
  17530. MidiOutput::PendingMessage::PendingMessage (const uint8* const data,
  17531. const int len,
  17532. const double sampleNumber) throw()
  17533. : message (data, len, sampleNumber)
  17534. {
  17535. }
  17536. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  17537. const double millisecondCounterToStartAt,
  17538. double samplesPerSecondForBuffer) throw()
  17539. {
  17540. // You've got to call startBackgroundThread() for this to actually work..
  17541. jassert (isThreadRunning());
  17542. // this needs to be a value in the future - RTFM for this method!
  17543. jassert (millisecondCounterToStartAt > 0);
  17544. samplesPerSecondForBuffer *= 0.001;
  17545. MidiBuffer::Iterator i (buffer);
  17546. const uint8* data;
  17547. int len, time;
  17548. while (i.getNextEvent (data, len, time))
  17549. {
  17550. const double eventTime = millisecondCounterToStartAt + samplesPerSecondForBuffer * time;
  17551. PendingMessage* const m
  17552. = new PendingMessage (data, len, eventTime);
  17553. const ScopedLock sl (lock);
  17554. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  17555. {
  17556. m->next = firstMessage;
  17557. firstMessage = m;
  17558. }
  17559. else
  17560. {
  17561. PendingMessage* mm = firstMessage;
  17562. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  17563. mm = mm->next;
  17564. m->next = mm->next;
  17565. mm->next = m;
  17566. }
  17567. }
  17568. notify();
  17569. }
  17570. void MidiOutput::clearAllPendingMessages() throw()
  17571. {
  17572. const ScopedLock sl (lock);
  17573. while (firstMessage != 0)
  17574. {
  17575. PendingMessage* const m = firstMessage;
  17576. firstMessage = firstMessage->next;
  17577. delete m;
  17578. }
  17579. }
  17580. void MidiOutput::startBackgroundThread() throw()
  17581. {
  17582. startThread (9);
  17583. }
  17584. void MidiOutput::stopBackgroundThread() throw()
  17585. {
  17586. stopThread (5000);
  17587. }
  17588. void MidiOutput::run()
  17589. {
  17590. while (! threadShouldExit())
  17591. {
  17592. uint32 now = Time::getMillisecondCounter();
  17593. uint32 eventTime = 0;
  17594. uint32 timeToWait = 500;
  17595. lock.enter();
  17596. PendingMessage* message = firstMessage;
  17597. if (message != 0)
  17598. {
  17599. eventTime = roundDoubleToInt (message->message.getTimeStamp());
  17600. if (eventTime > now + 20)
  17601. {
  17602. timeToWait = jmax (10, eventTime - now - 100);
  17603. message = 0;
  17604. }
  17605. else
  17606. {
  17607. firstMessage = message->next;
  17608. }
  17609. }
  17610. lock.exit();
  17611. if (message != 0)
  17612. {
  17613. if (eventTime > now)
  17614. {
  17615. Time::waitForMillisecondCounter (eventTime);
  17616. if (threadShouldExit())
  17617. break;
  17618. }
  17619. if (eventTime > now - 200)
  17620. sendMessageNow (message->message);
  17621. delete message;
  17622. }
  17623. else
  17624. {
  17625. jassert (timeToWait < 1000 * 30);
  17626. wait (timeToWait);
  17627. }
  17628. }
  17629. clearAllPendingMessages();
  17630. }
  17631. END_JUCE_NAMESPACE
  17632. /********* End of inlined file: juce_MidiOutput.cpp *********/
  17633. /********* Start of inlined file: juce_AudioDataConverters.cpp *********/
  17634. BEGIN_JUCE_NAMESPACE
  17635. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17636. {
  17637. const double maxVal = (double) 0x7fff;
  17638. char* intData = (char*) dest;
  17639. for (int i = 0; i < numSamples; ++i)
  17640. {
  17641. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17642. intData += destBytesPerSample;
  17643. }
  17644. }
  17645. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17646. {
  17647. const double maxVal = (double) 0x7fff;
  17648. char* intData = (char*) dest;
  17649. for (int i = 0; i < numSamples; ++i)
  17650. {
  17651. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17652. intData += destBytesPerSample;
  17653. }
  17654. }
  17655. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17656. {
  17657. const double maxVal = (double) 0x7fffff;
  17658. char* intData = (char*) dest;
  17659. for (int i = 0; i < numSamples; ++i)
  17660. {
  17661. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  17662. intData += destBytesPerSample;
  17663. }
  17664. }
  17665. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17666. {
  17667. const double maxVal = (double) 0x7fffff;
  17668. char* intData = (char*) dest;
  17669. for (int i = 0; i < numSamples; ++i)
  17670. {
  17671. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  17672. intData += destBytesPerSample;
  17673. }
  17674. }
  17675. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17676. {
  17677. const double maxVal = (double) 0x7fffffff;
  17678. char* intData = (char*) dest;
  17679. for (int i = 0; i < numSamples; ++i)
  17680. {
  17681. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17682. intData += destBytesPerSample;
  17683. }
  17684. }
  17685. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17686. {
  17687. const double maxVal = (double) 0x7fffffff;
  17688. char* intData = (char*) dest;
  17689. for (int i = 0; i < numSamples; ++i)
  17690. {
  17691. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17692. intData += destBytesPerSample;
  17693. }
  17694. }
  17695. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17696. {
  17697. char* d = (char*) dest;
  17698. for (int i = 0; i < numSamples; ++i)
  17699. {
  17700. *(float*)d = source[i];
  17701. #if JUCE_BIG_ENDIAN
  17702. *(uint32*)d = swapByteOrder (*(uint32*)d);
  17703. #endif
  17704. d += destBytesPerSample;
  17705. }
  17706. }
  17707. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17708. {
  17709. char* d = (char*) dest;
  17710. for (int i = 0; i < numSamples; ++i)
  17711. {
  17712. *(float*)d = source[i];
  17713. #if JUCE_LITTLE_ENDIAN
  17714. *(uint32*)d = swapByteOrder (*(uint32*)d);
  17715. #endif
  17716. d += destBytesPerSample;
  17717. }
  17718. }
  17719. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17720. {
  17721. const float scale = 1.0f / 0x7fff;
  17722. const char* intData = (const char*) source;
  17723. for (int i = 0; i < numSamples; ++i)
  17724. {
  17725. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  17726. intData += srcBytesPerSample;
  17727. }
  17728. }
  17729. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17730. {
  17731. const float scale = 1.0f / 0x7fff;
  17732. const char* intData = (const char*) source;
  17733. for (int i = 0; i < numSamples; ++i)
  17734. {
  17735. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  17736. intData += srcBytesPerSample;
  17737. }
  17738. }
  17739. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17740. {
  17741. const float scale = 1.0f / 0x7fffff;
  17742. const char* intData = (const char*) source;
  17743. for (int i = 0; i < numSamples; ++i)
  17744. {
  17745. dest[i] = scale * (short) littleEndian24Bit (intData);
  17746. intData += srcBytesPerSample;
  17747. }
  17748. }
  17749. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17750. {
  17751. const float scale = 1.0f / 0x7fffff;
  17752. const char* intData = (const char*) source;
  17753. for (int i = 0; i < numSamples; ++i)
  17754. {
  17755. dest[i] = scale * (short) bigEndian24Bit (intData);
  17756. intData += srcBytesPerSample;
  17757. }
  17758. }
  17759. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17760. {
  17761. const float scale = 1.0f / 0x7fffffff;
  17762. const char* intData = (const char*) source;
  17763. for (int i = 0; i < numSamples; ++i)
  17764. {
  17765. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  17766. intData += srcBytesPerSample;
  17767. }
  17768. }
  17769. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17770. {
  17771. const float scale = 1.0f / 0x7fffffff;
  17772. const char* intData = (const char*) source;
  17773. for (int i = 0; i < numSamples; ++i)
  17774. {
  17775. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  17776. intData += srcBytesPerSample;
  17777. }
  17778. }
  17779. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17780. {
  17781. const char* s = (const char*) source;
  17782. for (int i = 0; i < numSamples; ++i)
  17783. {
  17784. dest[i] = *(float*)s;
  17785. #if JUCE_BIG_ENDIAN
  17786. uint32* const d = (uint32*) (dest + i);
  17787. *d = swapByteOrder (*d);
  17788. #endif
  17789. s += srcBytesPerSample;
  17790. }
  17791. }
  17792. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17793. {
  17794. const char* s = (const char*) source;
  17795. for (int i = 0; i < numSamples; ++i)
  17796. {
  17797. dest[i] = *(float*)s;
  17798. #if JUCE_LITTLE_ENDIAN
  17799. uint32* const d = (uint32*) (dest + i);
  17800. *d = swapByteOrder (*d);
  17801. #endif
  17802. s += srcBytesPerSample;
  17803. }
  17804. }
  17805. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  17806. const float* const source,
  17807. void* const dest,
  17808. const int numSamples)
  17809. {
  17810. switch (destFormat)
  17811. {
  17812. case int16LE:
  17813. convertFloatToInt16LE (source, dest, numSamples);
  17814. break;
  17815. case int16BE:
  17816. convertFloatToInt16BE (source, dest, numSamples);
  17817. break;
  17818. case int24LE:
  17819. convertFloatToInt24LE (source, dest, numSamples);
  17820. break;
  17821. case int24BE:
  17822. convertFloatToInt24BE (source, dest, numSamples);
  17823. break;
  17824. case int32LE:
  17825. convertFloatToInt32LE (source, dest, numSamples);
  17826. break;
  17827. case int32BE:
  17828. convertFloatToInt32BE (source, dest, numSamples);
  17829. break;
  17830. case float32LE:
  17831. convertFloatToFloat32LE (source, dest, numSamples);
  17832. break;
  17833. case float32BE:
  17834. convertFloatToFloat32BE (source, dest, numSamples);
  17835. break;
  17836. default:
  17837. jassertfalse
  17838. break;
  17839. }
  17840. }
  17841. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  17842. const void* const source,
  17843. float* const dest,
  17844. const int numSamples)
  17845. {
  17846. switch (sourceFormat)
  17847. {
  17848. case int16LE:
  17849. convertInt16LEToFloat (source, dest, numSamples);
  17850. break;
  17851. case int16BE:
  17852. convertInt16BEToFloat (source, dest, numSamples);
  17853. break;
  17854. case int24LE:
  17855. convertInt24LEToFloat (source, dest, numSamples);
  17856. break;
  17857. case int24BE:
  17858. convertInt24BEToFloat (source, dest, numSamples);
  17859. break;
  17860. case int32LE:
  17861. convertInt32LEToFloat (source, dest, numSamples);
  17862. break;
  17863. case int32BE:
  17864. convertInt32BEToFloat (source, dest, numSamples);
  17865. break;
  17866. case float32LE:
  17867. convertFloat32LEToFloat (source, dest, numSamples);
  17868. break;
  17869. case float32BE:
  17870. convertFloat32BEToFloat (source, dest, numSamples);
  17871. break;
  17872. default:
  17873. jassertfalse
  17874. break;
  17875. }
  17876. }
  17877. void AudioDataConverters::interleaveSamples (const float** const source,
  17878. float* const dest,
  17879. const int numSamples,
  17880. const int numChannels)
  17881. {
  17882. for (int chan = 0; chan < numChannels; ++chan)
  17883. {
  17884. int i = chan;
  17885. const float* src = source [chan];
  17886. for (int j = 0; j < numSamples; ++j)
  17887. {
  17888. dest [i] = src [j];
  17889. i += numChannels;
  17890. }
  17891. }
  17892. }
  17893. void AudioDataConverters::deinterleaveSamples (const float* const source,
  17894. float** const dest,
  17895. const int numSamples,
  17896. const int numChannels)
  17897. {
  17898. for (int chan = 0; chan < numChannels; ++chan)
  17899. {
  17900. int i = chan;
  17901. float* dst = dest [chan];
  17902. for (int j = 0; j < numSamples; ++j)
  17903. {
  17904. dst [j] = source [i];
  17905. i += numChannels;
  17906. }
  17907. }
  17908. }
  17909. END_JUCE_NAMESPACE
  17910. /********* End of inlined file: juce_AudioDataConverters.cpp *********/
  17911. /********* Start of inlined file: juce_AudioSampleBuffer.cpp *********/
  17912. BEGIN_JUCE_NAMESPACE
  17913. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  17914. const int numSamples) throw()
  17915. : numChannels (numChannels_),
  17916. size (numSamples)
  17917. {
  17918. jassert (numSamples >= 0);
  17919. jassert (numChannels_ > 0 && numChannels_ <= maxNumAudioSampleBufferChannels);
  17920. allocatedBytes = numChannels * numSamples * sizeof (float) + 32;
  17921. allocatedData = (float*) juce_malloc (allocatedBytes);
  17922. float* chan = allocatedData;
  17923. for (int i = 0; i < numChannels_; ++i)
  17924. {
  17925. channels[i] = chan;
  17926. chan += numSamples;
  17927. }
  17928. channels [numChannels_] = 0;
  17929. }
  17930. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  17931. const int numChannels_,
  17932. const int numSamples) throw()
  17933. : numChannels (numChannels_),
  17934. size (numSamples),
  17935. allocatedBytes (0),
  17936. allocatedData (0)
  17937. {
  17938. jassert (((unsigned int) numChannels_) <= (unsigned int) maxNumAudioSampleBufferChannels);
  17939. for (int i = 0; i < numChannels_; ++i)
  17940. {
  17941. // you have to pass in the same number of valid pointers as numChannels
  17942. jassert (dataToReferTo[i] != 0);
  17943. channels[i] = dataToReferTo[i];
  17944. }
  17945. channels [numChannels_] = 0;
  17946. }
  17947. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  17948. const int numChannels_,
  17949. const int numSamples) throw()
  17950. {
  17951. jassert (((unsigned int) numChannels_) <= (unsigned int) maxNumAudioSampleBufferChannels);
  17952. juce_free (allocatedData);
  17953. allocatedData = 0;
  17954. allocatedBytes = 0;
  17955. numChannels = numChannels_;
  17956. size = numSamples;
  17957. for (int i = 0; i < numChannels_; ++i)
  17958. {
  17959. // you have to pass in the same number of valid pointers as numChannels
  17960. jassert (dataToReferTo[i] != 0);
  17961. channels[i] = dataToReferTo[i];
  17962. }
  17963. channels [numChannels_] = 0;
  17964. }
  17965. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  17966. : numChannels (other.numChannels),
  17967. size (other.size)
  17968. {
  17969. if (other.allocatedData != 0)
  17970. {
  17971. allocatedBytes = numChannels * size * sizeof (float) + 32;
  17972. allocatedData = (float*) juce_malloc (allocatedBytes);
  17973. memcpy (allocatedData, other.allocatedData, allocatedBytes);
  17974. float* chan = allocatedData;
  17975. for (int i = 0; i < numChannels; ++i)
  17976. {
  17977. channels[i] = chan;
  17978. chan += size;
  17979. }
  17980. channels [numChannels] = 0;
  17981. }
  17982. else
  17983. {
  17984. allocatedData = 0;
  17985. allocatedBytes = 0;
  17986. memcpy (channels, other.channels, sizeof (channels));
  17987. }
  17988. }
  17989. const AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  17990. {
  17991. if (this != &other)
  17992. {
  17993. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  17994. const int numBytes = size * sizeof (float);
  17995. for (int i = 0; i < numChannels; ++i)
  17996. memcpy (channels[i], other.channels[i], numBytes);
  17997. }
  17998. return *this;
  17999. }
  18000. AudioSampleBuffer::~AudioSampleBuffer() throw()
  18001. {
  18002. juce_free (allocatedData);
  18003. }
  18004. float* AudioSampleBuffer::getSampleData (const int channelNumber,
  18005. const int sampleOffset) const throw()
  18006. {
  18007. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  18008. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  18009. return channels [channelNumber] + sampleOffset;
  18010. }
  18011. void AudioSampleBuffer::setSize (const int newNumChannels,
  18012. const int newNumSamples,
  18013. const bool keepExistingContent,
  18014. const bool clearExtraSpace,
  18015. const bool avoidReallocating) throw()
  18016. {
  18017. jassert (newNumChannels > 0 && newNumChannels <= maxNumAudioSampleBufferChannels);
  18018. if (newNumSamples != size || newNumChannels != numChannels)
  18019. {
  18020. const int newTotalBytes = newNumChannels * newNumSamples * sizeof (float) + 32;
  18021. if (keepExistingContent)
  18022. {
  18023. float* const newData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  18024. : (float*) juce_malloc (newTotalBytes);
  18025. const int sizeToCopy = sizeof (float) * jmin (newNumSamples, size);
  18026. for (int i = jmin (newNumChannels, numChannels); --i >= 0;)
  18027. {
  18028. memcpy (newData + i * newNumSamples,
  18029. channels[i],
  18030. sizeToCopy);
  18031. }
  18032. juce_free (allocatedData);
  18033. allocatedData = newData;
  18034. allocatedBytes = newTotalBytes;
  18035. }
  18036. else
  18037. {
  18038. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  18039. {
  18040. if (clearExtraSpace)
  18041. zeromem (allocatedData, newTotalBytes);
  18042. }
  18043. else
  18044. {
  18045. juce_free (allocatedData);
  18046. allocatedData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  18047. : (float*) juce_malloc (newTotalBytes);
  18048. allocatedBytes = newTotalBytes;
  18049. }
  18050. }
  18051. size = newNumSamples;
  18052. numChannels = newNumChannels;
  18053. float* chan = allocatedData;
  18054. for (int i = 0; i < newNumChannels; ++i)
  18055. {
  18056. channels[i] = chan;
  18057. chan += size;
  18058. }
  18059. channels [newNumChannels] = 0;
  18060. }
  18061. }
  18062. void AudioSampleBuffer::clear() throw()
  18063. {
  18064. for (int i = 0; i < numChannels; ++i)
  18065. zeromem (channels[i], size * sizeof (float));
  18066. }
  18067. void AudioSampleBuffer::clear (const int startSample,
  18068. const int numSamples) throw()
  18069. {
  18070. jassert (startSample >= 0 && startSample + numSamples <= size);
  18071. for (int i = 0; i < numChannels; ++i)
  18072. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  18073. }
  18074. void AudioSampleBuffer::clear (const int channel,
  18075. const int startSample,
  18076. const int numSamples) throw()
  18077. {
  18078. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18079. jassert (startSample >= 0 && startSample + numSamples <= size);
  18080. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  18081. }
  18082. void AudioSampleBuffer::applyGain (const int channel,
  18083. const int startSample,
  18084. int numSamples,
  18085. const float gain) throw()
  18086. {
  18087. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18088. jassert (startSample >= 0 && startSample + numSamples <= size);
  18089. if (gain != 1.0f)
  18090. {
  18091. float* d = channels [channel] + startSample;
  18092. if (gain == 0.0f)
  18093. {
  18094. zeromem (d, sizeof (float) * numSamples);
  18095. }
  18096. else
  18097. {
  18098. while (--numSamples >= 0)
  18099. *d++ *= gain;
  18100. }
  18101. }
  18102. }
  18103. void AudioSampleBuffer::applyGainRamp (const int channel,
  18104. const int startSample,
  18105. int numSamples,
  18106. float startGain,
  18107. float endGain) throw()
  18108. {
  18109. if (startGain == endGain)
  18110. {
  18111. applyGain (channel, startSample, numSamples, startGain);
  18112. }
  18113. else
  18114. {
  18115. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18116. jassert (startSample >= 0 && startSample + numSamples <= size);
  18117. const float increment = (endGain - startGain) / numSamples;
  18118. float* d = channels [channel] + startSample;
  18119. while (--numSamples >= 0)
  18120. {
  18121. *d++ *= startGain;
  18122. startGain += increment;
  18123. }
  18124. }
  18125. }
  18126. void AudioSampleBuffer::applyGain (const int startSample,
  18127. const int numSamples,
  18128. const float gain) throw()
  18129. {
  18130. for (int i = 0; i < numChannels; ++i)
  18131. applyGain (i, startSample, numSamples, gain);
  18132. }
  18133. void AudioSampleBuffer::addFrom (const int destChannel,
  18134. const int destStartSample,
  18135. const AudioSampleBuffer& source,
  18136. const int sourceChannel,
  18137. const int sourceStartSample,
  18138. int numSamples,
  18139. const float gain) throw()
  18140. {
  18141. jassert (&source != this || sourceChannel != destChannel);
  18142. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18143. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18144. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  18145. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  18146. if (gain != 0.0f && numSamples > 0)
  18147. {
  18148. float* d = channels [destChannel] + destStartSample;
  18149. const float* s = source.channels [sourceChannel] + sourceStartSample;
  18150. if (gain != 1.0f)
  18151. {
  18152. while (--numSamples >= 0)
  18153. *d++ += gain * *s++;
  18154. }
  18155. else
  18156. {
  18157. while (--numSamples >= 0)
  18158. *d++ += *s++;
  18159. }
  18160. }
  18161. }
  18162. void AudioSampleBuffer::addFrom (const int destChannel,
  18163. const int destStartSample,
  18164. const float* source,
  18165. int numSamples,
  18166. const float gain) throw()
  18167. {
  18168. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18169. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18170. jassert (source != 0);
  18171. if (gain != 0.0f && numSamples > 0)
  18172. {
  18173. float* d = channels [destChannel] + destStartSample;
  18174. if (gain != 1.0f)
  18175. {
  18176. while (--numSamples >= 0)
  18177. *d++ += gain * *source++;
  18178. }
  18179. else
  18180. {
  18181. while (--numSamples >= 0)
  18182. *d++ += *source++;
  18183. }
  18184. }
  18185. }
  18186. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  18187. const int destStartSample,
  18188. const float* source,
  18189. int numSamples,
  18190. float startGain,
  18191. const float endGain) throw()
  18192. {
  18193. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18194. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18195. jassert (source != 0);
  18196. if (startGain == endGain)
  18197. {
  18198. addFrom (destChannel,
  18199. destStartSample,
  18200. source,
  18201. numSamples,
  18202. startGain);
  18203. }
  18204. else
  18205. {
  18206. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  18207. {
  18208. const float increment = (endGain - startGain) / numSamples;
  18209. float* d = channels [destChannel] + destStartSample;
  18210. while (--numSamples >= 0)
  18211. {
  18212. *d++ += startGain * *source++;
  18213. startGain += increment;
  18214. }
  18215. }
  18216. }
  18217. }
  18218. void AudioSampleBuffer::copyFrom (const int destChannel,
  18219. const int destStartSample,
  18220. const AudioSampleBuffer& source,
  18221. const int sourceChannel,
  18222. const int sourceStartSample,
  18223. int numSamples) throw()
  18224. {
  18225. jassert (&source != this || sourceChannel != destChannel);
  18226. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18227. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18228. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  18229. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  18230. if (numSamples > 0)
  18231. {
  18232. memcpy (channels [destChannel] + destStartSample,
  18233. source.channels [sourceChannel] + sourceStartSample,
  18234. sizeof (float) * numSamples);
  18235. }
  18236. }
  18237. void AudioSampleBuffer::copyFrom (const int destChannel,
  18238. const int destStartSample,
  18239. const float* source,
  18240. int numSamples) throw()
  18241. {
  18242. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18243. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18244. jassert (source != 0);
  18245. if (numSamples > 0)
  18246. {
  18247. memcpy (channels [destChannel] + destStartSample,
  18248. source,
  18249. sizeof (float) * numSamples);
  18250. }
  18251. }
  18252. void AudioSampleBuffer::findMinMax (const int channel,
  18253. const int startSample,
  18254. int numSamples,
  18255. float& minVal,
  18256. float& maxVal) const throw()
  18257. {
  18258. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18259. jassert (startSample >= 0 && startSample + numSamples <= size);
  18260. if (numSamples <= 0)
  18261. {
  18262. minVal = 0.0f;
  18263. maxVal = 0.0f;
  18264. }
  18265. else
  18266. {
  18267. const float* d = channels [channel] + startSample;
  18268. float mn = *d++;
  18269. float mx = mn;
  18270. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  18271. {
  18272. const float samp = *d++;
  18273. if (samp > mx)
  18274. mx = samp;
  18275. if (samp < mn)
  18276. mn = samp;
  18277. }
  18278. maxVal = mx;
  18279. minVal = mn;
  18280. }
  18281. }
  18282. float AudioSampleBuffer::getMagnitude (const int channel,
  18283. const int startSample,
  18284. const int numSamples) const throw()
  18285. {
  18286. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18287. jassert (startSample >= 0 && startSample + numSamples <= size);
  18288. float mn, mx;
  18289. findMinMax (channel, startSample, numSamples, mn, mx);
  18290. return jmax (mn, -mn, mx, -mx);
  18291. }
  18292. float AudioSampleBuffer::getMagnitude (const int startSample,
  18293. const int numSamples) const throw()
  18294. {
  18295. float mag = 0.0f;
  18296. for (int i = 0; i < numChannels; ++i)
  18297. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  18298. return mag;
  18299. }
  18300. float AudioSampleBuffer::getRMSLevel (const int channel,
  18301. const int startSample,
  18302. const int numSamples) const throw()
  18303. {
  18304. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18305. jassert (startSample >= 0 && startSample + numSamples <= size);
  18306. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  18307. return 0.0f;
  18308. const float* const data = channels [channel] + startSample;
  18309. double sum = 0.0;
  18310. for (int i = 0; i < numSamples; ++i)
  18311. {
  18312. const float sample = data [i];
  18313. sum += sample * sample;
  18314. }
  18315. return (float) sqrt (sum / numSamples);
  18316. }
  18317. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  18318. const int startSample,
  18319. const int numSamples,
  18320. const int readerStartSample,
  18321. const bool useLeftChan,
  18322. const bool useRightChan) throw()
  18323. {
  18324. jassert (reader != 0);
  18325. jassert (startSample >= 0 && startSample + numSamples <= size);
  18326. if (numSamples > 0)
  18327. {
  18328. int* chans[3];
  18329. if (useLeftChan == useRightChan)
  18330. {
  18331. chans[0] = (int*) getSampleData (0, startSample);
  18332. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  18333. }
  18334. else if (useLeftChan || (reader->numChannels == 1))
  18335. {
  18336. chans[0] = (int*) getSampleData (0, startSample);
  18337. chans[1] = 0;
  18338. }
  18339. else if (useRightChan)
  18340. {
  18341. chans[0] = 0;
  18342. chans[1] = (int*) getSampleData (0, startSample);
  18343. }
  18344. chans[2] = 0;
  18345. reader->read (chans, readerStartSample, numSamples);
  18346. if (! reader->usesFloatingPointData)
  18347. {
  18348. for (int j = 0; j < 2; ++j)
  18349. {
  18350. float* const d = (float*) (chans[j]);
  18351. if (d != 0)
  18352. {
  18353. const float multiplier = 1.0f / 0x7fffffff;
  18354. for (int i = 0; i < numSamples; ++i)
  18355. d[i] = *(int*)(d + i) * multiplier;
  18356. }
  18357. }
  18358. }
  18359. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  18360. {
  18361. // if this is a stereo buffer and the source was mono, dupe the first channel..
  18362. memcpy (getSampleData (1, startSample),
  18363. getSampleData (0, startSample),
  18364. sizeof (float) * numSamples);
  18365. }
  18366. }
  18367. }
  18368. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  18369. const int startSample,
  18370. const int numSamples) const throw()
  18371. {
  18372. jassert (startSample >= 0 && startSample + numSamples <= size);
  18373. if (numSamples > 0)
  18374. {
  18375. int* chans [3];
  18376. if (writer->isFloatingPoint())
  18377. {
  18378. chans[0] = (int*) getSampleData (0, startSample);
  18379. if (numChannels > 1)
  18380. chans[1] = (int*) getSampleData (1, startSample);
  18381. else
  18382. chans[1] = 0;
  18383. chans[2] = 0;
  18384. writer->write ((const int**) chans, numSamples);
  18385. }
  18386. else
  18387. {
  18388. chans[0] = (int*) juce_malloc (sizeof (int) * numSamples * 2);
  18389. if (numChannels > 1)
  18390. chans[1] = chans[0] + numSamples;
  18391. else
  18392. chans[1] = 0;
  18393. chans[2] = 0;
  18394. for (int j = 0; j < 2; ++j)
  18395. {
  18396. int* const dest = chans[j];
  18397. if (dest != 0)
  18398. {
  18399. const float* const src = channels [j] + startSample;
  18400. for (int i = 0; i < numSamples; ++i)
  18401. {
  18402. const double samp = src[i];
  18403. if (samp <= -1.0)
  18404. dest[i] = INT_MIN;
  18405. else if (samp >= 1.0)
  18406. dest[i] = INT_MAX;
  18407. else
  18408. dest[i] = roundDoubleToInt (INT_MAX * samp);
  18409. }
  18410. }
  18411. }
  18412. writer->write ((const int**) chans, numSamples);
  18413. juce_free (chans[0]);
  18414. }
  18415. }
  18416. }
  18417. END_JUCE_NAMESPACE
  18418. /********* End of inlined file: juce_AudioSampleBuffer.cpp *********/
  18419. /********* Start of inlined file: juce_IIRFilter.cpp *********/
  18420. BEGIN_JUCE_NAMESPACE
  18421. IIRFilter::IIRFilter() throw()
  18422. : active (false)
  18423. {
  18424. reset();
  18425. }
  18426. IIRFilter::IIRFilter (const IIRFilter& other) throw()
  18427. : active (other.active)
  18428. {
  18429. const ScopedLock sl (other.processLock);
  18430. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  18431. reset();
  18432. }
  18433. IIRFilter::~IIRFilter() throw()
  18434. {
  18435. }
  18436. void IIRFilter::reset() throw()
  18437. {
  18438. const ScopedLock sl (processLock);
  18439. x1 = 0;
  18440. x2 = 0;
  18441. y1 = 0;
  18442. y2 = 0;
  18443. }
  18444. void IIRFilter::processSamples (float* const samples,
  18445. const int numSamples) throw()
  18446. {
  18447. const ScopedLock sl (processLock);
  18448. if (active)
  18449. {
  18450. for (int i = 0; i < numSamples; ++i)
  18451. {
  18452. const float in = samples[i];
  18453. float out = coefficients[0] * in
  18454. + coefficients[1] * x1
  18455. + coefficients[2] * x2
  18456. - coefficients[4] * y1
  18457. - coefficients[5] * y2;
  18458. #if JUCE_INTEL
  18459. if (! (out < -1.0e-8 || out > 1.0e-8))
  18460. out = 0;
  18461. #endif
  18462. x2 = x1;
  18463. x1 = in;
  18464. y2 = y1;
  18465. y1 = out;
  18466. samples[i] = out;
  18467. }
  18468. }
  18469. }
  18470. void IIRFilter::makeLowPass (const double sampleRate,
  18471. const double frequency) throw()
  18472. {
  18473. jassert (sampleRate > 0);
  18474. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  18475. const double nSquared = n * n;
  18476. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  18477. setCoefficients (c1,
  18478. c1 * 2.0f,
  18479. c1,
  18480. 1.0,
  18481. c1 * 2.0 * (1.0 - nSquared),
  18482. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  18483. }
  18484. void IIRFilter::makeHighPass (const double sampleRate,
  18485. const double frequency) throw()
  18486. {
  18487. const double n = tan (double_Pi * frequency / sampleRate);
  18488. const double nSquared = n * n;
  18489. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  18490. setCoefficients (c1,
  18491. c1 * -2.0f,
  18492. c1,
  18493. 1.0,
  18494. c1 * 2.0 * (nSquared - 1.0),
  18495. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  18496. }
  18497. void IIRFilter::makeLowShelf (const double sampleRate,
  18498. const double cutOffFrequency,
  18499. const double Q,
  18500. const float gainFactor) throw()
  18501. {
  18502. jassert (sampleRate > 0);
  18503. jassert (Q > 0);
  18504. const double A = jmax (0.0f, gainFactor);
  18505. const double aminus1 = A - 1.0;
  18506. const double aplus1 = A + 1.0;
  18507. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  18508. const double coso = cos (omega);
  18509. const double beta = sin (omega) * sqrt (A) / Q;
  18510. const double aminus1TimesCoso = aminus1 * coso;
  18511. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  18512. A * 2.0 * (aminus1 - aplus1 * coso),
  18513. A * (aplus1 - aminus1TimesCoso - beta),
  18514. aplus1 + aminus1TimesCoso + beta,
  18515. -2.0 * (aminus1 + aplus1 * coso),
  18516. aplus1 + aminus1TimesCoso - beta);
  18517. }
  18518. void IIRFilter::makeHighShelf (const double sampleRate,
  18519. const double cutOffFrequency,
  18520. const double Q,
  18521. const float gainFactor) throw()
  18522. {
  18523. jassert (sampleRate > 0);
  18524. jassert (Q > 0);
  18525. const double A = jmax (0.0f, gainFactor);
  18526. const double aminus1 = A - 1.0;
  18527. const double aplus1 = A + 1.0;
  18528. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  18529. const double coso = cos (omega);
  18530. const double beta = sin (omega) * sqrt (A) / Q;
  18531. const double aminus1TimesCoso = aminus1 * coso;
  18532. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  18533. A * -2.0 * (aminus1 + aplus1 * coso),
  18534. A * (aplus1 + aminus1TimesCoso - beta),
  18535. aplus1 - aminus1TimesCoso + beta,
  18536. 2.0 * (aminus1 - aplus1 * coso),
  18537. aplus1 - aminus1TimesCoso - beta);
  18538. }
  18539. void IIRFilter::makeBandPass (const double sampleRate,
  18540. const double centreFrequency,
  18541. const double Q,
  18542. const float gainFactor) throw()
  18543. {
  18544. jassert (sampleRate > 0);
  18545. jassert (Q > 0);
  18546. const double A = jmax (0.0f, gainFactor);
  18547. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  18548. const double alpha = 0.5 * sin (omega) / Q;
  18549. const double c2 = -2.0 * cos (omega);
  18550. const double alphaTimesA = alpha * A;
  18551. const double alphaOverA = alpha / A;
  18552. setCoefficients (1.0 + alphaTimesA,
  18553. c2,
  18554. 1.0 - alphaTimesA,
  18555. 1.0 + alphaOverA,
  18556. c2,
  18557. 1.0 - alphaOverA);
  18558. }
  18559. void IIRFilter::makeInactive() throw()
  18560. {
  18561. const ScopedLock sl (processLock);
  18562. active = false;
  18563. }
  18564. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  18565. {
  18566. const ScopedLock sl (processLock);
  18567. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  18568. active = other.active;
  18569. }
  18570. void IIRFilter::setCoefficients (double c1,
  18571. double c2,
  18572. double c3,
  18573. double c4,
  18574. double c5,
  18575. double c6) throw()
  18576. {
  18577. const double a = 1.0 / c4;
  18578. c1 *= a;
  18579. c2 *= a;
  18580. c3 *= a;
  18581. c5 *= a;
  18582. c6 *= a;
  18583. const ScopedLock sl (processLock);
  18584. coefficients[0] = (float) c1;
  18585. coefficients[1] = (float) c2;
  18586. coefficients[2] = (float) c3;
  18587. coefficients[3] = (float) c4;
  18588. coefficients[4] = (float) c5;
  18589. coefficients[5] = (float) c6;
  18590. active = true;
  18591. }
  18592. END_JUCE_NAMESPACE
  18593. /********* End of inlined file: juce_IIRFilter.cpp *********/
  18594. /********* Start of inlined file: juce_MidiBuffer.cpp *********/
  18595. BEGIN_JUCE_NAMESPACE
  18596. MidiBuffer::MidiBuffer() throw()
  18597. : ArrayAllocationBase <uint8> (32),
  18598. bytesUsed (0)
  18599. {
  18600. }
  18601. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  18602. : ArrayAllocationBase <uint8> (32),
  18603. bytesUsed (other.bytesUsed)
  18604. {
  18605. ensureAllocatedSize (bytesUsed);
  18606. memcpy (elements, other.elements, bytesUsed);
  18607. }
  18608. const MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  18609. {
  18610. if (this != &other)
  18611. {
  18612. bytesUsed = other.bytesUsed;
  18613. ensureAllocatedSize (bytesUsed);
  18614. if (bytesUsed > 0)
  18615. memcpy (elements, other.elements, bytesUsed);
  18616. }
  18617. return *this;
  18618. }
  18619. MidiBuffer::~MidiBuffer() throw()
  18620. {
  18621. }
  18622. void MidiBuffer::clear() throw()
  18623. {
  18624. bytesUsed = 0;
  18625. }
  18626. void MidiBuffer::clear (const int startSample,
  18627. const int numSamples) throw()
  18628. {
  18629. uint8* const start = findEventAfter (elements, startSample - 1);
  18630. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  18631. if (end > start)
  18632. {
  18633. const size_t bytesToMove = (size_t) (bytesUsed - (end - elements));
  18634. if (bytesToMove > 0)
  18635. memmove (start, end, bytesToMove);
  18636. bytesUsed -= (int) (end - start);
  18637. }
  18638. }
  18639. void MidiBuffer::addEvent (const MidiMessage& m,
  18640. const int sampleNumber) throw()
  18641. {
  18642. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  18643. }
  18644. static int findActualEventLength (const uint8* const data,
  18645. const int maxBytes) throw()
  18646. {
  18647. unsigned int byte = (unsigned int) *data;
  18648. int size = 0;
  18649. if (byte == 0xf0 || byte == 0xf7)
  18650. {
  18651. const uint8* d = data + 1;
  18652. while (d < data + maxBytes)
  18653. if (*d++ == 0xf7)
  18654. break;
  18655. size = (int) (d - data);
  18656. }
  18657. else if (byte == 0xff)
  18658. {
  18659. int n;
  18660. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  18661. size = jmin (maxBytes, n + 2 + bytesLeft);
  18662. }
  18663. else if (byte >= 0x80)
  18664. {
  18665. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  18666. }
  18667. return size;
  18668. }
  18669. void MidiBuffer::addEvent (const uint8* const newData,
  18670. const int maxBytes,
  18671. const int sampleNumber) throw()
  18672. {
  18673. const int numBytes = findActualEventLength (newData, maxBytes);
  18674. if (numBytes > 0)
  18675. {
  18676. ensureAllocatedSize (bytesUsed + numBytes + 6);
  18677. uint8* d = findEventAfter (elements, sampleNumber);
  18678. const size_t bytesToMove = (size_t) (bytesUsed - (d - elements));
  18679. if (bytesToMove > 0)
  18680. memmove (d + numBytes + 6,
  18681. d,
  18682. bytesToMove);
  18683. *(int*) d = sampleNumber;
  18684. d += 4;
  18685. *(uint16*) d = (uint16) numBytes;
  18686. d += 2;
  18687. memcpy (d, newData, numBytes);
  18688. bytesUsed += numBytes + 6;
  18689. }
  18690. }
  18691. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  18692. const int startSample,
  18693. const int numSamples,
  18694. const int sampleDeltaToAdd) throw()
  18695. {
  18696. Iterator i (otherBuffer);
  18697. i.setNextSamplePosition (startSample);
  18698. const uint8* data;
  18699. int size, position;
  18700. while (i.getNextEvent (data, size, position)
  18701. && (position < startSample + numSamples || numSamples < 0))
  18702. {
  18703. addEvent (data, size, position + sampleDeltaToAdd);
  18704. }
  18705. }
  18706. bool MidiBuffer::isEmpty() const throw()
  18707. {
  18708. return bytesUsed == 0;
  18709. }
  18710. int MidiBuffer::getNumEvents() const throw()
  18711. {
  18712. int n = 0;
  18713. const uint8* d = elements;
  18714. const uint8* const end = elements + bytesUsed;
  18715. while (d < end)
  18716. {
  18717. d += 4;
  18718. d += 2 + *(const uint16*) d;
  18719. ++n;
  18720. }
  18721. return n;
  18722. }
  18723. int MidiBuffer::getFirstEventTime() const throw()
  18724. {
  18725. return (bytesUsed > 0) ? *(const int*) elements : 0;
  18726. }
  18727. int MidiBuffer::getLastEventTime() const throw()
  18728. {
  18729. if (bytesUsed == 0)
  18730. return 0;
  18731. const uint8* d = elements;
  18732. const uint8* const endData = d + bytesUsed;
  18733. for (;;)
  18734. {
  18735. const uint8* nextOne = d + 6 + * (const uint16*) (d + 4);
  18736. if (nextOne >= endData)
  18737. return *(const int*) d;
  18738. d = nextOne;
  18739. }
  18740. }
  18741. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  18742. {
  18743. const uint8* const endData = elements + bytesUsed;
  18744. while (d < endData && *(int*) d <= samplePosition)
  18745. {
  18746. d += 4;
  18747. d += 2 + *(uint16*) d;
  18748. }
  18749. return d;
  18750. }
  18751. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer) throw()
  18752. : buffer (buffer),
  18753. data (buffer.elements)
  18754. {
  18755. }
  18756. MidiBuffer::Iterator::~Iterator() throw()
  18757. {
  18758. }
  18759. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  18760. {
  18761. data = buffer.elements;
  18762. const uint8* dataEnd = buffer.elements + buffer.bytesUsed;
  18763. while (data < dataEnd && *(int*) data < samplePosition)
  18764. {
  18765. data += 4;
  18766. data += 2 + *(uint16*) data;
  18767. }
  18768. }
  18769. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData,
  18770. int& numBytes,
  18771. int& samplePosition) throw()
  18772. {
  18773. if (data >= buffer.elements + buffer.bytesUsed)
  18774. return false;
  18775. samplePosition = *(int*) data;
  18776. data += 4;
  18777. numBytes = *(uint16*) data;
  18778. data += 2;
  18779. midiData = data;
  18780. data += numBytes;
  18781. return true;
  18782. }
  18783. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result,
  18784. int& samplePosition) throw()
  18785. {
  18786. if (data >= buffer.elements + buffer.bytesUsed)
  18787. return false;
  18788. samplePosition = *(int*) data;
  18789. data += 4;
  18790. const int numBytes = *(uint16*) data;
  18791. data += 2;
  18792. result = MidiMessage (data, numBytes, samplePosition);
  18793. data += numBytes;
  18794. return true;
  18795. }
  18796. END_JUCE_NAMESPACE
  18797. /********* End of inlined file: juce_MidiBuffer.cpp *********/
  18798. /********* Start of inlined file: juce_MidiFile.cpp *********/
  18799. BEGIN_JUCE_NAMESPACE
  18800. struct TempoInfo
  18801. {
  18802. double bpm, timestamp;
  18803. };
  18804. struct TimeSigInfo
  18805. {
  18806. int numerator, denominator;
  18807. double timestamp;
  18808. };
  18809. MidiFile::MidiFile() throw()
  18810. : numTracks (0),
  18811. timeFormat ((short)(unsigned short)0xe728)
  18812. {
  18813. }
  18814. MidiFile::~MidiFile() throw()
  18815. {
  18816. clear();
  18817. }
  18818. void MidiFile::clear() throw()
  18819. {
  18820. while (numTracks > 0)
  18821. delete tracks [--numTracks];
  18822. }
  18823. int MidiFile::getNumTracks() const throw()
  18824. {
  18825. return numTracks;
  18826. }
  18827. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  18828. {
  18829. return (((unsigned int) index) < (unsigned int) numTracks) ? tracks[index] : 0;
  18830. }
  18831. void MidiFile::addTrack (const MidiMessageSequence& trackSequence) throw()
  18832. {
  18833. jassert (numTracks < numElementsInArray (tracks));
  18834. if (numTracks < numElementsInArray (tracks))
  18835. tracks [numTracks++] = new MidiMessageSequence (trackSequence);
  18836. }
  18837. short MidiFile::getTimeFormat() const throw()
  18838. {
  18839. return timeFormat;
  18840. }
  18841. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  18842. {
  18843. timeFormat = (short)ticks;
  18844. }
  18845. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  18846. const int subframeResolution) throw()
  18847. {
  18848. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  18849. }
  18850. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  18851. {
  18852. for (int i = numTracks; --i >= 0;)
  18853. {
  18854. const int numEvents = tracks[i]->getNumEvents();
  18855. for (int j = 0; j < numEvents; ++j)
  18856. {
  18857. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  18858. if (m.isTempoMetaEvent())
  18859. tempoChangeEvents.addEvent (m);
  18860. }
  18861. }
  18862. }
  18863. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  18864. {
  18865. for (int i = numTracks; --i >= 0;)
  18866. {
  18867. const int numEvents = tracks[i]->getNumEvents();
  18868. for (int j = 0; j < numEvents; ++j)
  18869. {
  18870. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  18871. if (m.isTimeSignatureMetaEvent())
  18872. timeSigEvents.addEvent (m);
  18873. }
  18874. }
  18875. }
  18876. double MidiFile::getLastTimestamp() const
  18877. {
  18878. double t = 0.0;
  18879. for (int i = numTracks; --i >= 0;)
  18880. t = jmax (t, tracks[i]->getEndTime());
  18881. return t;
  18882. }
  18883. static bool parseMidiHeader (const char* &data,
  18884. short& timeFormat,
  18885. short& fileType,
  18886. short& numberOfTracks)
  18887. {
  18888. unsigned int ch = (int) bigEndianInt (data);
  18889. data += 4;
  18890. if (ch != bigEndianInt ("MThd"))
  18891. {
  18892. bool ok = false;
  18893. if (ch == bigEndianInt ("RIFF"))
  18894. {
  18895. for (int i = 0; i < 8; ++i)
  18896. {
  18897. ch = bigEndianInt (data);
  18898. data += 4;
  18899. if (ch == bigEndianInt ("MThd"))
  18900. {
  18901. ok = true;
  18902. break;
  18903. }
  18904. }
  18905. }
  18906. if (! ok)
  18907. return false;
  18908. }
  18909. unsigned int bytesRemaining = bigEndianInt (data);
  18910. data += 4;
  18911. fileType = (short)bigEndianShort (data);
  18912. data += 2;
  18913. numberOfTracks = (short)bigEndianShort (data);
  18914. data += 2;
  18915. timeFormat = (short)bigEndianShort (data);
  18916. data += 2;
  18917. bytesRemaining -= 6;
  18918. data += bytesRemaining;
  18919. return true;
  18920. }
  18921. bool MidiFile::readFrom (InputStream& sourceStream)
  18922. {
  18923. clear();
  18924. MemoryBlock data;
  18925. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  18926. // (put a sanity-check on the file size, as midi files are generally small)
  18927. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  18928. {
  18929. int size = data.getSize();
  18930. const char* d = (char*) data.getData();
  18931. short fileType, expectedTracks;
  18932. if (size > 16 && parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  18933. {
  18934. size -= (int) (d - (char*) data.getData());
  18935. int track = 0;
  18936. while (size > 0 && track < expectedTracks)
  18937. {
  18938. const int chunkType = (int)bigEndianInt (d);
  18939. d += 4;
  18940. const int chunkSize = (int)bigEndianInt (d);
  18941. d += 4;
  18942. if (chunkSize <= 0)
  18943. break;
  18944. if (size < 0)
  18945. return false;
  18946. if (chunkType == (int)bigEndianInt ("MTrk"))
  18947. {
  18948. readNextTrack (d, chunkSize);
  18949. }
  18950. size -= chunkSize + 8;
  18951. d += chunkSize;
  18952. ++track;
  18953. }
  18954. return true;
  18955. }
  18956. }
  18957. return false;
  18958. }
  18959. // a comparator that puts all the note-offs before note-ons that have the same time
  18960. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  18961. const MidiMessageSequence::MidiEventHolder* const second) throw()
  18962. {
  18963. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  18964. if (diff == 0)
  18965. {
  18966. if (first->message.isNoteOff() && second->message.isNoteOn())
  18967. return -1;
  18968. else if (first->message.isNoteOn() && second->message.isNoteOff())
  18969. return 1;
  18970. else
  18971. return 0;
  18972. }
  18973. else
  18974. {
  18975. return (diff > 0) ? 1 : -1;
  18976. }
  18977. }
  18978. void MidiFile::readNextTrack (const char* data, int size)
  18979. {
  18980. double time = 0;
  18981. char lastStatusByte = 0;
  18982. MidiMessageSequence result;
  18983. while (size > 0)
  18984. {
  18985. int bytesUsed;
  18986. const int delay = MidiMessage::readVariableLengthVal ((const uint8*) data, bytesUsed);
  18987. data += bytesUsed;
  18988. size -= bytesUsed;
  18989. time += delay;
  18990. int messSize = 0;
  18991. const MidiMessage mm ((const uint8*) data, size, messSize, lastStatusByte, time);
  18992. if (messSize <= 0)
  18993. break;
  18994. size -= messSize;
  18995. data += messSize;
  18996. result.addEvent (mm);
  18997. const char firstByte = *(mm.getRawData());
  18998. if ((firstByte & 0xf0) != 0xf0)
  18999. lastStatusByte = firstByte;
  19000. }
  19001. // use a sort that puts all the note-offs before note-ons that have the same time
  19002. result.list.sort (*this, true);
  19003. result.updateMatchedPairs();
  19004. addTrack (result);
  19005. }
  19006. static double convertTicksToSeconds (const double time,
  19007. const MidiMessageSequence& tempoEvents,
  19008. const int timeFormat)
  19009. {
  19010. if (timeFormat > 0)
  19011. {
  19012. int numer = 4, denom = 4;
  19013. double tempoTime = 0.0, correctedTempoTime = 0.0;
  19014. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  19015. double secsPerTick = 0.5 * tickLen;
  19016. const int numEvents = tempoEvents.getNumEvents();
  19017. for (int i = 0; i < numEvents; ++i)
  19018. {
  19019. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  19020. if (time <= m.getTimeStamp())
  19021. break;
  19022. if (timeFormat > 0)
  19023. {
  19024. correctedTempoTime = correctedTempoTime
  19025. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  19026. }
  19027. else
  19028. {
  19029. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  19030. }
  19031. tempoTime = m.getTimeStamp();
  19032. if (m.isTempoMetaEvent())
  19033. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  19034. else if (m.isTimeSignatureMetaEvent())
  19035. m.getTimeSignatureInfo (numer, denom);
  19036. while (i + 1 < numEvents)
  19037. {
  19038. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  19039. if (m2.getTimeStamp() == tempoTime)
  19040. {
  19041. ++i;
  19042. if (m2.isTempoMetaEvent())
  19043. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  19044. else if (m2.isTimeSignatureMetaEvent())
  19045. m2.getTimeSignatureInfo (numer, denom);
  19046. }
  19047. else
  19048. {
  19049. break;
  19050. }
  19051. }
  19052. }
  19053. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  19054. }
  19055. else
  19056. {
  19057. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  19058. }
  19059. }
  19060. void MidiFile::convertTimestampTicksToSeconds()
  19061. {
  19062. MidiMessageSequence tempoEvents;
  19063. findAllTempoEvents (tempoEvents);
  19064. findAllTimeSigEvents (tempoEvents);
  19065. for (int i = 0; i < numTracks; ++i)
  19066. {
  19067. MidiMessageSequence& ms = *tracks[i];
  19068. for (int j = ms.getNumEvents(); --j >= 0;)
  19069. {
  19070. MidiMessage& m = ms.getEventPointer(j)->message;
  19071. m.setTimeStamp (convertTicksToSeconds (m.getTimeStamp(),
  19072. tempoEvents,
  19073. timeFormat));
  19074. }
  19075. }
  19076. }
  19077. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  19078. {
  19079. unsigned int buffer = v & 0x7F;
  19080. while ((v >>= 7) != 0)
  19081. {
  19082. buffer <<= 8;
  19083. buffer |= ((v & 0x7F) | 0x80);
  19084. }
  19085. for (;;)
  19086. {
  19087. out.writeByte ((char) buffer);
  19088. if (buffer & 0x80)
  19089. buffer >>= 8;
  19090. else
  19091. break;
  19092. }
  19093. }
  19094. bool MidiFile::writeTo (OutputStream& out)
  19095. {
  19096. out.writeIntBigEndian ((int) bigEndianInt ("MThd"));
  19097. out.writeIntBigEndian (6);
  19098. out.writeShortBigEndian (1); // type
  19099. out.writeShortBigEndian (numTracks);
  19100. out.writeShortBigEndian (timeFormat);
  19101. for (int i = 0; i < numTracks; ++i)
  19102. writeTrack (out, i);
  19103. out.flush();
  19104. return true;
  19105. }
  19106. void MidiFile::writeTrack (OutputStream& mainOut,
  19107. const int trackNum)
  19108. {
  19109. MemoryOutputStream out;
  19110. const MidiMessageSequence& ms = *tracks[trackNum];
  19111. int lastTick = 0;
  19112. char lastStatusByte = 0;
  19113. for (int i = 0; i < ms.getNumEvents(); ++i)
  19114. {
  19115. const MidiMessage& mm = ms.getEventPointer(i)->message;
  19116. const int tick = roundDoubleToInt (mm.getTimeStamp());
  19117. const int delta = jmax (0, tick - lastTick);
  19118. writeVariableLengthInt (out, delta);
  19119. lastTick = tick;
  19120. const char statusByte = *(mm.getRawData());
  19121. if ((statusByte == lastStatusByte)
  19122. && ((statusByte & 0xf0) != 0xf0)
  19123. && i > 0
  19124. && mm.getRawDataSize() > 1)
  19125. {
  19126. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  19127. }
  19128. else
  19129. {
  19130. out.write (mm.getRawData(), mm.getRawDataSize());
  19131. }
  19132. lastStatusByte = statusByte;
  19133. }
  19134. out.writeByte (0);
  19135. const MidiMessage m (MidiMessage::endOfTrack());
  19136. out.write (m.getRawData(),
  19137. m.getRawDataSize());
  19138. mainOut.writeIntBigEndian ((int)bigEndianInt ("MTrk"));
  19139. mainOut.writeIntBigEndian (out.getDataSize());
  19140. mainOut.write (out.getData(), out.getDataSize());
  19141. }
  19142. END_JUCE_NAMESPACE
  19143. /********* End of inlined file: juce_MidiFile.cpp *********/
  19144. /********* Start of inlined file: juce_MidiKeyboardState.cpp *********/
  19145. BEGIN_JUCE_NAMESPACE
  19146. MidiKeyboardState::MidiKeyboardState()
  19147. : listeners (2)
  19148. {
  19149. zeromem (noteStates, sizeof (noteStates));
  19150. }
  19151. MidiKeyboardState::~MidiKeyboardState()
  19152. {
  19153. }
  19154. void MidiKeyboardState::reset()
  19155. {
  19156. const ScopedLock sl (lock);
  19157. zeromem (noteStates, sizeof (noteStates));
  19158. eventsToAdd.clear();
  19159. }
  19160. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  19161. {
  19162. jassert (midiChannel >= 0 && midiChannel <= 16);
  19163. return ((unsigned int) n) < 128
  19164. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  19165. }
  19166. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  19167. {
  19168. return ((unsigned int) n) < 128
  19169. && (noteStates[n] & midiChannelMask) != 0;
  19170. }
  19171. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  19172. {
  19173. jassert (midiChannel >= 0 && midiChannel <= 16);
  19174. jassert (((unsigned int) midiNoteNumber) < 128);
  19175. const ScopedLock sl (lock);
  19176. if (((unsigned int) midiNoteNumber) < 128)
  19177. {
  19178. const int timeNow = (int) Time::getMillisecondCounter();
  19179. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  19180. eventsToAdd.clear (0, timeNow - 500);
  19181. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  19182. }
  19183. }
  19184. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  19185. {
  19186. if (((unsigned int) midiNoteNumber) < 128)
  19187. {
  19188. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  19189. for (int i = listeners.size(); --i >= 0;)
  19190. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  19191. ->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  19192. }
  19193. }
  19194. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  19195. {
  19196. const ScopedLock sl (lock);
  19197. if (isNoteOn (midiChannel, midiNoteNumber))
  19198. {
  19199. const int timeNow = (int) Time::getMillisecondCounter();
  19200. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  19201. eventsToAdd.clear (0, timeNow - 500);
  19202. noteOffInternal (midiChannel, midiNoteNumber);
  19203. }
  19204. }
  19205. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  19206. {
  19207. if (isNoteOn (midiChannel, midiNoteNumber))
  19208. {
  19209. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  19210. for (int i = listeners.size(); --i >= 0;)
  19211. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  19212. ->handleNoteOff (this, midiChannel, midiNoteNumber);
  19213. }
  19214. }
  19215. void MidiKeyboardState::allNotesOff (const int midiChannel)
  19216. {
  19217. const ScopedLock sl (lock);
  19218. if (midiChannel <= 0)
  19219. {
  19220. for (int i = 1; i <= 16; ++i)
  19221. allNotesOff (i);
  19222. }
  19223. else
  19224. {
  19225. for (int i = 0; i < 128; ++i)
  19226. noteOff (midiChannel, i);
  19227. }
  19228. }
  19229. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  19230. {
  19231. if (message.isNoteOn())
  19232. {
  19233. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  19234. }
  19235. else if (message.isNoteOff())
  19236. {
  19237. noteOffInternal (message.getChannel(), message.getNoteNumber());
  19238. }
  19239. else if (message.isAllNotesOff())
  19240. {
  19241. for (int i = 0; i < 128; ++i)
  19242. noteOffInternal (message.getChannel(), i);
  19243. }
  19244. }
  19245. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  19246. const int startSample,
  19247. const int numSamples,
  19248. const bool injectIndirectEvents)
  19249. {
  19250. MidiBuffer::Iterator i (buffer);
  19251. MidiMessage message (0xf4, 0.0);
  19252. int time;
  19253. const ScopedLock sl (lock);
  19254. while (i.getNextEvent (message, time))
  19255. processNextMidiEvent (message);
  19256. if (injectIndirectEvents)
  19257. {
  19258. MidiBuffer::Iterator i2 (eventsToAdd);
  19259. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  19260. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  19261. while (i2.getNextEvent (message, time))
  19262. {
  19263. const int pos = jlimit (0, numSamples - 1, roundDoubleToInt ((time - firstEventToAdd) * scaleFactor));
  19264. buffer.addEvent (message, startSample + pos);
  19265. }
  19266. }
  19267. eventsToAdd.clear();
  19268. }
  19269. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  19270. {
  19271. const ScopedLock sl (lock);
  19272. listeners.addIfNotAlreadyThere (listener);
  19273. }
  19274. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  19275. {
  19276. const ScopedLock sl (lock);
  19277. listeners.removeValue (listener);
  19278. }
  19279. END_JUCE_NAMESPACE
  19280. /********* End of inlined file: juce_MidiKeyboardState.cpp *********/
  19281. /********* Start of inlined file: juce_MidiMessage.cpp *********/
  19282. BEGIN_JUCE_NAMESPACE
  19283. int MidiMessage::readVariableLengthVal (const uint8* data,
  19284. int& numBytesUsed) throw()
  19285. {
  19286. numBytesUsed = 0;
  19287. int v = 0;
  19288. int i;
  19289. do
  19290. {
  19291. i = (int) *data++;
  19292. if (++numBytesUsed > 6)
  19293. break;
  19294. v = (v << 7) + (i & 0x7f);
  19295. } while (i & 0x80);
  19296. return v;
  19297. }
  19298. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  19299. {
  19300. // this method only works for valid starting bytes of a short midi message
  19301. jassert (firstByte >= 0x80
  19302. && firstByte != 0xf0
  19303. && firstByte != 0xf7);
  19304. static const char messageLengths[] =
  19305. {
  19306. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19307. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19308. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19309. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19310. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  19311. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  19312. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19313. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  19314. };
  19315. return messageLengths [firstByte & 0x7f];
  19316. }
  19317. MidiMessage::MidiMessage (const uint8* const d,
  19318. const int dataSize,
  19319. const double t) throw()
  19320. : timeStamp (t),
  19321. message (0),
  19322. size (dataSize)
  19323. {
  19324. jassert (dataSize > 0);
  19325. if (dataSize <= 4)
  19326. data = (uint8*) &message;
  19327. else
  19328. data = (uint8*) juce_malloc (dataSize);
  19329. memcpy (data, d, dataSize);
  19330. // check that the length matches the data..
  19331. jassert (size > 3 || *d >= 0xf0 || getMessageLengthFromFirstByte (*d) == size);
  19332. }
  19333. MidiMessage::MidiMessage (const int byte1,
  19334. const double t) throw()
  19335. : timeStamp (t),
  19336. data ((uint8*) &message),
  19337. size (1)
  19338. {
  19339. data[0] = (uint8) byte1;
  19340. // check that the length matches the data..
  19341. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  19342. }
  19343. MidiMessage::MidiMessage (const int byte1,
  19344. const int byte2,
  19345. const double t) throw()
  19346. : timeStamp (t),
  19347. data ((uint8*) &message),
  19348. size (2)
  19349. {
  19350. data[0] = (uint8) byte1;
  19351. data[1] = (uint8) byte2;
  19352. // check that the length matches the data..
  19353. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  19354. }
  19355. MidiMessage::MidiMessage (const int byte1,
  19356. const int byte2,
  19357. const int byte3,
  19358. const double t) throw()
  19359. : timeStamp (t),
  19360. data ((uint8*) &message),
  19361. size (3)
  19362. {
  19363. data[0] = (uint8) byte1;
  19364. data[1] = (uint8) byte2;
  19365. data[2] = (uint8) byte3;
  19366. // check that the length matches the data..
  19367. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  19368. }
  19369. MidiMessage::MidiMessage (const MidiMessage& other) throw()
  19370. : timeStamp (other.timeStamp),
  19371. message (other.message),
  19372. size (other.size)
  19373. {
  19374. if (other.data != (uint8*) &other.message)
  19375. {
  19376. data = (uint8*) juce_malloc (size);
  19377. memcpy (data, other.data, size);
  19378. }
  19379. else
  19380. {
  19381. data = (uint8*) &message;
  19382. }
  19383. }
  19384. MidiMessage::MidiMessage (const MidiMessage& other,
  19385. const double newTimeStamp) throw()
  19386. : timeStamp (newTimeStamp),
  19387. message (other.message),
  19388. size (other.size)
  19389. {
  19390. if (other.data != (uint8*) &other.message)
  19391. {
  19392. data = (uint8*) juce_malloc (size);
  19393. memcpy (data, other.data, size);
  19394. }
  19395. else
  19396. {
  19397. data = (uint8*) &message;
  19398. }
  19399. }
  19400. MidiMessage::MidiMessage (const uint8* src,
  19401. int sz,
  19402. int& numBytesUsed,
  19403. const uint8 lastStatusByte,
  19404. double t) throw()
  19405. : timeStamp (t),
  19406. data ((uint8*) &message),
  19407. message (0)
  19408. {
  19409. unsigned int byte = (unsigned int) *src;
  19410. if (byte < 0x80)
  19411. {
  19412. byte = (unsigned int) (uint8) lastStatusByte;
  19413. numBytesUsed = -1;
  19414. }
  19415. else
  19416. {
  19417. numBytesUsed = 0;
  19418. --sz;
  19419. ++src;
  19420. }
  19421. if (byte >= 0x80)
  19422. {
  19423. if (byte == 0xf0)
  19424. {
  19425. const uint8* d = (const uint8*) src;
  19426. while (d < src + sz)
  19427. {
  19428. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  19429. {
  19430. if (*d == 0xf7) // include an 0xf7 if we hit one
  19431. ++d;
  19432. break;
  19433. }
  19434. ++d;
  19435. }
  19436. size = 1 + (int) (d - src);
  19437. data = (uint8*) juce_malloc (size);
  19438. *data = (uint8) byte;
  19439. memcpy (data + 1, src, size - 1);
  19440. }
  19441. else if (byte == 0xff)
  19442. {
  19443. int n;
  19444. const int bytesLeft = readVariableLengthVal (src + 1, n);
  19445. size = jmin (sz + 1, n + 2 + bytesLeft);
  19446. data = (uint8*) juce_malloc (size);
  19447. *data = (uint8) byte;
  19448. memcpy (data + 1, src, size - 1);
  19449. }
  19450. else
  19451. {
  19452. size = getMessageLengthFromFirstByte ((uint8) byte);
  19453. *data = (uint8) byte;
  19454. if (size > 1)
  19455. {
  19456. data[1] = src[0];
  19457. if (size > 2)
  19458. data[2] = src[1];
  19459. }
  19460. }
  19461. numBytesUsed += size;
  19462. }
  19463. else
  19464. {
  19465. message = 0;
  19466. size = 0;
  19467. }
  19468. }
  19469. const MidiMessage& MidiMessage::operator= (const MidiMessage& other) throw()
  19470. {
  19471. if (this == &other)
  19472. return *this;
  19473. timeStamp = other.timeStamp;
  19474. size = other.size;
  19475. message = other.message;
  19476. if (data != (uint8*) &message)
  19477. juce_free (data);
  19478. if (other.data != (uint8*) &other.message)
  19479. {
  19480. data = (uint8*) juce_malloc (size);
  19481. memcpy (data, other.data, size);
  19482. }
  19483. else
  19484. {
  19485. data = (uint8*) &message;
  19486. }
  19487. return *this;
  19488. }
  19489. MidiMessage::~MidiMessage() throw()
  19490. {
  19491. if (data != (uint8*) &message)
  19492. juce_free (data);
  19493. }
  19494. int MidiMessage::getChannel() const throw()
  19495. {
  19496. if ((data[0] & 0xf0) != 0xf0)
  19497. return (data[0] & 0xf) + 1;
  19498. else
  19499. return 0;
  19500. }
  19501. bool MidiMessage::isForChannel (const int channel) const throw()
  19502. {
  19503. return ((data[0] & 0xf) == channel - 1)
  19504. && ((data[0] & 0xf0) != 0xf0);
  19505. }
  19506. void MidiMessage::setChannel (const int channel) throw()
  19507. {
  19508. if ((data[0] & 0xf0) != (uint8) 0xf0)
  19509. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  19510. | (uint8)(channel - 1));
  19511. }
  19512. bool MidiMessage::isNoteOn() const throw()
  19513. {
  19514. return ((data[0] & 0xf0) == 0x90)
  19515. && (data[2] != 0);
  19516. }
  19517. bool MidiMessage::isNoteOff() const throw()
  19518. {
  19519. return ((data[0] & 0xf0) == 0x80)
  19520. || ((data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  19521. }
  19522. bool MidiMessage::isNoteOnOrOff() const throw()
  19523. {
  19524. const int d = data[0] & 0xf0;
  19525. return (d == 0x90) || (d == 0x80);
  19526. }
  19527. int MidiMessage::getNoteNumber() const throw()
  19528. {
  19529. return data[1];
  19530. }
  19531. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  19532. {
  19533. if (isNoteOnOrOff())
  19534. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  19535. }
  19536. uint8 MidiMessage::getVelocity() const throw()
  19537. {
  19538. if (isNoteOnOrOff())
  19539. return data[2];
  19540. else
  19541. return 0;
  19542. }
  19543. float MidiMessage::getFloatVelocity() const throw()
  19544. {
  19545. return getVelocity() * (1.0f / 127.0f);
  19546. }
  19547. void MidiMessage::setVelocity (const float newVelocity) throw()
  19548. {
  19549. if (isNoteOnOrOff())
  19550. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (newVelocity * 127.0f));
  19551. }
  19552. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  19553. {
  19554. if (isNoteOnOrOff())
  19555. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (scaleFactor * data[2]));
  19556. }
  19557. bool MidiMessage::isAftertouch() const throw()
  19558. {
  19559. return (data[0] & 0xf0) == 0xa0;
  19560. }
  19561. int MidiMessage::getAfterTouchValue() const throw()
  19562. {
  19563. return data[2];
  19564. }
  19565. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  19566. const int noteNum,
  19567. const int aftertouchValue) throw()
  19568. {
  19569. jassert (channel > 0 && channel <= 16);
  19570. jassert (((unsigned int) noteNum) <= 127);
  19571. jassert (((unsigned int) aftertouchValue) <= 127);
  19572. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  19573. noteNum & 0x7f,
  19574. aftertouchValue & 0x7f);
  19575. }
  19576. bool MidiMessage::isChannelPressure() const throw()
  19577. {
  19578. return (data[0] & 0xf0) == 0xd0;
  19579. }
  19580. int MidiMessage::getChannelPressureValue() const throw()
  19581. {
  19582. jassert (isChannelPressure());
  19583. return data[1];
  19584. }
  19585. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  19586. const int pressure) throw()
  19587. {
  19588. jassert (channel > 0 && channel <= 16);
  19589. jassert (((unsigned int) pressure) <= 127);
  19590. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  19591. pressure & 0x7f);
  19592. }
  19593. bool MidiMessage::isProgramChange() const throw()
  19594. {
  19595. return (data[0] & 0xf0) == 0xc0;
  19596. }
  19597. int MidiMessage::getProgramChangeNumber() const throw()
  19598. {
  19599. return data[1];
  19600. }
  19601. const MidiMessage MidiMessage::programChange (const int channel,
  19602. const int programNumber) throw()
  19603. {
  19604. jassert (channel > 0 && channel <= 16);
  19605. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  19606. programNumber & 0x7f);
  19607. }
  19608. bool MidiMessage::isPitchWheel() const throw()
  19609. {
  19610. return (data[0] & 0xf0) == 0xe0;
  19611. }
  19612. int MidiMessage::getPitchWheelValue() const throw()
  19613. {
  19614. return data[1] | (data[2] << 7);
  19615. }
  19616. const MidiMessage MidiMessage::pitchWheel (const int channel,
  19617. const int position) throw()
  19618. {
  19619. jassert (channel > 0 && channel <= 16);
  19620. jassert (((unsigned int) position) <= 0x3fff);
  19621. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  19622. position & 127,
  19623. (position >> 7) & 127);
  19624. }
  19625. bool MidiMessage::isController() const throw()
  19626. {
  19627. return (data[0] & 0xf0) == 0xb0;
  19628. }
  19629. int MidiMessage::getControllerNumber() const throw()
  19630. {
  19631. jassert (isController());
  19632. return data[1];
  19633. }
  19634. int MidiMessage::getControllerValue() const throw()
  19635. {
  19636. jassert (isController());
  19637. return data[2];
  19638. }
  19639. const MidiMessage MidiMessage::controllerEvent (const int channel,
  19640. const int controllerType,
  19641. const int value) throw()
  19642. {
  19643. // the channel must be between 1 and 16 inclusive
  19644. jassert (channel > 0 && channel <= 16);
  19645. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  19646. controllerType & 127,
  19647. value & 127);
  19648. }
  19649. const MidiMessage MidiMessage::noteOn (const int channel,
  19650. const int noteNumber,
  19651. const float velocity) throw()
  19652. {
  19653. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  19654. }
  19655. const MidiMessage MidiMessage::noteOn (const int channel,
  19656. const int noteNumber,
  19657. const uint8 velocity) throw()
  19658. {
  19659. jassert (channel > 0 && channel <= 16);
  19660. jassert (((unsigned int) noteNumber) <= 127);
  19661. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  19662. noteNumber & 127,
  19663. jlimit (0, 127, roundFloatToInt (velocity)));
  19664. }
  19665. const MidiMessage MidiMessage::noteOff (const int channel,
  19666. const int noteNumber) throw()
  19667. {
  19668. jassert (channel > 0 && channel <= 16);
  19669. jassert (((unsigned int) noteNumber) <= 127);
  19670. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  19671. }
  19672. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  19673. {
  19674. jassert (channel > 0 && channel <= 16);
  19675. return controllerEvent (channel, 123, 0);
  19676. }
  19677. bool MidiMessage::isAllNotesOff() const throw()
  19678. {
  19679. return (data[0] & 0xf0) == 0xb0
  19680. && data[1] == 123;
  19681. }
  19682. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  19683. {
  19684. return controllerEvent (channel, 120, 0);
  19685. }
  19686. bool MidiMessage::isAllSoundOff() const throw()
  19687. {
  19688. return (data[0] & 0xf0) == 0xb0
  19689. && data[1] == 120;
  19690. }
  19691. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  19692. {
  19693. return controllerEvent (channel, 121, 0);
  19694. }
  19695. const MidiMessage MidiMessage::masterVolume (const float volume) throw()
  19696. {
  19697. const int vol = jlimit (0, 0x3fff, roundFloatToInt (volume * 0x4000));
  19698. uint8 buf[8];
  19699. buf[0] = 0xf0;
  19700. buf[1] = 0x7f;
  19701. buf[2] = 0x7f;
  19702. buf[3] = 0x04;
  19703. buf[4] = 0x01;
  19704. buf[5] = (uint8) (vol & 0x7f);
  19705. buf[6] = (uint8) (vol >> 7);
  19706. buf[7] = 0xf7;
  19707. return MidiMessage (buf, 8);
  19708. }
  19709. bool MidiMessage::isSysEx() const throw()
  19710. {
  19711. return *data == 0xf0;
  19712. }
  19713. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData,
  19714. const int dataSize) throw()
  19715. {
  19716. MemoryBlock mm (dataSize + 2);
  19717. uint8* const m = (uint8*) mm.getData();
  19718. m[0] = 0xf0;
  19719. memcpy (m + 1, sysexData, dataSize);
  19720. m[dataSize + 1] = 0xf7;
  19721. return MidiMessage (m, dataSize + 2);
  19722. }
  19723. const uint8* MidiMessage::getSysExData() const throw()
  19724. {
  19725. return (isSysEx()) ? getRawData() + 1
  19726. : 0;
  19727. }
  19728. int MidiMessage::getSysExDataSize() const throw()
  19729. {
  19730. return (isSysEx()) ? size - 2
  19731. : 0;
  19732. }
  19733. bool MidiMessage::isMetaEvent() const throw()
  19734. {
  19735. return *data == 0xff;
  19736. }
  19737. bool MidiMessage::isActiveSense() const throw()
  19738. {
  19739. return *data == 0xfe;
  19740. }
  19741. int MidiMessage::getMetaEventType() const throw()
  19742. {
  19743. if (*data != 0xff)
  19744. return -1;
  19745. else
  19746. return data[1];
  19747. }
  19748. int MidiMessage::getMetaEventLength() const throw()
  19749. {
  19750. if (*data == 0xff)
  19751. {
  19752. int n;
  19753. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  19754. }
  19755. return 0;
  19756. }
  19757. const uint8* MidiMessage::getMetaEventData() const throw()
  19758. {
  19759. int n;
  19760. const uint8* d = data + 2;
  19761. readVariableLengthVal (d, n);
  19762. return d + n;
  19763. }
  19764. bool MidiMessage::isTrackMetaEvent() const throw()
  19765. {
  19766. return getMetaEventType() == 0;
  19767. }
  19768. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  19769. {
  19770. return getMetaEventType() == 47;
  19771. }
  19772. bool MidiMessage::isTextMetaEvent() const throw()
  19773. {
  19774. const int t = getMetaEventType();
  19775. return t > 0 && t < 16;
  19776. }
  19777. const String MidiMessage::getTextFromTextMetaEvent() const throw()
  19778. {
  19779. return String ((const char*) getMetaEventData(),
  19780. getMetaEventLength());
  19781. }
  19782. bool MidiMessage::isTrackNameEvent() const throw()
  19783. {
  19784. return (data[1] == 3)
  19785. && (*data == 0xff);
  19786. }
  19787. bool MidiMessage::isTempoMetaEvent() const throw()
  19788. {
  19789. return (data[1] == 81)
  19790. && (*data == 0xff);
  19791. }
  19792. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  19793. {
  19794. return (data[1] == 0x20)
  19795. && (*data == 0xff)
  19796. && (data[2] == 1);
  19797. }
  19798. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  19799. {
  19800. return data[3] + 1;
  19801. }
  19802. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  19803. {
  19804. if (! isTempoMetaEvent())
  19805. return 0.0;
  19806. const uint8* const d = getMetaEventData();
  19807. return (((unsigned int) d[0] << 16)
  19808. | ((unsigned int) d[1] << 8)
  19809. | d[2])
  19810. / 1000000.0;
  19811. }
  19812. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  19813. {
  19814. if (timeFormat > 0)
  19815. {
  19816. if (! isTempoMetaEvent())
  19817. return 0.5 / timeFormat;
  19818. return getTempoSecondsPerQuarterNote() / timeFormat;
  19819. }
  19820. else
  19821. {
  19822. const int frameCode = (-timeFormat) >> 8;
  19823. double framesPerSecond;
  19824. switch (frameCode)
  19825. {
  19826. case 24: framesPerSecond = 24.0; break;
  19827. case 25: framesPerSecond = 25.0; break;
  19828. case 29: framesPerSecond = 29.97; break;
  19829. case 30: framesPerSecond = 30.0; break;
  19830. default: framesPerSecond = 30.0; break;
  19831. }
  19832. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  19833. }
  19834. }
  19835. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  19836. {
  19837. uint8 d[8];
  19838. d[0] = 0xff;
  19839. d[1] = 81;
  19840. d[2] = 3;
  19841. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  19842. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  19843. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  19844. return MidiMessage (d, 6, 0.0);
  19845. }
  19846. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  19847. {
  19848. return (data[1] == 0x58)
  19849. && (*data == (uint8) 0xff);
  19850. }
  19851. void MidiMessage::getTimeSignatureInfo (int& numerator,
  19852. int& denominator) const throw()
  19853. {
  19854. if (isTimeSignatureMetaEvent())
  19855. {
  19856. const uint8* const d = getMetaEventData();
  19857. numerator = d[0];
  19858. denominator = 1 << d[1];
  19859. }
  19860. else
  19861. {
  19862. numerator = 4;
  19863. denominator = 4;
  19864. }
  19865. }
  19866. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator,
  19867. const int denominator) throw()
  19868. {
  19869. uint8 d[8];
  19870. d[0] = 0xff;
  19871. d[1] = 0x58;
  19872. d[2] = 0x04;
  19873. d[3] = (uint8) numerator;
  19874. int n = 1;
  19875. int powerOfTwo = 0;
  19876. while (n < denominator)
  19877. {
  19878. n <<= 1;
  19879. ++powerOfTwo;
  19880. }
  19881. d[4] = (uint8) powerOfTwo;
  19882. d[5] = 0x01;
  19883. d[6] = 96;
  19884. return MidiMessage (d, 7, 0.0);
  19885. }
  19886. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  19887. {
  19888. uint8 d[8];
  19889. d[0] = 0xff;
  19890. d[1] = 0x20;
  19891. d[2] = 0x01;
  19892. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  19893. return MidiMessage (d, 4, 0.0);
  19894. }
  19895. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  19896. {
  19897. return getMetaEventType() == 89;
  19898. }
  19899. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  19900. {
  19901. return (int) *getMetaEventData();
  19902. }
  19903. const MidiMessage MidiMessage::endOfTrack() throw()
  19904. {
  19905. return MidiMessage (0xff, 0x2f, 0, 0.0);
  19906. }
  19907. bool MidiMessage::isSongPositionPointer() const throw()
  19908. {
  19909. return *data == 0xf2;
  19910. }
  19911. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  19912. {
  19913. return data[1] | (data[2] << 7);
  19914. }
  19915. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  19916. {
  19917. return MidiMessage (0xf2,
  19918. positionInMidiBeats & 127,
  19919. (positionInMidiBeats >> 7) & 127);
  19920. }
  19921. bool MidiMessage::isMidiStart() const throw()
  19922. {
  19923. return *data == 0xfa;
  19924. }
  19925. const MidiMessage MidiMessage::midiStart() throw()
  19926. {
  19927. return MidiMessage (0xfa);
  19928. }
  19929. bool MidiMessage::isMidiContinue() const throw()
  19930. {
  19931. return *data == 0xfb;
  19932. }
  19933. const MidiMessage MidiMessage::midiContinue() throw()
  19934. {
  19935. return MidiMessage (0xfb);
  19936. }
  19937. bool MidiMessage::isMidiStop() const throw()
  19938. {
  19939. return *data == 0xfc;
  19940. }
  19941. const MidiMessage MidiMessage::midiStop() throw()
  19942. {
  19943. return MidiMessage (0xfc);
  19944. }
  19945. bool MidiMessage::isMidiClock() const throw()
  19946. {
  19947. return *data == 0xf8;
  19948. }
  19949. const MidiMessage MidiMessage::midiClock() throw()
  19950. {
  19951. return MidiMessage (0xf8);
  19952. }
  19953. bool MidiMessage::isQuarterFrame() const throw()
  19954. {
  19955. return *data == 0xf1;
  19956. }
  19957. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  19958. {
  19959. return ((int) data[1]) >> 4;
  19960. }
  19961. int MidiMessage::getQuarterFrameValue() const throw()
  19962. {
  19963. return ((int) data[1]) & 0x0f;
  19964. }
  19965. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  19966. const int value) throw()
  19967. {
  19968. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  19969. }
  19970. bool MidiMessage::isFullFrame() const throw()
  19971. {
  19972. return data[0] == 0xf0
  19973. && data[1] == 0x7f
  19974. && size >= 10
  19975. && data[3] == 0x01
  19976. && data[4] == 0x01;
  19977. }
  19978. void MidiMessage::getFullFrameParameters (int& hours,
  19979. int& minutes,
  19980. int& seconds,
  19981. int& frames,
  19982. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  19983. {
  19984. jassert (isFullFrame());
  19985. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  19986. hours = data[5] & 0x1f;
  19987. minutes = data[6];
  19988. seconds = data[7];
  19989. frames = data[8];
  19990. }
  19991. const MidiMessage MidiMessage::fullFrame (const int hours,
  19992. const int minutes,
  19993. const int seconds,
  19994. const int frames,
  19995. MidiMessage::SmpteTimecodeType timecodeType)
  19996. {
  19997. uint8 d[10];
  19998. d[0] = 0xf0;
  19999. d[1] = 0x7f;
  20000. d[2] = 0x7f;
  20001. d[3] = 0x01;
  20002. d[4] = 0x01;
  20003. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  20004. d[6] = (uint8) minutes;
  20005. d[7] = (uint8) seconds;
  20006. d[8] = (uint8) frames;
  20007. d[9] = 0xf7;
  20008. return MidiMessage (d, 10, 0.0);
  20009. }
  20010. bool MidiMessage::isMidiMachineControlMessage() const throw()
  20011. {
  20012. return data[0] == 0xf0
  20013. && data[1] == 0x7f
  20014. && data[3] == 0x06
  20015. && size > 5;
  20016. }
  20017. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  20018. {
  20019. jassert (isMidiMachineControlMessage());
  20020. return (MidiMachineControlCommand) data[4];
  20021. }
  20022. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  20023. {
  20024. uint8 d[6];
  20025. d[0] = 0xf0;
  20026. d[1] = 0x7f;
  20027. d[2] = 0x00;
  20028. d[3] = 0x06;
  20029. d[4] = (uint8) command;
  20030. d[5] = 0xf7;
  20031. return MidiMessage (d, 6, 0.0);
  20032. }
  20033. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  20034. int& minutes,
  20035. int& seconds,
  20036. int& frames) const throw()
  20037. {
  20038. if (size >= 12
  20039. && data[0] == 0xf0
  20040. && data[1] == 0x7f
  20041. && data[3] == 0x06
  20042. && data[4] == 0x44
  20043. && data[5] == 0x06
  20044. && data[6] == 0x01)
  20045. {
  20046. hours = data[7] % 24; // (that some machines send out hours > 24)
  20047. minutes = data[8];
  20048. seconds = data[9];
  20049. frames = data[10];
  20050. return true;
  20051. }
  20052. return false;
  20053. }
  20054. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  20055. int minutes,
  20056. int seconds,
  20057. int frames)
  20058. {
  20059. uint8 d[12];
  20060. d[0] = 0xf0;
  20061. d[1] = 0x7f;
  20062. d[2] = 0x00;
  20063. d[3] = 0x06;
  20064. d[4] = 0x44;
  20065. d[5] = 0x06;
  20066. d[6] = 0x01;
  20067. d[7] = (uint8) hours;
  20068. d[8] = (uint8) minutes;
  20069. d[9] = (uint8) seconds;
  20070. d[10] = (uint8) frames;
  20071. d[11] = 0xf7;
  20072. return MidiMessage (d, 12, 0.0);
  20073. }
  20074. const String MidiMessage::getMidiNoteName (int note,
  20075. bool useSharps,
  20076. bool includeOctaveNumber,
  20077. int octaveNumForMiddleC) throw()
  20078. {
  20079. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  20080. "F", "F#", "G", "G#", "A",
  20081. "A#", "B" };
  20082. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  20083. "F", "Gb", "G", "Ab", "A",
  20084. "Bb", "B" };
  20085. if (((unsigned int) note) < 128)
  20086. {
  20087. const String s ((useSharps) ? sharpNoteNames [note % 12]
  20088. : flatNoteNames [note % 12]);
  20089. if (includeOctaveNumber)
  20090. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  20091. else
  20092. return s;
  20093. }
  20094. return String::empty;
  20095. }
  20096. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  20097. {
  20098. noteNumber -= 12 * 6 + 9; // now 0 = A440
  20099. return 440.0 * pow (2.0, noteNumber / 12.0);
  20100. }
  20101. const String MidiMessage::getGMInstrumentName (int n) throw()
  20102. {
  20103. const char *names[] =
  20104. {
  20105. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  20106. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  20107. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  20108. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  20109. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  20110. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  20111. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  20112. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  20113. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  20114. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  20115. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  20116. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  20117. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  20118. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  20119. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  20120. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  20121. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  20122. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  20123. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  20124. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  20125. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  20126. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  20127. "Applause", "Gunshot"
  20128. };
  20129. return (((unsigned int) n) < 128) ? names[n]
  20130. : (const char*)0;
  20131. }
  20132. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  20133. {
  20134. const char* names[] =
  20135. {
  20136. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  20137. "Bass", "Strings", "Ensemble", "Brass",
  20138. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  20139. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  20140. };
  20141. return (((unsigned int) n) <= 15) ? names[n]
  20142. : (const char*)0;
  20143. }
  20144. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  20145. {
  20146. const char* names[] =
  20147. {
  20148. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  20149. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  20150. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  20151. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  20152. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  20153. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  20154. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  20155. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  20156. "Mute Triangle", "Open Triangle"
  20157. };
  20158. return (n >= 35 && n <= 81) ? names [n - 35]
  20159. : (const char*)0;
  20160. }
  20161. const String MidiMessage::getControllerName (int n) throw()
  20162. {
  20163. const char* names[] =
  20164. {
  20165. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  20166. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  20167. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  20168. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  20169. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  20170. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  20171. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  20172. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  20173. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  20174. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  20175. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  20176. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  20177. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  20178. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  20179. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  20180. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  20181. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  20182. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  20183. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  20184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  20185. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  20186. "Poly Operation"
  20187. };
  20188. return (((unsigned int) n) < 128) ? names[n]
  20189. : (const char*)0;
  20190. }
  20191. END_JUCE_NAMESPACE
  20192. /********* End of inlined file: juce_MidiMessage.cpp *********/
  20193. /********* Start of inlined file: juce_MidiMessageCollector.cpp *********/
  20194. BEGIN_JUCE_NAMESPACE
  20195. MidiMessageCollector::MidiMessageCollector()
  20196. : lastCallbackTime (0),
  20197. sampleRate (44100.0001)
  20198. {
  20199. }
  20200. MidiMessageCollector::~MidiMessageCollector()
  20201. {
  20202. }
  20203. void MidiMessageCollector::reset (const double sampleRate_)
  20204. {
  20205. jassert (sampleRate_ > 0);
  20206. const ScopedLock sl (midiCallbackLock);
  20207. sampleRate = sampleRate_;
  20208. incomingMessages.clear();
  20209. lastCallbackTime = Time::getMillisecondCounterHiRes();
  20210. }
  20211. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  20212. {
  20213. // you need to call reset() to set the correct sample rate before using this object
  20214. jassert (sampleRate != 44100.0001);
  20215. // the messages that come in here need to be time-stamped correctly - see MidiInput
  20216. // for details of what the number should be.
  20217. jassert (message.getTimeStamp() != 0);
  20218. const ScopedLock sl (midiCallbackLock);
  20219. const int sampleNumber
  20220. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  20221. incomingMessages.addEvent (message, sampleNumber);
  20222. // if the messages don't get used for over a second, we'd better
  20223. // get rid of any old ones to avoid the queue getting too big
  20224. if (sampleNumber > sampleRate)
  20225. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  20226. }
  20227. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  20228. const int numSamples)
  20229. {
  20230. // you need to call reset() to set the correct sample rate before using this object
  20231. jassert (sampleRate != 44100.0001);
  20232. const double timeNow = Time::getMillisecondCounterHiRes();
  20233. const double msElapsed = timeNow - lastCallbackTime;
  20234. const ScopedLock sl (midiCallbackLock);
  20235. lastCallbackTime = timeNow;
  20236. if (! incomingMessages.isEmpty())
  20237. {
  20238. int numSourceSamples = jmax (1, roundDoubleToInt (msElapsed * 0.001 * sampleRate));
  20239. int startSample = 0;
  20240. int scale = 1 << 16;
  20241. const uint8* midiData;
  20242. int numBytes, samplePosition;
  20243. MidiBuffer::Iterator iter (incomingMessages);
  20244. if (numSourceSamples > numSamples)
  20245. {
  20246. // if our list of events is longer than the buffer we're being
  20247. // asked for, scale them down to squeeze them all in..
  20248. const int maxBlockLengthToUse = numSamples << 5;
  20249. if (numSourceSamples > maxBlockLengthToUse)
  20250. {
  20251. startSample = numSourceSamples - maxBlockLengthToUse;
  20252. numSourceSamples = maxBlockLengthToUse;
  20253. iter.setNextSamplePosition (startSample);
  20254. }
  20255. scale = (numSamples << 10) / numSourceSamples;
  20256. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  20257. {
  20258. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  20259. destBuffer.addEvent (midiData, numBytes,
  20260. jlimit (0, numSamples - 1, samplePosition));
  20261. }
  20262. }
  20263. else
  20264. {
  20265. // if our event list is shorter than the number we need, put them
  20266. // towards the end of the buffer
  20267. startSample = numSamples - numSourceSamples;
  20268. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  20269. {
  20270. destBuffer.addEvent (midiData, numBytes,
  20271. jlimit (0, numSamples - 1, samplePosition + startSample));
  20272. }
  20273. }
  20274. incomingMessages.clear();
  20275. }
  20276. }
  20277. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  20278. {
  20279. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  20280. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  20281. addMessageToQueue (m);
  20282. }
  20283. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  20284. {
  20285. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  20286. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  20287. addMessageToQueue (m);
  20288. }
  20289. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  20290. {
  20291. addMessageToQueue (message);
  20292. }
  20293. END_JUCE_NAMESPACE
  20294. /********* End of inlined file: juce_MidiMessageCollector.cpp *********/
  20295. /********* Start of inlined file: juce_MidiMessageSequence.cpp *********/
  20296. BEGIN_JUCE_NAMESPACE
  20297. MidiMessageSequence::MidiMessageSequence()
  20298. {
  20299. }
  20300. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  20301. {
  20302. list.ensureStorageAllocated (other.list.size());
  20303. for (int i = 0; i < other.list.size(); ++i)
  20304. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  20305. }
  20306. const MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  20307. {
  20308. if (this != &other)
  20309. {
  20310. clear();
  20311. for (int i = 0; i < other.list.size(); ++i)
  20312. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  20313. }
  20314. return *this;
  20315. }
  20316. MidiMessageSequence::~MidiMessageSequence()
  20317. {
  20318. }
  20319. void MidiMessageSequence::clear()
  20320. {
  20321. list.clear();
  20322. }
  20323. int MidiMessageSequence::getNumEvents() const
  20324. {
  20325. return list.size();
  20326. }
  20327. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  20328. {
  20329. return list [index];
  20330. }
  20331. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  20332. {
  20333. const MidiEventHolder* const meh = list [index];
  20334. if (meh != 0 && meh->noteOffObject != 0)
  20335. return meh->noteOffObject->message.getTimeStamp();
  20336. else
  20337. return 0.0;
  20338. }
  20339. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  20340. {
  20341. const MidiEventHolder* const meh = list [index];
  20342. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  20343. }
  20344. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  20345. {
  20346. return list.indexOf (event);
  20347. }
  20348. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  20349. {
  20350. const int numEvents = list.size();
  20351. int i;
  20352. for (i = 0; i < numEvents; ++i)
  20353. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  20354. break;
  20355. return i;
  20356. }
  20357. double MidiMessageSequence::getStartTime() const
  20358. {
  20359. if (list.size() > 0)
  20360. return list.getUnchecked(0)->message.getTimeStamp();
  20361. else
  20362. return 0;
  20363. }
  20364. double MidiMessageSequence::getEndTime() const
  20365. {
  20366. if (list.size() > 0)
  20367. return list.getLast()->message.getTimeStamp();
  20368. else
  20369. return 0;
  20370. }
  20371. double MidiMessageSequence::getEventTime (const int index) const
  20372. {
  20373. if (((unsigned int) index) < (unsigned int) list.size())
  20374. return list.getUnchecked (index)->message.getTimeStamp();
  20375. return 0.0;
  20376. }
  20377. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  20378. double timeAdjustment)
  20379. {
  20380. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  20381. timeAdjustment += newMessage.getTimeStamp();
  20382. newOne->message.setTimeStamp (timeAdjustment);
  20383. int i;
  20384. for (i = list.size(); --i >= 0;)
  20385. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  20386. break;
  20387. list.insert (i + 1, newOne);
  20388. }
  20389. void MidiMessageSequence::deleteEvent (const int index,
  20390. const bool deleteMatchingNoteUp)
  20391. {
  20392. if (((unsigned int) index) < (unsigned int) list.size())
  20393. {
  20394. if (deleteMatchingNoteUp)
  20395. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  20396. list.remove (index);
  20397. }
  20398. }
  20399. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  20400. double timeAdjustment,
  20401. double firstAllowableTime,
  20402. double endOfAllowableDestTimes)
  20403. {
  20404. firstAllowableTime -= timeAdjustment;
  20405. endOfAllowableDestTimes -= timeAdjustment;
  20406. for (int i = 0; i < other.list.size(); ++i)
  20407. {
  20408. const MidiMessage& m = other.list.getUnchecked(i)->message;
  20409. const double t = m.getTimeStamp();
  20410. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  20411. {
  20412. MidiEventHolder* const newOne = new MidiEventHolder (m);
  20413. newOne->message.setTimeStamp (timeAdjustment + t);
  20414. list.add (newOne);
  20415. }
  20416. }
  20417. sort();
  20418. }
  20419. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  20420. const MidiMessageSequence::MidiEventHolder* const second) throw()
  20421. {
  20422. const double diff = first->message.getTimeStamp()
  20423. - second->message.getTimeStamp();
  20424. return (diff == 0) ? 0
  20425. : ((diff > 0) ? 1
  20426. : -1);
  20427. }
  20428. void MidiMessageSequence::sort()
  20429. {
  20430. list.sort (*this, true);
  20431. }
  20432. void MidiMessageSequence::updateMatchedPairs()
  20433. {
  20434. for (int i = 0; i < list.size(); ++i)
  20435. {
  20436. const MidiMessage& m1 = list.getUnchecked(i)->message;
  20437. if (m1.isNoteOn())
  20438. {
  20439. list.getUnchecked(i)->noteOffObject = 0;
  20440. const int note = m1.getNoteNumber();
  20441. const int chan = m1.getChannel();
  20442. const int len = list.size();
  20443. for (int j = i + 1; j < len; ++j)
  20444. {
  20445. const MidiMessage& m = list.getUnchecked(j)->message;
  20446. if (m.getNoteNumber() == note && m.getChannel() == chan)
  20447. {
  20448. if (m.isNoteOff())
  20449. {
  20450. list.getUnchecked(i)->noteOffObject = list[j];
  20451. break;
  20452. }
  20453. else if (m.isNoteOn())
  20454. {
  20455. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  20456. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  20457. list.getUnchecked(i)->noteOffObject = list[j];
  20458. break;
  20459. }
  20460. }
  20461. }
  20462. }
  20463. }
  20464. }
  20465. void MidiMessageSequence::addTimeToMessages (const double delta)
  20466. {
  20467. for (int i = list.size(); --i >= 0;)
  20468. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  20469. + delta);
  20470. }
  20471. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  20472. MidiMessageSequence& destSequence,
  20473. const bool alsoIncludeMetaEvents) const
  20474. {
  20475. for (int i = 0; i < list.size(); ++i)
  20476. {
  20477. const MidiMessage& mm = list.getUnchecked(i)->message;
  20478. if (mm.isForChannel (channelNumberToExtract)
  20479. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  20480. {
  20481. destSequence.addEvent (mm);
  20482. }
  20483. }
  20484. }
  20485. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  20486. {
  20487. for (int i = 0; i < list.size(); ++i)
  20488. {
  20489. const MidiMessage& mm = list.getUnchecked(i)->message;
  20490. if (mm.isSysEx())
  20491. destSequence.addEvent (mm);
  20492. }
  20493. }
  20494. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  20495. {
  20496. for (int i = list.size(); --i >= 0;)
  20497. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  20498. list.remove(i);
  20499. }
  20500. void MidiMessageSequence::deleteSysExMessages()
  20501. {
  20502. for (int i = list.size(); --i >= 0;)
  20503. if (list.getUnchecked(i)->message.isSysEx())
  20504. list.remove(i);
  20505. }
  20506. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  20507. const double time,
  20508. OwnedArray<MidiMessage>& dest)
  20509. {
  20510. bool doneProg = false;
  20511. bool donePitchWheel = false;
  20512. Array <int> doneControllers (32);
  20513. for (int i = list.size(); --i >= 0;)
  20514. {
  20515. const MidiMessage& mm = list.getUnchecked(i)->message;
  20516. if (mm.isForChannel (channelNumber)
  20517. && mm.getTimeStamp() <= time)
  20518. {
  20519. if (mm.isProgramChange())
  20520. {
  20521. if (! doneProg)
  20522. {
  20523. dest.add (new MidiMessage (mm, 0.0));
  20524. doneProg = true;
  20525. }
  20526. }
  20527. else if (mm.isController())
  20528. {
  20529. if (! doneControllers.contains (mm.getControllerNumber()))
  20530. {
  20531. dest.add (new MidiMessage (mm, 0.0));
  20532. doneControllers.add (mm.getControllerNumber());
  20533. }
  20534. }
  20535. else if (mm.isPitchWheel())
  20536. {
  20537. if (! donePitchWheel)
  20538. {
  20539. dest.add (new MidiMessage (mm, 0.0));
  20540. donePitchWheel = true;
  20541. }
  20542. }
  20543. }
  20544. }
  20545. }
  20546. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  20547. : message (message_),
  20548. noteOffObject (0)
  20549. {
  20550. }
  20551. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  20552. {
  20553. }
  20554. END_JUCE_NAMESPACE
  20555. /********* End of inlined file: juce_MidiMessageSequence.cpp *********/
  20556. /********* Start of inlined file: juce_AudioPluginFormat.cpp *********/
  20557. BEGIN_JUCE_NAMESPACE
  20558. AudioPluginFormat::AudioPluginFormat() throw()
  20559. {
  20560. }
  20561. AudioPluginFormat::~AudioPluginFormat()
  20562. {
  20563. }
  20564. END_JUCE_NAMESPACE
  20565. /********* End of inlined file: juce_AudioPluginFormat.cpp *********/
  20566. /********* Start of inlined file: juce_AudioPluginFormatManager.cpp *********/
  20567. BEGIN_JUCE_NAMESPACE
  20568. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  20569. {
  20570. }
  20571. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  20572. {
  20573. }
  20574. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  20575. void AudioPluginFormatManager::addDefaultFormats()
  20576. {
  20577. #ifdef JUCE_DEBUG
  20578. // you should only call this method once!
  20579. for (int i = formats.size(); --i >= 0;)
  20580. {
  20581. #if JUCE_PLUGINHOST_VST
  20582. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  20583. #endif
  20584. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  20585. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  20586. #endif
  20587. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  20588. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  20589. #endif
  20590. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  20591. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  20592. #endif
  20593. }
  20594. #endif
  20595. #if JUCE_PLUGINHOST_VST
  20596. formats.add (new VSTPluginFormat());
  20597. #endif
  20598. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  20599. formats.add (new AudioUnitPluginFormat());
  20600. #endif
  20601. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  20602. formats.add (new DirectXPluginFormat());
  20603. #endif
  20604. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  20605. formats.add (new LADSPAPluginFormat());
  20606. #endif
  20607. }
  20608. int AudioPluginFormatManager::getNumFormats() throw()
  20609. {
  20610. return formats.size();
  20611. }
  20612. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  20613. {
  20614. return formats [index];
  20615. }
  20616. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  20617. {
  20618. formats.add (format);
  20619. }
  20620. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  20621. String& errorMessage) const
  20622. {
  20623. AudioPluginInstance* result = 0;
  20624. for (int i = 0; i < formats.size(); ++i)
  20625. {
  20626. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  20627. if (result != 0)
  20628. break;
  20629. }
  20630. if (result == 0)
  20631. {
  20632. if (description.file != File::nonexistent && ! description.file.exists())
  20633. errorMessage = TRANS ("This plug-in file no longer exists");
  20634. else
  20635. errorMessage = TRANS ("This plug-in failed to load correctly");
  20636. }
  20637. return result;
  20638. }
  20639. END_JUCE_NAMESPACE
  20640. /********* End of inlined file: juce_AudioPluginFormatManager.cpp *********/
  20641. /********* Start of inlined file: juce_AudioPluginInstance.cpp *********/
  20642. #define JUCE_PLUGIN_HOST 1
  20643. BEGIN_JUCE_NAMESPACE
  20644. AudioPluginInstance::AudioPluginInstance()
  20645. {
  20646. }
  20647. AudioPluginInstance::~AudioPluginInstance()
  20648. {
  20649. }
  20650. END_JUCE_NAMESPACE
  20651. /********* End of inlined file: juce_AudioPluginInstance.cpp *********/
  20652. /********* Start of inlined file: juce_KnownPluginList.cpp *********/
  20653. BEGIN_JUCE_NAMESPACE
  20654. KnownPluginList::KnownPluginList()
  20655. {
  20656. }
  20657. KnownPluginList::~KnownPluginList()
  20658. {
  20659. }
  20660. void KnownPluginList::clear()
  20661. {
  20662. if (types.size() > 0)
  20663. {
  20664. types.clear();
  20665. sendChangeMessage (this);
  20666. }
  20667. }
  20668. PluginDescription* KnownPluginList::getTypeForFile (const File& file) const throw()
  20669. {
  20670. for (int i = 0; i < types.size(); ++i)
  20671. if (types.getUnchecked(i)->file == file)
  20672. return types.getUnchecked(i);
  20673. return 0;
  20674. }
  20675. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  20676. {
  20677. for (int i = 0; i < types.size(); ++i)
  20678. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  20679. return types.getUnchecked(i);
  20680. return 0;
  20681. }
  20682. bool KnownPluginList::addType (const PluginDescription& type)
  20683. {
  20684. for (int i = types.size(); --i >= 0;)
  20685. {
  20686. if (types.getUnchecked(i)->isDuplicateOf (type))
  20687. {
  20688. // strange - found a duplicate plugin with different info..
  20689. jassert (types.getUnchecked(i)->name == type.name);
  20690. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  20691. *types.getUnchecked(i) = type;
  20692. return false;
  20693. }
  20694. }
  20695. types.add (new PluginDescription (type));
  20696. sendChangeMessage (this);
  20697. return true;
  20698. }
  20699. void KnownPluginList::removeType (const int index) throw()
  20700. {
  20701. types.remove (index);
  20702. sendChangeMessage (this);
  20703. }
  20704. bool KnownPluginList::isListingUpToDate (const File& possiblePluginFile) const throw()
  20705. {
  20706. if (getTypeForFile (possiblePluginFile) == 0)
  20707. return false;
  20708. for (int i = types.size(); --i >= 0;)
  20709. {
  20710. const PluginDescription* const d = types.getUnchecked(i);
  20711. if (d->file == possiblePluginFile
  20712. && d->lastFileModTime != possiblePluginFile.getLastModificationTime())
  20713. {
  20714. return false;
  20715. }
  20716. }
  20717. return true;
  20718. }
  20719. bool KnownPluginList::scanAndAddFile (const File& possiblePluginFile,
  20720. const bool dontRescanIfAlreadyInList,
  20721. OwnedArray <PluginDescription>& typesFound)
  20722. {
  20723. bool addedOne = false;
  20724. if (dontRescanIfAlreadyInList
  20725. && getTypeForFile (possiblePluginFile) != 0)
  20726. {
  20727. bool needsRescanning = false;
  20728. for (int i = types.size(); --i >= 0;)
  20729. {
  20730. const PluginDescription* const d = types.getUnchecked(i);
  20731. if (d->file == possiblePluginFile)
  20732. {
  20733. if (d->lastFileModTime != possiblePluginFile.getLastModificationTime())
  20734. needsRescanning = true;
  20735. else
  20736. typesFound.add (new PluginDescription (*d));
  20737. }
  20738. }
  20739. if (! needsRescanning)
  20740. return false;
  20741. }
  20742. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  20743. {
  20744. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  20745. OwnedArray <PluginDescription> found;
  20746. format->findAllTypesForFile (found, possiblePluginFile);
  20747. for (int i = 0; i < found.size(); ++i)
  20748. {
  20749. PluginDescription* const desc = found.getUnchecked(i);
  20750. jassert (desc != 0);
  20751. if (addType (*desc))
  20752. addedOne = true;
  20753. typesFound.add (new PluginDescription (*desc));
  20754. }
  20755. }
  20756. return addedOne;
  20757. }
  20758. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  20759. OwnedArray <PluginDescription>& typesFound)
  20760. {
  20761. for (int i = 0; i < files.size(); ++i)
  20762. {
  20763. const File f (files [i]);
  20764. if (! scanAndAddFile (f, true, typesFound))
  20765. {
  20766. if (f.isDirectory())
  20767. {
  20768. StringArray s;
  20769. {
  20770. OwnedArray <File> subFiles;
  20771. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  20772. for (int j = 0; j < subFiles.size(); ++j)
  20773. s.add (subFiles.getUnchecked (j)->getFullPathName());
  20774. }
  20775. scanAndAddDragAndDroppedFiles (s, typesFound);
  20776. }
  20777. }
  20778. }
  20779. }
  20780. class PluginSorter
  20781. {
  20782. public:
  20783. KnownPluginList::SortMethod method;
  20784. PluginSorter() throw() {}
  20785. int compareElements (const PluginDescription* const first,
  20786. const PluginDescription* const second) const throw()
  20787. {
  20788. int diff = 0;
  20789. if (method == KnownPluginList::sortByCategory)
  20790. diff = first->category.compareLexicographically (second->category);
  20791. else if (method == KnownPluginList::sortByManufacturer)
  20792. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  20793. else if (method == KnownPluginList::sortByFileSystemLocation)
  20794. diff = first->file.getParentDirectory().getFullPathName().compare (second->file.getParentDirectory().getFullPathName());
  20795. if (diff == 0)
  20796. diff = first->name.compareLexicographically (second->name);
  20797. return diff;
  20798. }
  20799. };
  20800. void KnownPluginList::sort (const SortMethod method)
  20801. {
  20802. if (method != defaultOrder)
  20803. {
  20804. PluginSorter sorter;
  20805. sorter.method = method;
  20806. types.sort (sorter, true);
  20807. sendChangeMessage (this);
  20808. }
  20809. }
  20810. XmlElement* KnownPluginList::createXml() const
  20811. {
  20812. XmlElement* const e = new XmlElement (T("KNOWNPLUGINS"));
  20813. for (int i = 0; i < types.size(); ++i)
  20814. e->addChildElement (types.getUnchecked(i)->createXml());
  20815. return e;
  20816. }
  20817. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  20818. {
  20819. clear();
  20820. if (xml.hasTagName (T("KNOWNPLUGINS")))
  20821. {
  20822. forEachXmlChildElement (xml, e)
  20823. {
  20824. PluginDescription info;
  20825. if (info.loadFromXml (*e))
  20826. addType (info);
  20827. }
  20828. }
  20829. }
  20830. const int menuIdBase = 0x324503f4;
  20831. // This is used to turn a bunch of paths into a nested menu structure.
  20832. struct PluginFilesystemTree
  20833. {
  20834. private:
  20835. String folder;
  20836. OwnedArray <PluginFilesystemTree> subFolders;
  20837. Array <PluginDescription*> plugins;
  20838. void addPlugin (PluginDescription* const pd, const String& path)
  20839. {
  20840. if (path.isEmpty())
  20841. {
  20842. plugins.add (pd);
  20843. }
  20844. else
  20845. {
  20846. const String firstSubFolder (path.upToFirstOccurrenceOf (T("/"), false, false));
  20847. const String remainingPath (path.fromFirstOccurrenceOf (T("/"), false, false));
  20848. for (int i = subFolders.size(); --i >= 0;)
  20849. {
  20850. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  20851. {
  20852. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  20853. return;
  20854. }
  20855. }
  20856. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  20857. newFolder->folder = firstSubFolder;
  20858. subFolders.add (newFolder);
  20859. newFolder->addPlugin (pd, remainingPath);
  20860. }
  20861. }
  20862. // removes any deeply nested folders that don't contain any actual plugins
  20863. void optimise()
  20864. {
  20865. for (int i = subFolders.size(); --i >= 0;)
  20866. {
  20867. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  20868. sub->optimise();
  20869. if (sub->plugins.size() == 0)
  20870. {
  20871. for (int j = 0; j < sub->subFolders.size(); ++j)
  20872. subFolders.add (sub->subFolders.getUnchecked(j));
  20873. sub->subFolders.clear (false);
  20874. subFolders.remove (i);
  20875. }
  20876. }
  20877. }
  20878. public:
  20879. void buildTree (const Array <PluginDescription*>& allPlugins)
  20880. {
  20881. for (int i = 0; i < allPlugins.size(); ++i)
  20882. {
  20883. String path (allPlugins.getUnchecked(i)->file.getParentDirectory().getFullPathName());
  20884. if (path.substring (1, 2) == T(":"))
  20885. path = path.substring (2);
  20886. path = path.replaceCharacter (T('\\'), T('/'));
  20887. addPlugin (allPlugins.getUnchecked(i), path);
  20888. }
  20889. optimise();
  20890. }
  20891. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  20892. {
  20893. int i;
  20894. for (i = 0; i < subFolders.size(); ++i)
  20895. {
  20896. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  20897. PopupMenu subMenu;
  20898. sub->addToMenu (subMenu, allPlugins);
  20899. m.addSubMenu (sub->folder, subMenu);
  20900. }
  20901. for (i = 0; i < plugins.size(); ++i)
  20902. {
  20903. PluginDescription* const plugin = plugins.getUnchecked(i);
  20904. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  20905. plugin->name, true, false);
  20906. }
  20907. }
  20908. };
  20909. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  20910. {
  20911. Array <PluginDescription*> sorted;
  20912. {
  20913. PluginSorter sorter;
  20914. sorter.method = sortMethod;
  20915. for (int i = 0; i < types.size(); ++i)
  20916. sorted.addSorted (sorter, types.getUnchecked(i));
  20917. }
  20918. if (sortMethod == sortByCategory
  20919. || sortMethod == sortByManufacturer)
  20920. {
  20921. String lastSubMenuName;
  20922. PopupMenu sub;
  20923. for (int i = 0; i < sorted.size(); ++i)
  20924. {
  20925. const PluginDescription* const pd = sorted.getUnchecked(i);
  20926. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  20927. : pd->manufacturerName);
  20928. if (thisSubMenuName.trim().isEmpty())
  20929. thisSubMenuName = T("Other");
  20930. if (thisSubMenuName != lastSubMenuName)
  20931. {
  20932. if (sub.getNumItems() > 0)
  20933. {
  20934. menu.addSubMenu (lastSubMenuName, sub);
  20935. sub.clear();
  20936. }
  20937. lastSubMenuName = thisSubMenuName;
  20938. }
  20939. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  20940. }
  20941. if (sub.getNumItems() > 0)
  20942. menu.addSubMenu (lastSubMenuName, sub);
  20943. }
  20944. else if (sortMethod == sortByFileSystemLocation)
  20945. {
  20946. PluginFilesystemTree root;
  20947. root.buildTree (sorted);
  20948. root.addToMenu (menu, types);
  20949. }
  20950. else
  20951. {
  20952. for (int i = 0; i < sorted.size(); ++i)
  20953. {
  20954. const PluginDescription* const pd = sorted.getUnchecked(i);
  20955. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  20956. }
  20957. }
  20958. }
  20959. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  20960. {
  20961. const int i = menuResultCode - menuIdBase;
  20962. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  20963. }
  20964. END_JUCE_NAMESPACE
  20965. /********* End of inlined file: juce_KnownPluginList.cpp *********/
  20966. /********* Start of inlined file: juce_PluginDescription.cpp *********/
  20967. BEGIN_JUCE_NAMESPACE
  20968. PluginDescription::PluginDescription() throw()
  20969. : uid (0),
  20970. isInstrument (false),
  20971. numInputChannels (0),
  20972. numOutputChannels (0)
  20973. {
  20974. }
  20975. PluginDescription::~PluginDescription() throw()
  20976. {
  20977. }
  20978. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  20979. : name (other.name),
  20980. pluginFormatName (other.pluginFormatName),
  20981. category (other.category),
  20982. manufacturerName (other.manufacturerName),
  20983. version (other.version),
  20984. file (other.file),
  20985. lastFileModTime (other.lastFileModTime),
  20986. uid (other.uid),
  20987. isInstrument (other.isInstrument),
  20988. numInputChannels (other.numInputChannels),
  20989. numOutputChannels (other.numOutputChannels)
  20990. {
  20991. }
  20992. const PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  20993. {
  20994. name = other.name;
  20995. pluginFormatName = other.pluginFormatName;
  20996. category = other.category;
  20997. manufacturerName = other.manufacturerName;
  20998. version = other.version;
  20999. file = other.file;
  21000. uid = other.uid;
  21001. isInstrument = other.isInstrument;
  21002. lastFileModTime = other.lastFileModTime;
  21003. numInputChannels = other.numInputChannels;
  21004. numOutputChannels = other.numOutputChannels;
  21005. return *this;
  21006. }
  21007. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  21008. {
  21009. return file == other.file
  21010. && uid == other.uid;
  21011. }
  21012. const String PluginDescription::createIdentifierString() const throw()
  21013. {
  21014. return pluginFormatName
  21015. + T("-") + name
  21016. + T("-") + String::toHexString (file.getFileName().hashCode())
  21017. + T("-") + String::toHexString (uid);
  21018. }
  21019. XmlElement* PluginDescription::createXml() const
  21020. {
  21021. XmlElement* const e = new XmlElement (T("PLUGIN"));
  21022. e->setAttribute (T("name"), name);
  21023. e->setAttribute (T("format"), pluginFormatName);
  21024. e->setAttribute (T("category"), category);
  21025. e->setAttribute (T("manufacturer"), manufacturerName);
  21026. e->setAttribute (T("version"), version);
  21027. e->setAttribute (T("file"), file.getFullPathName());
  21028. e->setAttribute (T("uid"), String::toHexString (uid));
  21029. e->setAttribute (T("isInstrument"), isInstrument);
  21030. e->setAttribute (T("fileTime"), String::toHexString (lastFileModTime.toMilliseconds()));
  21031. e->setAttribute (T("numInputs"), numInputChannels);
  21032. e->setAttribute (T("numOutputs"), numOutputChannels);
  21033. return e;
  21034. }
  21035. bool PluginDescription::loadFromXml (const XmlElement& xml)
  21036. {
  21037. if (xml.hasTagName (T("PLUGIN")))
  21038. {
  21039. name = xml.getStringAttribute (T("name"));
  21040. pluginFormatName = xml.getStringAttribute (T("format"));
  21041. category = xml.getStringAttribute (T("category"));
  21042. manufacturerName = xml.getStringAttribute (T("manufacturer"));
  21043. version = xml.getStringAttribute (T("version"));
  21044. file = File (xml.getStringAttribute (T("file")));
  21045. uid = xml.getStringAttribute (T("uid")).getHexValue32();
  21046. isInstrument = xml.getBoolAttribute (T("isInstrument"), false);
  21047. lastFileModTime = Time (xml.getStringAttribute (T("fileTime")).getHexValue64());
  21048. numInputChannels = xml.getIntAttribute (T("numInputs"));
  21049. numOutputChannels = xml.getIntAttribute (T("numOutputs"));
  21050. return true;
  21051. }
  21052. return false;
  21053. }
  21054. END_JUCE_NAMESPACE
  21055. /********* End of inlined file: juce_PluginDescription.cpp *********/
  21056. /********* Start of inlined file: juce_PluginDirectoryScanner.cpp *********/
  21057. BEGIN_JUCE_NAMESPACE
  21058. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  21059. AudioPluginFormat& formatToLookFor,
  21060. FileSearchPath directoriesToSearch,
  21061. const bool recursive,
  21062. const File& deadMansPedalFile_)
  21063. : list (listToAddTo),
  21064. format (formatToLookFor),
  21065. deadMansPedalFile (deadMansPedalFile_),
  21066. nextIndex (0),
  21067. progress (0)
  21068. {
  21069. directoriesToSearch.removeRedundantPaths();
  21070. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  21071. recursiveFileSearch (directoriesToSearch [j], recursive);
  21072. // If any plugins have crashed recently when being loaded, move them to the
  21073. // end of the list to give the others a chance to load correctly..
  21074. const StringArray crashedPlugins (getDeadMansPedalFile());
  21075. for (int i = 0; i < crashedPlugins.size(); ++i)
  21076. {
  21077. const File f (crashedPlugins[i]);
  21078. for (int j = filesToScan.size(); --j >= 0;)
  21079. if (f == *filesToScan.getUnchecked (j))
  21080. filesToScan.move (j, -1);
  21081. }
  21082. }
  21083. void PluginDirectoryScanner::recursiveFileSearch (const File& dir, const bool recursive)
  21084. {
  21085. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  21086. // .component or .vst directories.
  21087. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  21088. while (iter.next())
  21089. {
  21090. const File f (iter.getFile());
  21091. bool isPlugin = false;
  21092. if (format.fileMightContainThisPluginType (f))
  21093. {
  21094. isPlugin = true;
  21095. filesToScan.add (new File (f));
  21096. }
  21097. if (recursive && (! isPlugin) && f.isDirectory())
  21098. recursiveFileSearch (f, true);
  21099. }
  21100. }
  21101. PluginDirectoryScanner::~PluginDirectoryScanner()
  21102. {
  21103. }
  21104. const File PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  21105. {
  21106. File* const file = filesToScan [nextIndex];
  21107. if (file != 0)
  21108. return *file;
  21109. return File::nonexistent;
  21110. }
  21111. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  21112. {
  21113. File* const file = filesToScan [nextIndex];
  21114. if (file != 0)
  21115. {
  21116. if (! list.isListingUpToDate (*file))
  21117. {
  21118. OwnedArray <PluginDescription> typesFound;
  21119. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  21120. StringArray crashedPlugins (getDeadMansPedalFile());
  21121. crashedPlugins.removeString (file->getFullPathName());
  21122. crashedPlugins.add (file->getFullPathName());
  21123. setDeadMansPedalFile (crashedPlugins);
  21124. list.scanAndAddFile (*file,
  21125. dontRescanIfAlreadyInList,
  21126. typesFound);
  21127. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  21128. crashedPlugins.removeString (file->getFullPathName());
  21129. setDeadMansPedalFile (crashedPlugins);
  21130. if (typesFound.size() == 0)
  21131. failedFiles.add (file->getFullPathName());
  21132. }
  21133. ++nextIndex;
  21134. progress = nextIndex / (float) filesToScan.size();
  21135. }
  21136. return nextIndex < filesToScan.size();
  21137. }
  21138. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  21139. {
  21140. StringArray lines;
  21141. if (deadMansPedalFile != File::nonexistent)
  21142. {
  21143. lines.addLines (deadMansPedalFile.loadFileAsString());
  21144. lines.removeEmptyStrings();
  21145. }
  21146. return lines;
  21147. }
  21148. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  21149. {
  21150. if (deadMansPedalFile != File::nonexistent)
  21151. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  21152. }
  21153. END_JUCE_NAMESPACE
  21154. /********* End of inlined file: juce_PluginDirectoryScanner.cpp *********/
  21155. /********* Start of inlined file: juce_PluginListComponent.cpp *********/
  21156. BEGIN_JUCE_NAMESPACE
  21157. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  21158. const File& deadMansPedalFile_,
  21159. PropertiesFile* const propertiesToUse_)
  21160. : list (listToEdit),
  21161. deadMansPedalFile (deadMansPedalFile_),
  21162. propertiesToUse (propertiesToUse_)
  21163. {
  21164. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  21165. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  21166. optionsButton->addButtonListener (this);
  21167. optionsButton->setTriggeredOnMouseDown (true);
  21168. setSize (400, 600);
  21169. list.addChangeListener (this);
  21170. }
  21171. PluginListComponent::~PluginListComponent()
  21172. {
  21173. list.removeChangeListener (this);
  21174. deleteAllChildren();
  21175. }
  21176. void PluginListComponent::resized()
  21177. {
  21178. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  21179. optionsButton->changeWidthToFitText (24);
  21180. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  21181. }
  21182. void PluginListComponent::changeListenerCallback (void*)
  21183. {
  21184. listBox->updateContent();
  21185. listBox->repaint();
  21186. }
  21187. int PluginListComponent::getNumRows()
  21188. {
  21189. return list.getNumTypes();
  21190. }
  21191. void PluginListComponent::paintListBoxItem (int row,
  21192. Graphics& g,
  21193. int width, int height,
  21194. bool rowIsSelected)
  21195. {
  21196. if (rowIsSelected)
  21197. g.fillAll (findColour (TextEditor::highlightColourId));
  21198. const PluginDescription* const pd = list.getType (row);
  21199. if (pd != 0)
  21200. {
  21201. GlyphArrangement ga;
  21202. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  21203. g.setColour (Colours::black);
  21204. ga.draw (g);
  21205. float x, y, r, b;
  21206. ga.getBoundingBox (0, -1, x, y, r, b, false);
  21207. String desc;
  21208. desc << pd->pluginFormatName
  21209. << (pd->isInstrument ? " instrument" : " effect")
  21210. << " - "
  21211. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  21212. << " / "
  21213. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  21214. if (pd->manufacturerName.isNotEmpty())
  21215. desc << " - " << pd->manufacturerName;
  21216. if (pd->version.isNotEmpty())
  21217. desc << " - " << pd->version;
  21218. if (pd->category.isNotEmpty())
  21219. desc << " - category: '" << pd->category << '\'';
  21220. g.setColour (Colours::grey);
  21221. ga.clear();
  21222. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, r + 10.0f, height * 0.8f, width - r - 12.0f, true);
  21223. ga.draw (g);
  21224. }
  21225. }
  21226. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  21227. {
  21228. list.removeType (lastRowSelected);
  21229. }
  21230. void PluginListComponent::buttonClicked (Button* b)
  21231. {
  21232. if (optionsButton == b)
  21233. {
  21234. PopupMenu menu;
  21235. menu.addItem (1, TRANS("Clear list"));
  21236. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  21237. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  21238. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  21239. menu.addSeparator();
  21240. menu.addItem (2, TRANS("Sort alphabetically"));
  21241. menu.addItem (3, TRANS("Sort by category"));
  21242. menu.addItem (4, TRANS("Sort by manufacturer"));
  21243. menu.addSeparator();
  21244. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  21245. {
  21246. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  21247. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  21248. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  21249. }
  21250. const int r = menu.showAt (optionsButton);
  21251. if (r == 1)
  21252. {
  21253. list.clear();
  21254. }
  21255. else if (r == 2)
  21256. {
  21257. list.sort (KnownPluginList::sortAlphabetically);
  21258. }
  21259. else if (r == 3)
  21260. {
  21261. list.sort (KnownPluginList::sortByCategory);
  21262. }
  21263. else if (r == 4)
  21264. {
  21265. list.sort (KnownPluginList::sortByManufacturer);
  21266. }
  21267. else if (r == 5)
  21268. {
  21269. const SparseSet <int> selected (listBox->getSelectedRows());
  21270. for (int i = list.getNumTypes(); --i >= 0;)
  21271. if (selected.contains (i))
  21272. list.removeType (i);
  21273. }
  21274. else if (r == 6)
  21275. {
  21276. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  21277. if (desc != 0)
  21278. desc->file.getParentDirectory().startAsProcess();
  21279. }
  21280. else if (r == 7)
  21281. {
  21282. for (int i = list.getNumTypes(); --i >= 0;)
  21283. {
  21284. if (list.getType (i)->file != File::nonexistent
  21285. && ! list.getType (i)->file.exists())
  21286. {
  21287. list.removeType (i);
  21288. }
  21289. }
  21290. }
  21291. else if (r != 0)
  21292. {
  21293. typeToScan = r - 10;
  21294. startTimer (1);
  21295. }
  21296. }
  21297. }
  21298. void PluginListComponent::timerCallback()
  21299. {
  21300. stopTimer();
  21301. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  21302. }
  21303. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  21304. {
  21305. return true;
  21306. }
  21307. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  21308. {
  21309. OwnedArray <PluginDescription> typesFound;
  21310. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  21311. }
  21312. void PluginListComponent::scanFor (AudioPluginFormat* format)
  21313. {
  21314. if (format == 0)
  21315. return;
  21316. FileSearchPath path (format->getDefaultLocationsToSearch());
  21317. if (propertiesToUse != 0)
  21318. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  21319. {
  21320. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  21321. FileSearchPathListComponent pathList;
  21322. pathList.setSize (500, 300);
  21323. pathList.setPath (path);
  21324. aw.addCustomComponent (&pathList);
  21325. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  21326. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  21327. if (aw.runModalLoop() == 0)
  21328. return;
  21329. path = pathList.getPath();
  21330. }
  21331. if (propertiesToUse != 0)
  21332. {
  21333. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  21334. propertiesToUse->saveIfNeeded();
  21335. }
  21336. double progress = 0.0;
  21337. AlertWindow aw (TRANS("Scanning for plugins..."),
  21338. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  21339. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  21340. aw.addProgressBarComponent (progress);
  21341. aw.enterModalState();
  21342. MessageManager::getInstance()->dispatchPendingMessages();
  21343. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  21344. for (;;)
  21345. {
  21346. aw.setMessage (TRANS("Testing:\n\n")
  21347. + scanner.getNextPluginFileThatWillBeScanned().getFileName());
  21348. MessageManager::getInstance()->dispatchPendingMessages (500);
  21349. if (! scanner.scanNextFile (true))
  21350. break;
  21351. if (! aw.isCurrentlyModal())
  21352. break;
  21353. progress = scanner.getProgress();
  21354. }
  21355. if (scanner.getFailedFiles().size() > 0)
  21356. {
  21357. StringArray shortNames;
  21358. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  21359. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  21360. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  21361. TRANS("Scan complete"),
  21362. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  21363. + shortNames.joinIntoString (", "));
  21364. }
  21365. }
  21366. END_JUCE_NAMESPACE
  21367. /********* End of inlined file: juce_PluginListComponent.cpp *********/
  21368. /********* Start of inlined file: juce_AudioUnitPluginFormat.cpp *********/
  21369. #if JUCE_PLUGINHOST_AU && (! (defined (LINUX) || defined (_WIN32)))
  21370. #include <Carbon/Carbon.h>
  21371. #include <AudioToolbox/AudioToolbox.h>
  21372. #include <AudioUnit/AudioUnitCarbonView.h>
  21373. BEGIN_JUCE_NAMESPACE
  21374. #if JUCE_MAC
  21375. extern void juce_callAnyTimersSynchronously();
  21376. extern bool juce_isHIViewCreatedByJuce (HIViewRef view);
  21377. extern bool juce_isWindowCreatedByJuce (WindowRef window);
  21378. #if MACOS_10_3_OR_EARLIER
  21379. #define kAudioUnitType_Generator 'augn'
  21380. #endif
  21381. // Change this to disable logging of various activities
  21382. #ifndef AU_LOGGING
  21383. #define AU_LOGGING 1
  21384. #endif
  21385. #if AU_LOGGING
  21386. #define log(a) Logger::writeToLog(a);
  21387. #else
  21388. #define log(a)
  21389. #endif
  21390. static int insideCallback = 0;
  21391. class AudioUnitPluginWindow;
  21392. class AudioUnitPluginInstance : public AudioPluginInstance
  21393. {
  21394. public:
  21395. ~AudioUnitPluginInstance();
  21396. // AudioPluginInstance methods:
  21397. void fillInPluginDescription (PluginDescription& desc) const
  21398. {
  21399. desc.name = pluginName;
  21400. desc.file = file;
  21401. desc.uid = ((int) componentDesc.componentType)
  21402. ^ ((int) componentDesc.componentSubType)
  21403. ^ ((int) componentDesc.componentManufacturer);
  21404. desc.lastFileModTime = file.getLastModificationTime();
  21405. desc.pluginFormatName = "AudioUnit";
  21406. desc.category = getCategory();
  21407. desc.manufacturerName = manufacturer;
  21408. desc.version = version;
  21409. desc.numInputChannels = getNumInputChannels();
  21410. desc.numOutputChannels = getNumOutputChannels();
  21411. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  21412. }
  21413. const String getName() const { return pluginName; }
  21414. bool acceptsMidi() const { return wantsMidiMessages; }
  21415. bool producesMidi() const { return false; }
  21416. // AudioProcessor methods:
  21417. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21418. void releaseResources();
  21419. void processBlock (AudioSampleBuffer& buffer,
  21420. MidiBuffer& midiMessages);
  21421. AudioProcessorEditor* createEditor();
  21422. const String getInputChannelName (const int index) const;
  21423. bool isInputChannelStereoPair (int index) const;
  21424. const String getOutputChannelName (const int index) const;
  21425. bool isOutputChannelStereoPair (int index) const;
  21426. int getNumParameters();
  21427. float getParameter (int index);
  21428. void setParameter (int index, float newValue);
  21429. const String getParameterName (int index);
  21430. const String getParameterText (int index);
  21431. bool isParameterAutomatable (int index) const;
  21432. int getNumPrograms();
  21433. int getCurrentProgram();
  21434. void setCurrentProgram (int index);
  21435. const String getProgramName (int index);
  21436. void changeProgramName (int index, const String& newName);
  21437. void getStateInformation (MemoryBlock& destData);
  21438. void getCurrentProgramStateInformation (MemoryBlock& destData);
  21439. void setStateInformation (const void* data, int sizeInBytes);
  21440. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  21441. juce_UseDebuggingNewOperator
  21442. private:
  21443. friend class AudioUnitPluginWindow;
  21444. friend class AudioUnitPluginFormat;
  21445. ComponentDescription componentDesc;
  21446. String pluginName, manufacturer, version;
  21447. File file;
  21448. CriticalSection lock;
  21449. bool initialised, wantsMidiMessages, wasPlaying;
  21450. AudioBufferList* outputBufferList;
  21451. AudioTimeStamp timeStamp;
  21452. AudioSampleBuffer* currentBuffer;
  21453. AudioUnit audioUnit;
  21454. Array <int> parameterIds;
  21455. bool getComponentDescFromFile (const File& file);
  21456. void initialise();
  21457. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  21458. const AudioTimeStamp* inTimeStamp,
  21459. UInt32 inBusNumber,
  21460. UInt32 inNumberFrames,
  21461. AudioBufferList* ioData) const;
  21462. static OSStatus renderGetInputCallback (void* inRefCon,
  21463. AudioUnitRenderActionFlags* ioActionFlags,
  21464. const AudioTimeStamp* inTimeStamp,
  21465. UInt32 inBusNumber,
  21466. UInt32 inNumberFrames,
  21467. AudioBufferList* ioData)
  21468. {
  21469. return ((AudioUnitPluginInstance*) inRefCon)
  21470. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  21471. }
  21472. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  21473. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  21474. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  21475. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  21476. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  21477. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  21478. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  21479. {
  21480. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  21481. }
  21482. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  21483. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  21484. Float64* outCurrentMeasureDownBeat)
  21485. {
  21486. return ((AudioUnitPluginInstance*) inHostUserData)
  21487. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  21488. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  21489. }
  21490. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  21491. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  21492. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  21493. {
  21494. return ((AudioUnitPluginInstance*) inHostUserData)
  21495. ->getTransportState (outIsPlaying, outTransportStateChanged,
  21496. outCurrentSampleInTimeLine, outIsCycling,
  21497. outCycleStartBeat, outCycleEndBeat);
  21498. }
  21499. void getNumChannels (int& numIns, int& numOuts)
  21500. {
  21501. numIns = 0;
  21502. numOuts = 0;
  21503. AUChannelInfo supportedChannels [128];
  21504. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  21505. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  21506. 0, supportedChannels, &supportedChannelsSize) == noErr
  21507. && supportedChannelsSize > 0)
  21508. {
  21509. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  21510. {
  21511. numIns = jmax (numIns, supportedChannels[i].inChannels);
  21512. numOuts = jmax (numOuts, supportedChannels[i].outChannels);
  21513. }
  21514. }
  21515. else
  21516. {
  21517. // (this really means the plugin will take any number of ins/outs as long
  21518. // as they are the same)
  21519. numIns = numOuts = 2;
  21520. }
  21521. }
  21522. const String getCategory() const;
  21523. AudioUnitPluginInstance (const File& file);
  21524. };
  21525. AudioUnitPluginInstance::AudioUnitPluginInstance (const File& file_)
  21526. : file (file_),
  21527. initialised (false),
  21528. wantsMidiMessages (false),
  21529. audioUnit (0),
  21530. outputBufferList (0),
  21531. currentBuffer (0)
  21532. {
  21533. try
  21534. {
  21535. ++insideCallback;
  21536. log (T("Opening AU: ") + file.getFullPathName());
  21537. if (getComponentDescFromFile (file))
  21538. {
  21539. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  21540. if (comp != 0)
  21541. {
  21542. audioUnit = (AudioUnit) OpenComponent (comp);
  21543. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  21544. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  21545. }
  21546. }
  21547. --insideCallback;
  21548. }
  21549. catch (...)
  21550. {
  21551. --insideCallback;
  21552. }
  21553. }
  21554. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  21555. {
  21556. {
  21557. const ScopedLock sl (lock);
  21558. jassert (insideCallback == 0);
  21559. if (audioUnit != 0)
  21560. {
  21561. AudioUnitUninitialize (audioUnit);
  21562. CloseComponent (audioUnit);
  21563. audioUnit = 0;
  21564. }
  21565. }
  21566. juce_free (outputBufferList);
  21567. }
  21568. bool AudioUnitPluginInstance::getComponentDescFromFile (const File& file)
  21569. {
  21570. zerostruct (componentDesc);
  21571. if (! file.hasFileExtension (T(".component")))
  21572. return false;
  21573. const String filename (file.getFullPathName());
  21574. const char* const utf8 = filename.toUTF8();
  21575. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  21576. strlen (utf8), file.isDirectory());
  21577. if (url != 0)
  21578. {
  21579. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  21580. CFRelease (url);
  21581. if (bundleRef != 0)
  21582. {
  21583. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  21584. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  21585. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  21586. if (pluginName.isEmpty())
  21587. pluginName = file.getFileNameWithoutExtension();
  21588. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  21589. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  21590. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  21591. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  21592. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  21593. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  21594. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  21595. UseResFile (resFileId);
  21596. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  21597. {
  21598. Handle h = Get1IndResource ('thng', i);
  21599. if (h != 0)
  21600. {
  21601. HLock (h);
  21602. const uint32* const types = (const uint32*) *h;
  21603. if (types[0] == kAudioUnitType_MusicDevice
  21604. || types[0] == kAudioUnitType_MusicEffect
  21605. || types[0] == kAudioUnitType_Effect
  21606. || types[0] == kAudioUnitType_Generator
  21607. || types[0] == kAudioUnitType_Panner)
  21608. {
  21609. componentDesc.componentType = types[0];
  21610. componentDesc.componentSubType = types[1];
  21611. componentDesc.componentManufacturer = types[2];
  21612. break;
  21613. }
  21614. HUnlock (h);
  21615. ReleaseResource (h);
  21616. }
  21617. }
  21618. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  21619. CFRelease (bundleRef);
  21620. }
  21621. }
  21622. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  21623. }
  21624. void AudioUnitPluginInstance::initialise()
  21625. {
  21626. if (initialised || audioUnit == 0)
  21627. return;
  21628. log (T("Initialising AU: ") + pluginName);
  21629. parameterIds.clear();
  21630. {
  21631. UInt32 paramListSize = 0;
  21632. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  21633. 0, 0, &paramListSize);
  21634. if (paramListSize > 0)
  21635. {
  21636. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  21637. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  21638. 0, &parameterIds.getReference(0), &paramListSize);
  21639. }
  21640. }
  21641. {
  21642. AURenderCallbackStruct info;
  21643. zerostruct (info);
  21644. info.inputProcRefCon = this;
  21645. info.inputProc = renderGetInputCallback;
  21646. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  21647. 0, &info, sizeof (info));
  21648. }
  21649. {
  21650. HostCallbackInfo info;
  21651. zerostruct (info);
  21652. info.hostUserData = this;
  21653. info.beatAndTempoProc = getBeatAndTempoCallback;
  21654. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  21655. info.transportStateProc = getTransportStateCallback;
  21656. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  21657. 0, &info, sizeof (info));
  21658. }
  21659. int numIns, numOuts;
  21660. getNumChannels (numIns, numOuts);
  21661. setPlayConfigDetails (numIns, numOuts, 0, 0);
  21662. initialised = AudioUnitInitialize (audioUnit) == noErr;
  21663. setLatencySamples (0);
  21664. }
  21665. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  21666. int samplesPerBlockExpected)
  21667. {
  21668. initialise();
  21669. if (initialised)
  21670. {
  21671. int numIns, numOuts;
  21672. getNumChannels (numIns, numOuts);
  21673. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  21674. Float64 latencySecs = 0.0;
  21675. UInt32 latencySize = sizeof (latencySecs);
  21676. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  21677. 0, &latencySecs, &latencySize);
  21678. setLatencySamples (roundDoubleToInt (latencySecs * sampleRate_));
  21679. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  21680. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  21681. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  21682. AudioStreamBasicDescription stream;
  21683. zerostruct (stream);
  21684. stream.mSampleRate = sampleRate_;
  21685. stream.mFormatID = kAudioFormatLinearPCM;
  21686. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  21687. stream.mFramesPerPacket = 1;
  21688. stream.mBytesPerPacket = 4;
  21689. stream.mBytesPerFrame = 4;
  21690. stream.mBitsPerChannel = 32;
  21691. stream.mChannelsPerFrame = numIns;
  21692. OSStatus err = AudioUnitSetProperty (audioUnit,
  21693. kAudioUnitProperty_StreamFormat,
  21694. kAudioUnitScope_Input,
  21695. 0, &stream, sizeof (stream));
  21696. stream.mChannelsPerFrame = numOuts;
  21697. err = AudioUnitSetProperty (audioUnit,
  21698. kAudioUnitProperty_StreamFormat,
  21699. kAudioUnitScope_Output,
  21700. 0, &stream, sizeof (stream));
  21701. juce_free (outputBufferList);
  21702. outputBufferList = (AudioBufferList*) juce_calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1));
  21703. outputBufferList->mNumberBuffers = numOuts;
  21704. for (int i = numOuts; --i >= 0;)
  21705. outputBufferList->mBuffers[i].mNumberChannels = 1;
  21706. zerostruct (timeStamp);
  21707. timeStamp.mSampleTime = 0;
  21708. timeStamp.mHostTime = AudioGetCurrentHostTime();
  21709. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  21710. currentBuffer = 0;
  21711. wasPlaying = false;
  21712. }
  21713. }
  21714. void AudioUnitPluginInstance::releaseResources()
  21715. {
  21716. if (initialised)
  21717. {
  21718. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  21719. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  21720. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  21721. juce_free (outputBufferList);
  21722. outputBufferList = 0;
  21723. currentBuffer = 0;
  21724. }
  21725. }
  21726. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  21727. const AudioTimeStamp* inTimeStamp,
  21728. UInt32 inBusNumber,
  21729. UInt32 inNumberFrames,
  21730. AudioBufferList* ioData) const
  21731. {
  21732. if (inBusNumber == 0
  21733. && currentBuffer != 0)
  21734. {
  21735. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  21736. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  21737. {
  21738. if (i < currentBuffer->getNumChannels())
  21739. {
  21740. memcpy (ioData->mBuffers[i].mData,
  21741. currentBuffer->getSampleData (i, 0),
  21742. sizeof (float) * inNumberFrames);
  21743. }
  21744. else
  21745. {
  21746. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  21747. }
  21748. }
  21749. }
  21750. return noErr;
  21751. }
  21752. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  21753. MidiBuffer& midiMessages)
  21754. {
  21755. const int numSamples = buffer.getNumSamples();
  21756. if (initialised)
  21757. {
  21758. AudioUnitRenderActionFlags flags = 0;
  21759. timeStamp.mHostTime = AudioGetCurrentHostTime();
  21760. for (int i = getNumOutputChannels(); --i >= 0;)
  21761. {
  21762. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  21763. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  21764. }
  21765. currentBuffer = &buffer;
  21766. if (wantsMidiMessages)
  21767. {
  21768. const uint8* midiEventData;
  21769. int midiEventSize, midiEventPosition;
  21770. MidiBuffer::Iterator i (midiMessages);
  21771. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  21772. {
  21773. if (midiEventSize <= 3)
  21774. MusicDeviceMIDIEvent (audioUnit,
  21775. midiEventData[0], midiEventData[1], midiEventData[2],
  21776. midiEventPosition);
  21777. else
  21778. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  21779. }
  21780. midiMessages.clear();
  21781. }
  21782. AudioUnitRender (audioUnit, &flags, &timeStamp,
  21783. 0, numSamples, outputBufferList);
  21784. timeStamp.mSampleTime += numSamples;
  21785. }
  21786. else
  21787. {
  21788. // Not initialised, so just bypass..
  21789. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  21790. buffer.clear (i, 0, buffer.getNumSamples());
  21791. }
  21792. }
  21793. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  21794. {
  21795. AudioPlayHead* const ph = getPlayHead();
  21796. AudioPlayHead::CurrentPositionInfo result;
  21797. if (ph != 0 && ph->getCurrentPosition (result))
  21798. {
  21799. *outCurrentBeat = result.ppqPosition;
  21800. *outCurrentTempo = result.bpm;
  21801. }
  21802. else
  21803. {
  21804. *outCurrentBeat = 0;
  21805. *outCurrentTempo = 120.0;
  21806. }
  21807. return noErr;
  21808. }
  21809. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  21810. Float32* outTimeSig_Numerator,
  21811. UInt32* outTimeSig_Denominator,
  21812. Float64* outCurrentMeasureDownBeat) const
  21813. {
  21814. AudioPlayHead* const ph = getPlayHead();
  21815. AudioPlayHead::CurrentPositionInfo result;
  21816. if (ph != 0 && ph->getCurrentPosition (result))
  21817. {
  21818. *outTimeSig_Numerator = result.timeSigNumerator;
  21819. *outTimeSig_Denominator = result.timeSigDenominator;
  21820. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  21821. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  21822. }
  21823. else
  21824. {
  21825. *outDeltaSampleOffsetToNextBeat = 0;
  21826. *outTimeSig_Numerator = 4;
  21827. *outTimeSig_Denominator = 4;
  21828. *outCurrentMeasureDownBeat = 0;
  21829. }
  21830. return noErr;
  21831. }
  21832. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  21833. Boolean* outTransportStateChanged,
  21834. Float64* outCurrentSampleInTimeLine,
  21835. Boolean* outIsCycling,
  21836. Float64* outCycleStartBeat,
  21837. Float64* outCycleEndBeat)
  21838. {
  21839. AudioPlayHead* const ph = getPlayHead();
  21840. AudioPlayHead::CurrentPositionInfo result;
  21841. if (ph != 0 && ph->getCurrentPosition (result))
  21842. {
  21843. *outIsPlaying = result.isPlaying;
  21844. *outTransportStateChanged = result.isPlaying != wasPlaying;
  21845. wasPlaying = result.isPlaying;
  21846. *outCurrentSampleInTimeLine = roundDoubleToInt (result.timeInSeconds * getSampleRate());
  21847. *outIsCycling = false;
  21848. *outCycleStartBeat = 0;
  21849. *outCycleEndBeat = 0;
  21850. }
  21851. else
  21852. {
  21853. *outIsPlaying = false;
  21854. *outTransportStateChanged = false;
  21855. *outCurrentSampleInTimeLine = 0;
  21856. *outIsCycling = false;
  21857. *outCycleStartBeat = 0;
  21858. *outCycleEndBeat = 0;
  21859. }
  21860. return noErr;
  21861. }
  21862. static VoidArray activeWindows;
  21863. class AudioUnitPluginWindow : public AudioProcessorEditor,
  21864. public Timer
  21865. {
  21866. public:
  21867. AudioUnitPluginWindow (AudioUnitPluginInstance& plugin_)
  21868. : AudioProcessorEditor (&plugin_),
  21869. plugin (plugin_),
  21870. isOpen (false),
  21871. pluginWantsKeys (false),
  21872. wasShowing (false),
  21873. recursiveResize (false),
  21874. viewComponent (0),
  21875. pluginViewRef (0)
  21876. {
  21877. movementWatcher = new CompMovementWatcher (this);
  21878. activeWindows.add (this);
  21879. setOpaque (true);
  21880. setVisible (true);
  21881. setSize (1, 1);
  21882. ComponentDescription viewList [16];
  21883. UInt32 viewListSize = sizeof (viewList);
  21884. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  21885. 0, &viewList, &viewListSize);
  21886. componentRecord = FindNextComponent (0, &viewList[0]);
  21887. }
  21888. ~AudioUnitPluginWindow()
  21889. {
  21890. deleteAndZero (movementWatcher);
  21891. closePluginWindow();
  21892. activeWindows.removeValue (this);
  21893. plugin.editorBeingDeleted (this);
  21894. }
  21895. bool isValid() const throw() { return componentRecord != 0; }
  21896. void componentMovedOrResized()
  21897. {
  21898. if (recursiveResize)
  21899. return;
  21900. Component* const topComp = getTopLevelComponent();
  21901. if (topComp->getPeer() != 0)
  21902. {
  21903. int x = 0, y = 0;
  21904. relativePositionToOtherComponent (topComp, x, y);
  21905. recursiveResize = true;
  21906. if (pluginViewRef != 0)
  21907. {
  21908. HIRect r;
  21909. r.origin.x = (float) x;
  21910. r.origin.y = (float) y;
  21911. r.size.width = (float) getWidth();
  21912. r.size.height = (float) getHeight();
  21913. HIViewSetFrame (pluginViewRef, &r);
  21914. }
  21915. recursiveResize = false;
  21916. }
  21917. }
  21918. void componentVisibilityChanged()
  21919. {
  21920. const bool isShowingNow = isShowing();
  21921. if (wasShowing != isShowingNow)
  21922. {
  21923. wasShowing = isShowingNow;
  21924. if (isShowingNow)
  21925. openPluginWindow();
  21926. else
  21927. closePluginWindow();
  21928. }
  21929. componentMovedOrResized();
  21930. }
  21931. void componentPeerChanged()
  21932. {
  21933. closePluginWindow();
  21934. openPluginWindow();
  21935. }
  21936. void timerCallback()
  21937. {
  21938. if (pluginViewRef != 0)
  21939. {
  21940. HIRect bounds;
  21941. HIViewGetBounds (pluginViewRef, &bounds);
  21942. const int w = jmax (32, (int) bounds.size.width);
  21943. const int h = jmax (32, (int) bounds.size.height);
  21944. if (w != getWidth() || h != getHeight())
  21945. {
  21946. setSize (w, h);
  21947. startTimer (50);
  21948. }
  21949. else
  21950. {
  21951. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  21952. }
  21953. }
  21954. }
  21955. bool keyStateChanged()
  21956. {
  21957. return pluginWantsKeys;
  21958. }
  21959. bool keyPressed (const KeyPress&)
  21960. {
  21961. return pluginWantsKeys;
  21962. }
  21963. void paint (Graphics& g)
  21964. {
  21965. if (isOpen)
  21966. {
  21967. ComponentPeer* const peer = getPeer();
  21968. if (peer != 0)
  21969. {
  21970. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  21971. getScreenY() - peer->getScreenY(),
  21972. getWidth(), getHeight());
  21973. }
  21974. }
  21975. else
  21976. {
  21977. g.fillAll (Colours::black);
  21978. }
  21979. }
  21980. void broughtToFront()
  21981. {
  21982. activeWindows.removeValue (this);
  21983. activeWindows.add (this);
  21984. }
  21985. juce_UseDebuggingNewOperator
  21986. private:
  21987. AudioUnitPluginInstance& plugin;
  21988. bool isOpen, wasShowing, recursiveResize;
  21989. bool pluginWantsKeys;
  21990. ComponentRecord* componentRecord;
  21991. AudioUnitCarbonView viewComponent;
  21992. HIViewRef pluginViewRef;
  21993. void openPluginWindow()
  21994. {
  21995. if (isOpen || getWindowHandle() == 0 || componentRecord == 0)
  21996. return;
  21997. log (T("Opening AU GUI: ") + plugin.getName());
  21998. isOpen = true;
  21999. pluginWantsKeys = true; //xxx any way to find this out? Does it matter?
  22000. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  22001. if (viewComponent != 0)
  22002. {
  22003. Float32Point pos = { getScreenX() - getTopLevelComponent()->getScreenX(),
  22004. getScreenY() - getTopLevelComponent()->getScreenY() };
  22005. Float32Point size = { 250, 200 };
  22006. AudioUnitCarbonViewCreate (viewComponent,
  22007. plugin.audioUnit,
  22008. (WindowRef) getWindowHandle(),
  22009. HIViewGetRoot ((WindowRef) getWindowHandle()),
  22010. &pos, &size,
  22011. (ControlRef*) &pluginViewRef);
  22012. }
  22013. timerCallback(); // to set our comp to the right size
  22014. repaint();
  22015. }
  22016. void closePluginWindow()
  22017. {
  22018. stopTimer();
  22019. if (isOpen)
  22020. {
  22021. log (T("Closing AU GUI: ") + plugin.getName());
  22022. isOpen = false;
  22023. if (viewComponent != 0)
  22024. CloseComponent (viewComponent);
  22025. pluginViewRef = 0;
  22026. }
  22027. }
  22028. class CompMovementWatcher : public ComponentMovementWatcher
  22029. {
  22030. public:
  22031. CompMovementWatcher (AudioUnitPluginWindow* const owner_)
  22032. : ComponentMovementWatcher (owner_),
  22033. owner (owner_)
  22034. {
  22035. }
  22036. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  22037. {
  22038. owner->componentMovedOrResized();
  22039. }
  22040. void componentPeerChanged()
  22041. {
  22042. owner->componentPeerChanged();
  22043. }
  22044. void componentVisibilityChanged (Component&)
  22045. {
  22046. owner->componentVisibilityChanged();
  22047. }
  22048. private:
  22049. AudioUnitPluginWindow* const owner;
  22050. };
  22051. CompMovementWatcher* movementWatcher;
  22052. };
  22053. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  22054. {
  22055. AudioUnitPluginWindow* w = new AudioUnitPluginWindow (*this);
  22056. if (! w->isValid())
  22057. deleteAndZero (w);
  22058. return w;
  22059. }
  22060. const String AudioUnitPluginInstance::getCategory() const
  22061. {
  22062. const char* result = 0;
  22063. switch (componentDesc.componentType)
  22064. {
  22065. case kAudioUnitType_Effect:
  22066. case kAudioUnitType_MusicEffect:
  22067. result = "Effect";
  22068. break;
  22069. case kAudioUnitType_MusicDevice:
  22070. result = "Synth";
  22071. break;
  22072. case kAudioUnitType_Generator:
  22073. result = "Generator";
  22074. break;
  22075. case kAudioUnitType_Panner:
  22076. result = "Panner";
  22077. break;
  22078. default:
  22079. break;
  22080. }
  22081. return result;
  22082. }
  22083. int AudioUnitPluginInstance::getNumParameters()
  22084. {
  22085. return parameterIds.size();
  22086. }
  22087. float AudioUnitPluginInstance::getParameter (int index)
  22088. {
  22089. const ScopedLock sl (lock);
  22090. Float32 value = 0.0f;
  22091. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  22092. {
  22093. AudioUnitGetParameter (audioUnit,
  22094. (UInt32) parameterIds.getUnchecked (index),
  22095. kAudioUnitScope_Global, 0,
  22096. &value);
  22097. }
  22098. return value;
  22099. }
  22100. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  22101. {
  22102. const ScopedLock sl (lock);
  22103. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  22104. {
  22105. AudioUnitSetParameter (audioUnit,
  22106. (UInt32) parameterIds.getUnchecked (index),
  22107. kAudioUnitScope_Global, 0,
  22108. newValue, 0);
  22109. }
  22110. }
  22111. const String AudioUnitPluginInstance::getParameterName (int index)
  22112. {
  22113. AudioUnitParameterInfo info;
  22114. zerostruct (info);
  22115. UInt32 sz = sizeof (info);
  22116. String name;
  22117. if (AudioUnitGetProperty (audioUnit,
  22118. kAudioUnitProperty_ParameterInfo,
  22119. kAudioUnitScope_Global,
  22120. parameterIds [index], &info, &sz) == noErr)
  22121. {
  22122. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  22123. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  22124. else
  22125. name = String (info.name, sizeof (info.name));
  22126. }
  22127. return name;
  22128. }
  22129. const String AudioUnitPluginInstance::getParameterText (int index)
  22130. {
  22131. return String (getParameter (index));
  22132. }
  22133. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  22134. {
  22135. AudioUnitParameterInfo info;
  22136. UInt32 sz = sizeof (info);
  22137. if (AudioUnitGetProperty (audioUnit,
  22138. kAudioUnitProperty_ParameterInfo,
  22139. kAudioUnitScope_Global,
  22140. parameterIds [index], &info, &sz) == noErr)
  22141. {
  22142. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  22143. }
  22144. return true;
  22145. }
  22146. int AudioUnitPluginInstance::getNumPrograms()
  22147. {
  22148. CFArrayRef presets;
  22149. UInt32 sz = sizeof (CFArrayRef);
  22150. int num = 0;
  22151. if (AudioUnitGetProperty (audioUnit,
  22152. kAudioUnitProperty_FactoryPresets,
  22153. kAudioUnitScope_Global,
  22154. 0, &presets, &sz) == noErr)
  22155. {
  22156. num = (int) CFArrayGetCount (presets);
  22157. CFRelease (presets);
  22158. }
  22159. return num;
  22160. }
  22161. int AudioUnitPluginInstance::getCurrentProgram()
  22162. {
  22163. AUPreset current;
  22164. current.presetNumber = 0;
  22165. UInt32 sz = sizeof (AUPreset);
  22166. AudioUnitGetProperty (audioUnit,
  22167. kAudioUnitProperty_FactoryPresets,
  22168. kAudioUnitScope_Global,
  22169. 0, &current, &sz);
  22170. return current.presetNumber;
  22171. }
  22172. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  22173. {
  22174. AUPreset current;
  22175. current.presetNumber = newIndex;
  22176. current.presetName = 0;
  22177. AudioUnitSetProperty (audioUnit,
  22178. kAudioUnitProperty_FactoryPresets,
  22179. kAudioUnitScope_Global,
  22180. 0, &current, sizeof (AUPreset));
  22181. }
  22182. const String AudioUnitPluginInstance::getProgramName (int index)
  22183. {
  22184. String s;
  22185. CFArrayRef presets;
  22186. UInt32 sz = sizeof (CFArrayRef);
  22187. if (AudioUnitGetProperty (audioUnit,
  22188. kAudioUnitProperty_FactoryPresets,
  22189. kAudioUnitScope_Global,
  22190. 0, &presets, &sz) == noErr)
  22191. {
  22192. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  22193. {
  22194. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  22195. if (p != 0 && p->presetNumber == index)
  22196. {
  22197. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  22198. break;
  22199. }
  22200. }
  22201. CFRelease (presets);
  22202. }
  22203. return s;
  22204. }
  22205. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  22206. {
  22207. jassertfalse // xxx not implemented!
  22208. }
  22209. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  22210. {
  22211. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  22212. return T("Input ") + String (index + 1);
  22213. return String::empty;
  22214. }
  22215. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  22216. {
  22217. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  22218. return false;
  22219. return true;
  22220. }
  22221. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  22222. {
  22223. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  22224. return T("Output ") + String (index + 1);
  22225. return String::empty;
  22226. }
  22227. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  22228. {
  22229. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  22230. return false;
  22231. return true;
  22232. }
  22233. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  22234. {
  22235. getCurrentProgramStateInformation (destData);
  22236. }
  22237. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  22238. {
  22239. CFPropertyListRef propertyList = 0;
  22240. UInt32 sz = sizeof (CFPropertyListRef);
  22241. if (AudioUnitGetProperty (audioUnit,
  22242. kAudioUnitProperty_ClassInfo,
  22243. kAudioUnitScope_Global,
  22244. 0, &propertyList, &sz) == noErr)
  22245. {
  22246. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  22247. CFWriteStreamOpen (stream);
  22248. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  22249. CFWriteStreamClose (stream);
  22250. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  22251. destData.setSize (bytesWritten);
  22252. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  22253. CFRelease (data);
  22254. CFRelease (stream);
  22255. CFRelease (propertyList);
  22256. }
  22257. }
  22258. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  22259. {
  22260. setCurrentProgramStateInformation (data, sizeInBytes);
  22261. }
  22262. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  22263. {
  22264. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  22265. (const UInt8*) data,
  22266. sizeInBytes,
  22267. kCFAllocatorNull);
  22268. CFReadStreamOpen (stream);
  22269. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  22270. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  22271. stream,
  22272. 0,
  22273. kCFPropertyListImmutable,
  22274. &format,
  22275. 0);
  22276. CFRelease (stream);
  22277. if (propertyList != 0)
  22278. AudioUnitSetProperty (audioUnit,
  22279. kAudioUnitProperty_ClassInfo,
  22280. kAudioUnitScope_Global,
  22281. 0, &propertyList, sizeof (propertyList));
  22282. }
  22283. AudioUnitPluginFormat::AudioUnitPluginFormat()
  22284. {
  22285. }
  22286. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  22287. {
  22288. }
  22289. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  22290. const File& file)
  22291. {
  22292. if (! fileMightContainThisPluginType (file))
  22293. return;
  22294. PluginDescription desc;
  22295. desc.file = file;
  22296. desc.uid = 0;
  22297. AudioUnitPluginInstance* instance = dynamic_cast <AudioUnitPluginInstance*> (createInstanceFromDescription (desc));
  22298. if (instance == 0)
  22299. return;
  22300. try
  22301. {
  22302. instance->fillInPluginDescription (desc);
  22303. results.add (new PluginDescription (desc));
  22304. }
  22305. catch (...)
  22306. {
  22307. // crashed while loading...
  22308. }
  22309. deleteAndZero (instance);
  22310. }
  22311. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  22312. {
  22313. AudioUnitPluginInstance* result = 0;
  22314. if (fileMightContainThisPluginType (desc.file))
  22315. {
  22316. result = new AudioUnitPluginInstance (desc.file);
  22317. if (result->audioUnit != 0)
  22318. {
  22319. result->initialise();
  22320. }
  22321. else
  22322. {
  22323. deleteAndZero (result);
  22324. }
  22325. }
  22326. return result;
  22327. }
  22328. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const File& f)
  22329. {
  22330. return f.hasFileExtension (T(".component"))
  22331. && f.isDirectory();
  22332. }
  22333. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  22334. {
  22335. return FileSearchPath ("~/Library/Audio/Plug-Ins/Components;/Library/Audio/Plug-Ins/Components");
  22336. }
  22337. #endif
  22338. END_JUCE_NAMESPACE
  22339. #undef log
  22340. #endif
  22341. /********* End of inlined file: juce_AudioUnitPluginFormat.cpp *********/
  22342. /********* Start of inlined file: juce_VSTPluginFormat.cpp *********/
  22343. #if JUCE_PLUGINHOST_VST
  22344. #ifdef _WIN32
  22345. #undef _WIN32_WINNT
  22346. #define _WIN32_WINNT 0x500
  22347. #undef STRICT
  22348. #define STRICT
  22349. #include <windows.h>
  22350. #include <float.h>
  22351. #pragma warning (disable : 4312)
  22352. #elif defined (LINUX)
  22353. #include <float.h>
  22354. #include <sys/time.h>
  22355. #include <X11/Xlib.h>
  22356. #include <X11/Xutil.h>
  22357. #include <X11/Xatom.h>
  22358. #undef Font
  22359. #undef KeyPress
  22360. #undef Drawable
  22361. #undef Time
  22362. #else
  22363. #include <Carbon/Carbon.h>
  22364. #endif
  22365. BEGIN_JUCE_NAMESPACE
  22366. #undef PRAGMA_ALIGN_SUPPORTED
  22367. #define VST_FORCE_DEPRECATED 0
  22368. #ifdef _MSC_VER
  22369. #pragma warning (push)
  22370. #pragma warning (disable: 4996)
  22371. #endif
  22372. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  22373. your include path if you want to add VST support.
  22374. If you're not interested in VSTs, you can disable them by changing the
  22375. JUCE_PLUGINHOST_VST flag in juce_Config.h
  22376. */
  22377. #include "pluginterfaces/vst2.x/aeffectx.h"
  22378. #ifdef _MSC_VER
  22379. #pragma warning (pop)
  22380. #endif
  22381. #if JUCE_LINUX
  22382. #define Font JUCE_NAMESPACE::Font
  22383. #define KeyPress JUCE_NAMESPACE::KeyPress
  22384. #define Drawable JUCE_NAMESPACE::Drawable
  22385. #define Time JUCE_NAMESPACE::Time
  22386. #endif
  22387. #if ! JUCE_WIN32
  22388. #define _fpreset()
  22389. #define _clearfp()
  22390. #endif
  22391. extern void juce_callAnyTimersSynchronously();
  22392. const int fxbVersionNum = 1;
  22393. struct fxProgram
  22394. {
  22395. long chunkMagic; // 'CcnK'
  22396. long byteSize; // of this chunk, excl. magic + byteSize
  22397. long fxMagic; // 'FxCk'
  22398. long version;
  22399. long fxID; // fx unique id
  22400. long fxVersion;
  22401. long numParams;
  22402. char prgName[28];
  22403. float params[1]; // variable no. of parameters
  22404. };
  22405. struct fxSet
  22406. {
  22407. long chunkMagic; // 'CcnK'
  22408. long byteSize; // of this chunk, excl. magic + byteSize
  22409. long fxMagic; // 'FxBk'
  22410. long version;
  22411. long fxID; // fx unique id
  22412. long fxVersion;
  22413. long numPrograms;
  22414. char future[128];
  22415. fxProgram programs[1]; // variable no. of programs
  22416. };
  22417. struct fxChunkSet
  22418. {
  22419. long chunkMagic; // 'CcnK'
  22420. long byteSize; // of this chunk, excl. magic + byteSize
  22421. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  22422. long version;
  22423. long fxID; // fx unique id
  22424. long fxVersion;
  22425. long numPrograms;
  22426. char future[128];
  22427. long chunkSize;
  22428. char chunk[8]; // variable
  22429. };
  22430. struct fxProgramSet
  22431. {
  22432. long chunkMagic; // 'CcnK'
  22433. long byteSize; // of this chunk, excl. magic + byteSize
  22434. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  22435. long version;
  22436. long fxID; // fx unique id
  22437. long fxVersion;
  22438. long numPrograms;
  22439. char name[28];
  22440. long chunkSize;
  22441. char chunk[8]; // variable
  22442. };
  22443. #ifdef JUCE_LITTLE_ENDIAN
  22444. static long vst_swap (const long x) throw() { return (long) swapByteOrder ((uint32) x); }
  22445. static float vst_swapFloat (const float x) throw()
  22446. {
  22447. union { uint32 asInt; float asFloat; } n;
  22448. n.asFloat = x;
  22449. n.asInt = swapByteOrder (n.asInt);
  22450. return n.asFloat;
  22451. }
  22452. #else
  22453. #define vst_swap(x) (x)
  22454. #define vst_swapFloat(x) (x)
  22455. #endif
  22456. typedef AEffect* (*MainCall) (audioMasterCallback);
  22457. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  22458. static int shellUIDToCreate = 0;
  22459. static int insideVSTCallback = 0;
  22460. class VSTPluginWindow;
  22461. // Change this to disable logging of various VST activities
  22462. #ifndef VST_LOGGING
  22463. #define VST_LOGGING 1
  22464. #endif
  22465. #if VST_LOGGING
  22466. #define log(a) Logger::writeToLog(a);
  22467. #else
  22468. #define log(a)
  22469. #endif
  22470. #if JUCE_MAC
  22471. extern bool juce_isHIViewCreatedByJuce (HIViewRef view);
  22472. extern bool juce_isWindowCreatedByJuce (WindowRef window);
  22473. #if JUCE_PPC
  22474. static void* NewCFMFromMachO (void* const machofp) throw()
  22475. {
  22476. void* result = juce_malloc (8);
  22477. ((void**) result)[0] = machofp;
  22478. ((void**) result)[1] = result;
  22479. return result;
  22480. }
  22481. #endif
  22482. #endif
  22483. #if JUCE_LINUX
  22484. extern Display* display;
  22485. extern XContext improbableNumber;
  22486. typedef void (*EventProcPtr) (XEvent* ev);
  22487. static bool xErrorTriggered;
  22488. static int temporaryErrorHandler (Display*, XErrorEvent*)
  22489. {
  22490. xErrorTriggered = true;
  22491. return 0;
  22492. }
  22493. static int getPropertyFromXWindow (Window handle, Atom atom)
  22494. {
  22495. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  22496. xErrorTriggered = false;
  22497. int userSize;
  22498. unsigned long bytes, userCount;
  22499. unsigned char* data;
  22500. Atom userType;
  22501. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  22502. &userType, &userSize, &userCount, &bytes, &data);
  22503. XSetErrorHandler (oldErrorHandler);
  22504. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  22505. : 0;
  22506. }
  22507. static Window getChildWindow (Window windowToCheck)
  22508. {
  22509. Window rootWindow, parentWindow;
  22510. Window* childWindows;
  22511. unsigned int numChildren;
  22512. XQueryTree (display,
  22513. windowToCheck,
  22514. &rootWindow,
  22515. &parentWindow,
  22516. &childWindows,
  22517. &numChildren);
  22518. if (numChildren > 0)
  22519. return childWindows [0];
  22520. return 0;
  22521. }
  22522. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  22523. {
  22524. if (e.mods.isLeftButtonDown())
  22525. {
  22526. ev.xbutton.button = Button1;
  22527. ev.xbutton.state |= Button1Mask;
  22528. }
  22529. else if (e.mods.isRightButtonDown())
  22530. {
  22531. ev.xbutton.button = Button3;
  22532. ev.xbutton.state |= Button3Mask;
  22533. }
  22534. else if (e.mods.isMiddleButtonDown())
  22535. {
  22536. ev.xbutton.button = Button2;
  22537. ev.xbutton.state |= Button2Mask;
  22538. }
  22539. }
  22540. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  22541. {
  22542. if (e.mods.isLeftButtonDown())
  22543. ev.xmotion.state |= Button1Mask;
  22544. else if (e.mods.isRightButtonDown())
  22545. ev.xmotion.state |= Button3Mask;
  22546. else if (e.mods.isMiddleButtonDown())
  22547. ev.xmotion.state |= Button2Mask;
  22548. }
  22549. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  22550. {
  22551. if (e.mods.isLeftButtonDown())
  22552. ev.xcrossing.state |= Button1Mask;
  22553. else if (e.mods.isRightButtonDown())
  22554. ev.xcrossing.state |= Button3Mask;
  22555. else if (e.mods.isMiddleButtonDown())
  22556. ev.xcrossing.state |= Button2Mask;
  22557. }
  22558. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  22559. {
  22560. if (increment < 0)
  22561. {
  22562. ev.xbutton.button = Button5;
  22563. ev.xbutton.state |= Button5Mask;
  22564. }
  22565. else if (increment > 0)
  22566. {
  22567. ev.xbutton.button = Button4;
  22568. ev.xbutton.state |= Button4Mask;
  22569. }
  22570. }
  22571. #endif
  22572. static VoidArray activeModules;
  22573. class ModuleHandle : public ReferenceCountedObject
  22574. {
  22575. public:
  22576. File file;
  22577. MainCall moduleMain;
  22578. String pluginName;
  22579. static ModuleHandle* findOrCreateModule (const File& file)
  22580. {
  22581. for (int i = activeModules.size(); --i >= 0;)
  22582. {
  22583. ModuleHandle* const module = (ModuleHandle*) activeModules.getUnchecked(i);
  22584. if (module->file == file)
  22585. return module;
  22586. }
  22587. _fpreset(); // (doesn't do any harm)
  22588. ++insideVSTCallback;
  22589. shellUIDToCreate = 0;
  22590. log ("Attempting to load VST: " + file.getFullPathName());
  22591. ModuleHandle* m = new ModuleHandle (file);
  22592. if (! m->open())
  22593. deleteAndZero (m);
  22594. --insideVSTCallback;
  22595. _fpreset(); // (doesn't do any harm)
  22596. return m;
  22597. }
  22598. ModuleHandle (const File& file_)
  22599. : file (file_),
  22600. moduleMain (0),
  22601. #if JUCE_WIN32 || JUCE_LINUX
  22602. hModule (0)
  22603. #elif JUCE_MAC
  22604. fragId (0),
  22605. resHandle (0),
  22606. bundleRef (0),
  22607. resFileId (0)
  22608. #endif
  22609. {
  22610. activeModules.add (this);
  22611. #if JUCE_WIN32 || JUCE_LINUX
  22612. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  22613. #elif JUCE_MAC
  22614. PlatformUtilities::makeFSSpecFromPath (&parentDirFSSpec, file_.getParentDirectory().getFullPathName());
  22615. #endif
  22616. }
  22617. ~ModuleHandle()
  22618. {
  22619. activeModules.removeValue (this);
  22620. close();
  22621. }
  22622. juce_UseDebuggingNewOperator
  22623. #if JUCE_WIN32 || JUCE_LINUX
  22624. void* hModule;
  22625. String fullParentDirectoryPathName;
  22626. bool open()
  22627. {
  22628. #if JUCE_WIN32
  22629. static bool timePeriodSet = false;
  22630. if (! timePeriodSet)
  22631. {
  22632. timePeriodSet = true;
  22633. timeBeginPeriod (2);
  22634. }
  22635. #endif
  22636. pluginName = file.getFileNameWithoutExtension();
  22637. hModule = Process::loadDynamicLibrary (file.getFullPathName());
  22638. moduleMain = (MainCall) Process::getProcedureEntryPoint (hModule, "VSTPluginMain");
  22639. if (moduleMain == 0)
  22640. moduleMain = (MainCall) Process::getProcedureEntryPoint (hModule, "main");
  22641. return moduleMain != 0;
  22642. }
  22643. void close()
  22644. {
  22645. _fpreset(); // (doesn't do any harm)
  22646. Process::freeDynamicLibrary (hModule);
  22647. }
  22648. void closeEffect (AEffect* eff)
  22649. {
  22650. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  22651. }
  22652. #else
  22653. CFragConnectionID fragId;
  22654. Handle resHandle;
  22655. CFBundleRef bundleRef;
  22656. FSSpec parentDirFSSpec;
  22657. short resFileId;
  22658. bool open()
  22659. {
  22660. bool ok = false;
  22661. const String filename (file.getFullPathName());
  22662. if (file.hasFileExtension (T(".vst")))
  22663. {
  22664. const char* const utf8 = filename.toUTF8();
  22665. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  22666. strlen (utf8), file.isDirectory());
  22667. if (url != 0)
  22668. {
  22669. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  22670. CFRelease (url);
  22671. if (bundleRef != 0)
  22672. {
  22673. if (CFBundleLoadExecutable (bundleRef))
  22674. {
  22675. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  22676. if (moduleMain == 0)
  22677. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  22678. if (moduleMain != 0)
  22679. {
  22680. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  22681. if (name != 0)
  22682. {
  22683. if (CFGetTypeID (name) == CFStringGetTypeID())
  22684. {
  22685. char buffer[1024];
  22686. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  22687. pluginName = buffer;
  22688. }
  22689. }
  22690. if (pluginName.isEmpty())
  22691. pluginName = file.getFileNameWithoutExtension();
  22692. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  22693. ok = true;
  22694. }
  22695. }
  22696. if (! ok)
  22697. {
  22698. CFBundleUnloadExecutable (bundleRef);
  22699. CFRelease (bundleRef);
  22700. bundleRef = 0;
  22701. }
  22702. }
  22703. }
  22704. }
  22705. #if JUCE_PPC
  22706. else
  22707. {
  22708. FSRef fn;
  22709. if (FSPathMakeRef ((UInt8*) (const char*) filename, &fn, 0) == noErr)
  22710. {
  22711. resFileId = FSOpenResFile (&fn, fsRdPerm);
  22712. if (resFileId != -1)
  22713. {
  22714. const int numEffs = Count1Resources ('aEff');
  22715. for (int i = 0; i < numEffs; ++i)
  22716. {
  22717. resHandle = Get1IndResource ('aEff', i + 1);
  22718. if (resHandle != 0)
  22719. {
  22720. OSType type;
  22721. Str255 name;
  22722. SInt16 id;
  22723. GetResInfo (resHandle, &id, &type, name);
  22724. pluginName = String ((const char*) name + 1, name[0]);
  22725. DetachResource (resHandle);
  22726. HLock (resHandle);
  22727. Ptr ptr;
  22728. Str255 errorText;
  22729. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  22730. name, kPrivateCFragCopy,
  22731. &fragId, &ptr, errorText);
  22732. if (err == noErr)
  22733. {
  22734. moduleMain = (MainCall) newMachOFromCFM (ptr);
  22735. ok = true;
  22736. }
  22737. else
  22738. {
  22739. HUnlock (resHandle);
  22740. }
  22741. break;
  22742. }
  22743. }
  22744. if (! ok)
  22745. CloseResFile (resFileId);
  22746. }
  22747. }
  22748. }
  22749. #endif
  22750. return ok;
  22751. }
  22752. void close()
  22753. {
  22754. #if JUCE_PPC
  22755. if (fragId != 0)
  22756. {
  22757. if (moduleMain != 0)
  22758. disposeMachOFromCFM ((void*) moduleMain);
  22759. CloseConnection (&fragId);
  22760. HUnlock (resHandle);
  22761. if (resFileId != 0)
  22762. CloseResFile (resFileId);
  22763. }
  22764. else
  22765. #endif
  22766. if (bundleRef != 0)
  22767. {
  22768. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  22769. if (CFGetRetainCount (bundleRef) == 1)
  22770. CFBundleUnloadExecutable (bundleRef);
  22771. if (CFGetRetainCount (bundleRef) > 0)
  22772. CFRelease (bundleRef);
  22773. }
  22774. }
  22775. void closeEffect (AEffect* eff)
  22776. {
  22777. #if JUCE_PPC
  22778. if (fragId != 0)
  22779. {
  22780. VoidArray thingsToDelete;
  22781. thingsToDelete.add ((void*) eff->dispatcher);
  22782. thingsToDelete.add ((void*) eff->process);
  22783. thingsToDelete.add ((void*) eff->setParameter);
  22784. thingsToDelete.add ((void*) eff->getParameter);
  22785. thingsToDelete.add ((void*) eff->processReplacing);
  22786. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  22787. for (int i = thingsToDelete.size(); --i >= 0;)
  22788. disposeMachOFromCFM (thingsToDelete[i]);
  22789. }
  22790. else
  22791. #endif
  22792. {
  22793. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  22794. }
  22795. }
  22796. #if JUCE_PPC
  22797. static void* newMachOFromCFM (void* cfmfp)
  22798. {
  22799. if (cfmfp == 0)
  22800. return 0;
  22801. UInt32* const mfp = (UInt32*) juce_malloc (sizeof (UInt32) * 6);
  22802. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  22803. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  22804. mfp[2] = 0x800c0000;
  22805. mfp[3] = 0x804c0004;
  22806. mfp[4] = 0x7c0903a6;
  22807. mfp[5] = 0x4e800420;
  22808. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  22809. return mfp;
  22810. }
  22811. static void disposeMachOFromCFM (void* ptr)
  22812. {
  22813. juce_free (ptr);
  22814. }
  22815. void coerceAEffectFunctionCalls (AEffect* eff)
  22816. {
  22817. if (fragId != 0)
  22818. {
  22819. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  22820. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  22821. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  22822. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  22823. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  22824. }
  22825. }
  22826. #endif
  22827. #endif
  22828. };
  22829. /**
  22830. An instance of a plugin, created by a VSTPluginFormat.
  22831. */
  22832. class VSTPluginInstance : public AudioPluginInstance,
  22833. private Timer,
  22834. private AsyncUpdater
  22835. {
  22836. public:
  22837. ~VSTPluginInstance();
  22838. // AudioPluginInstance methods:
  22839. void fillInPluginDescription (PluginDescription& desc) const
  22840. {
  22841. desc.name = name;
  22842. desc.file = module->file;
  22843. desc.uid = getUID();
  22844. desc.lastFileModTime = desc.file.getLastModificationTime();
  22845. desc.pluginFormatName = "VST";
  22846. desc.category = getCategory();
  22847. {
  22848. char buffer [kVstMaxVendorStrLen + 8];
  22849. zerostruct (buffer);
  22850. dispatch (effGetVendorString, 0, 0, buffer, 0);
  22851. desc.manufacturerName = buffer;
  22852. }
  22853. desc.version = getVersion();
  22854. desc.numInputChannels = getNumInputChannels();
  22855. desc.numOutputChannels = getNumOutputChannels();
  22856. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  22857. }
  22858. const String getName() const { return name; }
  22859. int getUID() const throw();
  22860. bool acceptsMidi() const { return wantsMidiMessages; }
  22861. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  22862. // AudioProcessor methods:
  22863. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  22864. void releaseResources();
  22865. void processBlock (AudioSampleBuffer& buffer,
  22866. MidiBuffer& midiMessages);
  22867. AudioProcessorEditor* createEditor();
  22868. const String getInputChannelName (const int index) const;
  22869. bool isInputChannelStereoPair (int index) const;
  22870. const String getOutputChannelName (const int index) const;
  22871. bool isOutputChannelStereoPair (int index) const;
  22872. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  22873. float getParameter (int index);
  22874. void setParameter (int index, float newValue);
  22875. const String getParameterName (int index);
  22876. const String getParameterText (int index);
  22877. bool isParameterAutomatable (int index) const;
  22878. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  22879. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  22880. void setCurrentProgram (int index);
  22881. const String getProgramName (int index);
  22882. void changeProgramName (int index, const String& newName);
  22883. void getStateInformation (MemoryBlock& destData);
  22884. void getCurrentProgramStateInformation (MemoryBlock& destData);
  22885. void setStateInformation (const void* data, int sizeInBytes);
  22886. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  22887. void timerCallback();
  22888. void handleAsyncUpdate();
  22889. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  22890. juce_UseDebuggingNewOperator
  22891. private:
  22892. friend class VSTPluginWindow;
  22893. friend class VSTPluginFormat;
  22894. AEffect* effect;
  22895. String name;
  22896. CriticalSection lock;
  22897. bool wantsMidiMessages, initialised, isPowerOn;
  22898. mutable StringArray programNames;
  22899. AudioSampleBuffer tempBuffer;
  22900. CriticalSection midiInLock;
  22901. MidiBuffer incomingMidi;
  22902. void* midiEventsToSend;
  22903. int numAllocatedMidiEvents;
  22904. VstTimeInfo vstHostTime;
  22905. float** channels;
  22906. ReferenceCountedObjectPtr <ModuleHandle> module;
  22907. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  22908. bool restoreProgramSettings (const fxProgram* const prog);
  22909. const String getCurrentProgramName();
  22910. void setParamsInProgramBlock (fxProgram* const prog) throw();
  22911. void updateStoredProgramNames();
  22912. void initialise();
  22913. void ensureMidiEventSize (int numEventsNeeded);
  22914. void freeMidiEvents();
  22915. void handleMidiFromPlugin (const VstEvents* const events);
  22916. void createTempParameterStore (MemoryBlock& dest);
  22917. void restoreFromTempParameterStore (const MemoryBlock& mb);
  22918. const String getParameterLabel (int index) const;
  22919. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  22920. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  22921. void setChunkData (const char* data, int size, bool isPreset);
  22922. bool loadFromFXBFile (const void* data, int numBytes);
  22923. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  22924. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  22925. const String getVersion() const throw();
  22926. const String getCategory() const throw();
  22927. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  22928. void setPower (const bool on);
  22929. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  22930. };
  22931. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  22932. : effect (0),
  22933. wantsMidiMessages (false),
  22934. initialised (false),
  22935. isPowerOn (false),
  22936. numAllocatedMidiEvents (0),
  22937. midiEventsToSend (0),
  22938. tempBuffer (1, 1),
  22939. channels (0),
  22940. module (module_)
  22941. {
  22942. try
  22943. {
  22944. _fpreset();
  22945. ++insideVSTCallback;
  22946. name = module->pluginName;
  22947. log (T("Creating VST instance: ") + name);
  22948. #if JUCE_MAC
  22949. if (module->resFileId != 0)
  22950. UseResFile (module->resFileId);
  22951. #if JUCE_PPC
  22952. if (module->fragId != 0)
  22953. {
  22954. static void* audioMasterCoerced = 0;
  22955. if (audioMasterCoerced == 0)
  22956. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  22957. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  22958. }
  22959. else
  22960. #endif
  22961. #endif
  22962. {
  22963. effect = module->moduleMain (&audioMaster);
  22964. }
  22965. --insideVSTCallback;
  22966. if (effect != 0 && effect->magic == kEffectMagic)
  22967. {
  22968. #if JUCE_PPC
  22969. module->coerceAEffectFunctionCalls (effect);
  22970. #endif
  22971. jassert (effect->resvd2 == 0);
  22972. jassert (effect->object != 0);
  22973. _fpreset(); // some dodgy plugs fuck around with this
  22974. }
  22975. else
  22976. {
  22977. effect = 0;
  22978. }
  22979. }
  22980. catch (...)
  22981. {
  22982. --insideVSTCallback;
  22983. }
  22984. }
  22985. VSTPluginInstance::~VSTPluginInstance()
  22986. {
  22987. {
  22988. const ScopedLock sl (lock);
  22989. jassert (insideVSTCallback == 0);
  22990. if (effect != 0 && effect->magic == kEffectMagic)
  22991. {
  22992. try
  22993. {
  22994. #if JUCE_MAC
  22995. if (module->resFileId != 0)
  22996. UseResFile (module->resFileId);
  22997. #endif
  22998. // Must delete any editors before deleting the plugin instance!
  22999. jassert (getActiveEditor() == 0);
  23000. _fpreset(); // some dodgy plugs fuck around with this
  23001. module->closeEffect (effect);
  23002. }
  23003. catch (...)
  23004. {}
  23005. }
  23006. module = 0;
  23007. effect = 0;
  23008. }
  23009. freeMidiEvents();
  23010. juce_free (channels);
  23011. channels = 0;
  23012. }
  23013. void VSTPluginInstance::initialise()
  23014. {
  23015. if (initialised || effect == 0)
  23016. return;
  23017. log (T("Initialising VST: ") + module->pluginName);
  23018. initialised = true;
  23019. dispatch (effIdentify, 0, 0, 0, 0);
  23020. // this code would ask the plugin for its name, but so few plugins
  23021. // actually bother implementing this correctly, that it's better to
  23022. // just ignore it and use the file name instead.
  23023. /* {
  23024. char buffer [256];
  23025. zerostruct (buffer);
  23026. dispatch (effGetEffectName, 0, 0, buffer, 0);
  23027. name = String (buffer).trim();
  23028. if (name.isEmpty())
  23029. name = module->pluginName;
  23030. }
  23031. */
  23032. if (getSampleRate() > 0)
  23033. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  23034. if (getBlockSize() > 0)
  23035. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  23036. dispatch (effOpen, 0, 0, 0, 0);
  23037. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  23038. getSampleRate(), getBlockSize());
  23039. if (getNumPrograms() > 1)
  23040. setCurrentProgram (0);
  23041. else
  23042. dispatch (effSetProgram, 0, 0, 0, 0);
  23043. int i;
  23044. for (i = effect->numInputs; --i >= 0;)
  23045. dispatch (effConnectInput, i, 1, 0, 0);
  23046. for (i = effect->numOutputs; --i >= 0;)
  23047. dispatch (effConnectOutput, i, 1, 0, 0);
  23048. updateStoredProgramNames();
  23049. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  23050. setLatencySamples (effect->initialDelay);
  23051. }
  23052. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  23053. int samplesPerBlockExpected)
  23054. {
  23055. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  23056. sampleRate_, samplesPerBlockExpected);
  23057. setLatencySamples (effect->initialDelay);
  23058. juce_free (channels);
  23059. channels = (float**) juce_calloc (sizeof (float*) * jmax (16, getNumOutputChannels() + 2, getNumInputChannels() + 2));
  23060. vstHostTime.tempo = 120.0;
  23061. vstHostTime.timeSigNumerator = 4;
  23062. vstHostTime.timeSigDenominator = 4;
  23063. vstHostTime.sampleRate = sampleRate_;
  23064. vstHostTime.samplePos = 0;
  23065. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  23066. initialise();
  23067. if (initialised)
  23068. {
  23069. wantsMidiMessages = wantsMidiMessages
  23070. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  23071. if (wantsMidiMessages)
  23072. ensureMidiEventSize (256);
  23073. else
  23074. freeMidiEvents();
  23075. incomingMidi.clear();
  23076. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  23077. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  23078. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  23079. if (! isPowerOn)
  23080. setPower (true);
  23081. // dodgy hack to force some plugins to initialise the sample rate..
  23082. if ((! hasEditor()) && getNumParameters() > 0)
  23083. {
  23084. const float old = getParameter (0);
  23085. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  23086. setParameter (0, old);
  23087. }
  23088. dispatch (effStartProcess, 0, 0, 0, 0);
  23089. }
  23090. }
  23091. void VSTPluginInstance::releaseResources()
  23092. {
  23093. if (initialised)
  23094. {
  23095. dispatch (effStopProcess, 0, 0, 0, 0);
  23096. setPower (false);
  23097. }
  23098. tempBuffer.setSize (1, 1);
  23099. incomingMidi.clear();
  23100. freeMidiEvents();
  23101. juce_free (channels);
  23102. channels = 0;
  23103. }
  23104. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  23105. MidiBuffer& midiMessages)
  23106. {
  23107. const int numSamples = buffer.getNumSamples();
  23108. if (initialised)
  23109. {
  23110. #if JUCE_WIN32
  23111. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  23112. #elif JUCE_LINUX
  23113. timeval micro;
  23114. gettimeofday (&micro, 0);
  23115. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  23116. #elif JUCE_MAC
  23117. UnsignedWide micro;
  23118. Microseconds (&micro);
  23119. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  23120. #endif
  23121. if (wantsMidiMessages)
  23122. {
  23123. MidiBuffer::Iterator iter (midiMessages);
  23124. int eventIndex = 0;
  23125. const uint8* midiData;
  23126. int numBytesOfMidiData, samplePosition;
  23127. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  23128. {
  23129. if (numBytesOfMidiData < 4)
  23130. {
  23131. ensureMidiEventSize (eventIndex + 1);
  23132. VstMidiEvent* const e
  23133. = (VstMidiEvent*) ((VstEvents*) midiEventsToSend)->events [eventIndex++];
  23134. // check that some plugin hasn't messed up our objects
  23135. jassert (e->type == kVstMidiType);
  23136. jassert (e->byteSize == 24);
  23137. e->deltaFrames = jlimit (0, numSamples - 1, samplePosition);
  23138. e->noteLength = 0;
  23139. e->noteOffset = 0;
  23140. e->midiData[0] = midiData[0];
  23141. e->midiData[1] = midiData[1];
  23142. e->midiData[2] = midiData[2];
  23143. e->detune = 0;
  23144. e->noteOffVelocity = 0;
  23145. }
  23146. }
  23147. if (midiEventsToSend == 0)
  23148. ensureMidiEventSize (1);
  23149. ((VstEvents*) midiEventsToSend)->numEvents = eventIndex;
  23150. try
  23151. {
  23152. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend, 0);
  23153. }
  23154. catch (...)
  23155. {}
  23156. }
  23157. int i;
  23158. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  23159. for (i = 0; i < maxChans; ++i)
  23160. channels[i] = buffer.getSampleData (i);
  23161. channels [maxChans] = 0;
  23162. _clearfp();
  23163. if ((effect->flags & effFlagsCanReplacing) != 0)
  23164. {
  23165. try
  23166. {
  23167. effect->processReplacing (effect, channels, channels, numSamples);
  23168. }
  23169. catch (...)
  23170. {}
  23171. }
  23172. else
  23173. {
  23174. tempBuffer.setSize (effect->numOutputs, numSamples);
  23175. tempBuffer.clear();
  23176. float* outs [64];
  23177. for (i = effect->numOutputs; --i >= 0;)
  23178. outs[i] = tempBuffer.getSampleData (i);
  23179. outs [effect->numOutputs] = 0;
  23180. try
  23181. {
  23182. effect->process (effect, channels, outs, numSamples);
  23183. }
  23184. catch (...)
  23185. {}
  23186. for (i = effect->numOutputs; --i >= 0;)
  23187. buffer.copyFrom (i, 0, outs[i], numSamples);
  23188. }
  23189. }
  23190. else
  23191. {
  23192. // Not initialised, so just bypass..
  23193. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  23194. buffer.clear (i, 0, buffer.getNumSamples());
  23195. }
  23196. {
  23197. // copy any incoming midi..
  23198. const ScopedLock sl (midiInLock);
  23199. midiMessages = incomingMidi;
  23200. incomingMidi.clear();
  23201. }
  23202. }
  23203. void VSTPluginInstance::ensureMidiEventSize (int numEventsNeeded)
  23204. {
  23205. if (numEventsNeeded > numAllocatedMidiEvents)
  23206. {
  23207. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  23208. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  23209. if (midiEventsToSend == 0)
  23210. midiEventsToSend = juce_calloc (size);
  23211. else
  23212. midiEventsToSend = juce_realloc (midiEventsToSend, size);
  23213. for (int i = numAllocatedMidiEvents; i < numEventsNeeded; ++i)
  23214. {
  23215. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (sizeof (VstMidiEvent));
  23216. e->type = kVstMidiType;
  23217. e->byteSize = 24;
  23218. ((VstEvents*) midiEventsToSend)->events[i] = (VstEvent*) e;
  23219. }
  23220. numAllocatedMidiEvents = numEventsNeeded;
  23221. }
  23222. }
  23223. void VSTPluginInstance::freeMidiEvents()
  23224. {
  23225. if (midiEventsToSend != 0)
  23226. {
  23227. for (int i = numAllocatedMidiEvents; --i >= 0;)
  23228. juce_free (((VstEvents*) midiEventsToSend)->events[i]);
  23229. juce_free (midiEventsToSend);
  23230. midiEventsToSend = 0;
  23231. numAllocatedMidiEvents = 0;
  23232. }
  23233. }
  23234. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  23235. {
  23236. if (events != 0)
  23237. {
  23238. const ScopedLock sl (midiInLock);
  23239. for (int i = 0; i < events->numEvents; ++i)
  23240. {
  23241. const VstEvent* const e = events->events[i];
  23242. if (e->type == kVstMidiType)
  23243. {
  23244. incomingMidi.addEvent ((const uint8*) ((const VstMidiEvent*) e)->midiData,
  23245. 3, e->deltaFrames);
  23246. }
  23247. }
  23248. }
  23249. }
  23250. static Array <VSTPluginWindow*> activeVSTWindows;
  23251. class VSTPluginWindow : public AudioProcessorEditor,
  23252. public Timer
  23253. {
  23254. public:
  23255. VSTPluginWindow (VSTPluginInstance& plugin_)
  23256. : AudioProcessorEditor (&plugin_),
  23257. plugin (plugin_),
  23258. isOpen (false),
  23259. wasShowing (false),
  23260. pluginRefusesToResize (false),
  23261. pluginWantsKeys (false),
  23262. alreadyInside (false),
  23263. recursiveResize (false)
  23264. {
  23265. #if JUCE_WIN32
  23266. sizeCheckCount = 0;
  23267. pluginHWND = 0;
  23268. #elif JUCE_LINUX
  23269. pluginWindow = None;
  23270. pluginProc = None;
  23271. #else
  23272. pluginViewRef = 0;
  23273. #endif
  23274. movementWatcher = new CompMovementWatcher (this);
  23275. activeVSTWindows.add (this);
  23276. setSize (1, 1);
  23277. setOpaque (true);
  23278. setVisible (true);
  23279. }
  23280. ~VSTPluginWindow()
  23281. {
  23282. deleteAndZero (movementWatcher);
  23283. closePluginWindow();
  23284. activeVSTWindows.removeValue (this);
  23285. plugin.editorBeingDeleted (this);
  23286. }
  23287. void componentMovedOrResized()
  23288. {
  23289. if (recursiveResize)
  23290. return;
  23291. Component* const topComp = getTopLevelComponent();
  23292. if (topComp->getPeer() != 0)
  23293. {
  23294. int x = 0, y = 0;
  23295. relativePositionToOtherComponent (topComp, x, y);
  23296. recursiveResize = true;
  23297. #if JUCE_MAC
  23298. if (pluginViewRef != 0)
  23299. {
  23300. HIRect r;
  23301. r.origin.x = (float) x;
  23302. r.origin.y = (float) y;
  23303. r.size.width = (float) getWidth();
  23304. r.size.height = (float) getHeight();
  23305. HIViewSetFrame (pluginViewRef, &r);
  23306. }
  23307. else if (pluginWindowRef != 0)
  23308. {
  23309. Rect r;
  23310. r.left = getScreenX();
  23311. r.top = getScreenY();
  23312. r.right = r.left + getWidth();
  23313. r.bottom = r.top + getHeight();
  23314. WindowGroupRef group = GetWindowGroup (pluginWindowRef);
  23315. WindowGroupAttributes atts;
  23316. GetWindowGroupAttributes (group, &atts);
  23317. ChangeWindowGroupAttributes (group, 0, kWindowGroupAttrMoveTogether);
  23318. SetWindowBounds (pluginWindowRef, kWindowContentRgn, &r);
  23319. if ((atts & kWindowGroupAttrMoveTogether) != 0)
  23320. ChangeWindowGroupAttributes (group, kWindowGroupAttrMoveTogether, 0);
  23321. }
  23322. else
  23323. {
  23324. repaint();
  23325. }
  23326. #elif JUCE_WIN32
  23327. if (pluginHWND != 0)
  23328. MoveWindow (pluginHWND, x, y, getWidth(), getHeight(), TRUE);
  23329. #elif JUCE_LINUX
  23330. if (pluginWindow != 0)
  23331. {
  23332. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  23333. XMoveWindow (display, pluginWindow, x, y);
  23334. XMapRaised (display, pluginWindow);
  23335. }
  23336. #endif
  23337. recursiveResize = false;
  23338. }
  23339. }
  23340. void componentVisibilityChanged()
  23341. {
  23342. const bool isShowingNow = isShowing();
  23343. if (wasShowing != isShowingNow)
  23344. {
  23345. wasShowing = isShowingNow;
  23346. if (isShowingNow)
  23347. openPluginWindow();
  23348. else
  23349. closePluginWindow();
  23350. }
  23351. componentMovedOrResized();
  23352. }
  23353. void componentPeerChanged()
  23354. {
  23355. closePluginWindow();
  23356. openPluginWindow();
  23357. }
  23358. bool keyStateChanged()
  23359. {
  23360. return pluginWantsKeys;
  23361. }
  23362. bool keyPressed (const KeyPress&)
  23363. {
  23364. return pluginWantsKeys;
  23365. }
  23366. void paint (Graphics& g)
  23367. {
  23368. if (isOpen)
  23369. {
  23370. ComponentPeer* const peer = getPeer();
  23371. if (peer != 0)
  23372. {
  23373. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  23374. getScreenY() - peer->getScreenY(),
  23375. getWidth(), getHeight());
  23376. #if JUCE_MAC
  23377. if (pluginViewRef == 0)
  23378. {
  23379. ERect r;
  23380. r.left = getScreenX() - peer->getScreenX();
  23381. r.right = r.left + getWidth();
  23382. r.top = getScreenY() - peer->getScreenY();
  23383. r.bottom = r.top + getHeight();
  23384. dispatch (effEditDraw, 0, 0, &r, 0);
  23385. }
  23386. #elif JUCE_LINUX
  23387. if (pluginWindow != 0)
  23388. {
  23389. const Rectangle clip (g.getClipBounds());
  23390. XEvent ev;
  23391. zerostruct (ev);
  23392. ev.xexpose.type = Expose;
  23393. ev.xexpose.display = display;
  23394. ev.xexpose.window = pluginWindow;
  23395. ev.xexpose.x = clip.getX();
  23396. ev.xexpose.y = clip.getY();
  23397. ev.xexpose.width = clip.getWidth();
  23398. ev.xexpose.height = clip.getHeight();
  23399. sendEventToChild (&ev);
  23400. }
  23401. #endif
  23402. }
  23403. }
  23404. else
  23405. {
  23406. g.fillAll (Colours::black);
  23407. }
  23408. }
  23409. void timerCallback()
  23410. {
  23411. #if JUCE_WIN32
  23412. if (--sizeCheckCount <= 0)
  23413. {
  23414. sizeCheckCount = 10;
  23415. checkPluginWindowSize();
  23416. }
  23417. #endif
  23418. try
  23419. {
  23420. static bool reentrant = false;
  23421. if (! reentrant)
  23422. {
  23423. reentrant = true;
  23424. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  23425. reentrant = false;
  23426. }
  23427. }
  23428. catch (...)
  23429. {}
  23430. }
  23431. void mouseDown (const MouseEvent& e)
  23432. {
  23433. #if JUCE_MAC
  23434. if (! alreadyInside)
  23435. {
  23436. alreadyInside = true;
  23437. toFront (true);
  23438. dispatch (effEditMouse, e.x, e.y, 0, 0);
  23439. alreadyInside = false;
  23440. }
  23441. else
  23442. {
  23443. PostEvent (::mouseDown, 0);
  23444. }
  23445. #elif JUCE_LINUX
  23446. if (pluginWindow == 0)
  23447. return;
  23448. toFront (true);
  23449. XEvent ev;
  23450. zerostruct (ev);
  23451. ev.xbutton.display = display;
  23452. ev.xbutton.type = ButtonPress;
  23453. ev.xbutton.window = pluginWindow;
  23454. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  23455. ev.xbutton.time = CurrentTime;
  23456. ev.xbutton.x = e.x;
  23457. ev.xbutton.y = e.y;
  23458. ev.xbutton.x_root = e.getScreenX();
  23459. ev.xbutton.y_root = e.getScreenY();
  23460. translateJuceToXButtonModifiers (e, ev);
  23461. sendEventToChild (&ev);
  23462. #else
  23463. (void) e;
  23464. toFront (true);
  23465. #endif
  23466. }
  23467. void broughtToFront()
  23468. {
  23469. activeVSTWindows.removeValue (this);
  23470. activeVSTWindows.add (this);
  23471. #if JUCE_MAC
  23472. dispatch (effEditTop, 0, 0, 0, 0);
  23473. #endif
  23474. }
  23475. juce_UseDebuggingNewOperator
  23476. private:
  23477. VSTPluginInstance& plugin;
  23478. bool isOpen, wasShowing, recursiveResize;
  23479. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  23480. #if JUCE_WIN32
  23481. HWND pluginHWND;
  23482. void* originalWndProc;
  23483. int sizeCheckCount;
  23484. #elif JUCE_MAC
  23485. HIViewRef pluginViewRef;
  23486. WindowRef pluginWindowRef;
  23487. #elif JUCE_LINUX
  23488. Window pluginWindow;
  23489. EventProcPtr pluginProc;
  23490. #endif
  23491. void openPluginWindow()
  23492. {
  23493. if (isOpen || getWindowHandle() == 0)
  23494. return;
  23495. log (T("Opening VST UI: ") + plugin.name);
  23496. isOpen = true;
  23497. ERect* rect = 0;
  23498. dispatch (effEditGetRect, 0, 0, &rect, 0);
  23499. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  23500. // do this before and after like in the steinberg example
  23501. dispatch (effEditGetRect, 0, 0, &rect, 0);
  23502. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  23503. // Install keyboard hooks
  23504. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  23505. #if JUCE_WIN32
  23506. originalWndProc = 0;
  23507. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  23508. if (pluginHWND == 0)
  23509. {
  23510. isOpen = false;
  23511. setSize (300, 150);
  23512. return;
  23513. }
  23514. #pragma warning (push)
  23515. #pragma warning (disable: 4244)
  23516. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  23517. if (! pluginWantsKeys)
  23518. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) vstHookWndProc);
  23519. #pragma warning (pop)
  23520. int w, h;
  23521. RECT r;
  23522. GetWindowRect (pluginHWND, &r);
  23523. w = r.right - r.left;
  23524. h = r.bottom - r.top;
  23525. if (rect != 0)
  23526. {
  23527. const int rw = rect->right - rect->left;
  23528. const int rh = rect->bottom - rect->top;
  23529. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  23530. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  23531. {
  23532. // very dodgy logic to decide which size is right.
  23533. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  23534. {
  23535. SetWindowPos (pluginHWND, 0,
  23536. 0, 0, rw, rh,
  23537. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  23538. GetWindowRect (pluginHWND, &r);
  23539. w = r.right - r.left;
  23540. h = r.bottom - r.top;
  23541. pluginRefusesToResize = (w != rw) || (h != rh);
  23542. w = rw;
  23543. h = rh;
  23544. }
  23545. }
  23546. }
  23547. #elif JUCE_MAC
  23548. HIViewRef root = HIViewGetRoot ((WindowRef) getWindowHandle());
  23549. HIViewFindByID (root, kHIViewWindowContentID, &root);
  23550. pluginViewRef = HIViewGetFirstSubview (root);
  23551. while (pluginViewRef != 0 && juce_isHIViewCreatedByJuce (pluginViewRef))
  23552. pluginViewRef = HIViewGetNextView (pluginViewRef);
  23553. pluginWindowRef = 0;
  23554. if (pluginViewRef == 0)
  23555. {
  23556. WindowGroupRef ourGroup = GetWindowGroup ((WindowRef) getWindowHandle());
  23557. //DebugPrintWindowGroup (ourGroup);
  23558. //DebugPrintAllWindowGroups();
  23559. GetIndexedWindow (ourGroup, 1,
  23560. kWindowGroupContentsVisible,
  23561. &pluginWindowRef);
  23562. if (pluginWindowRef == (WindowRef) getWindowHandle()
  23563. || juce_isWindowCreatedByJuce (pluginWindowRef))
  23564. pluginWindowRef = 0;
  23565. }
  23566. int w = 250, h = 150;
  23567. if (rect != 0)
  23568. {
  23569. w = rect->right - rect->left;
  23570. h = rect->bottom - rect->top;
  23571. if (w == 0 || h == 0)
  23572. {
  23573. w = 250;
  23574. h = 150;
  23575. }
  23576. }
  23577. #elif JUCE_LINUX
  23578. pluginWindow = getChildWindow ((Window) getWindowHandle());
  23579. if (pluginWindow != 0)
  23580. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  23581. XInternAtom (display, "_XEventProc", False));
  23582. int w = 250, h = 150;
  23583. if (rect != 0)
  23584. {
  23585. w = rect->right - rect->left;
  23586. h = rect->bottom - rect->top;
  23587. if (w == 0 || h == 0)
  23588. {
  23589. w = 250;
  23590. h = 150;
  23591. }
  23592. }
  23593. if (pluginWindow != 0)
  23594. XMapRaised (display, pluginWindow);
  23595. #endif
  23596. // double-check it's not too tiny
  23597. w = jmax (w, 32);
  23598. h = jmax (h, 32);
  23599. setSize (w, h);
  23600. #if JUCE_WIN32
  23601. checkPluginWindowSize();
  23602. #endif
  23603. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  23604. repaint();
  23605. }
  23606. void closePluginWindow()
  23607. {
  23608. if (isOpen)
  23609. {
  23610. log (T("Closing VST UI: ") + plugin.getName());
  23611. isOpen = false;
  23612. dispatch (effEditClose, 0, 0, 0, 0);
  23613. #if JUCE_WIN32
  23614. #pragma warning (push)
  23615. #pragma warning (disable: 4244)
  23616. if (pluginHWND != 0 && IsWindow (pluginHWND))
  23617. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) originalWndProc);
  23618. #pragma warning (pop)
  23619. stopTimer();
  23620. if (pluginHWND != 0 && IsWindow (pluginHWND))
  23621. DestroyWindow (pluginHWND);
  23622. pluginHWND = 0;
  23623. #elif JUCE_MAC
  23624. dispatch (effEditSleep, 0, 0, 0, 0);
  23625. pluginViewRef = 0;
  23626. stopTimer();
  23627. #elif JUCE_LINUX
  23628. stopTimer();
  23629. pluginWindow = 0;
  23630. pluginProc = 0;
  23631. #endif
  23632. }
  23633. }
  23634. #if JUCE_WIN32
  23635. void checkPluginWindowSize() throw()
  23636. {
  23637. RECT r;
  23638. GetWindowRect (pluginHWND, &r);
  23639. const int w = r.right - r.left;
  23640. const int h = r.bottom - r.top;
  23641. if (isShowing() && w > 0 && h > 0
  23642. && (w != getWidth() || h != getHeight())
  23643. && ! pluginRefusesToResize)
  23644. {
  23645. setSize (w, h);
  23646. sizeCheckCount = 0;
  23647. }
  23648. }
  23649. #endif
  23650. class CompMovementWatcher : public ComponentMovementWatcher
  23651. {
  23652. public:
  23653. CompMovementWatcher (VSTPluginWindow* const owner_)
  23654. : ComponentMovementWatcher (owner_),
  23655. owner (owner_)
  23656. {
  23657. }
  23658. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  23659. {
  23660. owner->componentMovedOrResized();
  23661. }
  23662. void componentPeerChanged()
  23663. {
  23664. owner->componentPeerChanged();
  23665. }
  23666. void componentVisibilityChanged (Component&)
  23667. {
  23668. owner->componentVisibilityChanged();
  23669. }
  23670. private:
  23671. VSTPluginWindow* const owner;
  23672. };
  23673. CompMovementWatcher* movementWatcher;
  23674. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  23675. {
  23676. return plugin.dispatch (opcode, index, value, ptr, opt);
  23677. }
  23678. // hooks to get keyboard events from VST windows..
  23679. #if JUCE_WIN32
  23680. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  23681. {
  23682. for (int i = activeVSTWindows.size(); --i >= 0;)
  23683. {
  23684. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  23685. if (w->pluginHWND == hW)
  23686. {
  23687. if (message == WM_CHAR
  23688. || message == WM_KEYDOWN
  23689. || message == WM_SYSKEYDOWN
  23690. || message == WM_KEYUP
  23691. || message == WM_SYSKEYUP
  23692. || message == WM_APPCOMMAND)
  23693. {
  23694. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  23695. message, wParam, lParam);
  23696. }
  23697. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  23698. (HWND) w->pluginHWND,
  23699. message,
  23700. wParam,
  23701. lParam);
  23702. }
  23703. }
  23704. return DefWindowProc (hW, message, wParam, lParam);
  23705. }
  23706. #endif
  23707. #if JUCE_LINUX
  23708. // overload mouse/keyboard events to forward them to the plugin's inner window..
  23709. void sendEventToChild (XEvent* event)
  23710. {
  23711. if (pluginProc != 0)
  23712. {
  23713. // if the plugin publishes an event procedure, pass the event directly..
  23714. pluginProc (event);
  23715. }
  23716. else if (pluginWindow != 0)
  23717. {
  23718. // if the plugin has a window, then send the event to the window so that
  23719. // its message thread will pick it up..
  23720. XSendEvent (display, pluginWindow, False, 0L, event);
  23721. XFlush (display);
  23722. }
  23723. }
  23724. void mouseEnter (const MouseEvent& e)
  23725. {
  23726. if (pluginWindow != 0)
  23727. {
  23728. XEvent ev;
  23729. zerostruct (ev);
  23730. ev.xcrossing.display = display;
  23731. ev.xcrossing.type = EnterNotify;
  23732. ev.xcrossing.window = pluginWindow;
  23733. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  23734. ev.xcrossing.time = CurrentTime;
  23735. ev.xcrossing.x = e.x;
  23736. ev.xcrossing.y = e.y;
  23737. ev.xcrossing.x_root = e.getScreenX();
  23738. ev.xcrossing.y_root = e.getScreenY();
  23739. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  23740. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  23741. translateJuceToXCrossingModifiers (e, ev);
  23742. sendEventToChild (&ev);
  23743. }
  23744. }
  23745. void mouseExit (const MouseEvent& e)
  23746. {
  23747. if (pluginWindow != 0)
  23748. {
  23749. XEvent ev;
  23750. zerostruct (ev);
  23751. ev.xcrossing.display = display;
  23752. ev.xcrossing.type = LeaveNotify;
  23753. ev.xcrossing.window = pluginWindow;
  23754. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  23755. ev.xcrossing.time = CurrentTime;
  23756. ev.xcrossing.x = e.x;
  23757. ev.xcrossing.y = e.y;
  23758. ev.xcrossing.x_root = e.getScreenX();
  23759. ev.xcrossing.y_root = e.getScreenY();
  23760. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  23761. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  23762. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  23763. translateJuceToXCrossingModifiers (e, ev);
  23764. sendEventToChild (&ev);
  23765. }
  23766. }
  23767. void mouseMove (const MouseEvent& e)
  23768. {
  23769. if (pluginWindow != 0)
  23770. {
  23771. XEvent ev;
  23772. zerostruct (ev);
  23773. ev.xmotion.display = display;
  23774. ev.xmotion.type = MotionNotify;
  23775. ev.xmotion.window = pluginWindow;
  23776. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  23777. ev.xmotion.time = CurrentTime;
  23778. ev.xmotion.is_hint = NotifyNormal;
  23779. ev.xmotion.x = e.x;
  23780. ev.xmotion.y = e.y;
  23781. ev.xmotion.x_root = e.getScreenX();
  23782. ev.xmotion.y_root = e.getScreenY();
  23783. sendEventToChild (&ev);
  23784. }
  23785. }
  23786. void mouseDrag (const MouseEvent& e)
  23787. {
  23788. if (pluginWindow != 0)
  23789. {
  23790. XEvent ev;
  23791. zerostruct (ev);
  23792. ev.xmotion.display = display;
  23793. ev.xmotion.type = MotionNotify;
  23794. ev.xmotion.window = pluginWindow;
  23795. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  23796. ev.xmotion.time = CurrentTime;
  23797. ev.xmotion.x = e.x ;
  23798. ev.xmotion.y = e.y;
  23799. ev.xmotion.x_root = e.getScreenX();
  23800. ev.xmotion.y_root = e.getScreenY();
  23801. ev.xmotion.is_hint = NotifyNormal;
  23802. translateJuceToXMotionModifiers (e, ev);
  23803. sendEventToChild (&ev);
  23804. }
  23805. }
  23806. void mouseUp (const MouseEvent& e)
  23807. {
  23808. if (pluginWindow != 0)
  23809. {
  23810. XEvent ev;
  23811. zerostruct (ev);
  23812. ev.xbutton.display = display;
  23813. ev.xbutton.type = ButtonRelease;
  23814. ev.xbutton.window = pluginWindow;
  23815. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  23816. ev.xbutton.time = CurrentTime;
  23817. ev.xbutton.x = e.x;
  23818. ev.xbutton.y = e.y;
  23819. ev.xbutton.x_root = e.getScreenX();
  23820. ev.xbutton.y_root = e.getScreenY();
  23821. translateJuceToXButtonModifiers (e, ev);
  23822. sendEventToChild (&ev);
  23823. }
  23824. }
  23825. void mouseWheelMove (const MouseEvent& e,
  23826. float incrementX,
  23827. float incrementY)
  23828. {
  23829. if (pluginWindow != 0)
  23830. {
  23831. XEvent ev;
  23832. zerostruct (ev);
  23833. ev.xbutton.display = display;
  23834. ev.xbutton.type = ButtonPress;
  23835. ev.xbutton.window = pluginWindow;
  23836. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  23837. ev.xbutton.time = CurrentTime;
  23838. ev.xbutton.x = e.x;
  23839. ev.xbutton.y = e.y;
  23840. ev.xbutton.x_root = e.getScreenX();
  23841. ev.xbutton.y_root = e.getScreenY();
  23842. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  23843. sendEventToChild (&ev);
  23844. // TODO - put a usleep here ?
  23845. ev.xbutton.type = ButtonRelease;
  23846. sendEventToChild (&ev);
  23847. }
  23848. }
  23849. #endif
  23850. };
  23851. AudioProcessorEditor* VSTPluginInstance::createEditor()
  23852. {
  23853. if (hasEditor())
  23854. return new VSTPluginWindow (*this);
  23855. return 0;
  23856. }
  23857. void VSTPluginInstance::handleAsyncUpdate()
  23858. {
  23859. // indicates that something about the plugin has changed..
  23860. updateHostDisplay();
  23861. }
  23862. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  23863. {
  23864. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  23865. {
  23866. changeProgramName (getCurrentProgram(), prog->prgName);
  23867. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  23868. setParameter (i, vst_swapFloat (prog->params[i]));
  23869. return true;
  23870. }
  23871. return false;
  23872. }
  23873. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  23874. const int dataSize)
  23875. {
  23876. if (dataSize < 28)
  23877. return false;
  23878. const fxSet* const set = (const fxSet*) data;
  23879. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  23880. || vst_swap (set->version) > fxbVersionNum)
  23881. return false;
  23882. if (vst_swap (set->fxMagic) == 'FxBk')
  23883. {
  23884. // bank of programs
  23885. if (vst_swap (set->numPrograms) >= 0)
  23886. {
  23887. const int oldProg = getCurrentProgram();
  23888. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  23889. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  23890. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  23891. {
  23892. if (i != oldProg)
  23893. {
  23894. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  23895. if (((const char*) prog) - ((const char*) set) >= dataSize)
  23896. return false;
  23897. if (vst_swap (set->numPrograms) > 0)
  23898. setCurrentProgram (i);
  23899. if (! restoreProgramSettings (prog))
  23900. return false;
  23901. }
  23902. }
  23903. if (vst_swap (set->numPrograms) > 0)
  23904. setCurrentProgram (oldProg);
  23905. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  23906. if (((const char*) prog) - ((const char*) set) >= dataSize)
  23907. return false;
  23908. if (! restoreProgramSettings (prog))
  23909. return false;
  23910. }
  23911. }
  23912. else if (vst_swap (set->fxMagic) == 'FxCk')
  23913. {
  23914. // single program
  23915. const fxProgram* const prog = (const fxProgram*) data;
  23916. if (vst_swap (prog->chunkMagic) != 'CcnK')
  23917. return false;
  23918. changeProgramName (getCurrentProgram(), prog->prgName);
  23919. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  23920. setParameter (i, vst_swapFloat (prog->params[i]));
  23921. }
  23922. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  23923. {
  23924. // non-preset chunk
  23925. const fxChunkSet* const cset = (const fxChunkSet*) data;
  23926. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  23927. return false;
  23928. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  23929. }
  23930. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  23931. {
  23932. // preset chunk
  23933. const fxProgramSet* const cset = (const fxProgramSet*) data;
  23934. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  23935. return false;
  23936. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  23937. changeProgramName (getCurrentProgram(), cset->name);
  23938. }
  23939. else
  23940. {
  23941. return false;
  23942. }
  23943. return true;
  23944. }
  23945. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  23946. {
  23947. const int numParams = getNumParameters();
  23948. prog->chunkMagic = vst_swap ('CcnK');
  23949. prog->byteSize = 0;
  23950. prog->fxMagic = vst_swap ('FxCk');
  23951. prog->version = vst_swap (fxbVersionNum);
  23952. prog->fxID = vst_swap (getUID());
  23953. prog->fxVersion = vst_swap (getVersionNumber());
  23954. prog->numParams = vst_swap (numParams);
  23955. getCurrentProgramName().copyToBuffer (prog->prgName, sizeof (prog->prgName) - 1);
  23956. for (int i = 0; i < numParams; ++i)
  23957. prog->params[i] = vst_swapFloat (getParameter (i));
  23958. }
  23959. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  23960. {
  23961. const int numPrograms = getNumPrograms();
  23962. const int numParams = getNumParameters();
  23963. if (usesChunks())
  23964. {
  23965. if (isFXB)
  23966. {
  23967. MemoryBlock chunk;
  23968. getChunkData (chunk, false, maxSizeMB);
  23969. const int totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  23970. dest.setSize (totalLen, true);
  23971. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  23972. set->chunkMagic = vst_swap ('CcnK');
  23973. set->byteSize = 0;
  23974. set->fxMagic = vst_swap ('FBCh');
  23975. set->version = vst_swap (fxbVersionNum);
  23976. set->fxID = vst_swap (getUID());
  23977. set->fxVersion = vst_swap (getVersionNumber());
  23978. set->numPrograms = vst_swap (numPrograms);
  23979. set->chunkSize = vst_swap (chunk.getSize());
  23980. chunk.copyTo (set->chunk, 0, chunk.getSize());
  23981. }
  23982. else
  23983. {
  23984. MemoryBlock chunk;
  23985. getChunkData (chunk, true, maxSizeMB);
  23986. const int totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  23987. dest.setSize (totalLen, true);
  23988. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  23989. set->chunkMagic = vst_swap ('CcnK');
  23990. set->byteSize = 0;
  23991. set->fxMagic = vst_swap ('FPCh');
  23992. set->version = vst_swap (fxbVersionNum);
  23993. set->fxID = vst_swap (getUID());
  23994. set->fxVersion = vst_swap (getVersionNumber());
  23995. set->numPrograms = vst_swap (numPrograms);
  23996. set->chunkSize = vst_swap (chunk.getSize());
  23997. getCurrentProgramName().copyToBuffer (set->name, sizeof (set->name) - 1);
  23998. chunk.copyTo (set->chunk, 0, chunk.getSize());
  23999. }
  24000. }
  24001. else
  24002. {
  24003. if (isFXB)
  24004. {
  24005. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  24006. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  24007. dest.setSize (len, true);
  24008. fxSet* const set = (fxSet*) dest.getData();
  24009. set->chunkMagic = vst_swap ('CcnK');
  24010. set->byteSize = 0;
  24011. set->fxMagic = vst_swap ('FxBk');
  24012. set->version = vst_swap (fxbVersionNum);
  24013. set->fxID = vst_swap (getUID());
  24014. set->fxVersion = vst_swap (getVersionNumber());
  24015. set->numPrograms = vst_swap (numPrograms);
  24016. const int oldProgram = getCurrentProgram();
  24017. MemoryBlock oldSettings;
  24018. createTempParameterStore (oldSettings);
  24019. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  24020. for (int i = 0; i < numPrograms; ++i)
  24021. {
  24022. if (i != oldProgram)
  24023. {
  24024. setCurrentProgram (i);
  24025. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  24026. }
  24027. }
  24028. setCurrentProgram (oldProgram);
  24029. restoreFromTempParameterStore (oldSettings);
  24030. }
  24031. else
  24032. {
  24033. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  24034. dest.setSize (totalLen, true);
  24035. setParamsInProgramBlock ((fxProgram*) dest.getData());
  24036. }
  24037. }
  24038. return true;
  24039. }
  24040. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  24041. {
  24042. if (usesChunks())
  24043. {
  24044. void* data = 0;
  24045. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  24046. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  24047. {
  24048. mb.setSize (bytes);
  24049. mb.copyFrom (data, 0, bytes);
  24050. }
  24051. }
  24052. }
  24053. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  24054. {
  24055. if (size > 0 && usesChunks())
  24056. {
  24057. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  24058. if (! isPreset)
  24059. updateStoredProgramNames();
  24060. }
  24061. }
  24062. void VSTPluginInstance::timerCallback()
  24063. {
  24064. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  24065. stopTimer();
  24066. }
  24067. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  24068. {
  24069. const ScopedLock sl (lock);
  24070. ++insideVSTCallback;
  24071. int result = 0;
  24072. try
  24073. {
  24074. if (effect != 0)
  24075. {
  24076. #if JUCE_MAC
  24077. if (module->resFileId != 0)
  24078. UseResFile (module->resFileId);
  24079. CGrafPtr oldPort;
  24080. if (getActiveEditor() != 0)
  24081. {
  24082. int x = 0, y = 0;
  24083. getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), x, y);
  24084. GetPort (&oldPort);
  24085. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  24086. SetOrigin (-x, -y);
  24087. }
  24088. #endif
  24089. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  24090. #if JUCE_MAC
  24091. if (getActiveEditor() != 0)
  24092. SetPort (oldPort);
  24093. module->resFileId = CurResFile();
  24094. #endif
  24095. --insideVSTCallback;
  24096. return result;
  24097. }
  24098. }
  24099. catch (...)
  24100. {
  24101. //char s[512];
  24102. //sprintf (s, "dispatcher (%d, %d, %d, %x, %f)", opcode, index, value, (int)ptr, opt);
  24103. }
  24104. --insideVSTCallback;
  24105. return result;
  24106. }
  24107. // handles non plugin-specific callbacks..
  24108. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  24109. {
  24110. (void) index;
  24111. (void) value;
  24112. (void) opt;
  24113. switch (opcode)
  24114. {
  24115. case audioMasterCanDo:
  24116. {
  24117. static const char* canDos[] = { "supplyIdle",
  24118. "sendVstEvents",
  24119. "sendVstMidiEvent",
  24120. "sendVstTimeInfo",
  24121. "receiveVstEvents",
  24122. "receiveVstMidiEvent",
  24123. "supportShell",
  24124. "shellCategory" };
  24125. for (int i = 0; i < numElementsInArray (canDos); ++i)
  24126. if (strcmp (canDos[i], (const char*) ptr) == 0)
  24127. return 1;
  24128. return 0;
  24129. }
  24130. case audioMasterVersion:
  24131. return 0x2400;
  24132. case audioMasterCurrentId:
  24133. return shellUIDToCreate;
  24134. case audioMasterGetNumAutomatableParameters:
  24135. return 0;
  24136. case audioMasterGetAutomationState:
  24137. return 1;
  24138. case audioMasterGetVendorVersion:
  24139. return 0x0101;
  24140. case audioMasterGetVendorString:
  24141. case audioMasterGetProductString:
  24142. {
  24143. String hostName ("Juce VST Host");
  24144. if (JUCEApplication::getInstance() != 0)
  24145. hostName = JUCEApplication::getInstance()->getApplicationName();
  24146. hostName.copyToBuffer ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  24147. }
  24148. break;
  24149. case audioMasterGetSampleRate:
  24150. return 44100;
  24151. case audioMasterGetBlockSize:
  24152. return 512;
  24153. case audioMasterSetOutputSampleRate:
  24154. return 0;
  24155. default:
  24156. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  24157. break;
  24158. }
  24159. return 0;
  24160. }
  24161. // handles callbacks for a specific plugin
  24162. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  24163. {
  24164. switch (opcode)
  24165. {
  24166. case audioMasterAutomate:
  24167. sendParamChangeMessageToListeners (index, opt);
  24168. break;
  24169. case audioMasterProcessEvents:
  24170. handleMidiFromPlugin ((const VstEvents*) ptr);
  24171. break;
  24172. case audioMasterGetTime:
  24173. #ifdef _MSC_VER
  24174. #pragma warning (push)
  24175. #pragma warning (disable: 4311)
  24176. #endif
  24177. return (VstIntPtr) &vstHostTime;
  24178. #ifdef _MSC_VER
  24179. #pragma warning (pop)
  24180. #endif
  24181. break;
  24182. case audioMasterIdle:
  24183. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  24184. {
  24185. ++insideVSTCallback;
  24186. #if JUCE_MAC
  24187. if (getActiveEditor() != 0)
  24188. dispatch (effEditIdle, 0, 0, 0, 0);
  24189. #endif
  24190. const MessageManagerLock mml;
  24191. juce_callAnyTimersSynchronously();
  24192. handleUpdateNowIfNeeded();
  24193. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  24194. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  24195. --insideVSTCallback;
  24196. }
  24197. break;
  24198. case audioMasterUpdateDisplay:
  24199. triggerAsyncUpdate();
  24200. break;
  24201. case audioMasterTempoAt:
  24202. // returns (10000 * bpm)
  24203. break;
  24204. case audioMasterNeedIdle:
  24205. startTimer (50);
  24206. break;
  24207. case audioMasterSizeWindow:
  24208. if (getActiveEditor() != 0)
  24209. getActiveEditor()->setSize (index, value);
  24210. return 1;
  24211. case audioMasterGetSampleRate:
  24212. return (VstIntPtr) getSampleRate();
  24213. case audioMasterGetBlockSize:
  24214. return (VstIntPtr) getBlockSize();
  24215. case audioMasterWantMidi:
  24216. wantsMidiMessages = true;
  24217. break;
  24218. case audioMasterGetDirectory:
  24219. #if JUCE_MAC
  24220. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  24221. #else
  24222. return (VstIntPtr) (pointer_sized_uint) (const char*) module->fullParentDirectoryPathName;
  24223. #endif
  24224. case audioMasterGetAutomationState:
  24225. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  24226. break;
  24227. // none of these are handled (yet)..
  24228. case audioMasterBeginEdit:
  24229. case audioMasterEndEdit:
  24230. case audioMasterSetTime:
  24231. case audioMasterPinConnected:
  24232. case audioMasterGetParameterQuantization:
  24233. case audioMasterIOChanged:
  24234. case audioMasterGetInputLatency:
  24235. case audioMasterGetOutputLatency:
  24236. case audioMasterGetPreviousPlug:
  24237. case audioMasterGetNextPlug:
  24238. case audioMasterWillReplaceOrAccumulate:
  24239. case audioMasterGetCurrentProcessLevel:
  24240. case audioMasterOfflineStart:
  24241. case audioMasterOfflineRead:
  24242. case audioMasterOfflineWrite:
  24243. case audioMasterOfflineGetCurrentPass:
  24244. case audioMasterOfflineGetCurrentMetaPass:
  24245. case audioMasterVendorSpecific:
  24246. case audioMasterSetIcon:
  24247. case audioMasterGetLanguage:
  24248. case audioMasterOpenWindow:
  24249. case audioMasterCloseWindow:
  24250. break;
  24251. default:
  24252. return handleGeneralCallback (opcode, index, value, ptr, opt);
  24253. }
  24254. return 0;
  24255. }
  24256. // entry point for all callbacks from the plugin
  24257. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  24258. {
  24259. try
  24260. {
  24261. if (effect != 0 && effect->resvd2 != 0)
  24262. {
  24263. return ((VSTPluginInstance*)(effect->resvd2))
  24264. ->handleCallback (opcode, index, value, ptr, opt);
  24265. }
  24266. return handleGeneralCallback (opcode, index, value, ptr, opt);
  24267. }
  24268. catch (...)
  24269. {
  24270. return 0;
  24271. }
  24272. }
  24273. const String VSTPluginInstance::getVersion() const throw()
  24274. {
  24275. int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  24276. String s;
  24277. if (v != 0)
  24278. {
  24279. int versionBits[4];
  24280. int n = 0;
  24281. while (v != 0)
  24282. {
  24283. versionBits [n++] = (v & 0xff);
  24284. v >>= 8;
  24285. }
  24286. s << 'V';
  24287. while (n > 0)
  24288. {
  24289. s << versionBits [--n];
  24290. if (n > 0)
  24291. s << '.';
  24292. }
  24293. }
  24294. return s;
  24295. }
  24296. int VSTPluginInstance::getUID() const throw()
  24297. {
  24298. int uid = effect != 0 ? effect->uniqueID : 0;
  24299. if (uid == 0)
  24300. uid = module->file.hashCode();
  24301. return uid;
  24302. }
  24303. const String VSTPluginInstance::getCategory() const throw()
  24304. {
  24305. const char* result = 0;
  24306. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  24307. {
  24308. case kPlugCategEffect:
  24309. result = "Effect";
  24310. break;
  24311. case kPlugCategSynth:
  24312. result = "Synth";
  24313. break;
  24314. case kPlugCategAnalysis:
  24315. result = "Anaylsis";
  24316. break;
  24317. case kPlugCategMastering:
  24318. result = "Mastering";
  24319. break;
  24320. case kPlugCategSpacializer:
  24321. result = "Spacial";
  24322. break;
  24323. case kPlugCategRoomFx:
  24324. result = "Reverb";
  24325. break;
  24326. case kPlugSurroundFx:
  24327. result = "Surround";
  24328. break;
  24329. case kPlugCategRestoration:
  24330. result = "Restoration";
  24331. break;
  24332. case kPlugCategGenerator:
  24333. result = "Tone generation";
  24334. break;
  24335. default:
  24336. break;
  24337. }
  24338. return result;
  24339. }
  24340. float VSTPluginInstance::getParameter (int index)
  24341. {
  24342. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  24343. {
  24344. try
  24345. {
  24346. const ScopedLock sl (lock);
  24347. return effect->getParameter (effect, index);
  24348. }
  24349. catch (...)
  24350. {
  24351. }
  24352. }
  24353. return 0.0f;
  24354. }
  24355. void VSTPluginInstance::setParameter (int index, float newValue)
  24356. {
  24357. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  24358. {
  24359. try
  24360. {
  24361. const ScopedLock sl (lock);
  24362. if (effect->getParameter (effect, index) != newValue)
  24363. effect->setParameter (effect, index, newValue);
  24364. }
  24365. catch (...)
  24366. {
  24367. }
  24368. }
  24369. }
  24370. const String VSTPluginInstance::getParameterName (int index)
  24371. {
  24372. if (effect != 0)
  24373. {
  24374. jassert (index >= 0 && index < effect->numParams);
  24375. char nm [256];
  24376. zerostruct (nm);
  24377. dispatch (effGetParamName, index, 0, nm, 0);
  24378. return String (nm).trim();
  24379. }
  24380. return String::empty;
  24381. }
  24382. const String VSTPluginInstance::getParameterLabel (int index) const
  24383. {
  24384. if (effect != 0)
  24385. {
  24386. jassert (index >= 0 && index < effect->numParams);
  24387. char nm [256];
  24388. zerostruct (nm);
  24389. dispatch (effGetParamLabel, index, 0, nm, 0);
  24390. return String (nm).trim();
  24391. }
  24392. return String::empty;
  24393. }
  24394. const String VSTPluginInstance::getParameterText (int index)
  24395. {
  24396. if (effect != 0)
  24397. {
  24398. jassert (index >= 0 && index < effect->numParams);
  24399. char nm [256];
  24400. zerostruct (nm);
  24401. dispatch (effGetParamDisplay, index, 0, nm, 0);
  24402. return String (nm).trim();
  24403. }
  24404. return String::empty;
  24405. }
  24406. bool VSTPluginInstance::isParameterAutomatable (int index) const
  24407. {
  24408. if (effect != 0)
  24409. {
  24410. jassert (index >= 0 && index < effect->numParams);
  24411. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  24412. }
  24413. return false;
  24414. }
  24415. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  24416. {
  24417. dest.setSize (64 + 4 * getNumParameters());
  24418. dest.fillWith (0);
  24419. getCurrentProgramName().copyToBuffer ((char*) dest.getData(), 63);
  24420. float* const p = (float*) (((char*) dest.getData()) + 64);
  24421. for (int i = 0; i < getNumParameters(); ++i)
  24422. p[i] = getParameter(i);
  24423. }
  24424. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  24425. {
  24426. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  24427. float* p = (float*) (((char*) m.getData()) + 64);
  24428. for (int i = 0; i < getNumParameters(); ++i)
  24429. setParameter (i, p[i]);
  24430. }
  24431. void VSTPluginInstance::setCurrentProgram (int newIndex)
  24432. {
  24433. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  24434. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  24435. }
  24436. const String VSTPluginInstance::getProgramName (int index)
  24437. {
  24438. if (index == getCurrentProgram())
  24439. {
  24440. return getCurrentProgramName();
  24441. }
  24442. else if (effect != 0)
  24443. {
  24444. char nm [256];
  24445. zerostruct (nm);
  24446. if (dispatch (effGetProgramNameIndexed,
  24447. jlimit (0, getNumPrograms(), index),
  24448. -1, nm, 0) != 0)
  24449. {
  24450. return String (nm).trim();
  24451. }
  24452. }
  24453. return programNames [index];
  24454. }
  24455. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  24456. {
  24457. if (index == getCurrentProgram())
  24458. {
  24459. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  24460. dispatch (effSetProgramName, 0, 0, (void*) (const char*) newName.substring (0, 24), 0.0f);
  24461. }
  24462. else
  24463. {
  24464. jassertfalse // xxx not implemented!
  24465. }
  24466. }
  24467. void VSTPluginInstance::updateStoredProgramNames()
  24468. {
  24469. if (effect != 0 && getNumPrograms() > 0)
  24470. {
  24471. char nm [256];
  24472. zerostruct (nm);
  24473. // only do this if the plugin can't use indexed names..
  24474. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  24475. {
  24476. const int oldProgram = getCurrentProgram();
  24477. MemoryBlock oldSettings;
  24478. createTempParameterStore (oldSettings);
  24479. for (int i = 0; i < getNumPrograms(); ++i)
  24480. {
  24481. setCurrentProgram (i);
  24482. getCurrentProgramName(); // (this updates the list)
  24483. }
  24484. setCurrentProgram (oldProgram);
  24485. restoreFromTempParameterStore (oldSettings);
  24486. }
  24487. }
  24488. }
  24489. const String VSTPluginInstance::getCurrentProgramName()
  24490. {
  24491. if (effect != 0)
  24492. {
  24493. char nm [256];
  24494. zerostruct (nm);
  24495. dispatch (effGetProgramName, 0, 0, nm, 0);
  24496. const int index = getCurrentProgram();
  24497. if (programNames[index].isEmpty())
  24498. {
  24499. while (programNames.size() < index)
  24500. programNames.add (String::empty);
  24501. programNames.set (index, String (nm).trim());
  24502. }
  24503. return String (nm).trim();
  24504. }
  24505. return String::empty;
  24506. }
  24507. const String VSTPluginInstance::getInputChannelName (const int index) const
  24508. {
  24509. if (index >= 0 && index < getNumInputChannels())
  24510. {
  24511. VstPinProperties pinProps;
  24512. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  24513. return String (pinProps.label, sizeof (pinProps.label));
  24514. }
  24515. return String::empty;
  24516. }
  24517. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  24518. {
  24519. if (index < 0 || index >= getNumInputChannels())
  24520. return false;
  24521. VstPinProperties pinProps;
  24522. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  24523. return (pinProps.flags & kVstPinIsStereo) != 0;
  24524. return true;
  24525. }
  24526. const String VSTPluginInstance::getOutputChannelName (const int index) const
  24527. {
  24528. if (index >= 0 && index < getNumOutputChannels())
  24529. {
  24530. VstPinProperties pinProps;
  24531. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  24532. return String (pinProps.label, sizeof (pinProps.label));
  24533. }
  24534. return String::empty;
  24535. }
  24536. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  24537. {
  24538. if (index < 0 || index >= getNumOutputChannels())
  24539. return false;
  24540. VstPinProperties pinProps;
  24541. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  24542. return (pinProps.flags & kVstPinIsStereo) != 0;
  24543. return true;
  24544. }
  24545. void VSTPluginInstance::setPower (const bool on)
  24546. {
  24547. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  24548. isPowerOn = on;
  24549. }
  24550. const int defaultMaxSizeMB = 64;
  24551. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  24552. {
  24553. saveToFXBFile (destData, true, defaultMaxSizeMB);
  24554. }
  24555. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  24556. {
  24557. saveToFXBFile (destData, false, defaultMaxSizeMB);
  24558. }
  24559. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  24560. {
  24561. loadFromFXBFile (data, sizeInBytes);
  24562. }
  24563. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  24564. {
  24565. loadFromFXBFile (data, sizeInBytes);
  24566. }
  24567. VSTPluginFormat::VSTPluginFormat()
  24568. {
  24569. }
  24570. VSTPluginFormat::~VSTPluginFormat()
  24571. {
  24572. }
  24573. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  24574. const File& file)
  24575. {
  24576. if (! fileMightContainThisPluginType (file))
  24577. return;
  24578. PluginDescription desc;
  24579. desc.file = file;
  24580. desc.uid = 0;
  24581. VSTPluginInstance* instance = dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc));
  24582. if (instance == 0)
  24583. return;
  24584. try
  24585. {
  24586. #if JUCE_MAC
  24587. if (instance->module->resFileId != 0)
  24588. UseResFile (instance->module->resFileId);
  24589. #endif
  24590. instance->fillInPluginDescription (desc);
  24591. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  24592. if (category != kPlugCategShell)
  24593. {
  24594. // Normal plugin...
  24595. results.add (new PluginDescription (desc));
  24596. ++insideVSTCallback;
  24597. instance->dispatch (effOpen, 0, 0, 0, 0);
  24598. --insideVSTCallback;
  24599. }
  24600. else
  24601. {
  24602. // It's a shell plugin, so iterate all the subtypes...
  24603. char shellEffectName [64];
  24604. for (;;)
  24605. {
  24606. zerostruct (shellEffectName);
  24607. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  24608. if (uid == 0)
  24609. {
  24610. break;
  24611. }
  24612. else
  24613. {
  24614. desc.uid = uid;
  24615. desc.name = shellEffectName;
  24616. bool alreadyThere = false;
  24617. for (int i = results.size(); --i >= 0;)
  24618. {
  24619. PluginDescription* const d = results.getUnchecked(i);
  24620. if (d->isDuplicateOf (desc))
  24621. {
  24622. alreadyThere = true;
  24623. break;
  24624. }
  24625. }
  24626. if (! alreadyThere)
  24627. results.add (new PluginDescription (desc));
  24628. }
  24629. }
  24630. }
  24631. }
  24632. catch (...)
  24633. {
  24634. // crashed while loading...
  24635. }
  24636. deleteAndZero (instance);
  24637. }
  24638. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  24639. {
  24640. VSTPluginInstance* result = 0;
  24641. if (fileMightContainThisPluginType (desc.file))
  24642. {
  24643. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  24644. desc.file.getParentDirectory().setAsCurrentWorkingDirectory();
  24645. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (desc.file));
  24646. if (module != 0)
  24647. {
  24648. shellUIDToCreate = desc.uid;
  24649. result = new VSTPluginInstance (module);
  24650. if (result->effect != 0)
  24651. {
  24652. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) result;
  24653. result->initialise();
  24654. }
  24655. else
  24656. {
  24657. deleteAndZero (result);
  24658. }
  24659. }
  24660. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  24661. }
  24662. return result;
  24663. }
  24664. bool VSTPluginFormat::fileMightContainThisPluginType (const File& f)
  24665. {
  24666. #if JUCE_MAC
  24667. if (f.isDirectory() && f.hasFileExtension (T(".vst")))
  24668. return true;
  24669. #if JUCE_PPC
  24670. FSRef fileRef;
  24671. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  24672. {
  24673. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  24674. if (resFileId != -1)
  24675. {
  24676. const int numEffects = Count1Resources ('aEff');
  24677. CloseResFile (resFileId);
  24678. if (numEffects > 0)
  24679. return true;
  24680. }
  24681. }
  24682. #endif
  24683. return false;
  24684. #elif JUCE_WIN32
  24685. return f.existsAsFile()
  24686. && f.hasFileExtension (T(".dll"));
  24687. #elif JUCE_LINUX
  24688. return f.existsAsFile()
  24689. && f.hasFileExtension (T(".so"));
  24690. #endif
  24691. }
  24692. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  24693. {
  24694. #if JUCE_MAC
  24695. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  24696. #elif JUCE_WIN32
  24697. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  24698. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  24699. #elif JUCE_LINUX
  24700. return FileSearchPath ("/usr/lib/vst");
  24701. #endif
  24702. }
  24703. END_JUCE_NAMESPACE
  24704. #undef log
  24705. #endif
  24706. /********* End of inlined file: juce_VSTPluginFormat.cpp *********/
  24707. /********* Start of inlined file: juce_AudioProcessor.cpp *********/
  24708. BEGIN_JUCE_NAMESPACE
  24709. AudioProcessor::AudioProcessor()
  24710. : playHead (0),
  24711. activeEditor (0),
  24712. sampleRate (0),
  24713. blockSize (0),
  24714. numInputChannels (0),
  24715. numOutputChannels (0),
  24716. latencySamples (0),
  24717. suspended (false),
  24718. nonRealtime (false)
  24719. {
  24720. }
  24721. AudioProcessor::~AudioProcessor()
  24722. {
  24723. // ooh, nasty - the editor should have been deleted before the filter
  24724. // that it refers to is deleted..
  24725. jassert (activeEditor == 0);
  24726. #ifdef JUCE_DEBUG
  24727. // This will fail if you've called beginParameterChangeGesture() for one
  24728. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  24729. jassert (changingParams.countNumberOfSetBits() == 0);
  24730. #endif
  24731. }
  24732. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  24733. {
  24734. playHead = newPlayHead;
  24735. }
  24736. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  24737. {
  24738. const ScopedLock sl (listenerLock);
  24739. listeners.addIfNotAlreadyThere (newListener);
  24740. }
  24741. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  24742. {
  24743. const ScopedLock sl (listenerLock);
  24744. listeners.removeValue (listenerToRemove);
  24745. }
  24746. void AudioProcessor::setPlayConfigDetails (const int numIns,
  24747. const int numOuts,
  24748. const double sampleRate_,
  24749. const int blockSize_) throw()
  24750. {
  24751. numInputChannels = numIns;
  24752. numOutputChannels = numOuts;
  24753. sampleRate = sampleRate_;
  24754. blockSize = blockSize_;
  24755. }
  24756. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  24757. {
  24758. nonRealtime = nonRealtime_;
  24759. }
  24760. void AudioProcessor::setLatencySamples (const int newLatency)
  24761. {
  24762. if (latencySamples != newLatency)
  24763. {
  24764. latencySamples = newLatency;
  24765. updateHostDisplay();
  24766. }
  24767. }
  24768. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  24769. const float newValue)
  24770. {
  24771. setParameter (parameterIndex, newValue);
  24772. sendParamChangeMessageToListeners (parameterIndex, newValue);
  24773. }
  24774. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  24775. {
  24776. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  24777. for (int i = listeners.size(); --i >= 0;)
  24778. {
  24779. listenerLock.enter();
  24780. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24781. listenerLock.exit();
  24782. if (l != 0)
  24783. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  24784. }
  24785. }
  24786. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  24787. {
  24788. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  24789. #ifdef JUCE_DEBUG
  24790. // This means you've called beginParameterChangeGesture twice in succession without a matching
  24791. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  24792. jassert (! changingParams [parameterIndex]);
  24793. changingParams.setBit (parameterIndex);
  24794. #endif
  24795. for (int i = listeners.size(); --i >= 0;)
  24796. {
  24797. listenerLock.enter();
  24798. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24799. listenerLock.exit();
  24800. if (l != 0)
  24801. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  24802. }
  24803. }
  24804. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  24805. {
  24806. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  24807. #ifdef JUCE_DEBUG
  24808. // This means you've called endParameterChangeGesture without having previously called
  24809. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  24810. // calls matched correctly.
  24811. jassert (changingParams [parameterIndex]);
  24812. changingParams.clearBit (parameterIndex);
  24813. #endif
  24814. for (int i = listeners.size(); --i >= 0;)
  24815. {
  24816. listenerLock.enter();
  24817. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24818. listenerLock.exit();
  24819. if (l != 0)
  24820. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  24821. }
  24822. }
  24823. void AudioProcessor::updateHostDisplay()
  24824. {
  24825. for (int i = listeners.size(); --i >= 0;)
  24826. {
  24827. listenerLock.enter();
  24828. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24829. listenerLock.exit();
  24830. if (l != 0)
  24831. l->audioProcessorChanged (this);
  24832. }
  24833. }
  24834. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  24835. {
  24836. return true;
  24837. }
  24838. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  24839. {
  24840. return false;
  24841. }
  24842. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  24843. {
  24844. const ScopedLock sl (callbackLock);
  24845. suspended = shouldBeSuspended;
  24846. }
  24847. void AudioProcessor::reset()
  24848. {
  24849. }
  24850. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  24851. {
  24852. const ScopedLock sl (callbackLock);
  24853. jassert (activeEditor == editor);
  24854. if (activeEditor == editor)
  24855. activeEditor = 0;
  24856. }
  24857. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  24858. {
  24859. if (activeEditor != 0)
  24860. return activeEditor;
  24861. AudioProcessorEditor* const ed = createEditor();
  24862. if (ed != 0)
  24863. {
  24864. // you must give your editor comp a size before returning it..
  24865. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  24866. const ScopedLock sl (callbackLock);
  24867. activeEditor = ed;
  24868. }
  24869. return ed;
  24870. }
  24871. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  24872. {
  24873. getStateInformation (destData);
  24874. }
  24875. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  24876. {
  24877. setStateInformation (data, sizeInBytes);
  24878. }
  24879. // magic number to identify memory blocks that we've stored as XML
  24880. const uint32 magicXmlNumber = 0x21324356;
  24881. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  24882. JUCE_NAMESPACE::MemoryBlock& destData)
  24883. {
  24884. const String xmlString (xml.createDocument (String::empty, true, false));
  24885. const int stringLength = xmlString.length();
  24886. destData.setSize (stringLength + 10);
  24887. char* const d = (char*) destData.getData();
  24888. *(uint32*) d = swapIfBigEndian ((const uint32) magicXmlNumber);
  24889. *(uint32*) (d + 4) = swapIfBigEndian ((const uint32) stringLength);
  24890. xmlString.copyToBuffer (d + 8, stringLength);
  24891. }
  24892. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  24893. const int sizeInBytes)
  24894. {
  24895. if (sizeInBytes > 8
  24896. && littleEndianInt ((const char*) data) == magicXmlNumber)
  24897. {
  24898. const uint32 stringLength = littleEndianInt (((const char*) data) + 4);
  24899. if (stringLength > 0)
  24900. {
  24901. XmlDocument doc (String (((const char*) data) + 8,
  24902. jmin ((sizeInBytes - 8), stringLength)));
  24903. return doc.getDocumentElement();
  24904. }
  24905. }
  24906. return 0;
  24907. }
  24908. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  24909. {
  24910. }
  24911. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  24912. {
  24913. }
  24914. END_JUCE_NAMESPACE
  24915. /********* End of inlined file: juce_AudioProcessor.cpp *********/
  24916. /********* Start of inlined file: juce_AudioProcessorEditor.cpp *********/
  24917. BEGIN_JUCE_NAMESPACE
  24918. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  24919. : owner (owner_)
  24920. {
  24921. // the filter must be valid..
  24922. jassert (owner != 0);
  24923. }
  24924. AudioProcessorEditor::~AudioProcessorEditor()
  24925. {
  24926. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  24927. // filter for some reason..
  24928. jassert (owner->getActiveEditor() != this);
  24929. }
  24930. END_JUCE_NAMESPACE
  24931. /********* End of inlined file: juce_AudioProcessorEditor.cpp *********/
  24932. /********* Start of inlined file: juce_AudioProcessorGraph.cpp *********/
  24933. BEGIN_JUCE_NAMESPACE
  24934. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  24935. AudioProcessorGraph::Node::Node (const uint32 id_,
  24936. AudioProcessor* const processor_) throw()
  24937. : id (id_),
  24938. processor (processor_),
  24939. isPrepared (false)
  24940. {
  24941. jassert (processor_ != 0);
  24942. }
  24943. AudioProcessorGraph::Node::~Node()
  24944. {
  24945. delete processor;
  24946. }
  24947. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  24948. AudioProcessorGraph* const graph)
  24949. {
  24950. if (! isPrepared)
  24951. {
  24952. isPrepared = true;
  24953. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  24954. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  24955. if (ioProc != 0)
  24956. ioProc->setParentGraph (graph);
  24957. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  24958. processor->getNumOutputChannels(),
  24959. sampleRate, blockSize);
  24960. processor->prepareToPlay (sampleRate, blockSize);
  24961. }
  24962. }
  24963. void AudioProcessorGraph::Node::unprepare()
  24964. {
  24965. if (isPrepared)
  24966. {
  24967. isPrepared = false;
  24968. processor->releaseResources();
  24969. }
  24970. }
  24971. AudioProcessorGraph::AudioProcessorGraph()
  24972. : lastNodeId (0),
  24973. renderingBuffers (1, 1),
  24974. currentAudioOutputBuffer (1, 1)
  24975. {
  24976. }
  24977. AudioProcessorGraph::~AudioProcessorGraph()
  24978. {
  24979. clearRenderingSequence();
  24980. clear();
  24981. }
  24982. const String AudioProcessorGraph::getName() const
  24983. {
  24984. return "Audio Graph";
  24985. }
  24986. void AudioProcessorGraph::clear()
  24987. {
  24988. nodes.clear();
  24989. connections.clear();
  24990. triggerAsyncUpdate();
  24991. }
  24992. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const throw()
  24993. {
  24994. for (int i = nodes.size(); --i >= 0;)
  24995. if (nodes.getUnchecked(i)->id == nodeId)
  24996. return nodes.getUnchecked(i);
  24997. return 0;
  24998. }
  24999. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  25000. uint32 nodeId)
  25001. {
  25002. if (newProcessor == 0)
  25003. {
  25004. jassertfalse
  25005. return 0;
  25006. }
  25007. if (nodeId == 0)
  25008. {
  25009. nodeId = ++lastNodeId;
  25010. }
  25011. else
  25012. {
  25013. // you can't add a node with an id that already exists in the graph..
  25014. jassert (getNodeForId (nodeId) == 0);
  25015. removeNode (nodeId);
  25016. }
  25017. lastNodeId = nodeId;
  25018. Node* const n = new Node (nodeId, newProcessor);
  25019. nodes.add (n);
  25020. triggerAsyncUpdate();
  25021. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  25022. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  25023. if (ioProc != 0)
  25024. ioProc->setParentGraph (this);
  25025. return n;
  25026. }
  25027. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  25028. {
  25029. disconnectNode (nodeId);
  25030. for (int i = nodes.size(); --i >= 0;)
  25031. {
  25032. if (nodes.getUnchecked(i)->id == nodeId)
  25033. {
  25034. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  25035. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  25036. if (ioProc != 0)
  25037. ioProc->setParentGraph (0);
  25038. nodes.remove (i);
  25039. triggerAsyncUpdate();
  25040. return true;
  25041. }
  25042. }
  25043. return false;
  25044. }
  25045. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  25046. const int sourceChannelIndex,
  25047. const uint32 destNodeId,
  25048. const int destChannelIndex) const throw()
  25049. {
  25050. for (int i = connections.size(); --i >= 0;)
  25051. {
  25052. const Connection* const c = connections.getUnchecked(i);
  25053. if (c->sourceNodeId == sourceNodeId
  25054. && c->destNodeId == destNodeId
  25055. && c->sourceChannelIndex == sourceChannelIndex
  25056. && c->destChannelIndex == destChannelIndex)
  25057. {
  25058. return c;
  25059. }
  25060. }
  25061. return 0;
  25062. }
  25063. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  25064. const uint32 possibleDestNodeId) const throw()
  25065. {
  25066. for (int i = connections.size(); --i >= 0;)
  25067. {
  25068. const Connection* const c = connections.getUnchecked(i);
  25069. if (c->sourceNodeId == possibleSourceNodeId
  25070. && c->destNodeId == possibleDestNodeId)
  25071. {
  25072. return true;
  25073. }
  25074. }
  25075. return false;
  25076. }
  25077. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  25078. const int sourceChannelIndex,
  25079. const uint32 destNodeId,
  25080. const int destChannelIndex) const throw()
  25081. {
  25082. if (sourceChannelIndex < 0
  25083. || destChannelIndex < 0
  25084. || sourceNodeId == destNodeId
  25085. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  25086. return false;
  25087. const Node* const source = getNodeForId (sourceNodeId);
  25088. if (source == 0
  25089. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  25090. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  25091. return false;
  25092. const Node* const dest = getNodeForId (destNodeId);
  25093. if (dest == 0
  25094. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  25095. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  25096. return false;
  25097. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  25098. destNodeId, destChannelIndex) == 0;
  25099. }
  25100. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  25101. const int sourceChannelIndex,
  25102. const uint32 destNodeId,
  25103. const int destChannelIndex)
  25104. {
  25105. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  25106. return false;
  25107. Connection* const c = new Connection();
  25108. c->sourceNodeId = sourceNodeId;
  25109. c->sourceChannelIndex = sourceChannelIndex;
  25110. c->destNodeId = destNodeId;
  25111. c->destChannelIndex = destChannelIndex;
  25112. connections.add (c);
  25113. triggerAsyncUpdate();
  25114. return true;
  25115. }
  25116. void AudioProcessorGraph::removeConnection (const int index)
  25117. {
  25118. connections.remove (index);
  25119. triggerAsyncUpdate();
  25120. }
  25121. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  25122. const uint32 destNodeId, const int destChannelIndex)
  25123. {
  25124. bool doneAnything = false;
  25125. for (int i = connections.size(); --i >= 0;)
  25126. {
  25127. const Connection* const c = connections.getUnchecked(i);
  25128. if (c->sourceNodeId == sourceNodeId
  25129. && c->destNodeId == destNodeId
  25130. && c->sourceChannelIndex == sourceChannelIndex
  25131. && c->destChannelIndex == destChannelIndex)
  25132. {
  25133. removeConnection (i);
  25134. doneAnything = true;
  25135. triggerAsyncUpdate();
  25136. }
  25137. }
  25138. return doneAnything;
  25139. }
  25140. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  25141. {
  25142. bool doneAnything = false;
  25143. for (int i = connections.size(); --i >= 0;)
  25144. {
  25145. const Connection* const c = connections.getUnchecked(i);
  25146. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  25147. {
  25148. removeConnection (i);
  25149. doneAnything = true;
  25150. triggerAsyncUpdate();
  25151. }
  25152. }
  25153. return doneAnything;
  25154. }
  25155. bool AudioProcessorGraph::removeIllegalConnections()
  25156. {
  25157. bool doneAnything = false;
  25158. for (int i = connections.size(); --i >= 0;)
  25159. {
  25160. const Connection* const c = connections.getUnchecked(i);
  25161. const Node* const source = getNodeForId (c->sourceNodeId);
  25162. const Node* const dest = getNodeForId (c->destNodeId);
  25163. if (source == 0 || dest == 0
  25164. || (c->sourceChannelIndex != midiChannelIndex
  25165. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  25166. || (c->sourceChannelIndex == midiChannelIndex
  25167. && ! source->processor->producesMidi())
  25168. || (c->destChannelIndex != midiChannelIndex
  25169. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  25170. || (c->destChannelIndex == midiChannelIndex
  25171. && ! dest->processor->acceptsMidi()))
  25172. {
  25173. removeConnection (i);
  25174. doneAnything = true;
  25175. triggerAsyncUpdate();
  25176. }
  25177. }
  25178. return doneAnything;
  25179. }
  25180. namespace GraphRenderingOps
  25181. {
  25182. class AudioGraphRenderingOp
  25183. {
  25184. public:
  25185. AudioGraphRenderingOp() throw() {}
  25186. virtual ~AudioGraphRenderingOp() throw() {}
  25187. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  25188. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  25189. const int numSamples) throw() = 0;
  25190. juce_UseDebuggingNewOperator
  25191. };
  25192. class ClearChannelOp : public AudioGraphRenderingOp
  25193. {
  25194. public:
  25195. ClearChannelOp (const int channelNum_) throw()
  25196. : channelNum (channelNum_)
  25197. {}
  25198. ~ClearChannelOp() throw() {}
  25199. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  25200. {
  25201. sharedBufferChans.clear (channelNum, 0, numSamples);
  25202. }
  25203. private:
  25204. const int channelNum;
  25205. ClearChannelOp (const ClearChannelOp&);
  25206. const ClearChannelOp& operator= (const ClearChannelOp&);
  25207. };
  25208. class CopyChannelOp : public AudioGraphRenderingOp
  25209. {
  25210. public:
  25211. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  25212. : srcChannelNum (srcChannelNum_),
  25213. dstChannelNum (dstChannelNum_)
  25214. {}
  25215. ~CopyChannelOp() throw() {}
  25216. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  25217. {
  25218. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  25219. }
  25220. private:
  25221. const int srcChannelNum, dstChannelNum;
  25222. CopyChannelOp (const CopyChannelOp&);
  25223. const CopyChannelOp& operator= (const CopyChannelOp&);
  25224. };
  25225. class AddChannelOp : public AudioGraphRenderingOp
  25226. {
  25227. public:
  25228. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  25229. : srcChannelNum (srcChannelNum_),
  25230. dstChannelNum (dstChannelNum_)
  25231. {}
  25232. ~AddChannelOp() throw() {}
  25233. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  25234. {
  25235. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  25236. }
  25237. private:
  25238. const int srcChannelNum, dstChannelNum;
  25239. AddChannelOp (const AddChannelOp&);
  25240. const AddChannelOp& operator= (const AddChannelOp&);
  25241. };
  25242. class ClearMidiBufferOp : public AudioGraphRenderingOp
  25243. {
  25244. public:
  25245. ClearMidiBufferOp (const int bufferNum_) throw()
  25246. : bufferNum (bufferNum_)
  25247. {}
  25248. ~ClearMidiBufferOp() throw() {}
  25249. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  25250. {
  25251. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  25252. }
  25253. private:
  25254. const int bufferNum;
  25255. ClearMidiBufferOp (const ClearMidiBufferOp&);
  25256. const ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  25257. };
  25258. class CopyMidiBufferOp : public AudioGraphRenderingOp
  25259. {
  25260. public:
  25261. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  25262. : srcBufferNum (srcBufferNum_),
  25263. dstBufferNum (dstBufferNum_)
  25264. {}
  25265. ~CopyMidiBufferOp() throw() {}
  25266. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  25267. {
  25268. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  25269. }
  25270. private:
  25271. const int srcBufferNum, dstBufferNum;
  25272. CopyMidiBufferOp (const CopyMidiBufferOp&);
  25273. const CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  25274. };
  25275. class AddMidiBufferOp : public AudioGraphRenderingOp
  25276. {
  25277. public:
  25278. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  25279. : srcBufferNum (srcBufferNum_),
  25280. dstBufferNum (dstBufferNum_)
  25281. {}
  25282. ~AddMidiBufferOp() throw() {}
  25283. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  25284. {
  25285. sharedMidiBuffers.getUnchecked (dstBufferNum)
  25286. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  25287. }
  25288. private:
  25289. const int srcBufferNum, dstBufferNum;
  25290. AddMidiBufferOp (const AddMidiBufferOp&);
  25291. const AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  25292. };
  25293. class ProcessBufferOp : public AudioGraphRenderingOp
  25294. {
  25295. public:
  25296. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  25297. const Array <int>& audioChannelsToUse_,
  25298. const int totalChans_,
  25299. const int midiBufferToUse_) throw()
  25300. : node (node_),
  25301. processor (node_->processor),
  25302. audioChannelsToUse (audioChannelsToUse_),
  25303. totalChans (totalChans_),
  25304. midiBufferToUse (midiBufferToUse_)
  25305. {
  25306. channels = (float**) juce_calloc (sizeof (float*) * totalChans_);
  25307. }
  25308. ~ProcessBufferOp() throw()
  25309. {
  25310. juce_free (channels);
  25311. }
  25312. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  25313. {
  25314. for (int i = totalChans; --i >= 0;)
  25315. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  25316. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  25317. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  25318. }
  25319. const AudioProcessorGraph::Node::Ptr node;
  25320. AudioProcessor* const processor;
  25321. private:
  25322. Array <int> audioChannelsToUse;
  25323. float** channels;
  25324. int totalChans;
  25325. int midiBufferToUse;
  25326. ProcessBufferOp (const ProcessBufferOp&);
  25327. const ProcessBufferOp& operator= (const ProcessBufferOp&);
  25328. };
  25329. /** Used to calculate the correct sequence of rendering ops needed, based on
  25330. the best re-use of shared buffers at each stage.
  25331. */
  25332. class RenderingOpSequenceCalculator
  25333. {
  25334. public:
  25335. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  25336. const VoidArray& orderedNodes_,
  25337. VoidArray& renderingOps)
  25338. : graph (graph_),
  25339. orderedNodes (orderedNodes_)
  25340. {
  25341. nodeIds.add (-2); // first buffer is read-only zeros
  25342. channels.add (0);
  25343. midiNodeIds.add (-2);
  25344. for (int i = 0; i < orderedNodes.size(); ++i)
  25345. {
  25346. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  25347. renderingOps, i);
  25348. markAnyUnusedBuffersAsFree (i);
  25349. }
  25350. }
  25351. int getNumBuffersNeeded() const throw() { return nodeIds.size(); }
  25352. int getNumMidiBuffersNeeded() const throw() { return midiNodeIds.size(); }
  25353. juce_UseDebuggingNewOperator
  25354. private:
  25355. AudioProcessorGraph& graph;
  25356. const VoidArray& orderedNodes;
  25357. Array <int> nodeIds, channels, midiNodeIds;
  25358. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  25359. VoidArray& renderingOps,
  25360. const int ourRenderingIndex)
  25361. {
  25362. const int numIns = node->processor->getNumInputChannels();
  25363. const int numOuts = node->processor->getNumOutputChannels();
  25364. const int totalChans = jmax (numIns, numOuts);
  25365. Array <int> audioChannelsToUse;
  25366. int midiBufferToUse = -1;
  25367. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  25368. {
  25369. // get a list of all the inputs to this node
  25370. Array <int> sourceNodes, sourceOutputChans;
  25371. for (int i = graph.getNumConnections(); --i >= 0;)
  25372. {
  25373. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  25374. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  25375. {
  25376. sourceNodes.add (c->sourceNodeId);
  25377. sourceOutputChans.add (c->sourceChannelIndex);
  25378. }
  25379. }
  25380. int bufIndex = -1;
  25381. if (sourceNodes.size() == 0)
  25382. {
  25383. // unconnected input channel
  25384. if (inputChan >= numOuts)
  25385. {
  25386. bufIndex = getReadOnlyEmptyBuffer();
  25387. jassert (bufIndex >= 0);
  25388. }
  25389. else
  25390. {
  25391. bufIndex = getFreeBuffer (false);
  25392. renderingOps.add (new ClearChannelOp (bufIndex));
  25393. }
  25394. }
  25395. else if (sourceNodes.size() == 1)
  25396. {
  25397. // channel with a straightforward single input..
  25398. const int srcNode = sourceNodes.getUnchecked(0);
  25399. const int srcChan = sourceOutputChans.getUnchecked(0);
  25400. bufIndex = getBufferContaining (srcNode, srcChan);
  25401. if (bufIndex < 0)
  25402. {
  25403. // if not found, this is probably a feedback loop
  25404. bufIndex = getReadOnlyEmptyBuffer();
  25405. jassert (bufIndex >= 0);
  25406. }
  25407. if (inputChan < numOuts
  25408. && isBufferNeededLater (ourRenderingIndex,
  25409. inputChan,
  25410. srcNode, srcChan))
  25411. {
  25412. // can't mess up this channel because it's needed later by another node, so we
  25413. // need to use a copy of it..
  25414. const int newFreeBuffer = getFreeBuffer (false);
  25415. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  25416. bufIndex = newFreeBuffer;
  25417. }
  25418. }
  25419. else
  25420. {
  25421. // channel with a mix of several inputs..
  25422. // try to find a re-usable channel from our inputs..
  25423. int reusableInputIndex = -1;
  25424. for (int i = 0; i < sourceNodes.size(); ++i)
  25425. {
  25426. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  25427. sourceOutputChans.getUnchecked(i));
  25428. if (sourceBufIndex >= 0
  25429. && ! isBufferNeededLater (ourRenderingIndex,
  25430. inputChan,
  25431. sourceNodes.getUnchecked(i),
  25432. sourceOutputChans.getUnchecked(i)))
  25433. {
  25434. // we've found one of our input chans that can be re-used..
  25435. reusableInputIndex = i;
  25436. bufIndex = sourceBufIndex;
  25437. break;
  25438. }
  25439. }
  25440. if (reusableInputIndex < 0)
  25441. {
  25442. // can't re-use any of our input chans, so get a new one and copy everything into it..
  25443. bufIndex = getFreeBuffer (false);
  25444. jassert (bufIndex != 0);
  25445. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  25446. sourceOutputChans.getUnchecked (0));
  25447. if (srcIndex < 0)
  25448. {
  25449. // if not found, this is probably a feedback loop
  25450. renderingOps.add (new ClearChannelOp (bufIndex));
  25451. }
  25452. else
  25453. {
  25454. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  25455. }
  25456. reusableInputIndex = 0;
  25457. }
  25458. for (int j = 0; j < sourceNodes.size(); ++j)
  25459. {
  25460. if (j != reusableInputIndex)
  25461. {
  25462. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  25463. sourceOutputChans.getUnchecked(j));
  25464. if (srcIndex >= 0)
  25465. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  25466. }
  25467. }
  25468. }
  25469. jassert (bufIndex >= 0);
  25470. audioChannelsToUse.add (bufIndex);
  25471. if (inputChan < numOuts)
  25472. markBufferAsContaining (bufIndex, node->id, inputChan);
  25473. }
  25474. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  25475. {
  25476. const int bufIndex = getFreeBuffer (false);
  25477. jassert (bufIndex != 0);
  25478. audioChannelsToUse.add (bufIndex);
  25479. markBufferAsContaining (bufIndex, node->id, outputChan);
  25480. }
  25481. // Now the same thing for midi..
  25482. Array <int> midiSourceNodes;
  25483. for (int i = graph.getNumConnections(); --i >= 0;)
  25484. {
  25485. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  25486. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  25487. midiSourceNodes.add (c->sourceNodeId);
  25488. }
  25489. if (midiSourceNodes.size() == 0)
  25490. {
  25491. // No midi inputs..
  25492. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  25493. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  25494. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  25495. }
  25496. else if (midiSourceNodes.size() == 1)
  25497. {
  25498. // One midi input..
  25499. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  25500. AudioProcessorGraph::midiChannelIndex);
  25501. if (midiBufferToUse >= 0)
  25502. {
  25503. if (isBufferNeededLater (ourRenderingIndex,
  25504. AudioProcessorGraph::midiChannelIndex,
  25505. midiSourceNodes.getUnchecked(0),
  25506. AudioProcessorGraph::midiChannelIndex))
  25507. {
  25508. // can't mess up this channel because it's needed later by another node, so we
  25509. // need to use a copy of it..
  25510. const int newFreeBuffer = getFreeBuffer (true);
  25511. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  25512. midiBufferToUse = newFreeBuffer;
  25513. }
  25514. }
  25515. else
  25516. {
  25517. // probably a feedback loop, so just use an empty one..
  25518. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  25519. }
  25520. }
  25521. else
  25522. {
  25523. // More than one midi input being mixed..
  25524. int reusableInputIndex = -1;
  25525. for (int i = 0; i < midiSourceNodes.size(); ++i)
  25526. {
  25527. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  25528. AudioProcessorGraph::midiChannelIndex);
  25529. if (sourceBufIndex >= 0
  25530. && ! isBufferNeededLater (ourRenderingIndex,
  25531. AudioProcessorGraph::midiChannelIndex,
  25532. midiSourceNodes.getUnchecked(i),
  25533. AudioProcessorGraph::midiChannelIndex))
  25534. {
  25535. // we've found one of our input buffers that can be re-used..
  25536. reusableInputIndex = i;
  25537. midiBufferToUse = sourceBufIndex;
  25538. break;
  25539. }
  25540. }
  25541. if (reusableInputIndex < 0)
  25542. {
  25543. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  25544. midiBufferToUse = getFreeBuffer (true);
  25545. jassert (midiBufferToUse >= 0);
  25546. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  25547. AudioProcessorGraph::midiChannelIndex);
  25548. if (srcIndex >= 0)
  25549. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  25550. else
  25551. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  25552. reusableInputIndex = 0;
  25553. }
  25554. for (int j = 0; j < midiSourceNodes.size(); ++j)
  25555. {
  25556. if (j != reusableInputIndex)
  25557. {
  25558. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  25559. AudioProcessorGraph::midiChannelIndex);
  25560. if (srcIndex >= 0)
  25561. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  25562. }
  25563. }
  25564. }
  25565. if (node->processor->producesMidi())
  25566. markBufferAsContaining (midiBufferToUse, node->id,
  25567. AudioProcessorGraph::midiChannelIndex);
  25568. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  25569. totalChans, midiBufferToUse));
  25570. }
  25571. int getFreeBuffer (const bool forMidi)
  25572. {
  25573. if (forMidi)
  25574. {
  25575. for (int i = 1; i < midiNodeIds.size(); ++i)
  25576. if (midiNodeIds.getUnchecked(i) < 0)
  25577. return i;
  25578. midiNodeIds.add (-1);
  25579. return midiNodeIds.size() - 1;
  25580. }
  25581. else
  25582. {
  25583. for (int i = 1; i < nodeIds.size(); ++i)
  25584. if (nodeIds.getUnchecked(i) < 0)
  25585. return i;
  25586. nodeIds.add (-1);
  25587. channels.add (0);
  25588. return nodeIds.size() - 1;
  25589. }
  25590. }
  25591. int getReadOnlyEmptyBuffer() const throw()
  25592. {
  25593. return 0;
  25594. }
  25595. int getBufferContaining (const int nodeId, const int outputChannel) const throw()
  25596. {
  25597. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  25598. {
  25599. for (int i = midiNodeIds.size(); --i >= 0;)
  25600. if (midiNodeIds.getUnchecked(i) == nodeId)
  25601. return i;
  25602. }
  25603. else
  25604. {
  25605. for (int i = nodeIds.size(); --i >= 0;)
  25606. if (nodeIds.getUnchecked(i) == nodeId
  25607. && channels.getUnchecked(i) == outputChannel)
  25608. return i;
  25609. }
  25610. return -1;
  25611. }
  25612. void markAnyUnusedBuffersAsFree (const int stepIndex)
  25613. {
  25614. int i;
  25615. for (i = 0; i < nodeIds.size(); ++i)
  25616. {
  25617. if (nodeIds.getUnchecked(i) >= 0
  25618. && ! isBufferNeededLater (stepIndex, -1,
  25619. nodeIds.getUnchecked(i),
  25620. channels.getUnchecked(i)))
  25621. {
  25622. nodeIds.set (i, -1);
  25623. }
  25624. }
  25625. for (i = 0; i < midiNodeIds.size(); ++i)
  25626. {
  25627. if (midiNodeIds.getUnchecked(i) >= 0
  25628. && ! isBufferNeededLater (stepIndex, -1,
  25629. midiNodeIds.getUnchecked(i),
  25630. AudioProcessorGraph::midiChannelIndex))
  25631. {
  25632. midiNodeIds.set (i, -1);
  25633. }
  25634. }
  25635. }
  25636. bool isBufferNeededLater (int stepIndexToSearchFrom,
  25637. int inputChannelOfIndexToIgnore,
  25638. const int nodeId,
  25639. const int outputChanIndex) const throw()
  25640. {
  25641. while (stepIndexToSearchFrom < orderedNodes.size())
  25642. {
  25643. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  25644. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  25645. {
  25646. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  25647. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  25648. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  25649. return true;
  25650. }
  25651. else
  25652. {
  25653. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  25654. if (i != inputChannelOfIndexToIgnore
  25655. && graph.getConnectionBetween (nodeId, outputChanIndex,
  25656. node->id, i) != 0)
  25657. return true;
  25658. }
  25659. inputChannelOfIndexToIgnore = -1;
  25660. ++stepIndexToSearchFrom;
  25661. }
  25662. return false;
  25663. }
  25664. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  25665. {
  25666. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  25667. {
  25668. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  25669. midiNodeIds.set (bufferNum, nodeId);
  25670. }
  25671. else
  25672. {
  25673. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  25674. nodeIds.set (bufferNum, nodeId);
  25675. channels.set (bufferNum, outputIndex);
  25676. }
  25677. }
  25678. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  25679. const RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  25680. };
  25681. }
  25682. void AudioProcessorGraph::clearRenderingSequence()
  25683. {
  25684. const ScopedLock sl (renderLock);
  25685. for (int i = renderingOps.size(); --i >= 0;)
  25686. {
  25687. GraphRenderingOps::AudioGraphRenderingOp* const r
  25688. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  25689. renderingOps.remove (i);
  25690. delete r;
  25691. }
  25692. }
  25693. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  25694. const uint32 possibleDestinationId,
  25695. const int recursionCheck) const throw()
  25696. {
  25697. if (recursionCheck > 0)
  25698. {
  25699. for (int i = connections.size(); --i >= 0;)
  25700. {
  25701. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  25702. if (c->destNodeId == possibleDestinationId
  25703. && (c->sourceNodeId == possibleInputId
  25704. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  25705. return true;
  25706. }
  25707. }
  25708. return false;
  25709. }
  25710. void AudioProcessorGraph::buildRenderingSequence()
  25711. {
  25712. VoidArray newRenderingOps;
  25713. int numRenderingBuffersNeeded = 2;
  25714. int numMidiBuffersNeeded = 1;
  25715. {
  25716. MessageManagerLock mml;
  25717. VoidArray orderedNodes;
  25718. int i;
  25719. for (i = 0; i < nodes.size(); ++i)
  25720. {
  25721. Node* const node = nodes.getUnchecked(i);
  25722. node->prepare (getSampleRate(), getBlockSize(), this);
  25723. int j = 0;
  25724. for (; j < orderedNodes.size(); ++j)
  25725. if (isAnInputTo (node->id,
  25726. ((Node*) orderedNodes.getUnchecked (j))->id,
  25727. nodes.size() + 1))
  25728. break;
  25729. orderedNodes.insert (j, node);
  25730. }
  25731. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  25732. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  25733. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  25734. }
  25735. VoidArray oldRenderingOps (renderingOps);
  25736. {
  25737. // swap over to the new rendering sequence..
  25738. const ScopedLock sl (renderLock);
  25739. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  25740. renderingBuffers.clear();
  25741. for (int i = midiBuffers.size(); --i >= 0;)
  25742. midiBuffers.getUnchecked(i)->clear();
  25743. while (midiBuffers.size() < numMidiBuffersNeeded)
  25744. midiBuffers.add (new MidiBuffer());
  25745. renderingOps = newRenderingOps;
  25746. }
  25747. for (int i = oldRenderingOps.size(); --i >= 0;)
  25748. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  25749. }
  25750. void AudioProcessorGraph::handleAsyncUpdate()
  25751. {
  25752. buildRenderingSequence();
  25753. }
  25754. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  25755. {
  25756. currentAudioInputBuffer = 0;
  25757. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  25758. currentMidiInputBuffer = 0;
  25759. currentMidiOutputBuffer.clear();
  25760. clearRenderingSequence();
  25761. buildRenderingSequence();
  25762. }
  25763. void AudioProcessorGraph::releaseResources()
  25764. {
  25765. for (int i = 0; i < nodes.size(); ++i)
  25766. nodes.getUnchecked(i)->unprepare();
  25767. renderingBuffers.setSize (1, 1);
  25768. midiBuffers.clear();
  25769. currentAudioInputBuffer = 0;
  25770. currentAudioOutputBuffer.setSize (1, 1);
  25771. currentMidiInputBuffer = 0;
  25772. currentMidiOutputBuffer.clear();
  25773. }
  25774. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  25775. {
  25776. const int numSamples = buffer.getNumSamples();
  25777. const ScopedLock sl (renderLock);
  25778. currentAudioInputBuffer = &buffer;
  25779. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  25780. currentAudioOutputBuffer.clear();
  25781. currentMidiInputBuffer = &midiMessages;
  25782. currentMidiOutputBuffer.clear();
  25783. int i;
  25784. for (i = 0; i < renderingOps.size(); ++i)
  25785. {
  25786. GraphRenderingOps::AudioGraphRenderingOp* const op
  25787. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  25788. op->perform (renderingBuffers, midiBuffers, numSamples);
  25789. }
  25790. for (i = 0; i < buffer.getNumChannels(); ++i)
  25791. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  25792. }
  25793. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  25794. {
  25795. return "Input " + String (channelIndex + 1);
  25796. }
  25797. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  25798. {
  25799. return "Output " + String (channelIndex + 1);
  25800. }
  25801. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  25802. {
  25803. return true;
  25804. }
  25805. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  25806. {
  25807. return true;
  25808. }
  25809. bool AudioProcessorGraph::acceptsMidi() const
  25810. {
  25811. return true;
  25812. }
  25813. bool AudioProcessorGraph::producesMidi() const
  25814. {
  25815. return true;
  25816. }
  25817. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  25818. {
  25819. }
  25820. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  25821. {
  25822. }
  25823. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  25824. : type (type_),
  25825. graph (0)
  25826. {
  25827. }
  25828. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  25829. {
  25830. }
  25831. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  25832. {
  25833. switch (type)
  25834. {
  25835. case audioOutputNode:
  25836. return "Audio Output";
  25837. case audioInputNode:
  25838. return "Audio Input";
  25839. case midiOutputNode:
  25840. return "Midi Output";
  25841. case midiInputNode:
  25842. return "Midi Input";
  25843. default:
  25844. break;
  25845. }
  25846. return String::empty;
  25847. }
  25848. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  25849. {
  25850. d.name = getName();
  25851. d.uid = d.name.hashCode();
  25852. d.category = "I/O devices";
  25853. d.pluginFormatName = "Internal";
  25854. d.manufacturerName = "Raw Material Software";
  25855. d.version = "1.0";
  25856. d.isInstrument = false;
  25857. d.numInputChannels = getNumInputChannels();
  25858. if (type == audioOutputNode && graph != 0)
  25859. d.numInputChannels = graph->getNumInputChannels();
  25860. d.numOutputChannels = getNumOutputChannels();
  25861. if (type == audioInputNode && graph != 0)
  25862. d.numOutputChannels = graph->getNumOutputChannels();
  25863. }
  25864. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  25865. {
  25866. jassert (graph != 0);
  25867. }
  25868. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  25869. {
  25870. }
  25871. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  25872. MidiBuffer& midiMessages)
  25873. {
  25874. jassert (graph != 0);
  25875. switch (type)
  25876. {
  25877. case audioOutputNode:
  25878. {
  25879. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  25880. buffer.getNumChannels()); --i >= 0;)
  25881. {
  25882. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  25883. }
  25884. break;
  25885. }
  25886. case audioInputNode:
  25887. {
  25888. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  25889. buffer.getNumChannels()); --i >= 0;)
  25890. {
  25891. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  25892. }
  25893. break;
  25894. }
  25895. case midiOutputNode:
  25896. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  25897. break;
  25898. case midiInputNode:
  25899. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  25900. break;
  25901. default:
  25902. break;
  25903. }
  25904. }
  25905. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  25906. {
  25907. return type == midiOutputNode;
  25908. }
  25909. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  25910. {
  25911. return type == midiInputNode;
  25912. }
  25913. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  25914. {
  25915. switch (type)
  25916. {
  25917. case audioOutputNode:
  25918. return "Output " + String (channelIndex + 1);
  25919. case midiOutputNode:
  25920. return "Midi Output";
  25921. default:
  25922. break;
  25923. }
  25924. return String::empty;
  25925. }
  25926. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  25927. {
  25928. switch (type)
  25929. {
  25930. case audioInputNode:
  25931. return "Input " + String (channelIndex + 1);
  25932. case midiInputNode:
  25933. return "Midi Input";
  25934. default:
  25935. break;
  25936. }
  25937. return String::empty;
  25938. }
  25939. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  25940. {
  25941. return type == audioInputNode || type == audioOutputNode;
  25942. }
  25943. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  25944. {
  25945. return isInputChannelStereoPair (index);
  25946. }
  25947. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const throw()
  25948. {
  25949. return type == audioInputNode || type == midiInputNode;
  25950. }
  25951. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const throw()
  25952. {
  25953. return type == audioOutputNode || type == midiOutputNode;
  25954. }
  25955. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  25956. {
  25957. return 0;
  25958. }
  25959. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  25960. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  25961. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  25962. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  25963. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  25964. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  25965. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  25966. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  25967. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  25968. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  25969. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  25970. {
  25971. }
  25972. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  25973. {
  25974. }
  25975. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph) throw()
  25976. {
  25977. graph = newGraph;
  25978. if (graph != 0)
  25979. {
  25980. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  25981. type == audioInputNode ? graph->getNumInputChannels() : 0,
  25982. getSampleRate(),
  25983. getBlockSize());
  25984. updateHostDisplay();
  25985. }
  25986. }
  25987. END_JUCE_NAMESPACE
  25988. /********* End of inlined file: juce_AudioProcessorGraph.cpp *********/
  25989. /********* Start of inlined file: juce_AudioProcessorPlayer.cpp *********/
  25990. BEGIN_JUCE_NAMESPACE
  25991. AudioProcessorPlayer::AudioProcessorPlayer()
  25992. : processor (0),
  25993. sampleRate (0),
  25994. blockSize (0),
  25995. isPrepared (false),
  25996. numInputChans (0),
  25997. numOutputChans (0),
  25998. tempBuffer (1, 1)
  25999. {
  26000. }
  26001. AudioProcessorPlayer::~AudioProcessorPlayer()
  26002. {
  26003. setProcessor (0);
  26004. }
  26005. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  26006. {
  26007. if (processor != processorToPlay)
  26008. {
  26009. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  26010. {
  26011. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  26012. sampleRate, blockSize);
  26013. processorToPlay->prepareToPlay (sampleRate, blockSize);
  26014. }
  26015. lock.enter();
  26016. AudioProcessor* const oldOne = isPrepared ? processor : 0;
  26017. processor = processorToPlay;
  26018. isPrepared = true;
  26019. lock.exit();
  26020. if (oldOne != 0)
  26021. oldOne->releaseResources();
  26022. }
  26023. }
  26024. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  26025. int numInputChannels,
  26026. float** outputChannelData,
  26027. int numOutputChannels,
  26028. int numSamples)
  26029. {
  26030. // these should have been prepared by audioDeviceAboutToStart()...
  26031. jassert (sampleRate > 0 && blockSize > 0);
  26032. incomingMidi.clear();
  26033. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  26034. int i, totalNumChans = 0;
  26035. if (numInputChannels > numOutputChannels)
  26036. {
  26037. // if there aren't enough output channels for the number of
  26038. // inputs, we need to create some temporary extra ones (can't
  26039. // use the input data in case it gets written to)
  26040. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  26041. false, false, true);
  26042. for (i = 0; i < numOutputChannels; ++i)
  26043. {
  26044. channels[totalNumChans] = outputChannelData[i];
  26045. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  26046. ++totalNumChans;
  26047. }
  26048. for (i = numOutputChannels; i < numInputChannels; ++i)
  26049. {
  26050. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  26051. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  26052. ++totalNumChans;
  26053. }
  26054. }
  26055. else
  26056. {
  26057. for (i = 0; i < numInputChannels; ++i)
  26058. {
  26059. channels[totalNumChans] = outputChannelData[i];
  26060. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  26061. ++totalNumChans;
  26062. }
  26063. for (i = numInputChannels; i < numOutputChannels; ++i)
  26064. {
  26065. channels[totalNumChans] = outputChannelData[i];
  26066. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  26067. ++totalNumChans;
  26068. }
  26069. }
  26070. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  26071. const ScopedLock sl (lock);
  26072. if (processor != 0)
  26073. processor->processBlock (buffer, incomingMidi);
  26074. }
  26075. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  26076. {
  26077. const ScopedLock sl (lock);
  26078. sampleRate = device->getCurrentSampleRate();
  26079. blockSize = device->getCurrentBufferSizeSamples();
  26080. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  26081. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  26082. messageCollector.reset (sampleRate);
  26083. zeromem (channels, sizeof (channels));
  26084. if (processor != 0)
  26085. {
  26086. if (isPrepared)
  26087. processor->releaseResources();
  26088. AudioProcessor* const oldProcessor = processor;
  26089. setProcessor (0);
  26090. setProcessor (oldProcessor);
  26091. }
  26092. }
  26093. void AudioProcessorPlayer::audioDeviceStopped()
  26094. {
  26095. const ScopedLock sl (lock);
  26096. if (processor != 0 && isPrepared)
  26097. processor->releaseResources();
  26098. sampleRate = 0.0;
  26099. blockSize = 0;
  26100. isPrepared = false;
  26101. tempBuffer.setSize (1, 1);
  26102. }
  26103. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  26104. {
  26105. messageCollector.addMessageToQueue (message);
  26106. }
  26107. END_JUCE_NAMESPACE
  26108. /********* End of inlined file: juce_AudioProcessorPlayer.cpp *********/
  26109. /********* Start of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  26110. BEGIN_JUCE_NAMESPACE
  26111. class ProcessorParameterPropertyComp : public PropertyComponent,
  26112. public AudioProcessorListener,
  26113. public AsyncUpdater
  26114. {
  26115. public:
  26116. ProcessorParameterPropertyComp (const String& name,
  26117. AudioProcessor* const owner_,
  26118. const int index_)
  26119. : PropertyComponent (name),
  26120. owner (owner_),
  26121. index (index_)
  26122. {
  26123. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  26124. owner_->addListener (this);
  26125. }
  26126. ~ProcessorParameterPropertyComp()
  26127. {
  26128. owner->removeListener (this);
  26129. deleteAllChildren();
  26130. }
  26131. void refresh()
  26132. {
  26133. slider->setValue (owner->getParameter (index), false);
  26134. }
  26135. void audioProcessorChanged (AudioProcessor*) {}
  26136. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  26137. {
  26138. if (parameterIndex == index)
  26139. triggerAsyncUpdate();
  26140. }
  26141. void handleAsyncUpdate()
  26142. {
  26143. refresh();
  26144. }
  26145. juce_UseDebuggingNewOperator
  26146. private:
  26147. AudioProcessor* const owner;
  26148. const int index;
  26149. Slider* slider;
  26150. class ParamSlider : public Slider
  26151. {
  26152. public:
  26153. ParamSlider (AudioProcessor* const owner_, const int index_)
  26154. : Slider (String::empty),
  26155. owner (owner_),
  26156. index (index_)
  26157. {
  26158. setRange (0.0, 1.0, 0.0);
  26159. setSliderStyle (Slider::LinearBar);
  26160. setTextBoxIsEditable (false);
  26161. setScrollWheelEnabled (false);
  26162. }
  26163. ~ParamSlider()
  26164. {
  26165. }
  26166. void valueChanged()
  26167. {
  26168. const float newVal = (float) getValue();
  26169. if (owner->getParameter (index) != newVal)
  26170. owner->setParameter (index, newVal);
  26171. }
  26172. const String getTextFromValue (double /*value*/)
  26173. {
  26174. return owner->getParameterText (index);
  26175. }
  26176. juce_UseDebuggingNewOperator
  26177. private:
  26178. AudioProcessor* const owner;
  26179. const int index;
  26180. };
  26181. };
  26182. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner)
  26183. : AudioProcessorEditor (owner)
  26184. {
  26185. setOpaque (true);
  26186. addAndMakeVisible (panel = new PropertyPanel());
  26187. Array <PropertyComponent*> params;
  26188. const int numParams = owner->getNumParameters();
  26189. int totalHeight = 0;
  26190. for (int i = 0; i < numParams; ++i)
  26191. {
  26192. String name (owner->getParameterName (i));
  26193. if (name.trim().isEmpty())
  26194. name = "Unnamed";
  26195. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner, i);
  26196. params.add (pc);
  26197. totalHeight += pc->getPreferredHeight();
  26198. }
  26199. panel->addProperties (params);
  26200. setSize (400, jlimit (25, 400, totalHeight));
  26201. }
  26202. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  26203. {
  26204. deleteAllChildren();
  26205. }
  26206. void GenericAudioProcessorEditor::paint (Graphics& g)
  26207. {
  26208. g.fillAll (Colours::white);
  26209. }
  26210. void GenericAudioProcessorEditor::resized()
  26211. {
  26212. panel->setSize (getWidth(), getHeight());
  26213. }
  26214. END_JUCE_NAMESPACE
  26215. /********* End of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  26216. /********* Start of inlined file: juce_Sampler.cpp *********/
  26217. BEGIN_JUCE_NAMESPACE
  26218. SamplerSound::SamplerSound (const String& name_,
  26219. AudioFormatReader& source,
  26220. const BitArray& midiNotes_,
  26221. const int midiNoteForNormalPitch,
  26222. const double attackTimeSecs,
  26223. const double releaseTimeSecs,
  26224. const double maxSampleLengthSeconds)
  26225. : name (name_),
  26226. midiNotes (midiNotes_),
  26227. midiRootNote (midiNoteForNormalPitch)
  26228. {
  26229. sourceSampleRate = source.sampleRate;
  26230. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  26231. {
  26232. data = 0;
  26233. length = 0;
  26234. attackSamples = 0;
  26235. releaseSamples = 0;
  26236. }
  26237. else
  26238. {
  26239. length = jmin ((int) source.lengthInSamples,
  26240. (int) (maxSampleLengthSeconds * sourceSampleRate));
  26241. data = new AudioSampleBuffer (jmin (2, source.numChannels), length + 4);
  26242. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  26243. attackSamples = roundDoubleToInt (attackTimeSecs * sourceSampleRate);
  26244. releaseSamples = roundDoubleToInt (releaseTimeSecs * sourceSampleRate);
  26245. }
  26246. }
  26247. SamplerSound::~SamplerSound()
  26248. {
  26249. delete data;
  26250. data = 0;
  26251. }
  26252. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  26253. {
  26254. return midiNotes [midiNoteNumber];
  26255. }
  26256. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  26257. {
  26258. return true;
  26259. }
  26260. SamplerVoice::SamplerVoice()
  26261. : pitchRatio (0.0),
  26262. sourceSamplePosition (0.0),
  26263. lgain (0.0f),
  26264. rgain (0.0f),
  26265. isInAttack (false),
  26266. isInRelease (false)
  26267. {
  26268. }
  26269. SamplerVoice::~SamplerVoice()
  26270. {
  26271. }
  26272. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  26273. {
  26274. return dynamic_cast <const SamplerSound*> (sound) != 0;
  26275. }
  26276. void SamplerVoice::startNote (const int midiNoteNumber,
  26277. const float velocity,
  26278. SynthesiserSound* s,
  26279. const int /*currentPitchWheelPosition*/)
  26280. {
  26281. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  26282. jassert (sound != 0); // this object can only play SamplerSounds!
  26283. if (sound != 0)
  26284. {
  26285. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  26286. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  26287. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  26288. sourceSamplePosition = 0.0;
  26289. lgain = velocity;
  26290. rgain = velocity;
  26291. isInAttack = (sound->attackSamples > 0);
  26292. isInRelease = false;
  26293. if (isInAttack)
  26294. {
  26295. attackReleaseLevel = 0.0f;
  26296. attackDelta = (float) (pitchRatio / sound->attackSamples);
  26297. }
  26298. else
  26299. {
  26300. attackReleaseLevel = 1.0f;
  26301. attackDelta = 0.0f;
  26302. }
  26303. if (sound->releaseSamples > 0)
  26304. {
  26305. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  26306. }
  26307. else
  26308. {
  26309. releaseDelta = 0.0f;
  26310. }
  26311. }
  26312. }
  26313. void SamplerVoice::stopNote (const bool allowTailOff)
  26314. {
  26315. if (allowTailOff)
  26316. {
  26317. isInAttack = false;
  26318. isInRelease = true;
  26319. }
  26320. else
  26321. {
  26322. clearCurrentNote();
  26323. }
  26324. }
  26325. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  26326. {
  26327. }
  26328. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  26329. const int /*newValue*/)
  26330. {
  26331. }
  26332. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  26333. {
  26334. const SamplerSound* const playingSound = (SamplerSound*) (SynthesiserSound*) getCurrentlyPlayingSound();
  26335. if (playingSound != 0)
  26336. {
  26337. const float* const inL = playingSound->data->getSampleData (0, 0);
  26338. const float* const inR = playingSound->data->getNumChannels() > 1
  26339. ? playingSound->data->getSampleData (1, 0) : 0;
  26340. float* outL = outputBuffer.getSampleData (0, startSample);
  26341. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  26342. while (--numSamples >= 0)
  26343. {
  26344. const int pos = (int) sourceSamplePosition;
  26345. const float alpha = (float) (sourceSamplePosition - pos);
  26346. const float invAlpha = 1.0f - alpha;
  26347. // just using a very simple linear interpolation here..
  26348. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  26349. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  26350. : l;
  26351. l *= lgain;
  26352. r *= rgain;
  26353. if (isInAttack)
  26354. {
  26355. l *= attackReleaseLevel;
  26356. r *= attackReleaseLevel;
  26357. attackReleaseLevel += attackDelta;
  26358. if (attackReleaseLevel >= 1.0f)
  26359. {
  26360. attackReleaseLevel = 1.0f;
  26361. isInAttack = false;
  26362. }
  26363. }
  26364. else if (isInRelease)
  26365. {
  26366. l *= attackReleaseLevel;
  26367. r *= attackReleaseLevel;
  26368. attackReleaseLevel += releaseDelta;
  26369. if (attackReleaseLevel <= 0.0f)
  26370. {
  26371. stopNote (false);
  26372. break;
  26373. }
  26374. }
  26375. if (outR != 0)
  26376. {
  26377. *outL++ += l;
  26378. *outR++ += r;
  26379. }
  26380. else
  26381. {
  26382. *outL++ += (l + r) * 0.5f;
  26383. }
  26384. sourceSamplePosition += pitchRatio;
  26385. if (sourceSamplePosition > playingSound->length)
  26386. {
  26387. stopNote (false);
  26388. break;
  26389. }
  26390. }
  26391. }
  26392. }
  26393. END_JUCE_NAMESPACE
  26394. /********* End of inlined file: juce_Sampler.cpp *********/
  26395. /********* Start of inlined file: juce_Synthesiser.cpp *********/
  26396. BEGIN_JUCE_NAMESPACE
  26397. SynthesiserSound::SynthesiserSound()
  26398. {
  26399. }
  26400. SynthesiserSound::~SynthesiserSound()
  26401. {
  26402. }
  26403. SynthesiserVoice::SynthesiserVoice()
  26404. : currentSampleRate (44100.0),
  26405. currentlyPlayingNote (-1),
  26406. noteOnTime (0),
  26407. currentlyPlayingSound (0)
  26408. {
  26409. }
  26410. SynthesiserVoice::~SynthesiserVoice()
  26411. {
  26412. }
  26413. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  26414. {
  26415. return currentlyPlayingSound != 0
  26416. && currentlyPlayingSound->appliesToChannel (midiChannel);
  26417. }
  26418. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  26419. {
  26420. currentSampleRate = newRate;
  26421. }
  26422. void SynthesiserVoice::clearCurrentNote()
  26423. {
  26424. currentlyPlayingNote = -1;
  26425. currentlyPlayingSound = 0;
  26426. }
  26427. Synthesiser::Synthesiser()
  26428. : voices (2),
  26429. sounds (2),
  26430. sampleRate (0),
  26431. lastNoteOnCounter (0),
  26432. shouldStealNotes (true)
  26433. {
  26434. zeromem (lastPitchWheelValues, sizeof (lastPitchWheelValues));
  26435. }
  26436. Synthesiser::~Synthesiser()
  26437. {
  26438. }
  26439. SynthesiserVoice* Synthesiser::getVoice (const int index) const throw()
  26440. {
  26441. const ScopedLock sl (lock);
  26442. return voices [index];
  26443. }
  26444. void Synthesiser::clearVoices()
  26445. {
  26446. const ScopedLock sl (lock);
  26447. voices.clear();
  26448. }
  26449. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  26450. {
  26451. const ScopedLock sl (lock);
  26452. voices.add (newVoice);
  26453. }
  26454. void Synthesiser::removeVoice (const int index)
  26455. {
  26456. const ScopedLock sl (lock);
  26457. voices.remove (index);
  26458. }
  26459. void Synthesiser::clearSounds()
  26460. {
  26461. const ScopedLock sl (lock);
  26462. sounds.clear();
  26463. }
  26464. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  26465. {
  26466. const ScopedLock sl (lock);
  26467. sounds.add (newSound);
  26468. }
  26469. void Synthesiser::removeSound (const int index)
  26470. {
  26471. const ScopedLock sl (lock);
  26472. sounds.remove (index);
  26473. }
  26474. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  26475. {
  26476. shouldStealNotes = shouldStealNotes_;
  26477. }
  26478. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  26479. {
  26480. if (sampleRate != newRate)
  26481. {
  26482. const ScopedLock sl (lock);
  26483. allNotesOff (0, false);
  26484. sampleRate = newRate;
  26485. for (int i = voices.size(); --i >= 0;)
  26486. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  26487. }
  26488. }
  26489. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  26490. const MidiBuffer& midiData,
  26491. int startSample,
  26492. int numSamples)
  26493. {
  26494. // must set the sample rate before using this!
  26495. jassert (sampleRate != 0);
  26496. const ScopedLock sl (lock);
  26497. MidiBuffer::Iterator midiIterator (midiData);
  26498. midiIterator.setNextSamplePosition (startSample);
  26499. MidiMessage m (0xf4, 0.0);
  26500. while (numSamples > 0)
  26501. {
  26502. int midiEventPos;
  26503. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  26504. && midiEventPos < startSample + numSamples;
  26505. const int numThisTime = useEvent ? midiEventPos - startSample
  26506. : numSamples;
  26507. if (numThisTime > 0)
  26508. {
  26509. for (int i = voices.size(); --i >= 0;)
  26510. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  26511. }
  26512. if (useEvent)
  26513. {
  26514. if (m.isNoteOn())
  26515. {
  26516. const int channel = m.getChannel();
  26517. noteOn (channel,
  26518. m.getNoteNumber(),
  26519. m.getFloatVelocity());
  26520. }
  26521. else if (m.isNoteOff())
  26522. {
  26523. noteOff (m.getChannel(),
  26524. m.getNoteNumber(),
  26525. true);
  26526. }
  26527. else if (m.isAllNotesOff() || m.isAllSoundOff())
  26528. {
  26529. allNotesOff (m.getChannel(), true);
  26530. }
  26531. else if (m.isPitchWheel())
  26532. {
  26533. const int channel = m.getChannel();
  26534. const int wheelPos = m.getPitchWheelValue();
  26535. lastPitchWheelValues [channel - 1] = wheelPos;
  26536. handlePitchWheel (channel, wheelPos);
  26537. }
  26538. else if (m.isController())
  26539. {
  26540. handleController (m.getChannel(),
  26541. m.getControllerNumber(),
  26542. m.getControllerValue());
  26543. }
  26544. }
  26545. startSample += numThisTime;
  26546. numSamples -= numThisTime;
  26547. }
  26548. }
  26549. void Synthesiser::noteOn (const int midiChannel,
  26550. const int midiNoteNumber,
  26551. const float velocity)
  26552. {
  26553. const ScopedLock sl (lock);
  26554. for (int i = sounds.size(); --i >= 0;)
  26555. {
  26556. SynthesiserSound* const sound = sounds.getUnchecked(i);
  26557. if (sound->appliesToNote (midiNoteNumber)
  26558. && sound->appliesToChannel (midiChannel))
  26559. {
  26560. startVoice (findFreeVoice (sound, shouldStealNotes),
  26561. sound, midiChannel, midiNoteNumber, velocity);
  26562. }
  26563. }
  26564. }
  26565. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  26566. SynthesiserSound* const sound,
  26567. const int midiChannel,
  26568. const int midiNoteNumber,
  26569. const float velocity)
  26570. {
  26571. if (voice != 0 && sound != 0)
  26572. {
  26573. if (voice->currentlyPlayingSound != 0)
  26574. voice->stopNote (false);
  26575. voice->startNote (midiNoteNumber,
  26576. velocity,
  26577. sound,
  26578. lastPitchWheelValues [midiChannel - 1]);
  26579. voice->currentlyPlayingNote = midiNoteNumber;
  26580. voice->noteOnTime = ++lastNoteOnCounter;
  26581. voice->currentlyPlayingSound = sound;
  26582. }
  26583. }
  26584. void Synthesiser::noteOff (const int midiChannel,
  26585. const int midiNoteNumber,
  26586. const bool allowTailOff)
  26587. {
  26588. const ScopedLock sl (lock);
  26589. for (int i = voices.size(); --i >= 0;)
  26590. {
  26591. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26592. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  26593. {
  26594. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  26595. if (sound != 0
  26596. && sound->appliesToNote (midiNoteNumber)
  26597. && sound->appliesToChannel (midiChannel))
  26598. {
  26599. voice->stopNote (allowTailOff);
  26600. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  26601. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  26602. }
  26603. }
  26604. }
  26605. }
  26606. void Synthesiser::allNotesOff (const int midiChannel,
  26607. const bool allowTailOff)
  26608. {
  26609. const ScopedLock sl (lock);
  26610. for (int i = voices.size(); --i >= 0;)
  26611. {
  26612. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26613. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  26614. voice->stopNote (allowTailOff);
  26615. }
  26616. }
  26617. void Synthesiser::handlePitchWheel (const int midiChannel,
  26618. const int wheelValue)
  26619. {
  26620. const ScopedLock sl (lock);
  26621. for (int i = voices.size(); --i >= 0;)
  26622. {
  26623. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26624. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  26625. {
  26626. voice->pitchWheelMoved (wheelValue);
  26627. }
  26628. }
  26629. }
  26630. void Synthesiser::handleController (const int midiChannel,
  26631. const int controllerNumber,
  26632. const int controllerValue)
  26633. {
  26634. const ScopedLock sl (lock);
  26635. for (int i = voices.size(); --i >= 0;)
  26636. {
  26637. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26638. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  26639. voice->controllerMoved (controllerNumber, controllerValue);
  26640. }
  26641. }
  26642. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  26643. const bool stealIfNoneAvailable) const
  26644. {
  26645. const ScopedLock sl (lock);
  26646. for (int i = voices.size(); --i >= 0;)
  26647. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  26648. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  26649. return voices.getUnchecked (i);
  26650. if (stealIfNoneAvailable)
  26651. {
  26652. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  26653. SynthesiserVoice* oldest = 0;
  26654. for (int i = voices.size(); --i >= 0;)
  26655. {
  26656. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26657. if (voice->canPlaySound (soundToPlay)
  26658. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  26659. oldest = voice;
  26660. }
  26661. jassert (oldest != 0);
  26662. return oldest;
  26663. }
  26664. return 0;
  26665. }
  26666. END_JUCE_NAMESPACE
  26667. /********* End of inlined file: juce_Synthesiser.cpp *********/
  26668. /********* Start of inlined file: juce_FileBasedDocument.cpp *********/
  26669. BEGIN_JUCE_NAMESPACE
  26670. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  26671. const String& fileWildcard_,
  26672. const String& openFileDialogTitle_,
  26673. const String& saveFileDialogTitle_)
  26674. : changedSinceSave (false),
  26675. fileExtension (fileExtension_),
  26676. fileWildcard (fileWildcard_),
  26677. openFileDialogTitle (openFileDialogTitle_),
  26678. saveFileDialogTitle (saveFileDialogTitle_)
  26679. {
  26680. }
  26681. FileBasedDocument::~FileBasedDocument()
  26682. {
  26683. }
  26684. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  26685. {
  26686. changedSinceSave = hasChanged;
  26687. }
  26688. void FileBasedDocument::changed()
  26689. {
  26690. changedSinceSave = true;
  26691. sendChangeMessage (this);
  26692. }
  26693. void FileBasedDocument::setFile (const File& newFile)
  26694. {
  26695. if (documentFile != newFile)
  26696. {
  26697. documentFile = newFile;
  26698. changedSinceSave = true;
  26699. }
  26700. }
  26701. bool FileBasedDocument::loadFrom (const File& newFile,
  26702. const bool showMessageOnFailure)
  26703. {
  26704. MouseCursor::showWaitCursor();
  26705. const File oldFile (documentFile);
  26706. documentFile = newFile;
  26707. String error;
  26708. if (newFile.existsAsFile())
  26709. {
  26710. error = loadDocument (newFile);
  26711. if (error.isEmpty())
  26712. {
  26713. setChangedFlag (false);
  26714. MouseCursor::hideWaitCursor();
  26715. setLastDocumentOpened (newFile);
  26716. return true;
  26717. }
  26718. }
  26719. else
  26720. {
  26721. error = "The file doesn't exist";
  26722. }
  26723. documentFile = oldFile;
  26724. MouseCursor::hideWaitCursor();
  26725. if (showMessageOnFailure)
  26726. {
  26727. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  26728. TRANS("Failed to open file..."),
  26729. TRANS("There was an error while trying to load the file:\n\n")
  26730. + newFile.getFullPathName()
  26731. + T("\n\n")
  26732. + error);
  26733. }
  26734. return false;
  26735. }
  26736. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  26737. {
  26738. FileChooser fc (openFileDialogTitle,
  26739. getLastDocumentOpened(),
  26740. fileWildcard);
  26741. if (fc.browseForFileToOpen())
  26742. return loadFrom (fc.getResult(), showMessageOnFailure);
  26743. return false;
  26744. }
  26745. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  26746. const bool showMessageOnFailure)
  26747. {
  26748. return saveAs (documentFile,
  26749. false,
  26750. askUserForFileIfNotSpecified,
  26751. showMessageOnFailure);
  26752. }
  26753. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  26754. const bool warnAboutOverwritingExistingFiles,
  26755. const bool askUserForFileIfNotSpecified,
  26756. const bool showMessageOnFailure)
  26757. {
  26758. if (newFile == File::nonexistent)
  26759. {
  26760. if (askUserForFileIfNotSpecified)
  26761. {
  26762. return saveAsInteractive (true);
  26763. }
  26764. else
  26765. {
  26766. // can't save to an unspecified file
  26767. jassertfalse
  26768. return failedToWriteToFile;
  26769. }
  26770. }
  26771. if (warnAboutOverwritingExistingFiles && newFile.exists())
  26772. {
  26773. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  26774. TRANS("File already exists"),
  26775. TRANS("There's already a file called:\n\n")
  26776. + newFile.getFullPathName()
  26777. + TRANS("\n\nAre you sure you want to overwrite it?"),
  26778. TRANS("overwrite"),
  26779. TRANS("cancel")))
  26780. {
  26781. return userCancelledSave;
  26782. }
  26783. }
  26784. MouseCursor::showWaitCursor();
  26785. const File oldFile (documentFile);
  26786. documentFile = newFile;
  26787. String error (saveDocument (newFile));
  26788. if (error.isEmpty())
  26789. {
  26790. setChangedFlag (false);
  26791. MouseCursor::hideWaitCursor();
  26792. return savedOk;
  26793. }
  26794. documentFile = oldFile;
  26795. MouseCursor::hideWaitCursor();
  26796. if (showMessageOnFailure)
  26797. {
  26798. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  26799. TRANS("Error writing to file..."),
  26800. TRANS("An error occurred while trying to save \"")
  26801. + getDocumentTitle()
  26802. + TRANS("\" to the file:\n\n")
  26803. + newFile.getFullPathName()
  26804. + T("\n\n")
  26805. + error);
  26806. }
  26807. return failedToWriteToFile;
  26808. }
  26809. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  26810. {
  26811. if (! hasChangedSinceSaved())
  26812. return savedOk;
  26813. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  26814. TRANS("Closing document..."),
  26815. TRANS("Do you want to save the changes to \"")
  26816. + getDocumentTitle() + T("\"?"),
  26817. TRANS("save"),
  26818. TRANS("discard changes"),
  26819. TRANS("cancel"));
  26820. if (r == 1)
  26821. {
  26822. // save changes
  26823. return save (true, true);
  26824. }
  26825. else if (r == 2)
  26826. {
  26827. // discard changes
  26828. return savedOk;
  26829. }
  26830. return userCancelledSave;
  26831. }
  26832. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  26833. {
  26834. File f;
  26835. if (documentFile.existsAsFile())
  26836. f = documentFile;
  26837. else
  26838. f = getLastDocumentOpened();
  26839. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  26840. if (legalFilename.isEmpty())
  26841. legalFilename = "unnamed";
  26842. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  26843. f = f.getSiblingFile (legalFilename);
  26844. else
  26845. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  26846. f = f.withFileExtension (fileExtension)
  26847. .getNonexistentSibling (true);
  26848. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  26849. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  26850. {
  26851. setLastDocumentOpened (fc.getResult());
  26852. File chosen (fc.getResult());
  26853. if (chosen.getFileExtension().isEmpty())
  26854. chosen = chosen.withFileExtension (fileExtension);
  26855. return saveAs (chosen, false, false, true);
  26856. }
  26857. return userCancelledSave;
  26858. }
  26859. END_JUCE_NAMESPACE
  26860. /********* End of inlined file: juce_FileBasedDocument.cpp *********/
  26861. /********* Start of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  26862. BEGIN_JUCE_NAMESPACE
  26863. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  26864. : maxNumberOfItems (10)
  26865. {
  26866. }
  26867. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  26868. {
  26869. }
  26870. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  26871. {
  26872. maxNumberOfItems = jmax (1, newMaxNumber);
  26873. while (getNumFiles() > maxNumberOfItems)
  26874. files.remove (getNumFiles() - 1);
  26875. }
  26876. int RecentlyOpenedFilesList::getNumFiles() const
  26877. {
  26878. return files.size();
  26879. }
  26880. const File RecentlyOpenedFilesList::getFile (const int index) const
  26881. {
  26882. return File (files [index]);
  26883. }
  26884. void RecentlyOpenedFilesList::clear()
  26885. {
  26886. files.clear();
  26887. }
  26888. void RecentlyOpenedFilesList::addFile (const File& file)
  26889. {
  26890. const String path (file.getFullPathName());
  26891. files.removeString (path, true);
  26892. files.insert (0, path);
  26893. setMaxNumberOfItems (maxNumberOfItems);
  26894. }
  26895. void RecentlyOpenedFilesList::removeNonExistentFiles()
  26896. {
  26897. for (int i = getNumFiles(); --i >= 0;)
  26898. if (! getFile(i).exists())
  26899. files.remove (i);
  26900. }
  26901. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  26902. const int baseItemId,
  26903. const bool showFullPaths,
  26904. const bool dontAddNonExistentFiles,
  26905. const File** filesToAvoid)
  26906. {
  26907. int num = 0;
  26908. for (int i = 0; i < getNumFiles(); ++i)
  26909. {
  26910. const File f (getFile(i));
  26911. if ((! dontAddNonExistentFiles) || f.exists())
  26912. {
  26913. bool needsAvoiding = false;
  26914. if (filesToAvoid != 0)
  26915. {
  26916. const File** files = filesToAvoid;
  26917. while (*files != 0)
  26918. {
  26919. if (f == **files)
  26920. {
  26921. needsAvoiding = true;
  26922. break;
  26923. }
  26924. ++files;
  26925. }
  26926. }
  26927. if (! needsAvoiding)
  26928. {
  26929. menuToAddTo.addItem (baseItemId + i,
  26930. showFullPaths ? f.getFullPathName()
  26931. : f.getFileName());
  26932. ++num;
  26933. }
  26934. }
  26935. }
  26936. return num;
  26937. }
  26938. const String RecentlyOpenedFilesList::toString() const
  26939. {
  26940. return files.joinIntoString (T("\n"));
  26941. }
  26942. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  26943. {
  26944. clear();
  26945. files.addLines (stringifiedVersion);
  26946. setMaxNumberOfItems (maxNumberOfItems);
  26947. }
  26948. END_JUCE_NAMESPACE
  26949. /********* End of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  26950. /********* Start of inlined file: juce_UndoManager.cpp *********/
  26951. BEGIN_JUCE_NAMESPACE
  26952. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  26953. const int minimumTransactions)
  26954. : totalUnitsStored (0),
  26955. nextIndex (0),
  26956. newTransaction (true),
  26957. reentrancyCheck (false)
  26958. {
  26959. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  26960. minimumTransactions);
  26961. }
  26962. UndoManager::~UndoManager()
  26963. {
  26964. clearUndoHistory();
  26965. }
  26966. void UndoManager::clearUndoHistory()
  26967. {
  26968. transactions.clear();
  26969. transactionNames.clear();
  26970. totalUnitsStored = 0;
  26971. nextIndex = 0;
  26972. sendChangeMessage (this);
  26973. }
  26974. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  26975. {
  26976. return totalUnitsStored;
  26977. }
  26978. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  26979. const int minimumTransactions)
  26980. {
  26981. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  26982. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  26983. }
  26984. bool UndoManager::perform (UndoableAction* const command, const String& actionName)
  26985. {
  26986. if (command != 0)
  26987. {
  26988. if (actionName.isNotEmpty())
  26989. currentTransactionName = actionName;
  26990. if (reentrancyCheck)
  26991. {
  26992. jassertfalse // don't call perform() recursively from the UndoableAction::perform() or
  26993. // undo() methods, or else these actions won't actually get done.
  26994. return false;
  26995. }
  26996. else
  26997. {
  26998. bool success = false;
  26999. JUCE_TRY
  27000. {
  27001. success = command->perform();
  27002. }
  27003. JUCE_CATCH_EXCEPTION
  27004. jassert (success);
  27005. if (success)
  27006. {
  27007. if (nextIndex > 0 && ! newTransaction)
  27008. {
  27009. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  27010. jassert (commandSet != 0);
  27011. if (commandSet == 0)
  27012. return false;
  27013. commandSet->add (command);
  27014. }
  27015. else
  27016. {
  27017. OwnedArray<UndoableAction>* commandSet = new OwnedArray<UndoableAction>();
  27018. commandSet->add (command);
  27019. transactions.insert (nextIndex, commandSet);
  27020. transactionNames.insert (nextIndex, currentTransactionName);
  27021. ++nextIndex;
  27022. }
  27023. totalUnitsStored += command->getSizeInUnits();
  27024. newTransaction = false;
  27025. }
  27026. while (nextIndex < transactions.size())
  27027. {
  27028. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  27029. for (int i = lastSet->size(); --i >= 0;)
  27030. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  27031. transactions.removeLast();
  27032. transactionNames.remove (transactionNames.size() - 1);
  27033. }
  27034. while (nextIndex > 0
  27035. && totalUnitsStored > maxNumUnitsToKeep
  27036. && transactions.size() > minimumTransactionsToKeep)
  27037. {
  27038. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  27039. for (int i = firstSet->size(); --i >= 0;)
  27040. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  27041. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  27042. transactions.remove (0);
  27043. transactionNames.remove (0);
  27044. --nextIndex;
  27045. }
  27046. sendChangeMessage (this);
  27047. return success;
  27048. }
  27049. }
  27050. return false;
  27051. }
  27052. void UndoManager::beginNewTransaction (const String& actionName)
  27053. {
  27054. newTransaction = true;
  27055. currentTransactionName = actionName;
  27056. }
  27057. void UndoManager::setCurrentTransactionName (const String& newName)
  27058. {
  27059. currentTransactionName = newName;
  27060. }
  27061. bool UndoManager::canUndo() const
  27062. {
  27063. return nextIndex > 0;
  27064. }
  27065. bool UndoManager::canRedo() const
  27066. {
  27067. return nextIndex < transactions.size();
  27068. }
  27069. const String UndoManager::getUndoDescription() const
  27070. {
  27071. return transactionNames [nextIndex - 1];
  27072. }
  27073. const String UndoManager::getRedoDescription() const
  27074. {
  27075. return transactionNames [nextIndex];
  27076. }
  27077. bool UndoManager::undo()
  27078. {
  27079. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  27080. if (commandSet == 0)
  27081. return false;
  27082. reentrancyCheck = true;
  27083. bool failed = false;
  27084. for (int i = commandSet->size(); --i >= 0;)
  27085. {
  27086. if (! commandSet->getUnchecked(i)->undo())
  27087. {
  27088. jassertfalse
  27089. failed = true;
  27090. break;
  27091. }
  27092. }
  27093. reentrancyCheck = false;
  27094. if (failed)
  27095. {
  27096. clearUndoHistory();
  27097. }
  27098. else
  27099. {
  27100. --nextIndex;
  27101. }
  27102. beginNewTransaction();
  27103. sendChangeMessage (this);
  27104. return true;
  27105. }
  27106. bool UndoManager::redo()
  27107. {
  27108. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  27109. if (commandSet == 0)
  27110. return false;
  27111. reentrancyCheck = true;
  27112. bool failed = false;
  27113. for (int i = 0; i < commandSet->size(); ++i)
  27114. {
  27115. if (! commandSet->getUnchecked(i)->perform())
  27116. {
  27117. jassertfalse
  27118. failed = true;
  27119. break;
  27120. }
  27121. }
  27122. reentrancyCheck = false;
  27123. if (failed)
  27124. {
  27125. clearUndoHistory();
  27126. }
  27127. else
  27128. {
  27129. ++nextIndex;
  27130. }
  27131. beginNewTransaction();
  27132. sendChangeMessage (this);
  27133. return true;
  27134. }
  27135. bool UndoManager::undoCurrentTransactionOnly()
  27136. {
  27137. return newTransaction ? false
  27138. : undo();
  27139. }
  27140. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  27141. {
  27142. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  27143. if (commandSet != 0 && ! newTransaction)
  27144. {
  27145. for (int i = 0; i < commandSet->size(); ++i)
  27146. actionsFound.add (commandSet->getUnchecked(i));
  27147. }
  27148. }
  27149. END_JUCE_NAMESPACE
  27150. /********* End of inlined file: juce_UndoManager.cpp *********/
  27151. /********* Start of inlined file: juce_ActionBroadcaster.cpp *********/
  27152. BEGIN_JUCE_NAMESPACE
  27153. ActionBroadcaster::ActionBroadcaster() throw()
  27154. {
  27155. // are you trying to create this object before or after juce has been intialised??
  27156. jassert (MessageManager::instance != 0);
  27157. }
  27158. ActionBroadcaster::~ActionBroadcaster()
  27159. {
  27160. // all event-based objects must be deleted BEFORE juce is shut down!
  27161. jassert (MessageManager::instance != 0);
  27162. }
  27163. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  27164. {
  27165. actionListenerList.addActionListener (listener);
  27166. }
  27167. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  27168. {
  27169. jassert (actionListenerList.isValidMessageListener());
  27170. if (actionListenerList.isValidMessageListener())
  27171. actionListenerList.removeActionListener (listener);
  27172. }
  27173. void ActionBroadcaster::removeAllActionListeners()
  27174. {
  27175. actionListenerList.removeAllActionListeners();
  27176. }
  27177. void ActionBroadcaster::sendActionMessage (const String& message) const
  27178. {
  27179. actionListenerList.sendActionMessage (message);
  27180. }
  27181. END_JUCE_NAMESPACE
  27182. /********* End of inlined file: juce_ActionBroadcaster.cpp *********/
  27183. /********* Start of inlined file: juce_ActionListenerList.cpp *********/
  27184. BEGIN_JUCE_NAMESPACE
  27185. // special message of our own with a string in it
  27186. class ActionMessage : public Message
  27187. {
  27188. public:
  27189. const String message;
  27190. ActionMessage (const String& messageText,
  27191. void* const listener_) throw()
  27192. : message (messageText)
  27193. {
  27194. pointerParameter = listener_;
  27195. }
  27196. ~ActionMessage() throw()
  27197. {
  27198. }
  27199. private:
  27200. ActionMessage (const ActionMessage&);
  27201. const ActionMessage& operator= (const ActionMessage&);
  27202. };
  27203. ActionListenerList::ActionListenerList() throw()
  27204. {
  27205. }
  27206. ActionListenerList::~ActionListenerList() throw()
  27207. {
  27208. }
  27209. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  27210. {
  27211. const ScopedLock sl (actionListenerLock_);
  27212. jassert (listener != 0);
  27213. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  27214. if (listener != 0)
  27215. actionListeners_.add (listener);
  27216. }
  27217. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  27218. {
  27219. const ScopedLock sl (actionListenerLock_);
  27220. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  27221. actionListeners_.removeValue (listener);
  27222. }
  27223. void ActionListenerList::removeAllActionListeners() throw()
  27224. {
  27225. const ScopedLock sl (actionListenerLock_);
  27226. actionListeners_.clear();
  27227. }
  27228. void ActionListenerList::sendActionMessage (const String& message) const
  27229. {
  27230. const ScopedLock sl (actionListenerLock_);
  27231. for (int i = actionListeners_.size(); --i >= 0;)
  27232. {
  27233. postMessage (new ActionMessage (message,
  27234. (ActionListener*) actionListeners_.getUnchecked(i)));
  27235. }
  27236. }
  27237. void ActionListenerList::handleMessage (const Message& message)
  27238. {
  27239. const ActionMessage& am = (const ActionMessage&) message;
  27240. if (actionListeners_.contains (am.pointerParameter))
  27241. ((ActionListener*) am.pointerParameter)->actionListenerCallback (am.message);
  27242. }
  27243. END_JUCE_NAMESPACE
  27244. /********* End of inlined file: juce_ActionListenerList.cpp *********/
  27245. /********* Start of inlined file: juce_AsyncUpdater.cpp *********/
  27246. BEGIN_JUCE_NAMESPACE
  27247. AsyncUpdater::AsyncUpdater() throw()
  27248. : asyncMessagePending (false)
  27249. {
  27250. internalAsyncHandler.owner = this;
  27251. }
  27252. AsyncUpdater::~AsyncUpdater()
  27253. {
  27254. }
  27255. void AsyncUpdater::triggerAsyncUpdate() throw()
  27256. {
  27257. if (! asyncMessagePending)
  27258. {
  27259. asyncMessagePending = true;
  27260. internalAsyncHandler.postMessage (new Message());
  27261. }
  27262. }
  27263. void AsyncUpdater::cancelPendingUpdate() throw()
  27264. {
  27265. asyncMessagePending = false;
  27266. }
  27267. void AsyncUpdater::handleUpdateNowIfNeeded()
  27268. {
  27269. if (asyncMessagePending)
  27270. {
  27271. asyncMessagePending = false;
  27272. handleAsyncUpdate();
  27273. }
  27274. }
  27275. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  27276. {
  27277. owner->handleUpdateNowIfNeeded();
  27278. }
  27279. END_JUCE_NAMESPACE
  27280. /********* End of inlined file: juce_AsyncUpdater.cpp *********/
  27281. /********* Start of inlined file: juce_ChangeBroadcaster.cpp *********/
  27282. BEGIN_JUCE_NAMESPACE
  27283. ChangeBroadcaster::ChangeBroadcaster() throw()
  27284. {
  27285. // are you trying to create this object before or after juce has been intialised??
  27286. jassert (MessageManager::instance != 0);
  27287. }
  27288. ChangeBroadcaster::~ChangeBroadcaster()
  27289. {
  27290. // all event-based objects must be deleted BEFORE juce is shut down!
  27291. jassert (MessageManager::instance != 0);
  27292. }
  27293. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  27294. {
  27295. changeListenerList.addChangeListener (listener);
  27296. }
  27297. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  27298. {
  27299. jassert (changeListenerList.isValidMessageListener());
  27300. if (changeListenerList.isValidMessageListener())
  27301. changeListenerList.removeChangeListener (listener);
  27302. }
  27303. void ChangeBroadcaster::removeAllChangeListeners() throw()
  27304. {
  27305. changeListenerList.removeAllChangeListeners();
  27306. }
  27307. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  27308. {
  27309. changeListenerList.sendChangeMessage (objectThatHasChanged);
  27310. }
  27311. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  27312. {
  27313. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  27314. }
  27315. void ChangeBroadcaster::dispatchPendingMessages()
  27316. {
  27317. changeListenerList.dispatchPendingMessages();
  27318. }
  27319. END_JUCE_NAMESPACE
  27320. /********* End of inlined file: juce_ChangeBroadcaster.cpp *********/
  27321. /********* Start of inlined file: juce_ChangeListenerList.cpp *********/
  27322. BEGIN_JUCE_NAMESPACE
  27323. ChangeListenerList::ChangeListenerList() throw()
  27324. : lastChangedObject (0),
  27325. messagePending (false)
  27326. {
  27327. }
  27328. ChangeListenerList::~ChangeListenerList() throw()
  27329. {
  27330. }
  27331. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  27332. {
  27333. const ScopedLock sl (lock);
  27334. jassert (listener != 0);
  27335. if (listener != 0)
  27336. listeners.add (listener);
  27337. }
  27338. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  27339. {
  27340. const ScopedLock sl (lock);
  27341. listeners.removeValue (listener);
  27342. }
  27343. void ChangeListenerList::removeAllChangeListeners() throw()
  27344. {
  27345. const ScopedLock sl (lock);
  27346. listeners.clear();
  27347. }
  27348. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  27349. {
  27350. const ScopedLock sl (lock);
  27351. if ((! messagePending) && (listeners.size() > 0))
  27352. {
  27353. lastChangedObject = objectThatHasChanged;
  27354. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  27355. messagePending = true;
  27356. }
  27357. }
  27358. void ChangeListenerList::handleMessage (const Message& message)
  27359. {
  27360. sendSynchronousChangeMessage (message.pointerParameter);
  27361. }
  27362. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  27363. {
  27364. const ScopedLock sl (lock);
  27365. messagePending = false;
  27366. for (int i = listeners.size(); --i >= 0;)
  27367. {
  27368. ChangeListener* const l = (ChangeListener*) listeners.getUnchecked (i);
  27369. {
  27370. const ScopedUnlock tempUnlocker (lock);
  27371. l->changeListenerCallback (objectThatHasChanged);
  27372. }
  27373. i = jmin (i, listeners.size());
  27374. }
  27375. }
  27376. void ChangeListenerList::dispatchPendingMessages()
  27377. {
  27378. if (messagePending)
  27379. sendSynchronousChangeMessage (lastChangedObject);
  27380. }
  27381. END_JUCE_NAMESPACE
  27382. /********* End of inlined file: juce_ChangeListenerList.cpp *********/
  27383. /********* Start of inlined file: juce_InterprocessConnection.cpp *********/
  27384. BEGIN_JUCE_NAMESPACE
  27385. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  27386. const uint32 magicMessageHeaderNumber)
  27387. : Thread ("Juce IPC connection"),
  27388. socket (0),
  27389. pipe (0),
  27390. callbackConnectionState (false),
  27391. useMessageThread (callbacksOnMessageThread),
  27392. magicMessageHeader (magicMessageHeaderNumber),
  27393. pipeReceiveMessageTimeout (-1)
  27394. {
  27395. }
  27396. InterprocessConnection::~InterprocessConnection()
  27397. {
  27398. callbackConnectionState = false;
  27399. disconnect();
  27400. }
  27401. bool InterprocessConnection::connectToSocket (const String& hostName,
  27402. const int portNumber,
  27403. const int timeOutMillisecs)
  27404. {
  27405. disconnect();
  27406. const ScopedLock sl (pipeAndSocketLock);
  27407. socket = new StreamingSocket();
  27408. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  27409. {
  27410. connectionMadeInt();
  27411. startThread();
  27412. return true;
  27413. }
  27414. else
  27415. {
  27416. deleteAndZero (socket);
  27417. return false;
  27418. }
  27419. }
  27420. bool InterprocessConnection::connectToPipe (const String& pipeName,
  27421. const int pipeReceiveMessageTimeoutMs)
  27422. {
  27423. disconnect();
  27424. NamedPipe* const newPipe = new NamedPipe();
  27425. if (newPipe->openExisting (pipeName))
  27426. {
  27427. const ScopedLock sl (pipeAndSocketLock);
  27428. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  27429. initialiseWithPipe (newPipe);
  27430. return true;
  27431. }
  27432. else
  27433. {
  27434. delete newPipe;
  27435. return false;
  27436. }
  27437. }
  27438. bool InterprocessConnection::createPipe (const String& pipeName,
  27439. const int pipeReceiveMessageTimeoutMs)
  27440. {
  27441. disconnect();
  27442. NamedPipe* const newPipe = new NamedPipe();
  27443. if (newPipe->createNewPipe (pipeName))
  27444. {
  27445. const ScopedLock sl (pipeAndSocketLock);
  27446. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  27447. initialiseWithPipe (newPipe);
  27448. return true;
  27449. }
  27450. else
  27451. {
  27452. delete newPipe;
  27453. return false;
  27454. }
  27455. }
  27456. void InterprocessConnection::disconnect()
  27457. {
  27458. if (socket != 0)
  27459. socket->close();
  27460. if (pipe != 0)
  27461. {
  27462. pipe->cancelPendingReads();
  27463. pipe->close();
  27464. }
  27465. stopThread (4000);
  27466. {
  27467. const ScopedLock sl (pipeAndSocketLock);
  27468. deleteAndZero (socket);
  27469. deleteAndZero (pipe);
  27470. }
  27471. connectionLostInt();
  27472. }
  27473. bool InterprocessConnection::isConnected() const
  27474. {
  27475. const ScopedLock sl (pipeAndSocketLock);
  27476. return ((socket != 0 && socket->isConnected())
  27477. || (pipe != 0 && pipe->isOpen()))
  27478. && isThreadRunning();
  27479. }
  27480. const String InterprocessConnection::getConnectedHostName() const
  27481. {
  27482. if (pipe != 0)
  27483. {
  27484. return "localhost";
  27485. }
  27486. else if (socket != 0)
  27487. {
  27488. if (! socket->isLocal())
  27489. return socket->getHostName();
  27490. return "localhost";
  27491. }
  27492. return String::empty;
  27493. }
  27494. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  27495. {
  27496. uint32 messageHeader[2];
  27497. messageHeader [0] = swapIfBigEndian (magicMessageHeader);
  27498. messageHeader [1] = swapIfBigEndian ((uint32) message.getSize());
  27499. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  27500. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  27501. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  27502. int bytesWritten = 0;
  27503. const ScopedLock sl (pipeAndSocketLock);
  27504. if (socket != 0)
  27505. {
  27506. bytesWritten = socket->write (messageData.getData(), messageData.getSize());
  27507. }
  27508. else if (pipe != 0)
  27509. {
  27510. bytesWritten = pipe->write (messageData.getData(), messageData.getSize());
  27511. }
  27512. if (bytesWritten < 0)
  27513. {
  27514. // error..
  27515. return false;
  27516. }
  27517. return (bytesWritten == messageData.getSize());
  27518. }
  27519. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  27520. {
  27521. jassert (socket == 0);
  27522. socket = socket_;
  27523. connectionMadeInt();
  27524. startThread();
  27525. }
  27526. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  27527. {
  27528. jassert (pipe == 0);
  27529. pipe = pipe_;
  27530. connectionMadeInt();
  27531. startThread();
  27532. }
  27533. const int messageMagicNumber = 0xb734128b;
  27534. void InterprocessConnection::handleMessage (const Message& message)
  27535. {
  27536. if (message.intParameter1 == messageMagicNumber)
  27537. {
  27538. switch (message.intParameter2)
  27539. {
  27540. case 0:
  27541. {
  27542. MemoryBlock* const data = (MemoryBlock*) message.pointerParameter;
  27543. messageReceived (*data);
  27544. delete data;
  27545. break;
  27546. }
  27547. case 1:
  27548. connectionMade();
  27549. break;
  27550. case 2:
  27551. connectionLost();
  27552. break;
  27553. }
  27554. }
  27555. }
  27556. void InterprocessConnection::connectionMadeInt()
  27557. {
  27558. if (! callbackConnectionState)
  27559. {
  27560. callbackConnectionState = true;
  27561. if (useMessageThread)
  27562. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  27563. else
  27564. connectionMade();
  27565. }
  27566. }
  27567. void InterprocessConnection::connectionLostInt()
  27568. {
  27569. if (callbackConnectionState)
  27570. {
  27571. callbackConnectionState = false;
  27572. if (useMessageThread)
  27573. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  27574. else
  27575. connectionLost();
  27576. }
  27577. }
  27578. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  27579. {
  27580. jassert (callbackConnectionState);
  27581. if (useMessageThread)
  27582. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  27583. else
  27584. messageReceived (data);
  27585. }
  27586. bool InterprocessConnection::readNextMessageInt()
  27587. {
  27588. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  27589. uint32 messageHeader[2];
  27590. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader))
  27591. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  27592. if (bytes == sizeof (messageHeader)
  27593. && swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  27594. {
  27595. const int bytesInMessage = (int) swapIfBigEndian (messageHeader[1]);
  27596. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  27597. {
  27598. MemoryBlock messageData (bytesInMessage, true);
  27599. int bytesRead = 0;
  27600. while (bytesRead < bytesInMessage)
  27601. {
  27602. if (threadShouldExit())
  27603. return false;
  27604. const int numThisTime = jmin (bytesInMessage, 65536);
  27605. const int bytesIn = (socket != 0) ? socket->read (((char*) messageData.getData()) + bytesRead, numThisTime)
  27606. : pipe->read (((char*) messageData.getData()) + bytesRead, numThisTime,
  27607. pipeReceiveMessageTimeout);
  27608. if (bytesIn <= 0)
  27609. break;
  27610. bytesRead += bytesIn;
  27611. }
  27612. if (bytesRead >= 0)
  27613. deliverDataInt (messageData);
  27614. }
  27615. }
  27616. else if (bytes < 0)
  27617. {
  27618. {
  27619. const ScopedLock sl (pipeAndSocketLock);
  27620. deleteAndZero (socket);
  27621. }
  27622. connectionLostInt();
  27623. return false;
  27624. }
  27625. return true;
  27626. }
  27627. void InterprocessConnection::run()
  27628. {
  27629. while (! threadShouldExit())
  27630. {
  27631. if (socket != 0)
  27632. {
  27633. const int ready = socket->waitUntilReady (true, 0);
  27634. if (ready < 0)
  27635. {
  27636. {
  27637. const ScopedLock sl (pipeAndSocketLock);
  27638. deleteAndZero (socket);
  27639. }
  27640. connectionLostInt();
  27641. break;
  27642. }
  27643. else if (ready > 0)
  27644. {
  27645. if (! readNextMessageInt())
  27646. break;
  27647. }
  27648. else
  27649. {
  27650. Thread::sleep (2);
  27651. }
  27652. }
  27653. else if (pipe != 0)
  27654. {
  27655. if (! pipe->isOpen())
  27656. {
  27657. {
  27658. const ScopedLock sl (pipeAndSocketLock);
  27659. deleteAndZero (pipe);
  27660. }
  27661. connectionLostInt();
  27662. break;
  27663. }
  27664. else
  27665. {
  27666. if (! readNextMessageInt())
  27667. break;
  27668. }
  27669. }
  27670. else
  27671. {
  27672. break;
  27673. }
  27674. }
  27675. }
  27676. END_JUCE_NAMESPACE
  27677. /********* End of inlined file: juce_InterprocessConnection.cpp *********/
  27678. /********* Start of inlined file: juce_InterprocessConnectionServer.cpp *********/
  27679. BEGIN_JUCE_NAMESPACE
  27680. InterprocessConnectionServer::InterprocessConnectionServer()
  27681. : Thread ("Juce IPC server"),
  27682. socket (0)
  27683. {
  27684. }
  27685. InterprocessConnectionServer::~InterprocessConnectionServer()
  27686. {
  27687. stop();
  27688. }
  27689. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  27690. {
  27691. stop();
  27692. socket = new StreamingSocket();
  27693. if (socket->createListener (portNumber))
  27694. {
  27695. startThread();
  27696. return true;
  27697. }
  27698. deleteAndZero (socket);
  27699. return false;
  27700. }
  27701. void InterprocessConnectionServer::stop()
  27702. {
  27703. signalThreadShouldExit();
  27704. if (socket != 0)
  27705. socket->close();
  27706. stopThread (4000);
  27707. deleteAndZero (socket);
  27708. }
  27709. void InterprocessConnectionServer::run()
  27710. {
  27711. while ((! threadShouldExit()) && socket != 0)
  27712. {
  27713. StreamingSocket* const clientSocket = socket->waitForNextConnection();
  27714. if (clientSocket != 0)
  27715. {
  27716. InterprocessConnection* newConnection = createConnectionObject();
  27717. if (newConnection != 0)
  27718. {
  27719. newConnection->initialiseWithSocket (clientSocket);
  27720. }
  27721. else
  27722. {
  27723. delete clientSocket;
  27724. }
  27725. }
  27726. }
  27727. }
  27728. END_JUCE_NAMESPACE
  27729. /********* End of inlined file: juce_InterprocessConnectionServer.cpp *********/
  27730. /********* Start of inlined file: juce_Message.cpp *********/
  27731. BEGIN_JUCE_NAMESPACE
  27732. Message::Message() throw()
  27733. {
  27734. }
  27735. Message::~Message() throw()
  27736. {
  27737. }
  27738. Message::Message (const int intParameter1_,
  27739. const int intParameter2_,
  27740. const int intParameter3_,
  27741. void* const pointerParameter_) throw()
  27742. : intParameter1 (intParameter1_),
  27743. intParameter2 (intParameter2_),
  27744. intParameter3 (intParameter3_),
  27745. pointerParameter (pointerParameter_)
  27746. {
  27747. }
  27748. END_JUCE_NAMESPACE
  27749. /********* End of inlined file: juce_Message.cpp *********/
  27750. /********* Start of inlined file: juce_MessageListener.cpp *********/
  27751. BEGIN_JUCE_NAMESPACE
  27752. MessageListener::MessageListener() throw()
  27753. {
  27754. // are you trying to create a messagelistener before or after juce has been intialised??
  27755. jassert (MessageManager::instance != 0);
  27756. if (MessageManager::instance != 0)
  27757. MessageManager::instance->messageListeners.add (this);
  27758. }
  27759. MessageListener::~MessageListener()
  27760. {
  27761. if (MessageManager::instance != 0)
  27762. MessageManager::instance->messageListeners.removeValue (this);
  27763. }
  27764. void MessageListener::postMessage (Message* const message) const throw()
  27765. {
  27766. message->messageRecipient = const_cast <MessageListener*> (this);
  27767. if (MessageManager::instance == 0)
  27768. MessageManager::getInstance();
  27769. MessageManager::instance->postMessageToQueue (message);
  27770. }
  27771. bool MessageListener::isValidMessageListener() const throw()
  27772. {
  27773. return (MessageManager::instance != 0)
  27774. && MessageManager::instance->messageListeners.contains (this);
  27775. }
  27776. END_JUCE_NAMESPACE
  27777. /********* End of inlined file: juce_MessageListener.cpp *********/
  27778. /********* Start of inlined file: juce_MessageManager.cpp *********/
  27779. BEGIN_JUCE_NAMESPACE
  27780. // platform-specific functions..
  27781. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  27782. bool juce_postMessageToSystemQueue (void* message);
  27783. MessageManager* MessageManager::instance = 0;
  27784. static const int quitMessageId = 0xfffff321;
  27785. MessageManager::MessageManager() throw()
  27786. : broadcastListeners (0),
  27787. quitMessagePosted (false),
  27788. quitMessageReceived (false),
  27789. useMaximumForceWhenQuitting (true),
  27790. messageCounter (0),
  27791. lastMessageCounter (-1),
  27792. isInMessageDispatcher (0),
  27793. needToGetRidOfWaitCursor (false),
  27794. timeBeforeWaitCursor (0),
  27795. lastActivityCheckOkTime (0)
  27796. {
  27797. currentLockingThreadId = messageThreadId = Thread::getCurrentThreadId();
  27798. }
  27799. MessageManager::~MessageManager() throw()
  27800. {
  27801. jassert (instance == this);
  27802. instance = 0;
  27803. deleteAndZero (broadcastListeners);
  27804. doPlatformSpecificShutdown();
  27805. }
  27806. MessageManager* MessageManager::getInstance() throw()
  27807. {
  27808. if (instance == 0)
  27809. {
  27810. instance = new MessageManager();
  27811. doPlatformSpecificInitialisation();
  27812. instance->setTimeBeforeShowingWaitCursor (500);
  27813. }
  27814. return instance;
  27815. }
  27816. void MessageManager::postMessageToQueue (Message* const message)
  27817. {
  27818. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  27819. delete message;
  27820. }
  27821. // not for public use..
  27822. void MessageManager::deliverMessage (void* message)
  27823. {
  27824. const MessageManagerLock lock;
  27825. Message* const m = (Message*) message;
  27826. MessageListener* const recipient = m->messageRecipient;
  27827. if (messageListeners.contains (recipient))
  27828. {
  27829. JUCE_TRY
  27830. {
  27831. recipient->handleMessage (*m);
  27832. }
  27833. JUCE_CATCH_EXCEPTION
  27834. if (needToGetRidOfWaitCursor)
  27835. {
  27836. needToGetRidOfWaitCursor = false;
  27837. MouseCursor::hideWaitCursor();
  27838. }
  27839. ++messageCounter;
  27840. }
  27841. else if (recipient == 0 && m->intParameter1 == quitMessageId)
  27842. {
  27843. quitMessageReceived = true;
  27844. useMaximumForceWhenQuitting = (m->intParameter2 != 0);
  27845. }
  27846. delete m;
  27847. }
  27848. bool MessageManager::dispatchNextMessage (const bool returnImmediatelyIfNoMessages,
  27849. bool* const wasAMessageDispatched)
  27850. {
  27851. if (quitMessageReceived)
  27852. {
  27853. if (wasAMessageDispatched != 0)
  27854. *wasAMessageDispatched = false;
  27855. return false;
  27856. }
  27857. ++isInMessageDispatcher;
  27858. bool result = false;
  27859. JUCE_TRY
  27860. {
  27861. result = juce_dispatchNextMessageOnSystemQueue (returnImmediatelyIfNoMessages);
  27862. if (wasAMessageDispatched != 0)
  27863. *wasAMessageDispatched = result;
  27864. if (instance == 0)
  27865. return false;
  27866. }
  27867. JUCE_CATCH_EXCEPTION
  27868. --isInMessageDispatcher;
  27869. ++messageCounter;
  27870. return result || ! returnImmediatelyIfNoMessages;
  27871. }
  27872. void MessageManager::dispatchPendingMessages (int maxNumberOfMessagesToDispatch)
  27873. {
  27874. jassert (isThisTheMessageThread()); // must only be called by the message thread
  27875. while (--maxNumberOfMessagesToDispatch >= 0 && ! quitMessageReceived)
  27876. {
  27877. ++isInMessageDispatcher;
  27878. bool carryOn = false;
  27879. JUCE_TRY
  27880. {
  27881. carryOn = juce_dispatchNextMessageOnSystemQueue (true);
  27882. }
  27883. JUCE_CATCH_EXCEPTION
  27884. --isInMessageDispatcher;
  27885. ++messageCounter;
  27886. if (! carryOn)
  27887. break;
  27888. }
  27889. }
  27890. bool MessageManager::runDispatchLoop()
  27891. {
  27892. jassert (isThisTheMessageThread()); // must only be called by the message thread
  27893. while (dispatchNextMessage())
  27894. {
  27895. }
  27896. return useMaximumForceWhenQuitting;
  27897. }
  27898. void MessageManager::postQuitMessage (const bool useMaximumForce)
  27899. {
  27900. Message* const m = new Message (quitMessageId, (useMaximumForce) ? 1 : 0, 0, 0);
  27901. m->messageRecipient = 0;
  27902. postMessageToQueue (m);
  27903. quitMessagePosted = true;
  27904. }
  27905. bool MessageManager::hasQuitMessageBeenPosted() const throw()
  27906. {
  27907. return quitMessagePosted;
  27908. }
  27909. void MessageManager::deliverBroadcastMessage (const String& value)
  27910. {
  27911. if (broadcastListeners != 0)
  27912. broadcastListeners->sendActionMessage (value);
  27913. }
  27914. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  27915. {
  27916. if (broadcastListeners == 0)
  27917. broadcastListeners = new ActionListenerList();
  27918. broadcastListeners->addActionListener (listener);
  27919. }
  27920. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  27921. {
  27922. if (broadcastListeners != 0)
  27923. broadcastListeners->removeActionListener (listener);
  27924. }
  27925. // This gets called occasionally by the timer thread (to save using an extra thread
  27926. // for it).
  27927. void MessageManager::inactivityCheckCallback() throw()
  27928. {
  27929. if (instance != 0)
  27930. instance->inactivityCheckCallbackInt();
  27931. }
  27932. void MessageManager::inactivityCheckCallbackInt() throw()
  27933. {
  27934. const unsigned int now = Time::getApproximateMillisecondCounter();
  27935. if (isInMessageDispatcher > 0
  27936. && lastMessageCounter == messageCounter
  27937. && timeBeforeWaitCursor > 0
  27938. && lastActivityCheckOkTime > 0
  27939. && ! ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  27940. {
  27941. if (now >= lastActivityCheckOkTime + timeBeforeWaitCursor
  27942. && ! needToGetRidOfWaitCursor)
  27943. {
  27944. // been in the same message call too long..
  27945. MouseCursor::showWaitCursor();
  27946. needToGetRidOfWaitCursor = true;
  27947. }
  27948. }
  27949. else
  27950. {
  27951. lastActivityCheckOkTime = now;
  27952. lastMessageCounter = messageCounter;
  27953. }
  27954. }
  27955. void MessageManager::delayWaitCursor() throw()
  27956. {
  27957. if (instance != 0)
  27958. {
  27959. instance->messageCounter++;
  27960. if (instance->needToGetRidOfWaitCursor)
  27961. {
  27962. instance->needToGetRidOfWaitCursor = false;
  27963. MouseCursor::hideWaitCursor();
  27964. }
  27965. }
  27966. }
  27967. void MessageManager::setTimeBeforeShowingWaitCursor (const int millisecs) throw()
  27968. {
  27969. // if this is a bit too small you'll get a lot of unwanted hourglass cursors..
  27970. jassert (millisecs <= 0 || millisecs > 200);
  27971. timeBeforeWaitCursor = millisecs;
  27972. if (millisecs > 0)
  27973. startTimer (millisecs / 2); // (see timerCallback() for explanation of this)
  27974. else
  27975. stopTimer();
  27976. }
  27977. void MessageManager::timerCallback()
  27978. {
  27979. // dummy callback - the message manager is just a Timer to ensure that there are always
  27980. // some events coming in - otherwise it'll show the egg-timer/beachball-of-death.
  27981. ++messageCounter;
  27982. }
  27983. int MessageManager::getTimeBeforeShowingWaitCursor() const throw()
  27984. {
  27985. return timeBeforeWaitCursor;
  27986. }
  27987. bool MessageManager::isThisTheMessageThread() const throw()
  27988. {
  27989. return Thread::getCurrentThreadId() == messageThreadId;
  27990. }
  27991. void MessageManager::setCurrentMessageThread (const int threadId) throw()
  27992. {
  27993. messageThreadId = threadId;
  27994. }
  27995. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  27996. {
  27997. return Thread::getCurrentThreadId() == currentLockingThreadId;
  27998. }
  27999. MessageManagerLock::MessageManagerLock() throw()
  28000. : locked (false)
  28001. {
  28002. if (MessageManager::instance != 0)
  28003. {
  28004. MessageManager::instance->messageDispatchLock.enter();
  28005. lastLockingThreadId = MessageManager::instance->currentLockingThreadId;
  28006. MessageManager::instance->currentLockingThreadId = Thread::getCurrentThreadId();
  28007. locked = true;
  28008. }
  28009. }
  28010. MessageManagerLock::MessageManagerLock (Thread* const thread) throw()
  28011. : locked (false)
  28012. {
  28013. jassert (thread != 0); // This will only work if you give it a valid thread!
  28014. if (MessageManager::instance != 0)
  28015. {
  28016. for (;;)
  28017. {
  28018. if (MessageManager::instance->messageDispatchLock.tryEnter())
  28019. {
  28020. locked = true;
  28021. lastLockingThreadId = MessageManager::instance->currentLockingThreadId;
  28022. MessageManager::instance->currentLockingThreadId = Thread::getCurrentThreadId();
  28023. break;
  28024. }
  28025. if (thread != 0 && thread->threadShouldExit())
  28026. break;
  28027. Thread::sleep (1);
  28028. }
  28029. }
  28030. }
  28031. MessageManagerLock::~MessageManagerLock() throw()
  28032. {
  28033. if (locked && MessageManager::instance != 0)
  28034. {
  28035. MessageManager::instance->currentLockingThreadId = lastLockingThreadId;
  28036. MessageManager::instance->messageDispatchLock.exit();
  28037. }
  28038. }
  28039. END_JUCE_NAMESPACE
  28040. /********* End of inlined file: juce_MessageManager.cpp *********/
  28041. /********* Start of inlined file: juce_MultiTimer.cpp *********/
  28042. BEGIN_JUCE_NAMESPACE
  28043. class InternalMultiTimerCallback : public Timer
  28044. {
  28045. public:
  28046. InternalMultiTimerCallback (const int timerId_, MultiTimer& owner_)
  28047. : timerId (timerId_),
  28048. owner (owner_)
  28049. {
  28050. }
  28051. ~InternalMultiTimerCallback()
  28052. {
  28053. }
  28054. void timerCallback()
  28055. {
  28056. owner.timerCallback (timerId);
  28057. }
  28058. const int timerId;
  28059. private:
  28060. MultiTimer& owner;
  28061. };
  28062. MultiTimer::MultiTimer() throw()
  28063. {
  28064. }
  28065. MultiTimer::MultiTimer (const MultiTimer&) throw()
  28066. {
  28067. }
  28068. MultiTimer::~MultiTimer()
  28069. {
  28070. const ScopedLock sl (timerListLock);
  28071. for (int i = timers.size(); --i >= 0;)
  28072. delete (InternalMultiTimerCallback*) timers.getUnchecked(i);
  28073. timers.clear();
  28074. }
  28075. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  28076. {
  28077. const ScopedLock sl (timerListLock);
  28078. for (int i = timers.size(); --i >= 0;)
  28079. {
  28080. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  28081. if (t->timerId == timerId)
  28082. {
  28083. t->startTimer (intervalInMilliseconds);
  28084. return;
  28085. }
  28086. }
  28087. InternalMultiTimerCallback* const newTimer = new InternalMultiTimerCallback (timerId, *this);
  28088. timers.add (newTimer);
  28089. newTimer->startTimer (intervalInMilliseconds);
  28090. }
  28091. void MultiTimer::stopTimer (const int timerId) throw()
  28092. {
  28093. const ScopedLock sl (timerListLock);
  28094. for (int i = timers.size(); --i >= 0;)
  28095. {
  28096. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  28097. if (t->timerId == timerId)
  28098. t->stopTimer();
  28099. }
  28100. }
  28101. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  28102. {
  28103. const ScopedLock sl (timerListLock);
  28104. for (int i = timers.size(); --i >= 0;)
  28105. {
  28106. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  28107. if (t->timerId == timerId)
  28108. return t->isTimerRunning();
  28109. }
  28110. return false;
  28111. }
  28112. int MultiTimer::getTimerInterval (const int timerId) const throw()
  28113. {
  28114. const ScopedLock sl (timerListLock);
  28115. for (int i = timers.size(); --i >= 0;)
  28116. {
  28117. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  28118. if (t->timerId == timerId)
  28119. return t->getTimerInterval();
  28120. }
  28121. return 0;
  28122. }
  28123. END_JUCE_NAMESPACE
  28124. /********* End of inlined file: juce_MultiTimer.cpp *********/
  28125. /********* Start of inlined file: juce_Timer.cpp *********/
  28126. BEGIN_JUCE_NAMESPACE
  28127. class InternalTimerThread : private Thread,
  28128. private MessageListener,
  28129. private DeletedAtShutdown,
  28130. private AsyncUpdater
  28131. {
  28132. private:
  28133. friend class Timer;
  28134. static InternalTimerThread* instance;
  28135. static CriticalSection lock;
  28136. Timer* volatile firstTimer;
  28137. bool volatile callbackNeeded;
  28138. InternalTimerThread (const InternalTimerThread&);
  28139. const InternalTimerThread& operator= (const InternalTimerThread&);
  28140. void addTimer (Timer* const t) throw()
  28141. {
  28142. #ifdef JUCE_DEBUG
  28143. Timer* tt = firstTimer;
  28144. while (tt != 0)
  28145. {
  28146. // trying to add a timer that's already here - shouldn't get to this point,
  28147. // so if you get this assertion, let me know!
  28148. jassert (tt != t);
  28149. tt = tt->next;
  28150. }
  28151. jassert (t->previous == 0 && t->next == 0);
  28152. #endif
  28153. Timer* i = firstTimer;
  28154. if (i == 0 || i->countdownMs > t->countdownMs)
  28155. {
  28156. t->next = firstTimer;
  28157. firstTimer = t;
  28158. }
  28159. else
  28160. {
  28161. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  28162. i = i->next;
  28163. jassert (i != 0);
  28164. t->next = i->next;
  28165. t->previous = i;
  28166. i->next = t;
  28167. }
  28168. if (t->next != 0)
  28169. t->next->previous = t;
  28170. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  28171. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  28172. notify();
  28173. }
  28174. void removeTimer (Timer* const t) throw()
  28175. {
  28176. #ifdef JUCE_DEBUG
  28177. Timer* tt = firstTimer;
  28178. bool found = false;
  28179. while (tt != 0)
  28180. {
  28181. if (tt == t)
  28182. {
  28183. found = true;
  28184. break;
  28185. }
  28186. tt = tt->next;
  28187. }
  28188. // trying to remove a timer that's not here - shouldn't get to this point,
  28189. // so if you get this assertion, let me know!
  28190. jassert (found);
  28191. #endif
  28192. if (t->previous != 0)
  28193. {
  28194. jassert (firstTimer != t);
  28195. t->previous->next = t->next;
  28196. }
  28197. else
  28198. {
  28199. jassert (firstTimer == t);
  28200. firstTimer = t->next;
  28201. }
  28202. if (t->next != 0)
  28203. t->next->previous = t->previous;
  28204. t->next = 0;
  28205. t->previous = 0;
  28206. }
  28207. void decrementAllCounters (const int numMillisecs) const
  28208. {
  28209. Timer* t = firstTimer;
  28210. while (t != 0)
  28211. {
  28212. t->countdownMs -= numMillisecs;
  28213. t = t->next;
  28214. }
  28215. }
  28216. void handleAsyncUpdate()
  28217. {
  28218. startThread (7);
  28219. }
  28220. public:
  28221. InternalTimerThread()
  28222. : Thread ("Juce Timer"),
  28223. firstTimer (0),
  28224. callbackNeeded (false)
  28225. {
  28226. triggerAsyncUpdate();
  28227. }
  28228. ~InternalTimerThread() throw()
  28229. {
  28230. stopThread (4000);
  28231. jassert (instance == this || instance == 0);
  28232. if (instance == this)
  28233. instance = 0;
  28234. }
  28235. void run()
  28236. {
  28237. uint32 lastTime = Time::getMillisecondCounter();
  28238. uint32 lastMessageManagerCallback = lastTime;
  28239. while (! threadShouldExit())
  28240. {
  28241. uint32 now = Time::getMillisecondCounter();
  28242. if (now <= lastTime)
  28243. {
  28244. wait (2);
  28245. continue;
  28246. }
  28247. const int elapsed = now - lastTime;
  28248. lastTime = now;
  28249. lock.enter();
  28250. decrementAllCounters (elapsed);
  28251. const int timeUntilFirstTimer = (firstTimer != 0) ? firstTimer->countdownMs
  28252. : 1000;
  28253. lock.exit();
  28254. if (timeUntilFirstTimer <= 0)
  28255. {
  28256. callbackNeeded = true;
  28257. postMessage (new Message());
  28258. // sometimes, our message could get discarded by the OS (particularly when running as an RTAS when the app has a modal loop),
  28259. // so this is how long to wait before assuming the message has been lost and trying again.
  28260. const uint32 messageDeliveryTimeout = now + 2000;
  28261. while (callbackNeeded)
  28262. {
  28263. wait (4);
  28264. if (threadShouldExit())
  28265. return;
  28266. now = Time::getMillisecondCounter();
  28267. if (now > lastMessageManagerCallback + 200)
  28268. {
  28269. lastMessageManagerCallback = now;
  28270. MessageManager::inactivityCheckCallback();
  28271. }
  28272. if (now > messageDeliveryTimeout)
  28273. break;
  28274. }
  28275. }
  28276. else
  28277. {
  28278. // don't wait for too long because running this loop also helps keep the
  28279. // Time::getApproximateMillisecondTimer value stay up-to-date
  28280. wait (jlimit (1, 50, timeUntilFirstTimer));
  28281. }
  28282. if (now > lastMessageManagerCallback + 200)
  28283. {
  28284. lastMessageManagerCallback = now;
  28285. MessageManager::inactivityCheckCallback();
  28286. }
  28287. }
  28288. }
  28289. void handleMessage (const Message&)
  28290. {
  28291. const ScopedLock sl (lock);
  28292. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  28293. {
  28294. Timer* const t = firstTimer;
  28295. t->countdownMs = t->periodMs;
  28296. removeTimer (t);
  28297. addTimer (t);
  28298. const ScopedUnlock ul (lock);
  28299. callbackNeeded = false;
  28300. JUCE_TRY
  28301. {
  28302. t->timerCallback();
  28303. }
  28304. JUCE_CATCH_EXCEPTION
  28305. }
  28306. callbackNeeded = false;
  28307. }
  28308. static void callAnyTimersSynchronously()
  28309. {
  28310. if (InternalTimerThread::instance != 0)
  28311. {
  28312. const Message m;
  28313. InternalTimerThread::instance->handleMessage (m);
  28314. }
  28315. }
  28316. static inline void add (Timer* const tim) throw()
  28317. {
  28318. if (instance == 0)
  28319. instance = new InternalTimerThread();
  28320. instance->addTimer (tim);
  28321. }
  28322. static inline void remove (Timer* const tim) throw()
  28323. {
  28324. if (instance != 0)
  28325. instance->removeTimer (tim);
  28326. }
  28327. static inline void resetCounter (Timer* const tim,
  28328. const int newCounter) throw()
  28329. {
  28330. if (instance != 0)
  28331. {
  28332. tim->countdownMs = newCounter;
  28333. tim->periodMs = newCounter;
  28334. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  28335. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  28336. {
  28337. instance->removeTimer (tim);
  28338. instance->addTimer (tim);
  28339. }
  28340. }
  28341. }
  28342. };
  28343. InternalTimerThread* InternalTimerThread::instance = 0;
  28344. CriticalSection InternalTimerThread::lock;
  28345. void juce_callAnyTimersSynchronously()
  28346. {
  28347. InternalTimerThread::callAnyTimersSynchronously();
  28348. }
  28349. #ifdef JUCE_DEBUG
  28350. static SortedSet <Timer*> activeTimers;
  28351. #endif
  28352. Timer::Timer() throw()
  28353. : countdownMs (0),
  28354. periodMs (0),
  28355. previous (0),
  28356. next (0)
  28357. {
  28358. #ifdef JUCE_DEBUG
  28359. activeTimers.add (this);
  28360. #endif
  28361. }
  28362. Timer::Timer (const Timer&) throw()
  28363. : countdownMs (0),
  28364. periodMs (0),
  28365. previous (0),
  28366. next (0)
  28367. {
  28368. #ifdef JUCE_DEBUG
  28369. activeTimers.add (this);
  28370. #endif
  28371. }
  28372. Timer::~Timer()
  28373. {
  28374. stopTimer();
  28375. #ifdef JUCE_DEBUG
  28376. activeTimers.removeValue (this);
  28377. #endif
  28378. }
  28379. void Timer::startTimer (const int interval) throw()
  28380. {
  28381. const ScopedLock sl (InternalTimerThread::lock);
  28382. #ifdef JUCE_DEBUG
  28383. // this isn't a valid object! Your timer might be a dangling pointer or something..
  28384. jassert (activeTimers.contains (this));
  28385. #endif
  28386. if (periodMs == 0)
  28387. {
  28388. countdownMs = interval;
  28389. periodMs = jmax (1, interval);
  28390. InternalTimerThread::add (this);
  28391. }
  28392. else
  28393. {
  28394. InternalTimerThread::resetCounter (this, interval);
  28395. }
  28396. }
  28397. void Timer::stopTimer() throw()
  28398. {
  28399. const ScopedLock sl (InternalTimerThread::lock);
  28400. #ifdef JUCE_DEBUG
  28401. // this isn't a valid object! Your timer might be a dangling pointer or something..
  28402. jassert (activeTimers.contains (this));
  28403. #endif
  28404. if (periodMs > 0)
  28405. {
  28406. InternalTimerThread::remove (this);
  28407. periodMs = 0;
  28408. }
  28409. }
  28410. END_JUCE_NAMESPACE
  28411. /********* End of inlined file: juce_Timer.cpp *********/
  28412. /********* Start of inlined file: juce_Component.cpp *********/
  28413. BEGIN_JUCE_NAMESPACE
  28414. Component* Component::componentUnderMouse = 0;
  28415. Component* Component::currentlyFocusedComponent = 0;
  28416. static Array <Component*> modalComponentStack (4), modalComponentReturnValueKeys (4);
  28417. static Array <int> modalReturnValues (4);
  28418. static const int customCommandMessage = 0x7fff0001;
  28419. static const int exitModalStateMessage = 0x7fff0002;
  28420. // these are also used by ComponentPeer
  28421. int64 juce_recentMouseDownTimes [4] = { 0, 0, 0, 0 };
  28422. int juce_recentMouseDownX [4] = { 0, 0, 0, 0 };
  28423. int juce_recentMouseDownY [4] = { 0, 0, 0, 0 };
  28424. Component* juce_recentMouseDownComponent [4] = { 0, 0, 0, 0 };
  28425. int juce_LastMousePosX = 0;
  28426. int juce_LastMousePosY = 0;
  28427. int juce_MouseClickCounter = 0;
  28428. bool juce_MouseHasMovedSignificantlySincePressed = false;
  28429. static int countMouseClicks() throw()
  28430. {
  28431. int numClicks = 0;
  28432. if (juce_recentMouseDownTimes[0] != 0)
  28433. {
  28434. if (! juce_MouseHasMovedSignificantlySincePressed)
  28435. ++numClicks;
  28436. for (int i = 1; i < numElementsInArray (juce_recentMouseDownTimes); ++i)
  28437. {
  28438. if (juce_recentMouseDownTimes[0] - juce_recentMouseDownTimes [i]
  28439. < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  28440. && abs (juce_recentMouseDownX[0] - juce_recentMouseDownX[i]) < 8
  28441. && abs (juce_recentMouseDownY[0] - juce_recentMouseDownY[i]) < 8
  28442. && juce_recentMouseDownComponent[0] == juce_recentMouseDownComponent [i])
  28443. {
  28444. ++numClicks;
  28445. }
  28446. else
  28447. {
  28448. break;
  28449. }
  28450. }
  28451. }
  28452. return numClicks;
  28453. }
  28454. static int unboundedMouseOffsetX = 0;
  28455. static int unboundedMouseOffsetY = 0;
  28456. static bool isUnboundedMouseModeOn = false;
  28457. static bool isCursorVisibleUntilOffscreen;
  28458. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  28459. static uint32 nextComponentUID = 0;
  28460. Component::Component() throw()
  28461. : parentComponent_ (0),
  28462. componentUID (++nextComponentUID),
  28463. numDeepMouseListeners (0),
  28464. childComponentList_ (16),
  28465. lookAndFeel_ (0),
  28466. effect_ (0),
  28467. bufferedImage_ (0),
  28468. mouseListeners_ (0),
  28469. keyListeners_ (0),
  28470. componentListeners_ (0),
  28471. propertySet_ (0),
  28472. componentFlags_ (0)
  28473. {
  28474. }
  28475. Component::Component (const String& name) throw()
  28476. : componentName_ (name),
  28477. parentComponent_ (0),
  28478. componentUID (++nextComponentUID),
  28479. numDeepMouseListeners (0),
  28480. childComponentList_ (16),
  28481. lookAndFeel_ (0),
  28482. effect_ (0),
  28483. bufferedImage_ (0),
  28484. mouseListeners_ (0),
  28485. keyListeners_ (0),
  28486. componentListeners_ (0),
  28487. propertySet_ (0),
  28488. componentFlags_ (0)
  28489. {
  28490. }
  28491. Component::~Component()
  28492. {
  28493. if (parentComponent_ != 0)
  28494. {
  28495. parentComponent_->removeChildComponent (this);
  28496. }
  28497. else if ((currentlyFocusedComponent == this)
  28498. || isParentOf (currentlyFocusedComponent))
  28499. {
  28500. giveAwayFocus();
  28501. }
  28502. if (componentUnderMouse == this)
  28503. componentUnderMouse = 0;
  28504. if (flags.hasHeavyweightPeerFlag)
  28505. removeFromDesktop();
  28506. modalComponentStack.removeValue (this);
  28507. for (int i = childComponentList_.size(); --i >= 0;)
  28508. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  28509. delete bufferedImage_;
  28510. delete mouseListeners_;
  28511. delete keyListeners_;
  28512. delete componentListeners_;
  28513. delete propertySet_;
  28514. }
  28515. void Component::setName (const String& name)
  28516. {
  28517. // if component methods are being called from threads other than the message
  28518. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28519. checkMessageManagerIsLocked
  28520. if (componentName_ != name)
  28521. {
  28522. componentName_ = name;
  28523. if (flags.hasHeavyweightPeerFlag)
  28524. {
  28525. ComponentPeer* const peer = getPeer();
  28526. jassert (peer != 0);
  28527. if (peer != 0)
  28528. peer->setTitle (name);
  28529. }
  28530. if (componentListeners_ != 0)
  28531. {
  28532. const ComponentDeletionWatcher deletionChecker (this);
  28533. for (int i = componentListeners_->size(); --i >= 0;)
  28534. {
  28535. ((ComponentListener*) componentListeners_->getUnchecked (i))
  28536. ->componentNameChanged (*this);
  28537. if (deletionChecker.hasBeenDeleted())
  28538. return;
  28539. i = jmin (i, componentListeners_->size());
  28540. }
  28541. }
  28542. }
  28543. }
  28544. void Component::setVisible (bool shouldBeVisible)
  28545. {
  28546. if (flags.visibleFlag != shouldBeVisible)
  28547. {
  28548. // if component methods are being called from threads other than the message
  28549. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28550. checkMessageManagerIsLocked
  28551. const ComponentDeletionWatcher deletionChecker (this);
  28552. flags.visibleFlag = shouldBeVisible;
  28553. internalRepaint (0, 0, getWidth(), getHeight());
  28554. sendFakeMouseMove();
  28555. if (! shouldBeVisible)
  28556. {
  28557. if (currentlyFocusedComponent == this
  28558. || isParentOf (currentlyFocusedComponent))
  28559. {
  28560. if (parentComponent_ != 0)
  28561. parentComponent_->grabKeyboardFocus();
  28562. else
  28563. giveAwayFocus();
  28564. }
  28565. }
  28566. sendVisibilityChangeMessage();
  28567. if ((! deletionChecker.hasBeenDeleted()) && flags.hasHeavyweightPeerFlag)
  28568. {
  28569. ComponentPeer* const peer = getPeer();
  28570. jassert (peer != 0);
  28571. if (peer != 0)
  28572. {
  28573. peer->setVisible (shouldBeVisible);
  28574. internalHierarchyChanged();
  28575. }
  28576. }
  28577. }
  28578. }
  28579. void Component::visibilityChanged()
  28580. {
  28581. }
  28582. void Component::sendVisibilityChangeMessage()
  28583. {
  28584. const ComponentDeletionWatcher deletionChecker (this);
  28585. visibilityChanged();
  28586. if ((! deletionChecker.hasBeenDeleted()) && componentListeners_ != 0)
  28587. {
  28588. for (int i = componentListeners_->size(); --i >= 0;)
  28589. {
  28590. ((ComponentListener*) componentListeners_->getUnchecked (i))
  28591. ->componentVisibilityChanged (*this);
  28592. if (deletionChecker.hasBeenDeleted())
  28593. return;
  28594. i = jmin (i, componentListeners_->size());
  28595. }
  28596. }
  28597. }
  28598. bool Component::isShowing() const throw()
  28599. {
  28600. if (flags.visibleFlag)
  28601. {
  28602. if (parentComponent_ != 0)
  28603. {
  28604. return parentComponent_->isShowing();
  28605. }
  28606. else
  28607. {
  28608. const ComponentPeer* const peer = getPeer();
  28609. return peer != 0 && ! peer->isMinimised();
  28610. }
  28611. }
  28612. return false;
  28613. }
  28614. class FadeOutProxyComponent : public Component,
  28615. public Timer
  28616. {
  28617. public:
  28618. FadeOutProxyComponent (Component* comp,
  28619. const int fadeLengthMs,
  28620. const int deltaXToMove,
  28621. const int deltaYToMove,
  28622. const float scaleFactorAtEnd)
  28623. : lastTime (0),
  28624. alpha (1.0f),
  28625. scale (1.0f)
  28626. {
  28627. image = comp->createComponentSnapshot (Rectangle (0, 0, comp->getWidth(), comp->getHeight()));
  28628. setBounds (comp->getBounds());
  28629. comp->getParentComponent()->addAndMakeVisible (this);
  28630. toBehind (comp);
  28631. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  28632. centreX = comp->getX() + comp->getWidth() * 0.5f;
  28633. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  28634. centreY = comp->getY() + comp->getHeight() * 0.5f;
  28635. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  28636. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  28637. setInterceptsMouseClicks (false, false);
  28638. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  28639. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  28640. }
  28641. ~FadeOutProxyComponent()
  28642. {
  28643. delete image;
  28644. }
  28645. void paint (Graphics& g)
  28646. {
  28647. g.setOpacity (alpha);
  28648. g.drawImage (image,
  28649. 0, 0, getWidth(), getHeight(),
  28650. 0, 0, image->getWidth(), image->getHeight());
  28651. }
  28652. void timerCallback()
  28653. {
  28654. const uint32 now = Time::getMillisecondCounter();
  28655. if (lastTime == 0)
  28656. lastTime = now;
  28657. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  28658. lastTime = now;
  28659. alpha += alphaChangePerMs * msPassed;
  28660. if (alpha > 0)
  28661. {
  28662. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  28663. {
  28664. centreX += xChangePerMs * msPassed;
  28665. centreY += yChangePerMs * msPassed;
  28666. scale += scaleChangePerMs * msPassed;
  28667. const int w = roundFloatToInt (image->getWidth() * scale);
  28668. const int h = roundFloatToInt (image->getHeight() * scale);
  28669. setBounds (roundFloatToInt (centreX) - w / 2,
  28670. roundFloatToInt (centreY) - h / 2,
  28671. w, h);
  28672. }
  28673. repaint();
  28674. }
  28675. else
  28676. {
  28677. delete this;
  28678. }
  28679. }
  28680. juce_UseDebuggingNewOperator
  28681. private:
  28682. Image* image;
  28683. uint32 lastTime;
  28684. float alpha, alphaChangePerMs;
  28685. float centreX, xChangePerMs;
  28686. float centreY, yChangePerMs;
  28687. float scale, scaleChangePerMs;
  28688. FadeOutProxyComponent (const FadeOutProxyComponent&);
  28689. const FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  28690. };
  28691. void Component::fadeOutComponent (const int millisecondsToFade,
  28692. const int deltaXToMove,
  28693. const int deltaYToMove,
  28694. const float scaleFactorAtEnd)
  28695. {
  28696. //xxx won't work for comps without parents
  28697. if (isShowing() && millisecondsToFade > 0)
  28698. new FadeOutProxyComponent (this, millisecondsToFade,
  28699. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  28700. setVisible (false);
  28701. }
  28702. bool Component::isValidComponent() const throw()
  28703. {
  28704. return (this != 0) && isValidMessageListener();
  28705. }
  28706. void* Component::getWindowHandle() const throw()
  28707. {
  28708. const ComponentPeer* const peer = getPeer();
  28709. if (peer != 0)
  28710. return peer->getNativeHandle();
  28711. return 0;
  28712. }
  28713. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  28714. {
  28715. // if component methods are being called from threads other than the message
  28716. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28717. checkMessageManagerIsLocked
  28718. if (! isOpaque())
  28719. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  28720. int currentStyleFlags = 0;
  28721. // don't use getPeer(), so that we only get the peer that's specifically
  28722. // for this comp, and not for one of its parents.
  28723. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  28724. if (peer != 0)
  28725. currentStyleFlags = peer->getStyleFlags();
  28726. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  28727. {
  28728. const ComponentDeletionWatcher deletionChecker (this);
  28729. #if JUCE_LINUX
  28730. // it's wise to give the component a non-zero size before
  28731. // putting it on the desktop, as X windows get confused by this, and
  28732. // a (1, 1) minimum size is enforced here.
  28733. setSize (jmax (1, getWidth()),
  28734. jmax (1, getHeight()));
  28735. #endif
  28736. int x = 0, y = 0;
  28737. relativePositionToGlobal (x, y);
  28738. bool wasFullscreen = false;
  28739. bool wasMinimised = false;
  28740. ComponentBoundsConstrainer* currentConstainer = 0;
  28741. Rectangle oldNonFullScreenBounds;
  28742. if (peer != 0)
  28743. {
  28744. wasFullscreen = peer->isFullScreen();
  28745. wasMinimised = peer->isMinimised();
  28746. currentConstainer = peer->getConstrainer();
  28747. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  28748. removeFromDesktop();
  28749. }
  28750. if (parentComponent_ != 0)
  28751. parentComponent_->removeChildComponent (this);
  28752. if (! deletionChecker.hasBeenDeleted())
  28753. {
  28754. flags.hasHeavyweightPeerFlag = true;
  28755. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  28756. Desktop::getInstance().addDesktopComponent (this);
  28757. bounds_.setPosition (x, y);
  28758. peer->setBounds (x, y, getWidth(), getHeight(), false);
  28759. peer->setVisible (isVisible());
  28760. if (wasFullscreen)
  28761. {
  28762. peer->setFullScreen (true);
  28763. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  28764. }
  28765. if (wasMinimised)
  28766. peer->setMinimised (true);
  28767. if (isAlwaysOnTop())
  28768. peer->setAlwaysOnTop (true);
  28769. peer->setConstrainer (currentConstainer);
  28770. repaint();
  28771. }
  28772. internalHierarchyChanged();
  28773. }
  28774. }
  28775. void Component::removeFromDesktop()
  28776. {
  28777. // if component methods are being called from threads other than the message
  28778. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28779. checkMessageManagerIsLocked
  28780. if (flags.hasHeavyweightPeerFlag)
  28781. {
  28782. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  28783. flags.hasHeavyweightPeerFlag = false;
  28784. jassert (peer != 0);
  28785. delete peer;
  28786. Desktop::getInstance().removeDesktopComponent (this);
  28787. }
  28788. }
  28789. bool Component::isOnDesktop() const throw()
  28790. {
  28791. return flags.hasHeavyweightPeerFlag;
  28792. }
  28793. void Component::userTriedToCloseWindow()
  28794. {
  28795. /* This means that the user's trying to get rid of your window with the 'close window' system
  28796. menu option (on windows) or possibly the task manager - you should really handle this
  28797. and delete or hide your component in an appropriate way.
  28798. If you want to ignore the event and don't want to trigger this assertion, just override
  28799. this method and do nothing.
  28800. */
  28801. jassertfalse
  28802. }
  28803. void Component::minimisationStateChanged (bool)
  28804. {
  28805. }
  28806. void Component::setOpaque (const bool shouldBeOpaque) throw()
  28807. {
  28808. if (shouldBeOpaque != flags.opaqueFlag)
  28809. {
  28810. flags.opaqueFlag = shouldBeOpaque;
  28811. if (flags.hasHeavyweightPeerFlag)
  28812. {
  28813. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  28814. if (peer != 0)
  28815. {
  28816. // to make it recreate the heavyweight window
  28817. addToDesktop (peer->getStyleFlags());
  28818. }
  28819. }
  28820. repaint();
  28821. }
  28822. }
  28823. bool Component::isOpaque() const throw()
  28824. {
  28825. return flags.opaqueFlag;
  28826. }
  28827. void Component::setBufferedToImage (const bool shouldBeBuffered) throw()
  28828. {
  28829. if (shouldBeBuffered != flags.bufferToImageFlag)
  28830. {
  28831. deleteAndZero (bufferedImage_);
  28832. flags.bufferToImageFlag = shouldBeBuffered;
  28833. }
  28834. }
  28835. void Component::toFront (const bool setAsForeground)
  28836. {
  28837. // if component methods are being called from threads other than the message
  28838. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28839. checkMessageManagerIsLocked
  28840. if (flags.hasHeavyweightPeerFlag)
  28841. {
  28842. ComponentPeer* const peer = getPeer();
  28843. if (peer != 0)
  28844. {
  28845. peer->toFront (setAsForeground);
  28846. if (setAsForeground && ! hasKeyboardFocus (true))
  28847. grabKeyboardFocus();
  28848. }
  28849. }
  28850. else if (parentComponent_ != 0)
  28851. {
  28852. if (parentComponent_->childComponentList_.getLast() != this)
  28853. {
  28854. const int index = parentComponent_->childComponentList_.indexOf (this);
  28855. if (index >= 0)
  28856. {
  28857. int insertIndex = -1;
  28858. if (! flags.alwaysOnTopFlag)
  28859. {
  28860. insertIndex = parentComponent_->childComponentList_.size() - 1;
  28861. while (insertIndex > 0
  28862. && parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  28863. {
  28864. --insertIndex;
  28865. }
  28866. }
  28867. if (index != insertIndex)
  28868. {
  28869. parentComponent_->childComponentList_.move (index, insertIndex);
  28870. sendFakeMouseMove();
  28871. repaintParent();
  28872. }
  28873. }
  28874. }
  28875. if (setAsForeground)
  28876. {
  28877. internalBroughtToFront();
  28878. grabKeyboardFocus();
  28879. }
  28880. }
  28881. }
  28882. void Component::toBehind (Component* const other)
  28883. {
  28884. if (other != 0)
  28885. {
  28886. // the two components must belong to the same parent..
  28887. jassert (parentComponent_ == other->parentComponent_);
  28888. if (parentComponent_ != 0)
  28889. {
  28890. const int index = parentComponent_->childComponentList_.indexOf (this);
  28891. int otherIndex = parentComponent_->childComponentList_.indexOf (other);
  28892. if (index >= 0
  28893. && otherIndex >= 0
  28894. && index != otherIndex - 1
  28895. && other != this)
  28896. {
  28897. if (index < otherIndex)
  28898. --otherIndex;
  28899. parentComponent_->childComponentList_.move (index, otherIndex);
  28900. sendFakeMouseMove();
  28901. repaintParent();
  28902. }
  28903. }
  28904. else if (isOnDesktop())
  28905. {
  28906. jassert (other->isOnDesktop());
  28907. if (other->isOnDesktop())
  28908. {
  28909. ComponentPeer* const us = getPeer();
  28910. ComponentPeer* const them = other->getPeer();
  28911. jassert (us != 0 && them != 0);
  28912. if (us != 0 && them != 0)
  28913. us->toBehind (them);
  28914. }
  28915. }
  28916. }
  28917. }
  28918. void Component::toBack()
  28919. {
  28920. if (isOnDesktop())
  28921. {
  28922. jassertfalse //xxx need to add this to native window
  28923. }
  28924. else if (parentComponent_ != 0
  28925. && parentComponent_->childComponentList_.getFirst() != this)
  28926. {
  28927. const int index = parentComponent_->childComponentList_.indexOf (this);
  28928. if (index > 0)
  28929. {
  28930. int insertIndex = 0;
  28931. if (flags.alwaysOnTopFlag)
  28932. {
  28933. while (insertIndex < parentComponent_->childComponentList_.size()
  28934. && ! parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  28935. {
  28936. ++insertIndex;
  28937. }
  28938. }
  28939. if (index != insertIndex)
  28940. {
  28941. parentComponent_->childComponentList_.move (index, insertIndex);
  28942. sendFakeMouseMove();
  28943. repaintParent();
  28944. }
  28945. }
  28946. }
  28947. }
  28948. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  28949. {
  28950. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  28951. {
  28952. flags.alwaysOnTopFlag = shouldStayOnTop;
  28953. if (isOnDesktop())
  28954. {
  28955. ComponentPeer* const peer = getPeer();
  28956. jassert (peer != 0);
  28957. if (peer != 0)
  28958. {
  28959. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  28960. {
  28961. // some kinds of peer can't change their always-on-top status, so
  28962. // for these, we'll need to create a new window
  28963. const int oldFlags = peer->getStyleFlags();
  28964. removeFromDesktop();
  28965. addToDesktop (oldFlags);
  28966. }
  28967. }
  28968. }
  28969. if (shouldStayOnTop)
  28970. toFront (false);
  28971. internalHierarchyChanged();
  28972. }
  28973. }
  28974. bool Component::isAlwaysOnTop() const throw()
  28975. {
  28976. return flags.alwaysOnTopFlag;
  28977. }
  28978. int Component::proportionOfWidth (const float proportion) const throw()
  28979. {
  28980. return roundDoubleToInt (proportion * bounds_.getWidth());
  28981. }
  28982. int Component::proportionOfHeight (const float proportion) const throw()
  28983. {
  28984. return roundDoubleToInt (proportion * bounds_.getHeight());
  28985. }
  28986. int Component::getParentWidth() const throw()
  28987. {
  28988. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  28989. : getParentMonitorArea().getWidth();
  28990. }
  28991. int Component::getParentHeight() const throw()
  28992. {
  28993. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  28994. : getParentMonitorArea().getHeight();
  28995. }
  28996. int Component::getScreenX() const throw()
  28997. {
  28998. return (parentComponent_ != 0) ? parentComponent_->getScreenX() + getX()
  28999. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenX()
  29000. : getX());
  29001. }
  29002. int Component::getScreenY() const throw()
  29003. {
  29004. return (parentComponent_ != 0) ? parentComponent_->getScreenY() + getY()
  29005. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenY()
  29006. : getY());
  29007. }
  29008. void Component::relativePositionToGlobal (int& x, int& y) const throw()
  29009. {
  29010. const Component* c = this;
  29011. do
  29012. {
  29013. if (c->flags.hasHeavyweightPeerFlag)
  29014. {
  29015. c->getPeer()->relativePositionToGlobal (x, y);
  29016. break;
  29017. }
  29018. x += c->getX();
  29019. y += c->getY();
  29020. c = c->parentComponent_;
  29021. }
  29022. while (c != 0);
  29023. }
  29024. void Component::globalPositionToRelative (int& x, int& y) const throw()
  29025. {
  29026. if (flags.hasHeavyweightPeerFlag)
  29027. {
  29028. getPeer()->globalPositionToRelative (x, y);
  29029. }
  29030. else
  29031. {
  29032. if (parentComponent_ != 0)
  29033. parentComponent_->globalPositionToRelative (x, y);
  29034. x -= getX();
  29035. y -= getY();
  29036. }
  29037. }
  29038. void Component::relativePositionToOtherComponent (const Component* const targetComponent, int& x, int& y) const throw()
  29039. {
  29040. if (targetComponent != 0)
  29041. {
  29042. const Component* c = this;
  29043. do
  29044. {
  29045. if (c == targetComponent)
  29046. return;
  29047. if (c->flags.hasHeavyweightPeerFlag)
  29048. {
  29049. c->getPeer()->relativePositionToGlobal (x, y);
  29050. break;
  29051. }
  29052. x += c->getX();
  29053. y += c->getY();
  29054. c = c->parentComponent_;
  29055. }
  29056. while (c != 0);
  29057. targetComponent->globalPositionToRelative (x, y);
  29058. }
  29059. }
  29060. void Component::setBounds (int x, int y, int w, int h)
  29061. {
  29062. // if component methods are being called from threads other than the message
  29063. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29064. checkMessageManagerIsLocked
  29065. if (w < 0) w = 0;
  29066. if (h < 0) h = 0;
  29067. const bool wasResized = (getWidth() != w || getHeight() != h);
  29068. const bool wasMoved = (getX() != x || getY() != y);
  29069. #ifdef JUCE_DEBUG
  29070. // It's a very bad idea to try to resize a window during its paint() method!
  29071. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  29072. #endif
  29073. if (wasMoved || wasResized)
  29074. {
  29075. if (flags.visibleFlag)
  29076. {
  29077. // send a fake mouse move to trigger enter/exit messages if needed..
  29078. sendFakeMouseMove();
  29079. if (! flags.hasHeavyweightPeerFlag)
  29080. repaintParent();
  29081. }
  29082. bounds_.setBounds (x, y, w, h);
  29083. if (wasResized)
  29084. repaint();
  29085. else if (! flags.hasHeavyweightPeerFlag)
  29086. repaintParent();
  29087. if (flags.hasHeavyweightPeerFlag)
  29088. {
  29089. ComponentPeer* const peer = getPeer();
  29090. if (peer != 0)
  29091. {
  29092. if (wasMoved && wasResized)
  29093. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  29094. else if (wasMoved)
  29095. peer->setPosition (getX(), getY());
  29096. else if (wasResized)
  29097. peer->setSize (getWidth(), getHeight());
  29098. }
  29099. }
  29100. sendMovedResizedMessages (wasMoved, wasResized);
  29101. }
  29102. }
  29103. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  29104. {
  29105. JUCE_TRY
  29106. {
  29107. if (wasMoved)
  29108. moved();
  29109. if (wasResized)
  29110. {
  29111. resized();
  29112. for (int i = childComponentList_.size(); --i >= 0;)
  29113. {
  29114. childComponentList_.getUnchecked(i)->parentSizeChanged();
  29115. i = jmin (i, childComponentList_.size());
  29116. }
  29117. }
  29118. if (parentComponent_ != 0)
  29119. parentComponent_->childBoundsChanged (this);
  29120. if (componentListeners_ != 0)
  29121. {
  29122. const ComponentDeletionWatcher deletionChecker (this);
  29123. for (int i = componentListeners_->size(); --i >= 0;)
  29124. {
  29125. ((ComponentListener*) componentListeners_->getUnchecked (i))
  29126. ->componentMovedOrResized (*this, wasMoved, wasResized);
  29127. if (deletionChecker.hasBeenDeleted())
  29128. return;
  29129. i = jmin (i, componentListeners_->size());
  29130. }
  29131. }
  29132. }
  29133. JUCE_CATCH_EXCEPTION
  29134. }
  29135. void Component::setSize (const int w, const int h)
  29136. {
  29137. setBounds (getX(), getY(), w, h);
  29138. }
  29139. void Component::setTopLeftPosition (const int x, const int y)
  29140. {
  29141. setBounds (x, y, getWidth(), getHeight());
  29142. }
  29143. void Component::setTopRightPosition (const int x, const int y)
  29144. {
  29145. setTopLeftPosition (x - getWidth(), y);
  29146. }
  29147. void Component::setBounds (const Rectangle& r)
  29148. {
  29149. setBounds (r.getX(),
  29150. r.getY(),
  29151. r.getWidth(),
  29152. r.getHeight());
  29153. }
  29154. void Component::setBoundsRelative (const float x, const float y,
  29155. const float w, const float h)
  29156. {
  29157. const int pw = getParentWidth();
  29158. const int ph = getParentHeight();
  29159. setBounds (roundFloatToInt (x * pw),
  29160. roundFloatToInt (y * ph),
  29161. roundFloatToInt (w * pw),
  29162. roundFloatToInt (h * ph));
  29163. }
  29164. void Component::setCentrePosition (const int x, const int y)
  29165. {
  29166. setTopLeftPosition (x - getWidth() / 2,
  29167. y - getHeight() / 2);
  29168. }
  29169. void Component::setCentreRelative (const float x, const float y)
  29170. {
  29171. setCentrePosition (roundFloatToInt (getParentWidth() * x),
  29172. roundFloatToInt (getParentHeight() * y));
  29173. }
  29174. void Component::centreWithSize (const int width, const int height)
  29175. {
  29176. setBounds ((getParentWidth() - width) / 2,
  29177. (getParentHeight() - height) / 2,
  29178. width,
  29179. height);
  29180. }
  29181. void Component::setBoundsInset (const BorderSize& borders)
  29182. {
  29183. setBounds (borders.getLeft(),
  29184. borders.getTop(),
  29185. getParentWidth() - (borders.getLeftAndRight()),
  29186. getParentHeight() - (borders.getTopAndBottom()));
  29187. }
  29188. void Component::setBoundsToFit (int x, int y, int width, int height,
  29189. const Justification& justification,
  29190. const bool onlyReduceInSize)
  29191. {
  29192. // it's no good calling this method unless both the component and
  29193. // target rectangle have a finite size.
  29194. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  29195. if (getWidth() > 0 && getHeight() > 0
  29196. && width > 0 && height > 0)
  29197. {
  29198. int newW, newH;
  29199. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  29200. {
  29201. newW = getWidth();
  29202. newH = getHeight();
  29203. }
  29204. else
  29205. {
  29206. const double imageRatio = getHeight() / (double) getWidth();
  29207. const double targetRatio = height / (double) width;
  29208. if (imageRatio <= targetRatio)
  29209. {
  29210. newW = width;
  29211. newH = jmin (height, roundDoubleToInt (newW * imageRatio));
  29212. }
  29213. else
  29214. {
  29215. newH = height;
  29216. newW = jmin (width, roundDoubleToInt (newH / imageRatio));
  29217. }
  29218. }
  29219. if (newW > 0 && newH > 0)
  29220. {
  29221. int newX, newY;
  29222. justification.applyToRectangle (newX, newY, newW, newH,
  29223. x, y, width, height);
  29224. setBounds (newX, newY, newW, newH);
  29225. }
  29226. }
  29227. }
  29228. bool Component::hitTest (int x, int y)
  29229. {
  29230. if (! flags.ignoresMouseClicksFlag)
  29231. return true;
  29232. if (flags.allowChildMouseClicksFlag)
  29233. {
  29234. for (int i = getNumChildComponents(); --i >= 0;)
  29235. {
  29236. Component* const c = getChildComponent (i);
  29237. if (c->isVisible()
  29238. && c->bounds_.contains (x, y)
  29239. && c->hitTest (x - c->getX(),
  29240. y - c->getY()))
  29241. {
  29242. return true;
  29243. }
  29244. }
  29245. }
  29246. return false;
  29247. }
  29248. void Component::setInterceptsMouseClicks (const bool allowClicks,
  29249. const bool allowClicksOnChildComponents) throw()
  29250. {
  29251. flags.ignoresMouseClicksFlag = ! allowClicks;
  29252. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  29253. }
  29254. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  29255. bool& allowsClicksOnChildComponents) const throw()
  29256. {
  29257. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  29258. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  29259. }
  29260. bool Component::contains (const int x, const int y)
  29261. {
  29262. if (((unsigned int) x) < (unsigned int) getWidth()
  29263. && ((unsigned int) y) < (unsigned int) getHeight()
  29264. && hitTest (x, y))
  29265. {
  29266. if (parentComponent_ != 0)
  29267. {
  29268. return parentComponent_->contains (x + getX(),
  29269. y + getY());
  29270. }
  29271. else if (flags.hasHeavyweightPeerFlag)
  29272. {
  29273. const ComponentPeer* const peer = getPeer();
  29274. if (peer != 0)
  29275. return peer->contains (x, y, true);
  29276. }
  29277. }
  29278. return false;
  29279. }
  29280. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  29281. {
  29282. if (! contains (x, y))
  29283. return false;
  29284. Component* p = this;
  29285. while (p->parentComponent_ != 0)
  29286. {
  29287. x += p->getX();
  29288. y += p->getY();
  29289. p = p->parentComponent_;
  29290. }
  29291. const Component* const c = p->getComponentAt (x, y);
  29292. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  29293. }
  29294. Component* Component::getComponentAt (const int x, const int y)
  29295. {
  29296. if (flags.visibleFlag
  29297. && ((unsigned int) x) < (unsigned int) getWidth()
  29298. && ((unsigned int) y) < (unsigned int) getHeight()
  29299. && hitTest (x, y))
  29300. {
  29301. for (int i = childComponentList_.size(); --i >= 0;)
  29302. {
  29303. Component* const child = childComponentList_.getUnchecked(i);
  29304. Component* const c = child->getComponentAt (x - child->getX(),
  29305. y - child->getY());
  29306. if (c != 0)
  29307. return c;
  29308. }
  29309. return this;
  29310. }
  29311. return 0;
  29312. }
  29313. void Component::addChildComponent (Component* const child, int zOrder)
  29314. {
  29315. // if component methods are being called from threads other than the message
  29316. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29317. checkMessageManagerIsLocked
  29318. if (child != 0 && child->parentComponent_ != this)
  29319. {
  29320. if (child->parentComponent_ != 0)
  29321. child->parentComponent_->removeChildComponent (child);
  29322. else
  29323. child->removeFromDesktop();
  29324. child->parentComponent_ = this;
  29325. if (child->isVisible())
  29326. child->repaintParent();
  29327. if (! child->isAlwaysOnTop())
  29328. {
  29329. if (zOrder < 0 || zOrder > childComponentList_.size())
  29330. zOrder = childComponentList_.size();
  29331. while (zOrder > 0)
  29332. {
  29333. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  29334. break;
  29335. --zOrder;
  29336. }
  29337. }
  29338. childComponentList_.insert (zOrder, child);
  29339. child->internalHierarchyChanged();
  29340. internalChildrenChanged();
  29341. }
  29342. }
  29343. void Component::addAndMakeVisible (Component* const child, int zOrder)
  29344. {
  29345. if (child != 0)
  29346. {
  29347. child->setVisible (true);
  29348. addChildComponent (child, zOrder);
  29349. }
  29350. }
  29351. void Component::removeChildComponent (Component* const child)
  29352. {
  29353. removeChildComponent (childComponentList_.indexOf (child));
  29354. }
  29355. Component* Component::removeChildComponent (const int index)
  29356. {
  29357. // if component methods are being called from threads other than the message
  29358. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29359. checkMessageManagerIsLocked
  29360. Component* const child = childComponentList_ [index];
  29361. if (child != 0)
  29362. {
  29363. sendFakeMouseMove();
  29364. child->repaintParent();
  29365. childComponentList_.remove (index);
  29366. child->parentComponent_ = 0;
  29367. JUCE_TRY
  29368. {
  29369. if ((currentlyFocusedComponent == child)
  29370. || child->isParentOf (currentlyFocusedComponent))
  29371. {
  29372. // get rid first to force the grabKeyboardFocus to change to us.
  29373. giveAwayFocus();
  29374. grabKeyboardFocus();
  29375. }
  29376. }
  29377. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  29378. catch (const std::exception& e)
  29379. {
  29380. currentlyFocusedComponent = 0;
  29381. Desktop::getInstance().triggerFocusCallback();
  29382. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  29383. }
  29384. catch (...)
  29385. {
  29386. currentlyFocusedComponent = 0;
  29387. Desktop::getInstance().triggerFocusCallback();
  29388. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  29389. }
  29390. #endif
  29391. child->internalHierarchyChanged();
  29392. internalChildrenChanged();
  29393. }
  29394. return child;
  29395. }
  29396. void Component::removeAllChildren()
  29397. {
  29398. for (int i = childComponentList_.size(); --i >= 0;)
  29399. removeChildComponent (i);
  29400. }
  29401. void Component::deleteAllChildren()
  29402. {
  29403. for (int i = childComponentList_.size(); --i >= 0;)
  29404. delete (removeChildComponent (i));
  29405. }
  29406. int Component::getNumChildComponents() const throw()
  29407. {
  29408. return childComponentList_.size();
  29409. }
  29410. Component* Component::getChildComponent (const int index) const throw()
  29411. {
  29412. return childComponentList_ [index];
  29413. }
  29414. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  29415. {
  29416. return childComponentList_.indexOf (const_cast <Component*> (child));
  29417. }
  29418. Component* Component::getTopLevelComponent() const throw()
  29419. {
  29420. const Component* comp = this;
  29421. while (comp->parentComponent_ != 0)
  29422. comp = comp->parentComponent_;
  29423. return (Component*) comp;
  29424. }
  29425. bool Component::isParentOf (const Component* possibleChild) const throw()
  29426. {
  29427. while (possibleChild->isValidComponent())
  29428. {
  29429. possibleChild = possibleChild->parentComponent_;
  29430. if (possibleChild == this)
  29431. return true;
  29432. }
  29433. return false;
  29434. }
  29435. void Component::parentHierarchyChanged()
  29436. {
  29437. }
  29438. void Component::childrenChanged()
  29439. {
  29440. }
  29441. void Component::internalChildrenChanged()
  29442. {
  29443. const ComponentDeletionWatcher deletionChecker (this);
  29444. const bool hasListeners = componentListeners_ != 0;
  29445. childrenChanged();
  29446. if (hasListeners)
  29447. {
  29448. if (deletionChecker.hasBeenDeleted())
  29449. return;
  29450. for (int i = componentListeners_->size(); --i >= 0;)
  29451. {
  29452. ((ComponentListener*) componentListeners_->getUnchecked (i))
  29453. ->componentChildrenChanged (*this);
  29454. if (deletionChecker.hasBeenDeleted())
  29455. return;
  29456. i = jmin (i, componentListeners_->size());
  29457. }
  29458. }
  29459. }
  29460. void Component::internalHierarchyChanged()
  29461. {
  29462. parentHierarchyChanged();
  29463. const ComponentDeletionWatcher deletionChecker (this);
  29464. if (componentListeners_ != 0)
  29465. {
  29466. for (int i = componentListeners_->size(); --i >= 0;)
  29467. {
  29468. ((ComponentListener*) componentListeners_->getUnchecked (i))
  29469. ->componentParentHierarchyChanged (*this);
  29470. if (deletionChecker.hasBeenDeleted())
  29471. return;
  29472. i = jmin (i, componentListeners_->size());
  29473. }
  29474. }
  29475. for (int i = childComponentList_.size(); --i >= 0;)
  29476. {
  29477. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  29478. // you really shouldn't delete the parent component during a callback telling you
  29479. // that it's changed..
  29480. jassert (! deletionChecker.hasBeenDeleted());
  29481. if (deletionChecker.hasBeenDeleted())
  29482. return;
  29483. i = jmin (i, childComponentList_.size());
  29484. }
  29485. }
  29486. void* Component::runModalLoopCallback (void* userData)
  29487. {
  29488. return (void*) (pointer_sized_int) ((Component*) userData)->runModalLoop();
  29489. }
  29490. int Component::runModalLoop()
  29491. {
  29492. if (! MessageManager::getInstance()->isThisTheMessageThread())
  29493. {
  29494. // use a callback so this can be called from non-gui threads
  29495. return (int) (pointer_sized_int)
  29496. MessageManager::getInstance()
  29497. ->callFunctionOnMessageThread (&runModalLoopCallback, (void*) this);
  29498. }
  29499. Component* const prevFocused = getCurrentlyFocusedComponent();
  29500. ComponentDeletionWatcher* deletionChecker = 0;
  29501. if (prevFocused != 0)
  29502. deletionChecker = new ComponentDeletionWatcher (prevFocused);
  29503. if (! isCurrentlyModal())
  29504. enterModalState();
  29505. JUCE_TRY
  29506. {
  29507. while (flags.currentlyModalFlag && flags.visibleFlag)
  29508. {
  29509. if (! MessageManager::getInstance()->dispatchNextMessage())
  29510. break;
  29511. // check whether this component was deleted during the last message
  29512. if (! isValidMessageListener())
  29513. break;
  29514. }
  29515. }
  29516. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  29517. catch (const std::exception& e)
  29518. {
  29519. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  29520. return 0;
  29521. }
  29522. catch (...)
  29523. {
  29524. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  29525. return 0;
  29526. }
  29527. #endif
  29528. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  29529. int returnValue = 0;
  29530. if (modalIndex >= 0)
  29531. {
  29532. modalComponentReturnValueKeys.remove (modalIndex);
  29533. returnValue = modalReturnValues.remove (modalIndex);
  29534. }
  29535. modalComponentStack.removeValue (this);
  29536. if (deletionChecker != 0)
  29537. {
  29538. if (! deletionChecker->hasBeenDeleted())
  29539. prevFocused->grabKeyboardFocus();
  29540. delete deletionChecker;
  29541. }
  29542. return returnValue;
  29543. }
  29544. void Component::enterModalState (const bool takeKeyboardFocus)
  29545. {
  29546. // if component methods are being called from threads other than the message
  29547. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29548. checkMessageManagerIsLocked
  29549. // Check for an attempt to make a component modal when it already is!
  29550. // This can cause nasty problems..
  29551. jassert (! flags.currentlyModalFlag);
  29552. if (! isCurrentlyModal())
  29553. {
  29554. modalComponentStack.add (this);
  29555. modalComponentReturnValueKeys.add (this);
  29556. modalReturnValues.add (0);
  29557. flags.currentlyModalFlag = true;
  29558. setVisible (true);
  29559. if (takeKeyboardFocus)
  29560. grabKeyboardFocus();
  29561. }
  29562. }
  29563. void Component::exitModalState (const int returnValue)
  29564. {
  29565. if (isCurrentlyModal())
  29566. {
  29567. if (MessageManager::getInstance()->isThisTheMessageThread())
  29568. {
  29569. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  29570. if (modalIndex >= 0)
  29571. {
  29572. modalReturnValues.set (modalIndex, returnValue);
  29573. }
  29574. else
  29575. {
  29576. modalComponentReturnValueKeys.add (this);
  29577. modalReturnValues.add (returnValue);
  29578. }
  29579. modalComponentStack.removeValue (this);
  29580. flags.currentlyModalFlag = false;
  29581. }
  29582. else
  29583. {
  29584. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  29585. }
  29586. }
  29587. }
  29588. bool Component::isCurrentlyModal() const throw()
  29589. {
  29590. return flags.currentlyModalFlag
  29591. && getCurrentlyModalComponent() == this;
  29592. }
  29593. bool Component::isCurrentlyBlockedByAnotherModalComponent() const throw()
  29594. {
  29595. Component* const mc = getCurrentlyModalComponent();
  29596. return mc != 0
  29597. && mc != this
  29598. && (! mc->isParentOf (this))
  29599. && ! mc->canModalEventBeSentToComponent (this);
  29600. }
  29601. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent() throw()
  29602. {
  29603. Component* const c = (Component*) modalComponentStack.getLast();
  29604. return c->isValidComponent() ? c : 0;
  29605. }
  29606. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  29607. {
  29608. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  29609. }
  29610. bool Component::isBroughtToFrontOnMouseClick() const throw()
  29611. {
  29612. return flags.bringToFrontOnClickFlag;
  29613. }
  29614. void Component::setMouseCursor (const MouseCursor& cursor) throw()
  29615. {
  29616. cursor_ = cursor;
  29617. if (flags.visibleFlag)
  29618. {
  29619. int mx, my;
  29620. getMouseXYRelative (mx, my);
  29621. if (flags.draggingFlag || reallyContains (mx, my, false))
  29622. {
  29623. internalUpdateMouseCursor (false);
  29624. }
  29625. }
  29626. }
  29627. const MouseCursor Component::getMouseCursor()
  29628. {
  29629. return cursor_;
  29630. }
  29631. void Component::updateMouseCursor() const throw()
  29632. {
  29633. sendFakeMouseMove();
  29634. }
  29635. void Component::internalUpdateMouseCursor (const bool forcedUpdate) throw()
  29636. {
  29637. ComponentPeer* const peer = getPeer();
  29638. if (peer != 0)
  29639. {
  29640. MouseCursor mc (getMouseCursor());
  29641. if (isUnboundedMouseModeOn && (unboundedMouseOffsetX != 0
  29642. || unboundedMouseOffsetY != 0
  29643. || ! isCursorVisibleUntilOffscreen))
  29644. {
  29645. mc = MouseCursor::NoCursor;
  29646. }
  29647. static void* currentCursorHandle = 0;
  29648. if (forcedUpdate || mc.getHandle() != currentCursorHandle)
  29649. {
  29650. currentCursorHandle = mc.getHandle();
  29651. mc.showInWindow (peer);
  29652. }
  29653. }
  29654. }
  29655. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  29656. {
  29657. flags.repaintOnMouseActivityFlag = shouldRepaint;
  29658. }
  29659. void Component::repaintParent() throw()
  29660. {
  29661. if (flags.visibleFlag)
  29662. internalRepaint (0, 0, getWidth(), getHeight());
  29663. }
  29664. void Component::repaint() throw()
  29665. {
  29666. repaint (0, 0, getWidth(), getHeight());
  29667. }
  29668. void Component::repaint (const int x, const int y,
  29669. const int w, const int h) throw()
  29670. {
  29671. deleteAndZero (bufferedImage_);
  29672. if (flags.visibleFlag)
  29673. internalRepaint (x, y, w, h);
  29674. }
  29675. void Component::internalRepaint (int x, int y, int w, int h)
  29676. {
  29677. // if component methods are being called from threads other than the message
  29678. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29679. checkMessageManagerIsLocked
  29680. if (x < 0)
  29681. {
  29682. w += x;
  29683. x = 0;
  29684. }
  29685. if (x + w > getWidth())
  29686. w = getWidth() - x;
  29687. if (w > 0)
  29688. {
  29689. if (y < 0)
  29690. {
  29691. h += y;
  29692. y = 0;
  29693. }
  29694. if (y + h > getHeight())
  29695. h = getHeight() - y;
  29696. if (h > 0)
  29697. {
  29698. if (parentComponent_ != 0)
  29699. {
  29700. x += getX();
  29701. y += getY();
  29702. if (parentComponent_->flags.visibleFlag)
  29703. parentComponent_->internalRepaint (x, y, w, h);
  29704. }
  29705. else if (flags.hasHeavyweightPeerFlag)
  29706. {
  29707. ComponentPeer* const peer = getPeer();
  29708. if (peer != 0)
  29709. peer->repaint (x, y, w, h);
  29710. }
  29711. }
  29712. }
  29713. }
  29714. void Component::paintEntireComponent (Graphics& originalContext)
  29715. {
  29716. jassert (! originalContext.isClipEmpty());
  29717. #ifdef JUCE_DEBUG
  29718. flags.isInsidePaintCall = true;
  29719. #endif
  29720. Graphics* g = &originalContext;
  29721. Image* effectImage = 0;
  29722. if (effect_ != 0)
  29723. {
  29724. effectImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  29725. getWidth(), getHeight(),
  29726. ! flags.opaqueFlag);
  29727. g = new Graphics (*effectImage);
  29728. }
  29729. g->saveState();
  29730. clipObscuredRegions (*g, g->getClipBounds(), 0, 0);
  29731. if (! g->isClipEmpty())
  29732. {
  29733. if (bufferedImage_ != 0)
  29734. {
  29735. g->setColour (Colours::black);
  29736. g->drawImageAt (bufferedImage_, 0, 0);
  29737. }
  29738. else
  29739. {
  29740. if (flags.bufferToImageFlag)
  29741. {
  29742. if (bufferedImage_ == 0)
  29743. {
  29744. bufferedImage_ = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  29745. getWidth(), getHeight(), ! flags.opaqueFlag);
  29746. Graphics imG (*bufferedImage_);
  29747. paint (imG);
  29748. }
  29749. g->setColour (Colours::black);
  29750. g->drawImageAt (bufferedImage_, 0, 0);
  29751. }
  29752. else
  29753. {
  29754. paint (*g);
  29755. g->resetToDefaultState();
  29756. }
  29757. }
  29758. }
  29759. g->restoreState();
  29760. for (int i = 0; i < childComponentList_.size(); ++i)
  29761. {
  29762. Component* const child = childComponentList_.getUnchecked (i);
  29763. if (child->isVisible())
  29764. {
  29765. g->saveState();
  29766. if (g->reduceClipRegion (child->getX(), child->getY(),
  29767. child->getWidth(), child->getHeight()))
  29768. {
  29769. for (int j = i + 1; j < childComponentList_.size(); ++j)
  29770. {
  29771. const Component* const sibling = childComponentList_.getUnchecked (j);
  29772. if (sibling->flags.opaqueFlag && sibling->isVisible())
  29773. g->excludeClipRegion (sibling->getX(), sibling->getY(),
  29774. sibling->getWidth(), sibling->getHeight());
  29775. }
  29776. if (! g->isClipEmpty())
  29777. {
  29778. g->setOrigin (child->getX(), child->getY());
  29779. child->paintEntireComponent (*g);
  29780. }
  29781. }
  29782. g->restoreState();
  29783. }
  29784. }
  29785. JUCE_TRY
  29786. {
  29787. g->saveState();
  29788. paintOverChildren (*g);
  29789. g->restoreState();
  29790. }
  29791. JUCE_CATCH_EXCEPTION
  29792. if (effect_ != 0)
  29793. {
  29794. delete g;
  29795. effect_->applyEffect (*effectImage, originalContext);
  29796. delete effectImage;
  29797. }
  29798. #ifdef JUCE_DEBUG
  29799. flags.isInsidePaintCall = false;
  29800. #endif
  29801. }
  29802. Image* Component::createComponentSnapshot (const Rectangle& areaToGrab,
  29803. const bool clipImageToComponentBounds)
  29804. {
  29805. Rectangle r (areaToGrab);
  29806. if (clipImageToComponentBounds)
  29807. r = r.getIntersection (Rectangle (0, 0, getWidth(), getHeight()));
  29808. Image* const componentImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  29809. jmax (1, r.getWidth()),
  29810. jmax (1, r.getHeight()),
  29811. true);
  29812. Graphics imageContext (*componentImage);
  29813. imageContext.setOrigin (-r.getX(),
  29814. -r.getY());
  29815. paintEntireComponent (imageContext);
  29816. return componentImage;
  29817. }
  29818. void Component::setComponentEffect (ImageEffectFilter* const effect)
  29819. {
  29820. if (effect_ != effect)
  29821. {
  29822. effect_ = effect;
  29823. repaint();
  29824. }
  29825. }
  29826. LookAndFeel& Component::getLookAndFeel() const throw()
  29827. {
  29828. const Component* c = this;
  29829. do
  29830. {
  29831. if (c->lookAndFeel_ != 0)
  29832. return *(c->lookAndFeel_);
  29833. c = c->parentComponent_;
  29834. }
  29835. while (c != 0);
  29836. return LookAndFeel::getDefaultLookAndFeel();
  29837. }
  29838. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  29839. {
  29840. if (lookAndFeel_ != newLookAndFeel)
  29841. {
  29842. lookAndFeel_ = newLookAndFeel;
  29843. sendLookAndFeelChange();
  29844. }
  29845. }
  29846. void Component::lookAndFeelChanged()
  29847. {
  29848. }
  29849. void Component::sendLookAndFeelChange()
  29850. {
  29851. repaint();
  29852. lookAndFeelChanged();
  29853. // (it's not a great idea to do anything that would delete this component
  29854. // during the lookAndFeelChanged() callback)
  29855. jassert (isValidComponent());
  29856. const ComponentDeletionWatcher deletionChecker (this);
  29857. for (int i = childComponentList_.size(); --i >= 0;)
  29858. {
  29859. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  29860. if (deletionChecker.hasBeenDeleted())
  29861. return;
  29862. i = jmin (i, childComponentList_.size());
  29863. }
  29864. }
  29865. static const String getColourPropertyName (const int colourId) throw()
  29866. {
  29867. String s;
  29868. s.preallocateStorage (18);
  29869. s << T("jcclr_") << colourId;
  29870. return s;
  29871. }
  29872. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const throw()
  29873. {
  29874. const String customColour (getComponentProperty (getColourPropertyName (colourId),
  29875. inheritFromParent,
  29876. String::empty));
  29877. if (customColour.isNotEmpty())
  29878. return Colour (customColour.getIntValue());
  29879. return getLookAndFeel().findColour (colourId);
  29880. }
  29881. bool Component::isColourSpecified (const int colourId) const throw()
  29882. {
  29883. return getComponentProperty (getColourPropertyName (colourId),
  29884. false,
  29885. String::empty).isNotEmpty();
  29886. }
  29887. void Component::removeColour (const int colourId)
  29888. {
  29889. if (isColourSpecified (colourId))
  29890. {
  29891. removeComponentProperty (getColourPropertyName (colourId));
  29892. colourChanged();
  29893. }
  29894. }
  29895. void Component::setColour (const int colourId, const Colour& colour)
  29896. {
  29897. const String colourName (getColourPropertyName (colourId));
  29898. const String customColour (getComponentProperty (colourName, false, String::empty));
  29899. if (customColour.isEmpty() || Colour (customColour.getIntValue()) != colour)
  29900. {
  29901. setComponentProperty (colourName, colour);
  29902. colourChanged();
  29903. }
  29904. }
  29905. void Component::copyAllExplicitColoursTo (Component& target) const throw()
  29906. {
  29907. if (propertySet_ != 0)
  29908. {
  29909. const StringPairArray& props = propertySet_->getAllProperties();
  29910. const StringArray& keys = props.getAllKeys();
  29911. for (int i = 0; i < keys.size(); ++i)
  29912. {
  29913. if (keys[i].startsWith (T("jcclr_")))
  29914. {
  29915. target.setComponentProperty (keys[i],
  29916. props.getAllValues() [i]);
  29917. }
  29918. }
  29919. target.colourChanged();
  29920. }
  29921. }
  29922. void Component::colourChanged()
  29923. {
  29924. }
  29925. const Rectangle Component::getUnclippedArea() const
  29926. {
  29927. int x = 0, y = 0, w = getWidth(), h = getHeight();
  29928. Component* p = parentComponent_;
  29929. int px = getX();
  29930. int py = getY();
  29931. while (p != 0)
  29932. {
  29933. if (! Rectangle::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  29934. return Rectangle();
  29935. px += p->getX();
  29936. py += p->getY();
  29937. p = p->parentComponent_;
  29938. }
  29939. return Rectangle (x, y, w, h);
  29940. }
  29941. void Component::clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  29942. const int deltaX, const int deltaY) const throw()
  29943. {
  29944. for (int i = childComponentList_.size(); --i >= 0;)
  29945. {
  29946. const Component* const c = childComponentList_.getUnchecked(i);
  29947. if (c->isVisible())
  29948. {
  29949. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  29950. if (! newClip.isEmpty())
  29951. {
  29952. if (c->isOpaque())
  29953. {
  29954. g.excludeClipRegion (deltaX + newClip.getX(),
  29955. deltaY + newClip.getY(),
  29956. newClip.getWidth(),
  29957. newClip.getHeight());
  29958. }
  29959. else
  29960. {
  29961. newClip.translate (-c->getX(), -c->getY());
  29962. c->clipObscuredRegions (g, newClip,
  29963. c->getX() + deltaX,
  29964. c->getY() + deltaY);
  29965. }
  29966. }
  29967. }
  29968. }
  29969. }
  29970. void Component::getVisibleArea (RectangleList& result,
  29971. const bool includeSiblings) const
  29972. {
  29973. result.clear();
  29974. const Rectangle unclipped (getUnclippedArea());
  29975. if (! unclipped.isEmpty())
  29976. {
  29977. result.add (unclipped);
  29978. if (includeSiblings)
  29979. {
  29980. const Component* const c = getTopLevelComponent();
  29981. int x = 0, y = 0;
  29982. c->relativePositionToOtherComponent (this, x, y);
  29983. c->subtractObscuredRegions (result, x, y,
  29984. Rectangle (0, 0, c->getWidth(), c->getHeight()),
  29985. this);
  29986. }
  29987. subtractObscuredRegions (result, 0, 0, unclipped, 0);
  29988. result.consolidate();
  29989. }
  29990. }
  29991. void Component::subtractObscuredRegions (RectangleList& result,
  29992. const int deltaX,
  29993. const int deltaY,
  29994. const Rectangle& clipRect,
  29995. const Component* const compToAvoid) const throw()
  29996. {
  29997. for (int i = childComponentList_.size(); --i >= 0;)
  29998. {
  29999. const Component* const c = childComponentList_.getUnchecked(i);
  30000. if (c != compToAvoid && c->isVisible())
  30001. {
  30002. if (c->isOpaque())
  30003. {
  30004. Rectangle childBounds (c->bounds_.getIntersection (clipRect));
  30005. childBounds.translate (deltaX, deltaY);
  30006. result.subtract (childBounds);
  30007. }
  30008. else
  30009. {
  30010. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  30011. newClip.translate (-c->getX(), -c->getY());
  30012. c->subtractObscuredRegions (result,
  30013. c->getX() + deltaX,
  30014. c->getY() + deltaY,
  30015. newClip,
  30016. compToAvoid);
  30017. }
  30018. }
  30019. }
  30020. }
  30021. void Component::mouseEnter (const MouseEvent&)
  30022. {
  30023. // base class does nothing
  30024. }
  30025. void Component::mouseExit (const MouseEvent&)
  30026. {
  30027. // base class does nothing
  30028. }
  30029. void Component::mouseDown (const MouseEvent&)
  30030. {
  30031. // base class does nothing
  30032. }
  30033. void Component::mouseUp (const MouseEvent&)
  30034. {
  30035. // base class does nothing
  30036. }
  30037. void Component::mouseDrag (const MouseEvent&)
  30038. {
  30039. // base class does nothing
  30040. }
  30041. void Component::mouseMove (const MouseEvent&)
  30042. {
  30043. // base class does nothing
  30044. }
  30045. void Component::mouseDoubleClick (const MouseEvent&)
  30046. {
  30047. // base class does nothing
  30048. }
  30049. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  30050. {
  30051. // the base class just passes this event up to its parent..
  30052. if (parentComponent_ != 0)
  30053. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  30054. wheelIncrementX, wheelIncrementY);
  30055. }
  30056. void Component::resized()
  30057. {
  30058. // base class does nothing
  30059. }
  30060. void Component::moved()
  30061. {
  30062. // base class does nothing
  30063. }
  30064. void Component::childBoundsChanged (Component*)
  30065. {
  30066. // base class does nothing
  30067. }
  30068. void Component::parentSizeChanged()
  30069. {
  30070. // base class does nothing
  30071. }
  30072. void Component::addComponentListener (ComponentListener* const newListener) throw()
  30073. {
  30074. if (componentListeners_ == 0)
  30075. componentListeners_ = new VoidArray (4);
  30076. componentListeners_->addIfNotAlreadyThere (newListener);
  30077. }
  30078. void Component::removeComponentListener (ComponentListener* const listenerToRemove) throw()
  30079. {
  30080. jassert (isValidComponent());
  30081. if (componentListeners_ != 0)
  30082. componentListeners_->removeValue (listenerToRemove);
  30083. }
  30084. void Component::inputAttemptWhenModal()
  30085. {
  30086. getTopLevelComponent()->toFront (true);
  30087. getLookAndFeel().playAlertSound();
  30088. }
  30089. bool Component::canModalEventBeSentToComponent (const Component*)
  30090. {
  30091. return false;
  30092. }
  30093. void Component::internalModalInputAttempt()
  30094. {
  30095. Component* const current = getCurrentlyModalComponent();
  30096. if (current != 0)
  30097. current->inputAttemptWhenModal();
  30098. }
  30099. void Component::paint (Graphics&)
  30100. {
  30101. // all painting is done in the subclasses
  30102. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  30103. }
  30104. void Component::paintOverChildren (Graphics&)
  30105. {
  30106. // all painting is done in the subclasses
  30107. }
  30108. void Component::handleMessage (const Message& message)
  30109. {
  30110. if (message.intParameter1 == exitModalStateMessage)
  30111. {
  30112. exitModalState (message.intParameter2);
  30113. }
  30114. else if (message.intParameter1 == customCommandMessage)
  30115. {
  30116. handleCommandMessage (message.intParameter2);
  30117. }
  30118. }
  30119. void Component::postCommandMessage (const int commandId) throw()
  30120. {
  30121. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  30122. }
  30123. void Component::handleCommandMessage (int)
  30124. {
  30125. // used by subclasses
  30126. }
  30127. void Component::addMouseListener (MouseListener* const newListener,
  30128. const bool wantsEventsForAllNestedChildComponents) throw()
  30129. {
  30130. // if component methods are being called from threads other than the message
  30131. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30132. checkMessageManagerIsLocked
  30133. if (mouseListeners_ == 0)
  30134. mouseListeners_ = new VoidArray (4);
  30135. if (! mouseListeners_->contains (newListener))
  30136. {
  30137. if (wantsEventsForAllNestedChildComponents)
  30138. {
  30139. mouseListeners_->insert (0, newListener);
  30140. ++numDeepMouseListeners;
  30141. }
  30142. else
  30143. {
  30144. mouseListeners_->add (newListener);
  30145. }
  30146. }
  30147. }
  30148. void Component::removeMouseListener (MouseListener* const listenerToRemove) throw()
  30149. {
  30150. // if component methods are being called from threads other than the message
  30151. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30152. checkMessageManagerIsLocked
  30153. if (mouseListeners_ != 0)
  30154. {
  30155. const int index = mouseListeners_->indexOf (listenerToRemove);
  30156. if (index >= 0)
  30157. {
  30158. if (index < numDeepMouseListeners)
  30159. --numDeepMouseListeners;
  30160. mouseListeners_->remove (index);
  30161. }
  30162. }
  30163. }
  30164. void Component::internalMouseEnter (int x, int y, int64 time)
  30165. {
  30166. if (isCurrentlyBlockedByAnotherModalComponent())
  30167. {
  30168. // if something else is modal, always just show a normal mouse cursor
  30169. if (componentUnderMouse == this)
  30170. {
  30171. ComponentPeer* const peer = getPeer();
  30172. if (peer != 0)
  30173. {
  30174. MouseCursor mc (MouseCursor::NormalCursor);
  30175. mc.showInWindow (peer);
  30176. }
  30177. }
  30178. return;
  30179. }
  30180. if (! flags.mouseInsideFlag)
  30181. {
  30182. flags.mouseInsideFlag = true;
  30183. flags.mouseOverFlag = true;
  30184. flags.draggingFlag = false;
  30185. if (isValidComponent())
  30186. {
  30187. const ComponentDeletionWatcher deletionChecker (this);
  30188. if (flags.repaintOnMouseActivityFlag)
  30189. repaint();
  30190. const MouseEvent me (x, y,
  30191. ModifierKeys::getCurrentModifiers(),
  30192. this,
  30193. Time (time),
  30194. x, y,
  30195. Time (time),
  30196. 0, false);
  30197. mouseEnter (me);
  30198. if (deletionChecker.hasBeenDeleted())
  30199. return;
  30200. Desktop::getInstance().resetTimer();
  30201. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30202. {
  30203. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseEnter (me);
  30204. if (deletionChecker.hasBeenDeleted())
  30205. return;
  30206. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30207. }
  30208. if (mouseListeners_ != 0)
  30209. {
  30210. for (int i = mouseListeners_->size(); --i >= 0;)
  30211. {
  30212. ((MouseListener*) mouseListeners_->getUnchecked(i))->mouseEnter (me);
  30213. if (deletionChecker.hasBeenDeleted())
  30214. return;
  30215. i = jmin (i, mouseListeners_->size());
  30216. }
  30217. }
  30218. const Component* p = parentComponent_;
  30219. while (p != 0)
  30220. {
  30221. const ComponentDeletionWatcher parentDeletionChecker (p);
  30222. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30223. {
  30224. ((MouseListener*) (p->mouseListeners_->getUnchecked(i)))->mouseEnter (me);
  30225. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30226. return;
  30227. i = jmin (i, p->numDeepMouseListeners);
  30228. }
  30229. p = p->parentComponent_;
  30230. }
  30231. }
  30232. }
  30233. if (componentUnderMouse == this)
  30234. internalUpdateMouseCursor (true);
  30235. }
  30236. void Component::internalMouseExit (int x, int y, int64 time)
  30237. {
  30238. const ComponentDeletionWatcher deletionChecker (this);
  30239. if (flags.draggingFlag)
  30240. {
  30241. internalMouseUp (ModifierKeys::getCurrentModifiers().getRawFlags(), x, y, time);
  30242. if (deletionChecker.hasBeenDeleted())
  30243. return;
  30244. }
  30245. enableUnboundedMouseMovement (false);
  30246. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  30247. {
  30248. flags.mouseInsideFlag = false;
  30249. flags.mouseOverFlag = false;
  30250. flags.draggingFlag = false;
  30251. if (flags.repaintOnMouseActivityFlag)
  30252. repaint();
  30253. const MouseEvent me (x, y,
  30254. ModifierKeys::getCurrentModifiers(),
  30255. this,
  30256. Time (time),
  30257. x, y,
  30258. Time (time),
  30259. 0, false);
  30260. mouseExit (me);
  30261. if (deletionChecker.hasBeenDeleted())
  30262. return;
  30263. Desktop::getInstance().resetTimer();
  30264. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30265. {
  30266. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseExit (me);
  30267. if (deletionChecker.hasBeenDeleted())
  30268. return;
  30269. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30270. }
  30271. if (mouseListeners_ != 0)
  30272. {
  30273. for (int i = mouseListeners_->size(); --i >= 0;)
  30274. {
  30275. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  30276. if (deletionChecker.hasBeenDeleted())
  30277. return;
  30278. i = jmin (i, mouseListeners_->size());
  30279. }
  30280. }
  30281. const Component* p = parentComponent_;
  30282. while (p != 0)
  30283. {
  30284. const ComponentDeletionWatcher parentDeletionChecker (p);
  30285. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30286. {
  30287. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseExit (me);
  30288. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30289. return;
  30290. i = jmin (i, p->numDeepMouseListeners);
  30291. }
  30292. p = p->parentComponent_;
  30293. }
  30294. }
  30295. }
  30296. class InternalDragRepeater : public Timer
  30297. {
  30298. public:
  30299. InternalDragRepeater()
  30300. {}
  30301. ~InternalDragRepeater()
  30302. {}
  30303. void timerCallback()
  30304. {
  30305. Component* const c = Component::getComponentUnderMouse();
  30306. if (c != 0 && c->isMouseButtonDown())
  30307. {
  30308. int x, y;
  30309. c->getMouseXYRelative (x, y);
  30310. // the offsets have been added on, so must be taken off before calling the
  30311. // drag.. otherwise they'll be added twice
  30312. x -= unboundedMouseOffsetX;
  30313. y -= unboundedMouseOffsetY;
  30314. c->internalMouseDrag (x, y, Time::currentTimeMillis());
  30315. }
  30316. }
  30317. juce_UseDebuggingNewOperator
  30318. };
  30319. static InternalDragRepeater* dragRepeater = 0;
  30320. void Component::beginDragAutoRepeat (const int interval)
  30321. {
  30322. if (interval > 0)
  30323. {
  30324. if (dragRepeater == 0)
  30325. dragRepeater = new InternalDragRepeater();
  30326. if (dragRepeater->getTimerInterval() != interval)
  30327. dragRepeater->startTimer (interval);
  30328. }
  30329. else
  30330. {
  30331. deleteAndZero (dragRepeater);
  30332. }
  30333. }
  30334. void Component::internalMouseDown (const int x, const int y)
  30335. {
  30336. const ComponentDeletionWatcher deletionChecker (this);
  30337. if (isCurrentlyBlockedByAnotherModalComponent())
  30338. {
  30339. internalModalInputAttempt();
  30340. if (deletionChecker.hasBeenDeleted())
  30341. return;
  30342. // If processing the input attempt has exited the modal loop, we'll allow the event
  30343. // to be delivered..
  30344. if (isCurrentlyBlockedByAnotherModalComponent())
  30345. {
  30346. // allow blocked mouse-events to go to global listeners..
  30347. const MouseEvent me (x, y,
  30348. ModifierKeys::getCurrentModifiers(),
  30349. this,
  30350. Time (juce_recentMouseDownTimes[0]),
  30351. x, y,
  30352. Time (juce_recentMouseDownTimes[0]),
  30353. countMouseClicks(),
  30354. false);
  30355. Desktop::getInstance().resetTimer();
  30356. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30357. {
  30358. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  30359. if (deletionChecker.hasBeenDeleted())
  30360. return;
  30361. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30362. }
  30363. return;
  30364. }
  30365. }
  30366. {
  30367. Component* c = this;
  30368. while (c != 0)
  30369. {
  30370. if (c->isBroughtToFrontOnMouseClick())
  30371. {
  30372. c->toFront (true);
  30373. if (deletionChecker.hasBeenDeleted())
  30374. return;
  30375. }
  30376. c = c->parentComponent_;
  30377. }
  30378. }
  30379. if (! flags.dontFocusOnMouseClickFlag)
  30380. grabFocusInternal (focusChangedByMouseClick);
  30381. if (! deletionChecker.hasBeenDeleted())
  30382. {
  30383. flags.draggingFlag = true;
  30384. flags.mouseOverFlag = true;
  30385. if (flags.repaintOnMouseActivityFlag)
  30386. repaint();
  30387. const MouseEvent me (x, y,
  30388. ModifierKeys::getCurrentModifiers(),
  30389. this,
  30390. Time (juce_recentMouseDownTimes[0]),
  30391. x, y,
  30392. Time (juce_recentMouseDownTimes[0]),
  30393. countMouseClicks(),
  30394. false);
  30395. mouseDown (me);
  30396. if (deletionChecker.hasBeenDeleted())
  30397. return;
  30398. Desktop::getInstance().resetTimer();
  30399. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30400. {
  30401. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  30402. if (deletionChecker.hasBeenDeleted())
  30403. return;
  30404. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30405. }
  30406. if (mouseListeners_ != 0)
  30407. {
  30408. for (int i = mouseListeners_->size(); --i >= 0;)
  30409. {
  30410. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  30411. if (deletionChecker.hasBeenDeleted())
  30412. return;
  30413. i = jmin (i, mouseListeners_->size());
  30414. }
  30415. }
  30416. const Component* p = parentComponent_;
  30417. while (p != 0)
  30418. {
  30419. const ComponentDeletionWatcher parentDeletionChecker (p);
  30420. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30421. {
  30422. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDown (me);
  30423. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30424. return;
  30425. i = jmin (i, p->numDeepMouseListeners);
  30426. }
  30427. p = p->parentComponent_;
  30428. }
  30429. }
  30430. }
  30431. void Component::internalMouseUp (const int oldModifiers, int x, int y, const int64 time)
  30432. {
  30433. if (isValidComponent() && flags.draggingFlag)
  30434. {
  30435. flags.draggingFlag = false;
  30436. deleteAndZero (dragRepeater);
  30437. x += unboundedMouseOffsetX;
  30438. y += unboundedMouseOffsetY;
  30439. juce_LastMousePosX = x;
  30440. juce_LastMousePosY = y;
  30441. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  30442. const ComponentDeletionWatcher deletionChecker (this);
  30443. if (flags.repaintOnMouseActivityFlag)
  30444. repaint();
  30445. int mdx = juce_recentMouseDownX[0];
  30446. int mdy = juce_recentMouseDownY[0];
  30447. globalPositionToRelative (mdx, mdy);
  30448. const MouseEvent me (x, y,
  30449. oldModifiers,
  30450. this,
  30451. Time (time),
  30452. mdx, mdy,
  30453. Time (juce_recentMouseDownTimes [0]),
  30454. countMouseClicks(),
  30455. juce_MouseHasMovedSignificantlySincePressed
  30456. || juce_recentMouseDownTimes[0] + 300 < time);
  30457. mouseUp (me);
  30458. if (deletionChecker.hasBeenDeleted())
  30459. return;
  30460. Desktop::getInstance().resetTimer();
  30461. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30462. {
  30463. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseUp (me);
  30464. if (deletionChecker.hasBeenDeleted())
  30465. return;
  30466. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30467. }
  30468. if (mouseListeners_ != 0)
  30469. {
  30470. for (int i = mouseListeners_->size(); --i >= 0;)
  30471. {
  30472. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  30473. if (deletionChecker.hasBeenDeleted())
  30474. return;
  30475. i = jmin (i, mouseListeners_->size());
  30476. }
  30477. }
  30478. {
  30479. const Component* p = parentComponent_;
  30480. while (p != 0)
  30481. {
  30482. const ComponentDeletionWatcher parentDeletionChecker (p);
  30483. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30484. {
  30485. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseUp (me);
  30486. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30487. return;
  30488. i = jmin (i, p->numDeepMouseListeners);
  30489. }
  30490. p = p->parentComponent_;
  30491. }
  30492. }
  30493. // check for double-click
  30494. if (me.getNumberOfClicks() >= 2)
  30495. {
  30496. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  30497. mouseDoubleClick (me);
  30498. int i;
  30499. for (i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30500. {
  30501. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDoubleClick (me);
  30502. if (deletionChecker.hasBeenDeleted())
  30503. return;
  30504. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30505. }
  30506. for (i = numListeners; --i >= 0;)
  30507. {
  30508. if (deletionChecker.hasBeenDeleted() || mouseListeners_ == 0)
  30509. return;
  30510. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  30511. if (ml != 0)
  30512. ml->mouseDoubleClick (me);
  30513. }
  30514. if (deletionChecker.hasBeenDeleted())
  30515. return;
  30516. const Component* p = parentComponent_;
  30517. while (p != 0)
  30518. {
  30519. const ComponentDeletionWatcher parentDeletionChecker (p);
  30520. for (i = p->numDeepMouseListeners; --i >= 0;)
  30521. {
  30522. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDoubleClick (me);
  30523. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30524. return;
  30525. i = jmin (i, p->numDeepMouseListeners);
  30526. }
  30527. p = p->parentComponent_;
  30528. }
  30529. }
  30530. }
  30531. enableUnboundedMouseMovement (false);
  30532. }
  30533. void Component::internalMouseDrag (int x, int y, const int64 time)
  30534. {
  30535. if (isValidComponent() && flags.draggingFlag)
  30536. {
  30537. flags.mouseOverFlag = reallyContains (x, y, false);
  30538. x += unboundedMouseOffsetX;
  30539. y += unboundedMouseOffsetY;
  30540. juce_LastMousePosX = x;
  30541. juce_LastMousePosY = y;
  30542. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  30543. juce_MouseHasMovedSignificantlySincePressed
  30544. = juce_MouseHasMovedSignificantlySincePressed
  30545. || abs (juce_recentMouseDownX[0] - juce_LastMousePosX) >= 4
  30546. || abs (juce_recentMouseDownY[0] - juce_LastMousePosY) >= 4;
  30547. const ComponentDeletionWatcher deletionChecker (this);
  30548. int mdx = juce_recentMouseDownX[0];
  30549. int mdy = juce_recentMouseDownY[0];
  30550. globalPositionToRelative (mdx, mdy);
  30551. const MouseEvent me (x, y,
  30552. ModifierKeys::getCurrentModifiers(),
  30553. this,
  30554. Time (time),
  30555. mdx, mdy,
  30556. Time (juce_recentMouseDownTimes[0]),
  30557. countMouseClicks(),
  30558. juce_MouseHasMovedSignificantlySincePressed
  30559. || juce_recentMouseDownTimes[0] + 300 < time);
  30560. mouseDrag (me);
  30561. if (deletionChecker.hasBeenDeleted())
  30562. return;
  30563. Desktop::getInstance().resetTimer();
  30564. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30565. {
  30566. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDrag (me);
  30567. if (deletionChecker.hasBeenDeleted())
  30568. return;
  30569. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30570. }
  30571. if (mouseListeners_ != 0)
  30572. {
  30573. for (int i = mouseListeners_->size(); --i >= 0;)
  30574. {
  30575. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  30576. if (deletionChecker.hasBeenDeleted())
  30577. return;
  30578. i = jmin (i, mouseListeners_->size());
  30579. }
  30580. }
  30581. const Component* p = parentComponent_;
  30582. while (p != 0)
  30583. {
  30584. const ComponentDeletionWatcher parentDeletionChecker (p);
  30585. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30586. {
  30587. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDrag (me);
  30588. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30589. return;
  30590. i = jmin (i, p->numDeepMouseListeners);
  30591. }
  30592. p = p->parentComponent_;
  30593. }
  30594. if (this == componentUnderMouse)
  30595. {
  30596. if (isUnboundedMouseModeOn)
  30597. {
  30598. Rectangle screenArea (getParentMonitorArea().expanded (-2, -2));
  30599. int mx, my;
  30600. Desktop::getMousePosition (mx, my);
  30601. if (! screenArea.contains (mx, my))
  30602. {
  30603. int deltaX = 0, deltaY = 0;
  30604. if (mx <= screenArea.getX() || mx >= screenArea.getRight())
  30605. deltaX = getScreenX() + getWidth() / 2 - mx;
  30606. if (my <= screenArea.getY() || my >= screenArea.getBottom())
  30607. deltaY = getScreenY() + getHeight() / 2 - my;
  30608. unboundedMouseOffsetX -= deltaX;
  30609. unboundedMouseOffsetY -= deltaY;
  30610. Desktop::setMousePosition (mx + deltaX,
  30611. my + deltaY);
  30612. }
  30613. else if (isCursorVisibleUntilOffscreen
  30614. && (unboundedMouseOffsetX != 0 || unboundedMouseOffsetY != 0)
  30615. && screenArea.contains (mx + unboundedMouseOffsetX,
  30616. my + unboundedMouseOffsetY))
  30617. {
  30618. mx += unboundedMouseOffsetX;
  30619. my += unboundedMouseOffsetY;
  30620. unboundedMouseOffsetX = 0;
  30621. unboundedMouseOffsetY = 0;
  30622. Desktop::setMousePosition (mx, my);
  30623. }
  30624. }
  30625. internalUpdateMouseCursor (false);
  30626. }
  30627. }
  30628. }
  30629. void Component::internalMouseMove (const int x, const int y, const int64 time)
  30630. {
  30631. const ComponentDeletionWatcher deletionChecker (this);
  30632. if (isValidComponent())
  30633. {
  30634. const MouseEvent me (x, y,
  30635. ModifierKeys::getCurrentModifiers(),
  30636. this,
  30637. Time (time),
  30638. x, y,
  30639. Time (time),
  30640. 0, false);
  30641. if (isCurrentlyBlockedByAnotherModalComponent())
  30642. {
  30643. // allow blocked mouse-events to go to global listeners..
  30644. Desktop::getInstance().sendMouseMove();
  30645. }
  30646. else
  30647. {
  30648. if (this == componentUnderMouse)
  30649. internalUpdateMouseCursor (false);
  30650. flags.mouseOverFlag = true;
  30651. mouseMove (me);
  30652. if (deletionChecker.hasBeenDeleted())
  30653. return;
  30654. Desktop::getInstance().resetTimer();
  30655. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30656. {
  30657. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseMove (me);
  30658. if (deletionChecker.hasBeenDeleted())
  30659. return;
  30660. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30661. }
  30662. if (mouseListeners_ != 0)
  30663. {
  30664. for (int i = mouseListeners_->size(); --i >= 0;)
  30665. {
  30666. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  30667. if (deletionChecker.hasBeenDeleted())
  30668. return;
  30669. i = jmin (i, mouseListeners_->size());
  30670. }
  30671. }
  30672. const Component* p = parentComponent_;
  30673. while (p != 0)
  30674. {
  30675. const ComponentDeletionWatcher parentDeletionChecker (p);
  30676. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30677. {
  30678. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseMove (me);
  30679. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30680. return;
  30681. i = jmin (i, p->numDeepMouseListeners);
  30682. }
  30683. p = p->parentComponent_;
  30684. }
  30685. }
  30686. }
  30687. }
  30688. void Component::internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time)
  30689. {
  30690. const ComponentDeletionWatcher deletionChecker (this);
  30691. const float wheelIncrementX = intAmountX * (1.0f / 256.0f);
  30692. const float wheelIncrementY = intAmountY * (1.0f / 256.0f);
  30693. int mx, my;
  30694. getMouseXYRelative (mx, my);
  30695. const MouseEvent me (mx, my,
  30696. ModifierKeys::getCurrentModifiers(),
  30697. this,
  30698. Time (time),
  30699. mx, my,
  30700. Time (time),
  30701. 0, false);
  30702. if (isCurrentlyBlockedByAnotherModalComponent())
  30703. {
  30704. // allow blocked mouse-events to go to global listeners..
  30705. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30706. {
  30707. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30708. if (deletionChecker.hasBeenDeleted())
  30709. return;
  30710. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30711. }
  30712. }
  30713. else
  30714. {
  30715. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30716. if (deletionChecker.hasBeenDeleted())
  30717. return;
  30718. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30719. {
  30720. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30721. if (deletionChecker.hasBeenDeleted())
  30722. return;
  30723. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30724. }
  30725. if (mouseListeners_ != 0)
  30726. {
  30727. for (int i = mouseListeners_->size(); --i >= 0;)
  30728. {
  30729. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30730. if (deletionChecker.hasBeenDeleted())
  30731. return;
  30732. i = jmin (i, mouseListeners_->size());
  30733. }
  30734. }
  30735. const Component* p = parentComponent_;
  30736. while (p != 0)
  30737. {
  30738. const ComponentDeletionWatcher parentDeletionChecker (p);
  30739. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30740. {
  30741. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30742. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30743. return;
  30744. i = jmin (i, p->numDeepMouseListeners);
  30745. }
  30746. p = p->parentComponent_;
  30747. }
  30748. sendFakeMouseMove();
  30749. }
  30750. }
  30751. void Component::sendFakeMouseMove() const
  30752. {
  30753. ComponentPeer* const peer = getPeer();
  30754. if (peer != 0)
  30755. peer->sendFakeMouseMove();
  30756. }
  30757. void Component::broughtToFront()
  30758. {
  30759. }
  30760. void Component::internalBroughtToFront()
  30761. {
  30762. if (isValidComponent())
  30763. {
  30764. if (flags.hasHeavyweightPeerFlag)
  30765. Desktop::getInstance().componentBroughtToFront (this);
  30766. const ComponentDeletionWatcher deletionChecker (this);
  30767. broughtToFront();
  30768. if (deletionChecker.hasBeenDeleted())
  30769. return;
  30770. if (componentListeners_ != 0)
  30771. {
  30772. for (int i = componentListeners_->size(); --i >= 0;)
  30773. {
  30774. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30775. ->componentBroughtToFront (*this);
  30776. if (deletionChecker.hasBeenDeleted())
  30777. return;
  30778. i = jmin (i, componentListeners_->size());
  30779. }
  30780. }
  30781. // when brought to the front and there's a modal component blocking this one,
  30782. // we need to bring the modal one to the front instead..
  30783. Component* const cm = getCurrentlyModalComponent();
  30784. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  30785. {
  30786. cm->getTopLevelComponent()->toFront (false);
  30787. }
  30788. }
  30789. }
  30790. void Component::focusGained (FocusChangeType)
  30791. {
  30792. // base class does nothing
  30793. }
  30794. void Component::internalFocusGain (const FocusChangeType cause)
  30795. {
  30796. const ComponentDeletionWatcher deletionChecker (this);
  30797. focusGained (cause);
  30798. if (! deletionChecker.hasBeenDeleted())
  30799. internalChildFocusChange (cause);
  30800. }
  30801. void Component::focusLost (FocusChangeType)
  30802. {
  30803. // base class does nothing
  30804. }
  30805. void Component::internalFocusLoss (const FocusChangeType cause)
  30806. {
  30807. const ComponentDeletionWatcher deletionChecker (this);
  30808. focusLost (focusChangedDirectly);
  30809. if (! deletionChecker.hasBeenDeleted())
  30810. internalChildFocusChange (cause);
  30811. }
  30812. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  30813. {
  30814. // base class does nothing
  30815. }
  30816. void Component::internalChildFocusChange (FocusChangeType cause)
  30817. {
  30818. const bool childIsNowFocused = hasKeyboardFocus (true);
  30819. if (flags.childCompFocusedFlag != childIsNowFocused)
  30820. {
  30821. flags.childCompFocusedFlag = childIsNowFocused;
  30822. const ComponentDeletionWatcher deletionChecker (this);
  30823. focusOfChildComponentChanged (cause);
  30824. if (deletionChecker.hasBeenDeleted())
  30825. return;
  30826. }
  30827. if (parentComponent_ != 0)
  30828. parentComponent_->internalChildFocusChange (cause);
  30829. }
  30830. bool Component::isEnabled() const throw()
  30831. {
  30832. return (! flags.isDisabledFlag)
  30833. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  30834. }
  30835. void Component::setEnabled (const bool shouldBeEnabled)
  30836. {
  30837. if (flags.isDisabledFlag == shouldBeEnabled)
  30838. {
  30839. flags.isDisabledFlag = ! shouldBeEnabled;
  30840. // if any parent components are disabled, setting our flag won't make a difference,
  30841. // so no need to send a change message
  30842. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  30843. sendEnablementChangeMessage();
  30844. }
  30845. }
  30846. void Component::sendEnablementChangeMessage()
  30847. {
  30848. const ComponentDeletionWatcher deletionChecker (this);
  30849. enablementChanged();
  30850. if (deletionChecker.hasBeenDeleted())
  30851. return;
  30852. for (int i = getNumChildComponents(); --i >= 0;)
  30853. {
  30854. Component* const c = getChildComponent (i);
  30855. if (c != 0)
  30856. {
  30857. c->sendEnablementChangeMessage();
  30858. if (deletionChecker.hasBeenDeleted())
  30859. return;
  30860. }
  30861. }
  30862. }
  30863. void Component::enablementChanged()
  30864. {
  30865. }
  30866. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  30867. {
  30868. flags.wantsFocusFlag = wantsFocus;
  30869. }
  30870. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  30871. {
  30872. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  30873. }
  30874. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  30875. {
  30876. return ! flags.dontFocusOnMouseClickFlag;
  30877. }
  30878. bool Component::getWantsKeyboardFocus() const throw()
  30879. {
  30880. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  30881. }
  30882. void Component::setFocusContainer (const bool isFocusContainer) throw()
  30883. {
  30884. flags.isFocusContainerFlag = isFocusContainer;
  30885. }
  30886. bool Component::isFocusContainer() const throw()
  30887. {
  30888. return flags.isFocusContainerFlag;
  30889. }
  30890. int Component::getExplicitFocusOrder() const throw()
  30891. {
  30892. return getComponentPropertyInt (T("_jexfo"), false, 0);
  30893. }
  30894. void Component::setExplicitFocusOrder (const int newFocusOrderIndex) throw()
  30895. {
  30896. setComponentProperty (T("_jexfo"), newFocusOrderIndex);
  30897. }
  30898. KeyboardFocusTraverser* Component::createFocusTraverser()
  30899. {
  30900. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  30901. return new KeyboardFocusTraverser();
  30902. return parentComponent_->createFocusTraverser();
  30903. }
  30904. void Component::takeKeyboardFocus (const FocusChangeType cause)
  30905. {
  30906. // give the focus to this component
  30907. if (currentlyFocusedComponent != this)
  30908. {
  30909. JUCE_TRY
  30910. {
  30911. // get the focus onto our desktop window
  30912. ComponentPeer* const peer = getPeer();
  30913. if (peer != 0)
  30914. {
  30915. const ComponentDeletionWatcher deletionChecker (this);
  30916. peer->grabFocus();
  30917. if (peer->isFocused() && currentlyFocusedComponent != this)
  30918. {
  30919. Component* const componentLosingFocus = currentlyFocusedComponent;
  30920. currentlyFocusedComponent = this;
  30921. Desktop::getInstance().triggerFocusCallback();
  30922. // call this after setting currentlyFocusedComponent so that the one that's
  30923. // losing it has a chance to see where focus is going
  30924. if (componentLosingFocus->isValidComponent())
  30925. componentLosingFocus->internalFocusLoss (cause);
  30926. if (currentlyFocusedComponent == this)
  30927. {
  30928. focusGained (cause);
  30929. if (! deletionChecker.hasBeenDeleted())
  30930. internalChildFocusChange (cause);
  30931. }
  30932. }
  30933. }
  30934. }
  30935. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  30936. catch (const std::exception& e)
  30937. {
  30938. currentlyFocusedComponent = 0;
  30939. Desktop::getInstance().triggerFocusCallback();
  30940. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  30941. }
  30942. catch (...)
  30943. {
  30944. currentlyFocusedComponent = 0;
  30945. Desktop::getInstance().triggerFocusCallback();
  30946. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  30947. }
  30948. #endif
  30949. }
  30950. }
  30951. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  30952. {
  30953. if (isShowing())
  30954. {
  30955. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  30956. {
  30957. takeKeyboardFocus (cause);
  30958. }
  30959. else
  30960. {
  30961. if (isParentOf (currentlyFocusedComponent)
  30962. && currentlyFocusedComponent->isShowing())
  30963. {
  30964. // do nothing if the focused component is actually a child of ours..
  30965. }
  30966. else
  30967. {
  30968. // find the default child component..
  30969. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  30970. if (traverser != 0)
  30971. {
  30972. Component* const defaultComp = traverser->getDefaultComponent (this);
  30973. delete traverser;
  30974. if (defaultComp != 0)
  30975. {
  30976. defaultComp->grabFocusInternal (cause, false);
  30977. return;
  30978. }
  30979. }
  30980. if (canTryParent && parentComponent_ != 0)
  30981. {
  30982. // if no children want it and we're allowed to try our parent comp,
  30983. // then pass up to parent, which will try our siblings.
  30984. parentComponent_->grabFocusInternal (cause, true);
  30985. }
  30986. }
  30987. }
  30988. }
  30989. }
  30990. void Component::grabKeyboardFocus()
  30991. {
  30992. // if component methods are being called from threads other than the message
  30993. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30994. checkMessageManagerIsLocked
  30995. grabFocusInternal (focusChangedDirectly);
  30996. }
  30997. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  30998. {
  30999. // if component methods are being called from threads other than the message
  31000. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31001. checkMessageManagerIsLocked
  31002. if (parentComponent_ != 0)
  31003. {
  31004. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  31005. if (traverser != 0)
  31006. {
  31007. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  31008. : traverser->getPreviousComponent (this);
  31009. delete traverser;
  31010. if (nextComp != 0)
  31011. {
  31012. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  31013. {
  31014. const ComponentDeletionWatcher deletionChecker (nextComp);
  31015. internalModalInputAttempt();
  31016. if (deletionChecker.hasBeenDeleted()
  31017. || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  31018. return;
  31019. }
  31020. nextComp->grabFocusInternal (focusChangedByTabKey);
  31021. return;
  31022. }
  31023. }
  31024. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  31025. }
  31026. }
  31027. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const throw()
  31028. {
  31029. return (currentlyFocusedComponent == this)
  31030. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  31031. }
  31032. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  31033. {
  31034. return currentlyFocusedComponent;
  31035. }
  31036. void Component::giveAwayFocus()
  31037. {
  31038. // use a copy so we can clear the value before the call
  31039. Component* const componentLosingFocus = currentlyFocusedComponent;
  31040. currentlyFocusedComponent = 0;
  31041. Desktop::getInstance().triggerFocusCallback();
  31042. if (componentLosingFocus->isValidComponent())
  31043. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  31044. }
  31045. bool Component::isMouseOver() const throw()
  31046. {
  31047. return flags.mouseOverFlag;
  31048. }
  31049. bool Component::isMouseButtonDown() const throw()
  31050. {
  31051. return flags.draggingFlag;
  31052. }
  31053. bool Component::isMouseOverOrDragging() const throw()
  31054. {
  31055. return flags.mouseOverFlag || flags.draggingFlag;
  31056. }
  31057. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  31058. {
  31059. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  31060. }
  31061. void Component::getMouseXYRelative (int& mx, int& my) const throw()
  31062. {
  31063. Desktop::getMousePosition (mx, my);
  31064. globalPositionToRelative (mx, my);
  31065. mx += unboundedMouseOffsetX;
  31066. my += unboundedMouseOffsetY;
  31067. }
  31068. void Component::enableUnboundedMouseMovement (bool enable,
  31069. bool keepCursorVisibleUntilOffscreen) throw()
  31070. {
  31071. enable = enable && isMouseButtonDown();
  31072. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  31073. if (enable != isUnboundedMouseModeOn)
  31074. {
  31075. if ((! enable) && ((! isCursorVisibleUntilOffscreen)
  31076. || unboundedMouseOffsetX != 0
  31077. || unboundedMouseOffsetY != 0))
  31078. {
  31079. // when released, return the mouse to within the component's bounds
  31080. int mx, my;
  31081. getMouseXYRelative (mx, my);
  31082. mx = jlimit (0, getWidth(), mx);
  31083. my = jlimit (0, getHeight(), my);
  31084. relativePositionToGlobal (mx, my);
  31085. Desktop::setMousePosition (mx, my);
  31086. }
  31087. isUnboundedMouseModeOn = enable;
  31088. unboundedMouseOffsetX = 0;
  31089. unboundedMouseOffsetY = 0;
  31090. internalUpdateMouseCursor (true);
  31091. }
  31092. }
  31093. Component* JUCE_CALLTYPE Component::getComponentUnderMouse() throw()
  31094. {
  31095. return componentUnderMouse;
  31096. }
  31097. const Rectangle Component::getParentMonitorArea() const throw()
  31098. {
  31099. int centreX = getWidth() / 2;
  31100. int centreY = getHeight() / 2;
  31101. relativePositionToGlobal (centreX, centreY);
  31102. return Desktop::getInstance().getMonitorAreaContaining (centreX, centreY);
  31103. }
  31104. void Component::addKeyListener (KeyListener* const newListener) throw()
  31105. {
  31106. if (keyListeners_ == 0)
  31107. keyListeners_ = new VoidArray (4);
  31108. keyListeners_->addIfNotAlreadyThere (newListener);
  31109. }
  31110. void Component::removeKeyListener (KeyListener* const listenerToRemove) throw()
  31111. {
  31112. if (keyListeners_ != 0)
  31113. keyListeners_->removeValue (listenerToRemove);
  31114. }
  31115. bool Component::keyPressed (const KeyPress&)
  31116. {
  31117. return false;
  31118. }
  31119. bool Component::keyStateChanged()
  31120. {
  31121. return false;
  31122. }
  31123. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  31124. {
  31125. if (parentComponent_ != 0)
  31126. parentComponent_->modifierKeysChanged (modifiers);
  31127. }
  31128. void Component::internalModifierKeysChanged()
  31129. {
  31130. sendFakeMouseMove();
  31131. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  31132. }
  31133. ComponentPeer* Component::getPeer() const throw()
  31134. {
  31135. if (flags.hasHeavyweightPeerFlag)
  31136. return ComponentPeer::getPeerFor (this);
  31137. else if (parentComponent_ != 0)
  31138. return parentComponent_->getPeer();
  31139. else
  31140. return 0;
  31141. }
  31142. const String Component::getComponentProperty (const String& keyName,
  31143. const bool useParentComponentIfNotFound,
  31144. const String& defaultReturnValue) const throw()
  31145. {
  31146. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  31147. return propertySet_->getValue (keyName, defaultReturnValue);
  31148. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31149. return parentComponent_->getComponentProperty (keyName, true, defaultReturnValue);
  31150. return defaultReturnValue;
  31151. }
  31152. int Component::getComponentPropertyInt (const String& keyName,
  31153. const bool useParentComponentIfNotFound,
  31154. const int defaultReturnValue) const throw()
  31155. {
  31156. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  31157. return propertySet_->getIntValue (keyName, defaultReturnValue);
  31158. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31159. return parentComponent_->getComponentPropertyInt (keyName, true, defaultReturnValue);
  31160. return defaultReturnValue;
  31161. }
  31162. double Component::getComponentPropertyDouble (const String& keyName,
  31163. const bool useParentComponentIfNotFound,
  31164. const double defaultReturnValue) const throw()
  31165. {
  31166. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  31167. return propertySet_->getDoubleValue (keyName, defaultReturnValue);
  31168. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31169. return parentComponent_->getComponentPropertyDouble (keyName, true, defaultReturnValue);
  31170. return defaultReturnValue;
  31171. }
  31172. bool Component::getComponentPropertyBool (const String& keyName,
  31173. const bool useParentComponentIfNotFound,
  31174. const bool defaultReturnValue) const throw()
  31175. {
  31176. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  31177. return propertySet_->getBoolValue (keyName, defaultReturnValue);
  31178. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31179. return parentComponent_->getComponentPropertyBool (keyName, true, defaultReturnValue);
  31180. return defaultReturnValue;
  31181. }
  31182. const Colour Component::getComponentPropertyColour (const String& keyName,
  31183. const bool useParentComponentIfNotFound,
  31184. const Colour& defaultReturnValue) const throw()
  31185. {
  31186. return Colour ((uint32) getComponentPropertyInt (keyName,
  31187. useParentComponentIfNotFound,
  31188. defaultReturnValue.getARGB()));
  31189. }
  31190. void Component::setComponentProperty (const String& keyName, const String& value) throw()
  31191. {
  31192. if (propertySet_ == 0)
  31193. propertySet_ = new PropertySet();
  31194. propertySet_->setValue (keyName, value);
  31195. }
  31196. void Component::setComponentProperty (const String& keyName, const int value) throw()
  31197. {
  31198. if (propertySet_ == 0)
  31199. propertySet_ = new PropertySet();
  31200. propertySet_->setValue (keyName, value);
  31201. }
  31202. void Component::setComponentProperty (const String& keyName, const double value) throw()
  31203. {
  31204. if (propertySet_ == 0)
  31205. propertySet_ = new PropertySet();
  31206. propertySet_->setValue (keyName, value);
  31207. }
  31208. void Component::setComponentProperty (const String& keyName, const bool value) throw()
  31209. {
  31210. if (propertySet_ == 0)
  31211. propertySet_ = new PropertySet();
  31212. propertySet_->setValue (keyName, value);
  31213. }
  31214. void Component::setComponentProperty (const String& keyName, const Colour& colour) throw()
  31215. {
  31216. setComponentProperty (keyName, (int) colour.getARGB());
  31217. }
  31218. void Component::removeComponentProperty (const String& keyName) throw()
  31219. {
  31220. if (propertySet_ != 0)
  31221. propertySet_->removeValue (keyName);
  31222. }
  31223. ComponentDeletionWatcher::ComponentDeletionWatcher (const Component* const componentToWatch_) throw()
  31224. : componentToWatch (componentToWatch_),
  31225. componentUID (componentToWatch_->getComponentUID())
  31226. {
  31227. // not possible to check on an already-deleted object..
  31228. jassert (componentToWatch_->isValidComponent());
  31229. }
  31230. ComponentDeletionWatcher::~ComponentDeletionWatcher() throw() {}
  31231. bool ComponentDeletionWatcher::hasBeenDeleted() const throw()
  31232. {
  31233. return ! (componentToWatch->isValidComponent()
  31234. && componentToWatch->getComponentUID() == componentUID);
  31235. }
  31236. const Component* ComponentDeletionWatcher::getComponent() const throw()
  31237. {
  31238. return hasBeenDeleted() ? 0 : componentToWatch;
  31239. }
  31240. END_JUCE_NAMESPACE
  31241. /********* End of inlined file: juce_Component.cpp *********/
  31242. /********* Start of inlined file: juce_ComponentListener.cpp *********/
  31243. BEGIN_JUCE_NAMESPACE
  31244. void ComponentListener::componentMovedOrResized (Component&, bool, bool)
  31245. {
  31246. }
  31247. void ComponentListener::componentBroughtToFront (Component&)
  31248. {
  31249. }
  31250. void ComponentListener::componentVisibilityChanged (Component&)
  31251. {
  31252. }
  31253. void ComponentListener::componentChildrenChanged (Component&)
  31254. {
  31255. }
  31256. void ComponentListener::componentParentHierarchyChanged (Component&)
  31257. {
  31258. }
  31259. void ComponentListener::componentNameChanged (Component&)
  31260. {
  31261. }
  31262. END_JUCE_NAMESPACE
  31263. /********* End of inlined file: juce_ComponentListener.cpp *********/
  31264. /********* Start of inlined file: juce_Desktop.cpp *********/
  31265. BEGIN_JUCE_NAMESPACE
  31266. extern void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords,
  31267. const bool clipToWorkArea) throw();
  31268. static Desktop* juce_desktopInstance = 0;
  31269. Desktop::Desktop() throw()
  31270. : mouseListeners (2),
  31271. desktopComponents (4),
  31272. monitorCoordsClipped (2),
  31273. monitorCoordsUnclipped (2),
  31274. lastMouseX (0),
  31275. lastMouseY (0)
  31276. {
  31277. refreshMonitorSizes();
  31278. }
  31279. Desktop::~Desktop() throw()
  31280. {
  31281. jassert (juce_desktopInstance == this);
  31282. juce_desktopInstance = 0;
  31283. // doh! If you don't delete all your windows before exiting, you're going to
  31284. // be leaking memory!
  31285. jassert (desktopComponents.size() == 0);
  31286. }
  31287. Desktop& JUCE_CALLTYPE Desktop::getInstance() throw()
  31288. {
  31289. if (juce_desktopInstance == 0)
  31290. juce_desktopInstance = new Desktop();
  31291. return *juce_desktopInstance;
  31292. }
  31293. void Desktop::refreshMonitorSizes() throw()
  31294. {
  31295. const Array <Rectangle> oldClipped (monitorCoordsClipped);
  31296. const Array <Rectangle> oldUnclipped (monitorCoordsUnclipped);
  31297. monitorCoordsClipped.clear();
  31298. monitorCoordsUnclipped.clear();
  31299. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  31300. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  31301. jassert (monitorCoordsClipped.size() > 0
  31302. && monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  31303. if (oldClipped != monitorCoordsClipped
  31304. || oldUnclipped != monitorCoordsUnclipped)
  31305. {
  31306. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  31307. {
  31308. ComponentPeer* const p = ComponentPeer::getPeer (i);
  31309. if (p != 0)
  31310. p->handleScreenSizeChange();
  31311. }
  31312. }
  31313. }
  31314. int Desktop::getNumDisplayMonitors() const throw()
  31315. {
  31316. return monitorCoordsClipped.size();
  31317. }
  31318. const Rectangle Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  31319. {
  31320. return clippedToWorkArea ? monitorCoordsClipped [index]
  31321. : monitorCoordsUnclipped [index];
  31322. }
  31323. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  31324. {
  31325. RectangleList rl;
  31326. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  31327. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  31328. return rl;
  31329. }
  31330. const Rectangle Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  31331. {
  31332. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  31333. }
  31334. const Rectangle Desktop::getMonitorAreaContaining (int cx, int cy, const bool clippedToWorkArea) const throw()
  31335. {
  31336. Rectangle best (getMainMonitorArea (clippedToWorkArea));
  31337. double bestDistance = 1.0e10;
  31338. for (int i = getNumDisplayMonitors(); --i >= 0;)
  31339. {
  31340. const Rectangle rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  31341. if (rect.contains (cx, cy))
  31342. return rect;
  31343. const double distance = juce_hypot ((double) (rect.getCentreX() - cx),
  31344. (double) (rect.getCentreY() - cy));
  31345. if (distance < bestDistance)
  31346. {
  31347. bestDistance = distance;
  31348. best = rect;
  31349. }
  31350. }
  31351. return best;
  31352. }
  31353. int Desktop::getNumComponents() const throw()
  31354. {
  31355. return desktopComponents.size();
  31356. }
  31357. Component* Desktop::getComponent (const int index) const throw()
  31358. {
  31359. return (Component*) desktopComponents [index];
  31360. }
  31361. Component* Desktop::findComponentAt (const int screenX,
  31362. const int screenY) const
  31363. {
  31364. for (int i = desktopComponents.size(); --i >= 0;)
  31365. {
  31366. Component* const c = (Component*) desktopComponents.getUnchecked(i);
  31367. int x = screenX, y = screenY;
  31368. c->globalPositionToRelative (x, y);
  31369. if (c->contains (x, y))
  31370. return c->getComponentAt (x, y);
  31371. }
  31372. return 0;
  31373. }
  31374. void Desktop::addDesktopComponent (Component* const c) throw()
  31375. {
  31376. jassert (c != 0);
  31377. jassert (! desktopComponents.contains (c));
  31378. desktopComponents.addIfNotAlreadyThere (c);
  31379. }
  31380. void Desktop::removeDesktopComponent (Component* const c) throw()
  31381. {
  31382. desktopComponents.removeValue (c);
  31383. }
  31384. void Desktop::componentBroughtToFront (Component* const c) throw()
  31385. {
  31386. const int index = desktopComponents.indexOf (c);
  31387. jassert (index >= 0);
  31388. if (index >= 0)
  31389. desktopComponents.move (index, -1);
  31390. }
  31391. // from Component.cpp
  31392. extern int juce_recentMouseDownX [4];
  31393. extern int juce_recentMouseDownY [4];
  31394. extern int juce_MouseClickCounter;
  31395. void Desktop::getLastMouseDownPosition (int& x, int& y) throw()
  31396. {
  31397. x = juce_recentMouseDownX [0];
  31398. y = juce_recentMouseDownY [0];
  31399. }
  31400. int Desktop::getMouseButtonClickCounter() throw()
  31401. {
  31402. return juce_MouseClickCounter;
  31403. }
  31404. void Desktop::addGlobalMouseListener (MouseListener* const listener) throw()
  31405. {
  31406. jassert (listener != 0);
  31407. if (listener != 0)
  31408. {
  31409. mouseListeners.add (listener);
  31410. resetTimer();
  31411. }
  31412. }
  31413. void Desktop::removeGlobalMouseListener (MouseListener* const listener) throw()
  31414. {
  31415. mouseListeners.removeValue (listener);
  31416. resetTimer();
  31417. }
  31418. void Desktop::addFocusChangeListener (FocusChangeListener* const listener) throw()
  31419. {
  31420. jassert (listener != 0);
  31421. if (listener != 0)
  31422. focusListeners.add (listener);
  31423. }
  31424. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener) throw()
  31425. {
  31426. focusListeners.removeValue (listener);
  31427. }
  31428. void Desktop::triggerFocusCallback() throw()
  31429. {
  31430. triggerAsyncUpdate();
  31431. }
  31432. void Desktop::handleAsyncUpdate()
  31433. {
  31434. for (int i = focusListeners.size(); --i >= 0;)
  31435. {
  31436. ((FocusChangeListener*) focusListeners.getUnchecked (i))->globalFocusChanged (Component::getCurrentlyFocusedComponent());
  31437. i = jmin (i, focusListeners.size());
  31438. }
  31439. }
  31440. void Desktop::timerCallback()
  31441. {
  31442. int x, y;
  31443. getMousePosition (x, y);
  31444. if (lastMouseX != x || lastMouseY != y)
  31445. sendMouseMove();
  31446. }
  31447. void Desktop::sendMouseMove()
  31448. {
  31449. if (mouseListeners.size() > 0)
  31450. {
  31451. startTimer (20);
  31452. int x, y;
  31453. getMousePosition (x, y);
  31454. lastMouseX = x;
  31455. lastMouseY = y;
  31456. Component* const target = findComponentAt (x, y);
  31457. if (target != 0)
  31458. {
  31459. target->globalPositionToRelative (x, y);
  31460. ComponentDeletionWatcher deletionChecker (target);
  31461. const MouseEvent me (x, y,
  31462. ModifierKeys::getCurrentModifiers(),
  31463. target,
  31464. Time::getCurrentTime(),
  31465. x, y,
  31466. Time::getCurrentTime(),
  31467. 0, false);
  31468. for (int i = mouseListeners.size(); --i >= 0;)
  31469. {
  31470. if (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  31471. ((MouseListener*) mouseListeners[i])->mouseDrag (me);
  31472. else
  31473. ((MouseListener*) mouseListeners[i])->mouseMove (me);
  31474. if (deletionChecker.hasBeenDeleted())
  31475. return;
  31476. i = jmin (i, mouseListeners.size());
  31477. }
  31478. }
  31479. }
  31480. }
  31481. void Desktop::resetTimer() throw()
  31482. {
  31483. if (mouseListeners.size() == 0)
  31484. stopTimer();
  31485. else
  31486. startTimer (100);
  31487. getMousePosition (lastMouseX, lastMouseY);
  31488. }
  31489. END_JUCE_NAMESPACE
  31490. /********* End of inlined file: juce_Desktop.cpp *********/
  31491. /********* Start of inlined file: juce_ArrowButton.cpp *********/
  31492. BEGIN_JUCE_NAMESPACE
  31493. ArrowButton::ArrowButton (const String& name,
  31494. float arrowDirectionInRadians,
  31495. const Colour& arrowColour)
  31496. : Button (name),
  31497. colour (arrowColour)
  31498. {
  31499. path.lineTo (0.0f, 1.0f);
  31500. path.lineTo (1.0f, 0.5f);
  31501. path.closeSubPath();
  31502. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  31503. 0.5f, 0.5f));
  31504. setComponentEffect (&shadow);
  31505. buttonStateChanged();
  31506. }
  31507. ArrowButton::~ArrowButton()
  31508. {
  31509. }
  31510. void ArrowButton::paintButton (Graphics& g,
  31511. bool /*isMouseOverButton*/,
  31512. bool /*isButtonDown*/)
  31513. {
  31514. g.setColour (colour);
  31515. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  31516. (float) offset,
  31517. (float) (getWidth() - 3),
  31518. (float) (getHeight() - 3),
  31519. false));
  31520. }
  31521. void ArrowButton::buttonStateChanged()
  31522. {
  31523. offset = (isDown()) ? 1 : 0;
  31524. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  31525. 0.3f, -1, 0);
  31526. }
  31527. END_JUCE_NAMESPACE
  31528. /********* End of inlined file: juce_ArrowButton.cpp *********/
  31529. /********* Start of inlined file: juce_Button.cpp *********/
  31530. BEGIN_JUCE_NAMESPACE
  31531. Button::Button (const String& name)
  31532. : Component (name),
  31533. shortcuts (2),
  31534. keySource (0),
  31535. text (name),
  31536. buttonListeners (2),
  31537. repeatTimer (0),
  31538. buttonPressTime (0),
  31539. lastTimeCallbackTime (0),
  31540. commandManagerToUse (0),
  31541. autoRepeatDelay (-1),
  31542. autoRepeatSpeed (0),
  31543. autoRepeatMinimumDelay (-1),
  31544. radioGroupId (0),
  31545. commandID (0),
  31546. connectedEdgeFlags (0),
  31547. buttonState (buttonNormal),
  31548. isOn (false),
  31549. clickTogglesState (false),
  31550. needsToRelease (false),
  31551. needsRepainting (false),
  31552. isKeyDown (false),
  31553. triggerOnMouseDown (false),
  31554. generateTooltip (false)
  31555. {
  31556. setWantsKeyboardFocus (true);
  31557. }
  31558. Button::~Button()
  31559. {
  31560. if (commandManagerToUse != 0)
  31561. commandManagerToUse->removeListener (this);
  31562. delete repeatTimer;
  31563. clearShortcuts();
  31564. }
  31565. void Button::setButtonText (const String& newText) throw()
  31566. {
  31567. if (text != newText)
  31568. {
  31569. text = newText;
  31570. repaint();
  31571. }
  31572. }
  31573. void Button::setTooltip (const String& newTooltip)
  31574. {
  31575. SettableTooltipClient::setTooltip (newTooltip);
  31576. generateTooltip = false;
  31577. }
  31578. const String Button::getTooltip()
  31579. {
  31580. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  31581. {
  31582. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  31583. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  31584. for (int i = 0; i < keyPresses.size(); ++i)
  31585. {
  31586. const String key (keyPresses.getReference(i).getTextDescription());
  31587. if (key.length() == 1)
  31588. tt << " [shortcut: '" << key << "']";
  31589. else
  31590. tt << " [" << key << ']';
  31591. }
  31592. return tt;
  31593. }
  31594. return SettableTooltipClient::getTooltip();
  31595. }
  31596. void Button::setConnectedEdges (const int connectedEdgeFlags_) throw()
  31597. {
  31598. if (connectedEdgeFlags != connectedEdgeFlags_)
  31599. {
  31600. connectedEdgeFlags = connectedEdgeFlags_;
  31601. repaint();
  31602. }
  31603. }
  31604. void Button::setToggleState (const bool shouldBeOn,
  31605. const bool sendChangeNotification)
  31606. {
  31607. if (shouldBeOn != isOn)
  31608. {
  31609. const ComponentDeletionWatcher deletionWatcher (this);
  31610. isOn = shouldBeOn;
  31611. repaint();
  31612. if (sendChangeNotification)
  31613. sendClickMessage (ModifierKeys());
  31614. if ((! deletionWatcher.hasBeenDeleted()) && isOn)
  31615. turnOffOtherButtonsInGroup (sendChangeNotification);
  31616. }
  31617. }
  31618. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  31619. {
  31620. clickTogglesState = shouldToggle;
  31621. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  31622. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  31623. // it is that this button represents, and the button will update its state to reflect this
  31624. // in the applicationCommandListChanged() method.
  31625. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  31626. }
  31627. bool Button::getClickingTogglesState() const throw()
  31628. {
  31629. return clickTogglesState;
  31630. }
  31631. void Button::setRadioGroupId (const int newGroupId)
  31632. {
  31633. if (radioGroupId != newGroupId)
  31634. {
  31635. radioGroupId = newGroupId;
  31636. if (isOn)
  31637. turnOffOtherButtonsInGroup (true);
  31638. }
  31639. }
  31640. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  31641. {
  31642. Component* const p = getParentComponent();
  31643. if (p != 0 && radioGroupId != 0)
  31644. {
  31645. const ComponentDeletionWatcher deletionWatcher (this);
  31646. for (int i = p->getNumChildComponents(); --i >= 0;)
  31647. {
  31648. Component* const c = p->getChildComponent (i);
  31649. if (c != this)
  31650. {
  31651. Button* const b = dynamic_cast <Button*> (c);
  31652. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  31653. {
  31654. b->setToggleState (false, sendChangeNotification);
  31655. if (deletionWatcher.hasBeenDeleted())
  31656. return;
  31657. }
  31658. }
  31659. }
  31660. }
  31661. }
  31662. void Button::enablementChanged()
  31663. {
  31664. updateState (0);
  31665. repaint();
  31666. }
  31667. Button::ButtonState Button::updateState (const MouseEvent* const e) throw()
  31668. {
  31669. ButtonState state = buttonNormal;
  31670. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  31671. {
  31672. int mx, my;
  31673. if (e == 0)
  31674. {
  31675. getMouseXYRelative (mx, my);
  31676. }
  31677. else
  31678. {
  31679. const MouseEvent e2 (e->getEventRelativeTo (this));
  31680. mx = e2.x;
  31681. my = e2.y;
  31682. }
  31683. const bool over = reallyContains (mx, my, true);
  31684. const bool down = isMouseButtonDown();
  31685. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  31686. state = buttonDown;
  31687. else if (over)
  31688. state = buttonOver;
  31689. }
  31690. setState (state);
  31691. return state;
  31692. }
  31693. void Button::setState (const ButtonState newState)
  31694. {
  31695. if (buttonState != newState)
  31696. {
  31697. buttonState = newState;
  31698. repaint();
  31699. if (buttonState == buttonDown)
  31700. {
  31701. buttonPressTime = Time::getApproximateMillisecondCounter();
  31702. lastTimeCallbackTime = buttonPressTime;
  31703. }
  31704. sendStateMessage();
  31705. }
  31706. }
  31707. bool Button::isDown() const throw()
  31708. {
  31709. return buttonState == buttonDown;
  31710. }
  31711. bool Button::isOver() const throw()
  31712. {
  31713. return buttonState != buttonNormal;
  31714. }
  31715. void Button::buttonStateChanged()
  31716. {
  31717. }
  31718. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  31719. {
  31720. const uint32 now = Time::getApproximateMillisecondCounter();
  31721. return now > buttonPressTime ? now - buttonPressTime : 0;
  31722. }
  31723. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  31724. {
  31725. triggerOnMouseDown = isTriggeredOnMouseDown;
  31726. }
  31727. void Button::clicked()
  31728. {
  31729. }
  31730. void Button::clicked (const ModifierKeys& /*modifiers*/)
  31731. {
  31732. clicked();
  31733. }
  31734. static const int clickMessageId = 0x2f3f4f99;
  31735. void Button::triggerClick()
  31736. {
  31737. postCommandMessage (clickMessageId);
  31738. }
  31739. void Button::internalClickCallback (const ModifierKeys& modifiers)
  31740. {
  31741. if (clickTogglesState)
  31742. setToggleState ((radioGroupId != 0) || ! isOn, false);
  31743. sendClickMessage (modifiers);
  31744. }
  31745. void Button::flashButtonState() throw()
  31746. {
  31747. if (isEnabled())
  31748. {
  31749. needsToRelease = true;
  31750. setState (buttonDown);
  31751. getRepeatTimer().startTimer (100);
  31752. }
  31753. }
  31754. void Button::handleCommandMessage (int commandId)
  31755. {
  31756. if (commandId == clickMessageId)
  31757. {
  31758. if (isEnabled())
  31759. {
  31760. flashButtonState();
  31761. internalClickCallback (ModifierKeys::getCurrentModifiers());
  31762. }
  31763. }
  31764. else
  31765. {
  31766. Component::handleCommandMessage (commandId);
  31767. }
  31768. }
  31769. void Button::addButtonListener (ButtonListener* const newListener) throw()
  31770. {
  31771. jassert (newListener != 0);
  31772. jassert (! buttonListeners.contains (newListener)); // trying to add a listener to the list twice!
  31773. if (newListener != 0)
  31774. buttonListeners.add (newListener);
  31775. }
  31776. void Button::removeButtonListener (ButtonListener* const listener) throw()
  31777. {
  31778. jassert (buttonListeners.contains (listener)); // trying to remove a listener that isn't on the list!
  31779. buttonListeners.removeValue (listener);
  31780. }
  31781. void Button::sendClickMessage (const ModifierKeys& modifiers)
  31782. {
  31783. const ComponentDeletionWatcher cdw (this);
  31784. if (commandManagerToUse != 0 && commandID != 0)
  31785. {
  31786. ApplicationCommandTarget::InvocationInfo info (commandID);
  31787. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  31788. info.originatingComponent = this;
  31789. commandManagerToUse->invoke (info, true);
  31790. }
  31791. clicked (modifiers);
  31792. if (! cdw.hasBeenDeleted())
  31793. {
  31794. for (int i = buttonListeners.size(); --i >= 0;)
  31795. {
  31796. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  31797. if (bl != 0)
  31798. {
  31799. bl->buttonClicked (this);
  31800. if (cdw.hasBeenDeleted())
  31801. return;
  31802. }
  31803. }
  31804. }
  31805. }
  31806. void Button::sendStateMessage()
  31807. {
  31808. const ComponentDeletionWatcher cdw (this);
  31809. buttonStateChanged();
  31810. if (cdw.hasBeenDeleted())
  31811. return;
  31812. for (int i = buttonListeners.size(); --i >= 0;)
  31813. {
  31814. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  31815. if (bl != 0)
  31816. {
  31817. bl->buttonStateChanged (this);
  31818. if (cdw.hasBeenDeleted())
  31819. return;
  31820. }
  31821. }
  31822. }
  31823. void Button::paint (Graphics& g)
  31824. {
  31825. if (needsToRelease && isEnabled())
  31826. {
  31827. needsToRelease = false;
  31828. needsRepainting = true;
  31829. }
  31830. paintButton (g, isOver(), isDown());
  31831. }
  31832. void Button::mouseEnter (const MouseEvent& e)
  31833. {
  31834. updateState (&e);
  31835. }
  31836. void Button::mouseExit (const MouseEvent& e)
  31837. {
  31838. updateState (&e);
  31839. }
  31840. void Button::mouseDown (const MouseEvent& e)
  31841. {
  31842. updateState (&e);
  31843. if (isDown())
  31844. {
  31845. if (autoRepeatDelay >= 0)
  31846. getRepeatTimer().startTimer (autoRepeatDelay);
  31847. if (triggerOnMouseDown)
  31848. internalClickCallback (e.mods);
  31849. }
  31850. }
  31851. void Button::mouseUp (const MouseEvent& e)
  31852. {
  31853. const bool wasDown = isDown();
  31854. updateState (&e);
  31855. if (wasDown && isOver() && ! triggerOnMouseDown)
  31856. internalClickCallback (e.mods);
  31857. }
  31858. void Button::mouseDrag (const MouseEvent& e)
  31859. {
  31860. const ButtonState oldState = buttonState;
  31861. updateState (&e);
  31862. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  31863. getRepeatTimer().startTimer (autoRepeatSpeed);
  31864. }
  31865. void Button::focusGained (FocusChangeType)
  31866. {
  31867. updateState (0);
  31868. repaint();
  31869. }
  31870. void Button::focusLost (FocusChangeType)
  31871. {
  31872. updateState (0);
  31873. repaint();
  31874. }
  31875. void Button::setVisible (bool shouldBeVisible)
  31876. {
  31877. if (shouldBeVisible != isVisible())
  31878. {
  31879. Component::setVisible (shouldBeVisible);
  31880. if (! shouldBeVisible)
  31881. needsToRelease = false;
  31882. updateState (0);
  31883. }
  31884. else
  31885. {
  31886. Component::setVisible (shouldBeVisible);
  31887. }
  31888. }
  31889. void Button::parentHierarchyChanged()
  31890. {
  31891. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  31892. if (newKeySource != keySource)
  31893. {
  31894. if (keySource->isValidComponent())
  31895. keySource->removeKeyListener (this);
  31896. keySource = newKeySource;
  31897. if (keySource->isValidComponent())
  31898. keySource->addKeyListener (this);
  31899. }
  31900. }
  31901. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  31902. const int commandID_,
  31903. const bool generateTooltip_)
  31904. {
  31905. commandID = commandID_;
  31906. generateTooltip = generateTooltip_;
  31907. if (commandManagerToUse != commandManagerToUse_)
  31908. {
  31909. if (commandManagerToUse != 0)
  31910. commandManagerToUse->removeListener (this);
  31911. commandManagerToUse = commandManagerToUse_;
  31912. if (commandManagerToUse != 0)
  31913. commandManagerToUse->addListener (this);
  31914. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  31915. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  31916. // it is that this button represents, and the button will update its state to reflect this
  31917. // in the applicationCommandListChanged() method.
  31918. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  31919. }
  31920. if (commandManagerToUse != 0)
  31921. applicationCommandListChanged();
  31922. else
  31923. setEnabled (true);
  31924. }
  31925. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  31926. {
  31927. if (info.commandID == commandID
  31928. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  31929. {
  31930. flashButtonState();
  31931. }
  31932. }
  31933. void Button::applicationCommandListChanged()
  31934. {
  31935. if (commandManagerToUse != 0)
  31936. {
  31937. ApplicationCommandInfo info (0);
  31938. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  31939. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  31940. if (target != 0)
  31941. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  31942. }
  31943. }
  31944. void Button::addShortcut (const KeyPress& key)
  31945. {
  31946. if (key.isValid())
  31947. {
  31948. jassert (! isRegisteredForShortcut (key)); // already registered!
  31949. shortcuts.add (key);
  31950. parentHierarchyChanged();
  31951. }
  31952. }
  31953. void Button::clearShortcuts()
  31954. {
  31955. shortcuts.clear();
  31956. parentHierarchyChanged();
  31957. }
  31958. bool Button::isShortcutPressed() const throw()
  31959. {
  31960. if (! isCurrentlyBlockedByAnotherModalComponent())
  31961. {
  31962. for (int i = shortcuts.size(); --i >= 0;)
  31963. if (shortcuts.getReference(i).isCurrentlyDown())
  31964. return true;
  31965. }
  31966. return false;
  31967. }
  31968. bool Button::isRegisteredForShortcut (const KeyPress& key) const throw()
  31969. {
  31970. for (int i = shortcuts.size(); --i >= 0;)
  31971. if (key == shortcuts.getReference(i))
  31972. return true;
  31973. return false;
  31974. }
  31975. bool Button::keyStateChanged (Component*)
  31976. {
  31977. if (! isEnabled())
  31978. return false;
  31979. const bool wasDown = isKeyDown;
  31980. isKeyDown = isShortcutPressed();
  31981. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  31982. getRepeatTimer().startTimer (autoRepeatDelay);
  31983. updateState (0);
  31984. if (isEnabled() && wasDown && ! isKeyDown)
  31985. internalClickCallback (ModifierKeys::getCurrentModifiers());
  31986. return isKeyDown || wasDown;
  31987. }
  31988. bool Button::keyPressed (const KeyPress&, Component*)
  31989. {
  31990. // returning true will avoid forwarding events for keys that we're using as shortcuts
  31991. return isShortcutPressed();
  31992. }
  31993. bool Button::keyPressed (const KeyPress& key)
  31994. {
  31995. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  31996. {
  31997. triggerClick();
  31998. return true;
  31999. }
  32000. return false;
  32001. }
  32002. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  32003. const int repeatMillisecs,
  32004. const int minimumDelayInMillisecs) throw()
  32005. {
  32006. autoRepeatDelay = initialDelayMillisecs;
  32007. autoRepeatSpeed = repeatMillisecs;
  32008. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  32009. }
  32010. void Button::repeatTimerCallback() throw()
  32011. {
  32012. if (needsRepainting)
  32013. {
  32014. getRepeatTimer().stopTimer();
  32015. updateState (0);
  32016. needsRepainting = false;
  32017. }
  32018. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  32019. {
  32020. int repeatSpeed = autoRepeatSpeed;
  32021. if (autoRepeatMinimumDelay >= 0)
  32022. {
  32023. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  32024. timeHeldDown *= timeHeldDown;
  32025. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  32026. }
  32027. repeatSpeed = jmax (1, repeatSpeed);
  32028. getRepeatTimer().startTimer (repeatSpeed);
  32029. const uint32 now = Time::getApproximateMillisecondCounter();
  32030. const int numTimesToCallback
  32031. = (now > lastTimeCallbackTime) ? jmax (1, (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  32032. lastTimeCallbackTime = now;
  32033. const ComponentDeletionWatcher cdw (this);
  32034. for (int i = numTimesToCallback; --i >= 0;)
  32035. {
  32036. internalClickCallback (ModifierKeys::getCurrentModifiers());
  32037. if (cdw.hasBeenDeleted() || ! isDown())
  32038. return;
  32039. }
  32040. }
  32041. else if (! needsToRelease)
  32042. {
  32043. getRepeatTimer().stopTimer();
  32044. }
  32045. }
  32046. class InternalButtonRepeatTimer : public Timer
  32047. {
  32048. public:
  32049. InternalButtonRepeatTimer (Button& owner_) throw()
  32050. : owner (owner_)
  32051. {
  32052. }
  32053. ~InternalButtonRepeatTimer()
  32054. {
  32055. }
  32056. void timerCallback()
  32057. {
  32058. owner.repeatTimerCallback();
  32059. }
  32060. private:
  32061. Button& owner;
  32062. InternalButtonRepeatTimer (const InternalButtonRepeatTimer&);
  32063. const InternalButtonRepeatTimer& operator= (const InternalButtonRepeatTimer&);
  32064. };
  32065. Timer& Button::getRepeatTimer() throw()
  32066. {
  32067. if (repeatTimer == 0)
  32068. repeatTimer = new InternalButtonRepeatTimer (*this);
  32069. return *repeatTimer;
  32070. }
  32071. END_JUCE_NAMESPACE
  32072. /********* End of inlined file: juce_Button.cpp *********/
  32073. /********* Start of inlined file: juce_DrawableButton.cpp *********/
  32074. BEGIN_JUCE_NAMESPACE
  32075. DrawableButton::DrawableButton (const String& name,
  32076. const DrawableButton::ButtonStyle buttonStyle)
  32077. : Button (name),
  32078. style (buttonStyle),
  32079. normalImage (0),
  32080. overImage (0),
  32081. downImage (0),
  32082. disabledImage (0),
  32083. normalImageOn (0),
  32084. overImageOn (0),
  32085. downImageOn (0),
  32086. disabledImageOn (0),
  32087. edgeIndent (3)
  32088. {
  32089. if (buttonStyle == ImageOnButtonBackground)
  32090. {
  32091. backgroundOff = Colour (0xffbbbbff);
  32092. backgroundOn = Colour (0xff3333ff);
  32093. }
  32094. else
  32095. {
  32096. backgroundOff = Colours::transparentBlack;
  32097. backgroundOn = Colour (0xaabbbbff);
  32098. }
  32099. }
  32100. DrawableButton::~DrawableButton()
  32101. {
  32102. deleteImages();
  32103. }
  32104. void DrawableButton::deleteImages()
  32105. {
  32106. deleteAndZero (normalImage);
  32107. deleteAndZero (overImage);
  32108. deleteAndZero (downImage);
  32109. deleteAndZero (disabledImage);
  32110. deleteAndZero (normalImageOn);
  32111. deleteAndZero (overImageOn);
  32112. deleteAndZero (downImageOn);
  32113. deleteAndZero (disabledImageOn);
  32114. }
  32115. void DrawableButton::setImages (const Drawable* normal,
  32116. const Drawable* over,
  32117. const Drawable* down,
  32118. const Drawable* disabled,
  32119. const Drawable* normalOn,
  32120. const Drawable* overOn,
  32121. const Drawable* downOn,
  32122. const Drawable* disabledOn)
  32123. {
  32124. deleteImages();
  32125. jassert (normal != 0); // you really need to give it at least a normal image..
  32126. if (normal != 0)
  32127. normalImage = normal->createCopy();
  32128. if (over != 0)
  32129. overImage = over->createCopy();
  32130. if (down != 0)
  32131. downImage = down->createCopy();
  32132. if (disabled != 0)
  32133. disabledImage = disabled->createCopy();
  32134. if (normalOn != 0)
  32135. normalImageOn = normalOn->createCopy();
  32136. if (overOn != 0)
  32137. overImageOn = overOn->createCopy();
  32138. if (downOn != 0)
  32139. downImageOn = downOn->createCopy();
  32140. if (disabledOn != 0)
  32141. disabledImageOn = disabledOn->createCopy();
  32142. repaint();
  32143. }
  32144. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  32145. {
  32146. if (style != newStyle)
  32147. {
  32148. style = newStyle;
  32149. repaint();
  32150. }
  32151. }
  32152. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  32153. const Colour& toggledOnColour)
  32154. {
  32155. if (backgroundOff != toggledOffColour
  32156. || backgroundOn != toggledOnColour)
  32157. {
  32158. backgroundOff = toggledOffColour;
  32159. backgroundOn = toggledOnColour;
  32160. repaint();
  32161. }
  32162. }
  32163. const Colour& DrawableButton::getBackgroundColour() const throw()
  32164. {
  32165. return getToggleState() ? backgroundOn
  32166. : backgroundOff;
  32167. }
  32168. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  32169. {
  32170. edgeIndent = numPixelsIndent;
  32171. repaint();
  32172. }
  32173. void DrawableButton::paintButton (Graphics& g,
  32174. bool isMouseOverButton,
  32175. bool isButtonDown)
  32176. {
  32177. Rectangle imageSpace;
  32178. if (style == ImageOnButtonBackground)
  32179. {
  32180. const int insetX = getWidth() / 4;
  32181. const int insetY = getHeight() / 4;
  32182. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  32183. getLookAndFeel().drawButtonBackground (g, *this,
  32184. getBackgroundColour(),
  32185. isMouseOverButton,
  32186. isButtonDown);
  32187. }
  32188. else
  32189. {
  32190. g.fillAll (getBackgroundColour());
  32191. const int textH = (style == ImageAboveTextLabel)
  32192. ? jmin (16, proportionOfHeight (0.25f))
  32193. : 0;
  32194. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  32195. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  32196. imageSpace.setBounds (indentX, indentY,
  32197. getWidth() - indentX * 2,
  32198. getHeight() - indentY * 2 - textH);
  32199. if (textH > 0)
  32200. {
  32201. g.setFont ((float) textH);
  32202. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  32203. g.drawFittedText (getName(),
  32204. 2, getHeight() - textH - 1,
  32205. getWidth() - 4, textH,
  32206. Justification::centred, 1);
  32207. }
  32208. }
  32209. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  32210. g.setOpacity (1.0f);
  32211. const Drawable* imageToDraw = 0;
  32212. if (isEnabled())
  32213. {
  32214. imageToDraw = getCurrentImage();
  32215. }
  32216. else
  32217. {
  32218. imageToDraw = getToggleState() ? disabledImageOn
  32219. : disabledImage;
  32220. if (imageToDraw == 0)
  32221. {
  32222. g.setOpacity (0.4f);
  32223. imageToDraw = getNormalImage();
  32224. }
  32225. }
  32226. if (imageToDraw != 0)
  32227. {
  32228. if (style == ImageRaw)
  32229. {
  32230. imageToDraw->draw (g);
  32231. }
  32232. else
  32233. {
  32234. imageToDraw->drawWithin (g,
  32235. imageSpace.getX(),
  32236. imageSpace.getY(),
  32237. imageSpace.getWidth(),
  32238. imageSpace.getHeight(),
  32239. RectanglePlacement::centred);
  32240. }
  32241. }
  32242. }
  32243. const Drawable* DrawableButton::getCurrentImage() const throw()
  32244. {
  32245. if (isDown())
  32246. return getDownImage();
  32247. if (isOver())
  32248. return getOverImage();
  32249. return getNormalImage();
  32250. }
  32251. const Drawable* DrawableButton::getNormalImage() const throw()
  32252. {
  32253. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  32254. : normalImage;
  32255. }
  32256. const Drawable* DrawableButton::getOverImage() const throw()
  32257. {
  32258. const Drawable* d = normalImage;
  32259. if (getToggleState())
  32260. {
  32261. if (overImageOn != 0)
  32262. d = overImageOn;
  32263. else if (normalImageOn != 0)
  32264. d = normalImageOn;
  32265. else if (overImage != 0)
  32266. d = overImage;
  32267. }
  32268. else
  32269. {
  32270. if (overImage != 0)
  32271. d = overImage;
  32272. }
  32273. return d;
  32274. }
  32275. const Drawable* DrawableButton::getDownImage() const throw()
  32276. {
  32277. const Drawable* d = normalImage;
  32278. if (getToggleState())
  32279. {
  32280. if (downImageOn != 0)
  32281. d = downImageOn;
  32282. else if (overImageOn != 0)
  32283. d = overImageOn;
  32284. else if (normalImageOn != 0)
  32285. d = normalImageOn;
  32286. else if (downImage != 0)
  32287. d = downImage;
  32288. else
  32289. d = getOverImage();
  32290. }
  32291. else
  32292. {
  32293. if (downImage != 0)
  32294. d = downImage;
  32295. else
  32296. d = getOverImage();
  32297. }
  32298. return d;
  32299. }
  32300. END_JUCE_NAMESPACE
  32301. /********* End of inlined file: juce_DrawableButton.cpp *********/
  32302. /********* Start of inlined file: juce_HyperlinkButton.cpp *********/
  32303. BEGIN_JUCE_NAMESPACE
  32304. HyperlinkButton::HyperlinkButton (const String& linkText,
  32305. const URL& linkURL)
  32306. : Button (linkText),
  32307. url (linkURL),
  32308. font (14.0f, Font::underlined),
  32309. resizeFont (true),
  32310. justification (Justification::centred)
  32311. {
  32312. setMouseCursor (MouseCursor::PointingHandCursor);
  32313. setTooltip (linkURL.toString (false));
  32314. }
  32315. HyperlinkButton::~HyperlinkButton()
  32316. {
  32317. }
  32318. void HyperlinkButton::setFont (const Font& newFont,
  32319. const bool resizeToMatchComponentHeight,
  32320. const Justification& justificationType)
  32321. {
  32322. font = newFont;
  32323. resizeFont = resizeToMatchComponentHeight;
  32324. justification = justificationType;
  32325. repaint();
  32326. }
  32327. void HyperlinkButton::setURL (const URL& newURL) throw()
  32328. {
  32329. url = newURL;
  32330. setTooltip (newURL.toString (false));
  32331. }
  32332. const Font HyperlinkButton::getFontToUse() const
  32333. {
  32334. Font f (font);
  32335. if (resizeFont)
  32336. f.setHeight (getHeight() * 0.7f);
  32337. return f;
  32338. }
  32339. void HyperlinkButton::changeWidthToFitText()
  32340. {
  32341. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  32342. }
  32343. void HyperlinkButton::colourChanged()
  32344. {
  32345. repaint();
  32346. }
  32347. void HyperlinkButton::clicked()
  32348. {
  32349. if (url.isWellFormed())
  32350. url.launchInDefaultBrowser();
  32351. }
  32352. void HyperlinkButton::paintButton (Graphics& g,
  32353. bool isMouseOverButton,
  32354. bool isButtonDown)
  32355. {
  32356. const Colour textColour (findColour (textColourId));
  32357. if (isEnabled())
  32358. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  32359. : textColour);
  32360. else
  32361. g.setColour (textColour.withMultipliedAlpha (0.4f));
  32362. g.setFont (getFontToUse());
  32363. g.drawText (getButtonText(),
  32364. 2, 0, getWidth() - 2, getHeight(),
  32365. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  32366. true);
  32367. }
  32368. END_JUCE_NAMESPACE
  32369. /********* End of inlined file: juce_HyperlinkButton.cpp *********/
  32370. /********* Start of inlined file: juce_ImageButton.cpp *********/
  32371. BEGIN_JUCE_NAMESPACE
  32372. ImageButton::ImageButton (const String& text)
  32373. : Button (text),
  32374. scaleImageToFit (true),
  32375. preserveProportions (true),
  32376. alphaThreshold (0),
  32377. imageX (0),
  32378. imageY (0),
  32379. imageW (0),
  32380. imageH (0),
  32381. normalImage (0),
  32382. overImage (0),
  32383. downImage (0)
  32384. {
  32385. }
  32386. ImageButton::~ImageButton()
  32387. {
  32388. deleteImages();
  32389. }
  32390. void ImageButton::deleteImages()
  32391. {
  32392. if (normalImage != 0)
  32393. {
  32394. if (ImageCache::isImageInCache (normalImage))
  32395. ImageCache::release (normalImage);
  32396. else
  32397. delete normalImage;
  32398. }
  32399. if (overImage != 0)
  32400. {
  32401. if (ImageCache::isImageInCache (overImage))
  32402. ImageCache::release (overImage);
  32403. else
  32404. delete overImage;
  32405. }
  32406. if (downImage != 0)
  32407. {
  32408. if (ImageCache::isImageInCache (downImage))
  32409. ImageCache::release (downImage);
  32410. else
  32411. delete downImage;
  32412. }
  32413. }
  32414. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  32415. const bool rescaleImagesWhenButtonSizeChanges,
  32416. const bool preserveImageProportions,
  32417. Image* const normalImage_,
  32418. const float imageOpacityWhenNormal,
  32419. const Colour& overlayColourWhenNormal,
  32420. Image* const overImage_,
  32421. const float imageOpacityWhenOver,
  32422. const Colour& overlayColourWhenOver,
  32423. Image* const downImage_,
  32424. const float imageOpacityWhenDown,
  32425. const Colour& overlayColourWhenDown,
  32426. const float hitTestAlphaThreshold)
  32427. {
  32428. deleteImages();
  32429. normalImage = normalImage_;
  32430. overImage = overImage_;
  32431. downImage = downImage_;
  32432. if (resizeButtonNowToFitThisImage && normalImage != 0)
  32433. {
  32434. imageW = normalImage->getWidth();
  32435. imageH = normalImage->getHeight();
  32436. setSize (imageW, imageH);
  32437. }
  32438. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  32439. preserveProportions = preserveImageProportions;
  32440. normalOpacity = imageOpacityWhenNormal;
  32441. normalOverlay = overlayColourWhenNormal;
  32442. overOpacity = imageOpacityWhenOver;
  32443. overOverlay = overlayColourWhenOver;
  32444. downOpacity = imageOpacityWhenDown;
  32445. downOverlay = overlayColourWhenDown;
  32446. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundFloatToInt (255.0f * hitTestAlphaThreshold));
  32447. repaint();
  32448. }
  32449. Image* ImageButton::getCurrentImage() const
  32450. {
  32451. if (isDown())
  32452. return getDownImage();
  32453. if (isOver())
  32454. return getOverImage();
  32455. return getNormalImage();
  32456. }
  32457. Image* ImageButton::getNormalImage() const throw()
  32458. {
  32459. return normalImage;
  32460. }
  32461. Image* ImageButton::getOverImage() const throw()
  32462. {
  32463. return (overImage != 0) ? overImage
  32464. : normalImage;
  32465. }
  32466. Image* ImageButton::getDownImage() const throw()
  32467. {
  32468. return (downImage != 0) ? downImage
  32469. : getOverImage();
  32470. }
  32471. void ImageButton::paintButton (Graphics& g,
  32472. bool isMouseOverButton,
  32473. bool isButtonDown)
  32474. {
  32475. if (! isEnabled())
  32476. {
  32477. isMouseOverButton = false;
  32478. isButtonDown = false;
  32479. }
  32480. Image* const im = getCurrentImage();
  32481. if (im != 0)
  32482. {
  32483. const int iw = im->getWidth();
  32484. const int ih = im->getHeight();
  32485. imageW = getWidth();
  32486. imageH = getHeight();
  32487. imageX = (imageW - iw) >> 1;
  32488. imageY = (imageH - ih) >> 1;
  32489. if (scaleImageToFit)
  32490. {
  32491. if (preserveProportions)
  32492. {
  32493. int newW, newH;
  32494. const float imRatio = ih / (float)iw;
  32495. const float destRatio = imageH / (float)imageW;
  32496. if (imRatio > destRatio)
  32497. {
  32498. newW = roundFloatToInt (imageH / imRatio);
  32499. newH = imageH;
  32500. }
  32501. else
  32502. {
  32503. newW = imageW;
  32504. newH = roundFloatToInt (imageW * imRatio);
  32505. }
  32506. imageX = (imageW - newW) / 2;
  32507. imageY = (imageH - newH) / 2;
  32508. imageW = newW;
  32509. imageH = newH;
  32510. }
  32511. else
  32512. {
  32513. imageX = 0;
  32514. imageY = 0;
  32515. }
  32516. }
  32517. const Colour& overlayColour = (isButtonDown) ? downOverlay
  32518. : ((isMouseOverButton) ? overOverlay
  32519. : normalOverlay);
  32520. if (! overlayColour.isOpaque())
  32521. {
  32522. g.setOpacity ((isButtonDown) ? downOpacity
  32523. : ((isMouseOverButton) ? overOpacity
  32524. : normalOpacity));
  32525. if (scaleImageToFit)
  32526. g.drawImage (im, imageX, imageY, imageW, imageH, 0, 0, iw, ih, false);
  32527. else
  32528. g.drawImageAt (im, imageX, imageY, false);
  32529. }
  32530. if (! overlayColour.isTransparent())
  32531. {
  32532. g.setColour (overlayColour);
  32533. if (scaleImageToFit)
  32534. g.drawImage (im, imageX, imageY, imageW, imageH, 0, 0, iw, ih, true);
  32535. else
  32536. g.drawImageAt (im, imageX, imageY, true);
  32537. }
  32538. }
  32539. }
  32540. bool ImageButton::hitTest (int x, int y)
  32541. {
  32542. if (alphaThreshold == 0)
  32543. return true;
  32544. Image* const im = getCurrentImage();
  32545. return im == 0
  32546. || (imageW > 0 && imageH > 0
  32547. && alphaThreshold < im->getPixelAt (((x - imageX) * im->getWidth()) / imageW,
  32548. ((y - imageY) * im->getHeight()) / imageH).getAlpha());
  32549. }
  32550. END_JUCE_NAMESPACE
  32551. /********* End of inlined file: juce_ImageButton.cpp *********/
  32552. /********* Start of inlined file: juce_ShapeButton.cpp *********/
  32553. BEGIN_JUCE_NAMESPACE
  32554. ShapeButton::ShapeButton (const String& text,
  32555. const Colour& normalColour_,
  32556. const Colour& overColour_,
  32557. const Colour& downColour_)
  32558. : Button (text),
  32559. normalColour (normalColour_),
  32560. overColour (overColour_),
  32561. downColour (downColour_),
  32562. maintainShapeProportions (false),
  32563. outlineWidth (0.0f)
  32564. {
  32565. }
  32566. ShapeButton::~ShapeButton()
  32567. {
  32568. }
  32569. void ShapeButton::setColours (const Colour& newNormalColour,
  32570. const Colour& newOverColour,
  32571. const Colour& newDownColour)
  32572. {
  32573. normalColour = newNormalColour;
  32574. overColour = newOverColour;
  32575. downColour = newDownColour;
  32576. }
  32577. void ShapeButton::setOutline (const Colour& newOutlineColour,
  32578. const float newOutlineWidth)
  32579. {
  32580. outlineColour = newOutlineColour;
  32581. outlineWidth = newOutlineWidth;
  32582. }
  32583. void ShapeButton::setShape (const Path& newShape,
  32584. const bool resizeNowToFitThisShape,
  32585. const bool maintainShapeProportions_,
  32586. const bool hasShadow)
  32587. {
  32588. shape = newShape;
  32589. maintainShapeProportions = maintainShapeProportions_;
  32590. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  32591. setComponentEffect ((hasShadow) ? &shadow : 0);
  32592. if (resizeNowToFitThisShape)
  32593. {
  32594. float x, y, w, h;
  32595. shape.getBounds (x, y, w, h);
  32596. shape.applyTransform (AffineTransform::translation (-x, -y));
  32597. if (hasShadow)
  32598. {
  32599. w += 4.0f;
  32600. h += 4.0f;
  32601. shape.applyTransform (AffineTransform::translation (2.0f, 2.0f));
  32602. }
  32603. setSize (1 + (int) (w + outlineWidth),
  32604. 1 + (int) (h + outlineWidth));
  32605. }
  32606. }
  32607. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  32608. {
  32609. if (! isEnabled())
  32610. {
  32611. isMouseOverButton = false;
  32612. isButtonDown = false;
  32613. }
  32614. g.setColour ((isButtonDown) ? downColour
  32615. : (isMouseOverButton) ? overColour
  32616. : normalColour);
  32617. int w = getWidth();
  32618. int h = getHeight();
  32619. if (getComponentEffect() != 0)
  32620. {
  32621. w -= 4;
  32622. h -= 4;
  32623. }
  32624. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  32625. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  32626. w - offset - outlineWidth,
  32627. h - offset - outlineWidth,
  32628. maintainShapeProportions));
  32629. g.fillPath (shape, trans);
  32630. if (outlineWidth > 0.0f)
  32631. {
  32632. g.setColour (outlineColour);
  32633. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  32634. }
  32635. }
  32636. END_JUCE_NAMESPACE
  32637. /********* End of inlined file: juce_ShapeButton.cpp *********/
  32638. /********* Start of inlined file: juce_TextButton.cpp *********/
  32639. BEGIN_JUCE_NAMESPACE
  32640. TextButton::TextButton (const String& name,
  32641. const String& toolTip)
  32642. : Button (name)
  32643. {
  32644. setTooltip (toolTip);
  32645. }
  32646. TextButton::~TextButton()
  32647. {
  32648. }
  32649. void TextButton::paintButton (Graphics& g,
  32650. bool isMouseOverButton,
  32651. bool isButtonDown)
  32652. {
  32653. getLookAndFeel().drawButtonBackground (g, *this,
  32654. findColour (getToggleState() ? buttonOnColourId
  32655. : buttonColourId),
  32656. isMouseOverButton,
  32657. isButtonDown);
  32658. getLookAndFeel().drawButtonText (g, *this,
  32659. isMouseOverButton,
  32660. isButtonDown);
  32661. }
  32662. void TextButton::colourChanged()
  32663. {
  32664. repaint();
  32665. }
  32666. const Font TextButton::getFont()
  32667. {
  32668. return Font (jmin (15.0f, getHeight() * 0.6f));
  32669. }
  32670. void TextButton::changeWidthToFitText (const int newHeight)
  32671. {
  32672. if (newHeight >= 0)
  32673. setSize (jmax (1, getWidth()), newHeight);
  32674. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  32675. getHeight());
  32676. }
  32677. END_JUCE_NAMESPACE
  32678. /********* End of inlined file: juce_TextButton.cpp *********/
  32679. /********* Start of inlined file: juce_ToggleButton.cpp *********/
  32680. BEGIN_JUCE_NAMESPACE
  32681. ToggleButton::ToggleButton (const String& buttonText)
  32682. : Button (buttonText)
  32683. {
  32684. setClickingTogglesState (true);
  32685. }
  32686. ToggleButton::~ToggleButton()
  32687. {
  32688. }
  32689. void ToggleButton::paintButton (Graphics& g,
  32690. bool isMouseOverButton,
  32691. bool isButtonDown)
  32692. {
  32693. getLookAndFeel().drawToggleButton (g, *this,
  32694. isMouseOverButton,
  32695. isButtonDown);
  32696. }
  32697. void ToggleButton::changeWidthToFitText()
  32698. {
  32699. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  32700. }
  32701. void ToggleButton::colourChanged()
  32702. {
  32703. repaint();
  32704. }
  32705. END_JUCE_NAMESPACE
  32706. /********* End of inlined file: juce_ToggleButton.cpp *********/
  32707. /********* Start of inlined file: juce_ToolbarButton.cpp *********/
  32708. BEGIN_JUCE_NAMESPACE
  32709. ToolbarButton::ToolbarButton (const int itemId,
  32710. const String& buttonText,
  32711. Drawable* const normalImage_,
  32712. Drawable* const toggledOnImage_)
  32713. : ToolbarItemComponent (itemId, buttonText, true),
  32714. normalImage (normalImage_),
  32715. toggledOnImage (toggledOnImage_)
  32716. {
  32717. }
  32718. ToolbarButton::~ToolbarButton()
  32719. {
  32720. delete normalImage;
  32721. delete toggledOnImage;
  32722. }
  32723. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  32724. bool /*isToolbarVertical*/,
  32725. int& preferredSize,
  32726. int& minSize, int& maxSize)
  32727. {
  32728. preferredSize = minSize = maxSize = toolbarDepth;
  32729. return true;
  32730. }
  32731. void ToolbarButton::paintButtonArea (Graphics& g,
  32732. int width, int height,
  32733. bool /*isMouseOver*/,
  32734. bool /*isMouseDown*/)
  32735. {
  32736. Drawable* d = normalImage;
  32737. if (getToggleState() && toggledOnImage != 0)
  32738. d = toggledOnImage;
  32739. if (! isEnabled())
  32740. {
  32741. Image im (Image::ARGB, width, height, true);
  32742. Graphics g2 (im);
  32743. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred);
  32744. im.desaturate();
  32745. g.drawImageAt (&im, 0, 0);
  32746. }
  32747. else
  32748. {
  32749. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred);
  32750. }
  32751. }
  32752. void ToolbarButton::contentAreaChanged (const Rectangle&)
  32753. {
  32754. }
  32755. END_JUCE_NAMESPACE
  32756. /********* End of inlined file: juce_ToolbarButton.cpp *********/
  32757. /********* Start of inlined file: juce_ComboBox.cpp *********/
  32758. BEGIN_JUCE_NAMESPACE
  32759. ComboBox::ComboBox (const String& name)
  32760. : Component (name),
  32761. items (4),
  32762. currentIndex (-1),
  32763. isButtonDown (false),
  32764. separatorPending (false),
  32765. menuActive (false),
  32766. listeners (2),
  32767. label (0)
  32768. {
  32769. noChoicesMessage = TRANS("(no choices)");
  32770. setRepaintsOnMouseActivity (true);
  32771. lookAndFeelChanged();
  32772. }
  32773. ComboBox::~ComboBox()
  32774. {
  32775. if (menuActive)
  32776. PopupMenu::dismissAllActiveMenus();
  32777. deleteAllChildren();
  32778. }
  32779. void ComboBox::setEditableText (const bool isEditable)
  32780. {
  32781. label->setEditable (isEditable, isEditable, false);
  32782. setWantsKeyboardFocus (! isEditable);
  32783. resized();
  32784. }
  32785. bool ComboBox::isTextEditable() const throw()
  32786. {
  32787. return label->isEditable();
  32788. }
  32789. void ComboBox::setJustificationType (const Justification& justification) throw()
  32790. {
  32791. label->setJustificationType (justification);
  32792. }
  32793. const Justification ComboBox::getJustificationType() const throw()
  32794. {
  32795. return label->getJustificationType();
  32796. }
  32797. void ComboBox::setTooltip (const String& newTooltip)
  32798. {
  32799. SettableTooltipClient::setTooltip (newTooltip);
  32800. label->setTooltip (newTooltip);
  32801. }
  32802. void ComboBox::addItem (const String& newItemText,
  32803. const int newItemId) throw()
  32804. {
  32805. // you can't add empty strings to the list..
  32806. jassert (newItemText.isNotEmpty());
  32807. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  32808. jassert (newItemId != 0);
  32809. // you shouldn't use duplicate item IDs!
  32810. jassert (getItemForId (newItemId) == 0);
  32811. if (newItemText.isNotEmpty() && newItemId != 0)
  32812. {
  32813. if (separatorPending)
  32814. {
  32815. separatorPending = false;
  32816. ItemInfo* const item = new ItemInfo();
  32817. item->itemId = 0;
  32818. item->isEnabled = false;
  32819. item->isHeading = false;
  32820. items.add (item);
  32821. }
  32822. ItemInfo* const item = new ItemInfo();
  32823. item->name = newItemText;
  32824. item->itemId = newItemId;
  32825. item->isEnabled = true;
  32826. item->isHeading = false;
  32827. items.add (item);
  32828. }
  32829. }
  32830. void ComboBox::addSeparator() throw()
  32831. {
  32832. separatorPending = (items.size() > 0);
  32833. }
  32834. void ComboBox::addSectionHeading (const String& headingName) throw()
  32835. {
  32836. // you can't add empty strings to the list..
  32837. jassert (headingName.isNotEmpty());
  32838. if (headingName.isNotEmpty())
  32839. {
  32840. if (separatorPending)
  32841. {
  32842. separatorPending = false;
  32843. ItemInfo* const item = new ItemInfo();
  32844. item->itemId = 0;
  32845. item->isEnabled = false;
  32846. item->isHeading = false;
  32847. items.add (item);
  32848. }
  32849. ItemInfo* const item = new ItemInfo();
  32850. item->name = headingName;
  32851. item->itemId = 0;
  32852. item->isEnabled = true;
  32853. item->isHeading = true;
  32854. items.add (item);
  32855. }
  32856. }
  32857. void ComboBox::setItemEnabled (const int itemId,
  32858. const bool isEnabled) throw()
  32859. {
  32860. ItemInfo* const item = getItemForId (itemId);
  32861. if (item != 0)
  32862. item->isEnabled = isEnabled;
  32863. }
  32864. void ComboBox::changeItemText (const int itemId,
  32865. const String& newText) throw()
  32866. {
  32867. ItemInfo* const item = getItemForId (itemId);
  32868. jassert (item != 0);
  32869. if (item != 0)
  32870. item->name = newText;
  32871. }
  32872. void ComboBox::clear (const bool dontSendChangeMessage)
  32873. {
  32874. items.clear();
  32875. separatorPending = false;
  32876. if (! label->isEditable())
  32877. setSelectedItemIndex (-1, dontSendChangeMessage);
  32878. }
  32879. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  32880. {
  32881. jassert (itemId != 0);
  32882. if (itemId != 0)
  32883. {
  32884. for (int i = items.size(); --i >= 0;)
  32885. if (items.getUnchecked(i)->itemId == itemId)
  32886. return items.getUnchecked(i);
  32887. }
  32888. return 0;
  32889. }
  32890. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  32891. {
  32892. int n = 0;
  32893. for (int i = 0; i < items.size(); ++i)
  32894. {
  32895. ItemInfo* const item = items.getUnchecked(i);
  32896. if (item->isRealItem())
  32897. {
  32898. if (n++ == index)
  32899. return item;
  32900. }
  32901. }
  32902. return 0;
  32903. }
  32904. int ComboBox::getNumItems() const throw()
  32905. {
  32906. int n = 0;
  32907. for (int i = items.size(); --i >= 0;)
  32908. {
  32909. ItemInfo* const item = items.getUnchecked(i);
  32910. if (item->isRealItem())
  32911. ++n;
  32912. }
  32913. return n;
  32914. }
  32915. const String ComboBox::getItemText (const int index) const throw()
  32916. {
  32917. ItemInfo* const item = getItemForIndex (index);
  32918. if (item != 0)
  32919. return item->name;
  32920. return String::empty;
  32921. }
  32922. int ComboBox::getItemId (const int index) const throw()
  32923. {
  32924. ItemInfo* const item = getItemForIndex (index);
  32925. return (item != 0) ? item->itemId : 0;
  32926. }
  32927. bool ComboBox::ItemInfo::isSeparator() const throw()
  32928. {
  32929. return name.isEmpty();
  32930. }
  32931. bool ComboBox::ItemInfo::isRealItem() const throw()
  32932. {
  32933. return ! (isHeading || name.isEmpty());
  32934. }
  32935. int ComboBox::getSelectedItemIndex() const throw()
  32936. {
  32937. return (currentIndex >= 0 && getText() == getItemText (currentIndex))
  32938. ? currentIndex
  32939. : -1;
  32940. }
  32941. void ComboBox::setSelectedItemIndex (const int index,
  32942. const bool dontSendChangeMessage) throw()
  32943. {
  32944. if (currentIndex != index || label->getText() != getItemText (currentIndex))
  32945. {
  32946. if (((unsigned int) index) < (unsigned int) getNumItems())
  32947. currentIndex = index;
  32948. else
  32949. currentIndex = -1;
  32950. label->setText (getItemText (currentIndex), false);
  32951. if (! dontSendChangeMessage)
  32952. triggerAsyncUpdate();
  32953. }
  32954. }
  32955. void ComboBox::setSelectedId (const int newItemId,
  32956. const bool dontSendChangeMessage) throw()
  32957. {
  32958. for (int i = getNumItems(); --i >= 0;)
  32959. {
  32960. if (getItemId(i) == newItemId)
  32961. {
  32962. setSelectedItemIndex (i, dontSendChangeMessage);
  32963. break;
  32964. }
  32965. }
  32966. }
  32967. int ComboBox::getSelectedId() const throw()
  32968. {
  32969. const ItemInfo* const item = getItemForIndex (currentIndex);
  32970. return (item != 0 && getText() == item->name)
  32971. ? item->itemId
  32972. : 0;
  32973. }
  32974. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  32975. {
  32976. jassert (listener != 0);
  32977. if (listener != 0)
  32978. listeners.add (listener);
  32979. }
  32980. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  32981. {
  32982. listeners.removeValue (listener);
  32983. }
  32984. void ComboBox::handleAsyncUpdate()
  32985. {
  32986. for (int i = listeners.size(); --i >= 0;)
  32987. {
  32988. ((ComboBoxListener*) listeners.getUnchecked (i))->comboBoxChanged (this);
  32989. i = jmin (i, listeners.size());
  32990. }
  32991. }
  32992. const String ComboBox::getText() const throw()
  32993. {
  32994. return label->getText();
  32995. }
  32996. void ComboBox::setText (const String& newText,
  32997. const bool dontSendChangeMessage) throw()
  32998. {
  32999. for (int i = items.size(); --i >= 0;)
  33000. {
  33001. ItemInfo* const item = items.getUnchecked(i);
  33002. if (item->isRealItem()
  33003. && item->name == newText)
  33004. {
  33005. setSelectedId (item->itemId, dontSendChangeMessage);
  33006. return;
  33007. }
  33008. }
  33009. currentIndex = -1;
  33010. if (label->getText() != newText)
  33011. {
  33012. label->setText (newText, false);
  33013. if (! dontSendChangeMessage)
  33014. triggerAsyncUpdate();
  33015. }
  33016. repaint();
  33017. }
  33018. void ComboBox::showEditor()
  33019. {
  33020. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  33021. label->showEditor();
  33022. }
  33023. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  33024. {
  33025. textWhenNothingSelected = newMessage;
  33026. repaint();
  33027. }
  33028. const String ComboBox::getTextWhenNothingSelected() const throw()
  33029. {
  33030. return textWhenNothingSelected;
  33031. }
  33032. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  33033. {
  33034. noChoicesMessage = newMessage;
  33035. }
  33036. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  33037. {
  33038. return noChoicesMessage;
  33039. }
  33040. void ComboBox::paint (Graphics& g)
  33041. {
  33042. getLookAndFeel().drawComboBox (g,
  33043. getWidth(),
  33044. getHeight(),
  33045. isButtonDown,
  33046. label->getRight(),
  33047. 0,
  33048. getWidth() - label->getRight(),
  33049. getHeight(),
  33050. *this);
  33051. if (textWhenNothingSelected.isNotEmpty()
  33052. && label->getText().isEmpty()
  33053. && ! label->isBeingEdited())
  33054. {
  33055. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  33056. g.setFont (label->getFont());
  33057. g.drawFittedText (textWhenNothingSelected,
  33058. label->getX() + 2, label->getY() + 1,
  33059. label->getWidth() - 4, label->getHeight() - 2,
  33060. label->getJustificationType(),
  33061. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  33062. }
  33063. }
  33064. void ComboBox::resized()
  33065. {
  33066. if (getHeight() > 0 && getWidth() > 0)
  33067. getLookAndFeel().positionComboBoxText (*this, *label);
  33068. }
  33069. void ComboBox::enablementChanged()
  33070. {
  33071. repaint();
  33072. }
  33073. void ComboBox::lookAndFeelChanged()
  33074. {
  33075. repaint();
  33076. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  33077. if (label != 0)
  33078. {
  33079. newLabel->setEditable (label->isEditable());
  33080. newLabel->setJustificationType (label->getJustificationType());
  33081. newLabel->setTooltip (label->getTooltip());
  33082. newLabel->setText (label->getText(), false);
  33083. }
  33084. delete label;
  33085. label = newLabel;
  33086. addAndMakeVisible (newLabel);
  33087. newLabel->addListener (this);
  33088. newLabel->addMouseListener (this, false);
  33089. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  33090. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  33091. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  33092. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  33093. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  33094. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  33095. resized();
  33096. }
  33097. void ComboBox::colourChanged()
  33098. {
  33099. lookAndFeelChanged();
  33100. }
  33101. bool ComboBox::keyPressed (const KeyPress& key)
  33102. {
  33103. bool used = false;
  33104. if (key.isKeyCode (KeyPress::upKey)
  33105. || key.isKeyCode (KeyPress::leftKey))
  33106. {
  33107. setSelectedItemIndex (jmax (0, currentIndex - 1));
  33108. used = true;
  33109. }
  33110. else if (key.isKeyCode (KeyPress::downKey)
  33111. || key.isKeyCode (KeyPress::rightKey))
  33112. {
  33113. setSelectedItemIndex (jmin (currentIndex + 1, getNumItems() - 1));
  33114. used = true;
  33115. }
  33116. else if (key.isKeyCode (KeyPress::returnKey))
  33117. {
  33118. showPopup();
  33119. used = true;
  33120. }
  33121. return used;
  33122. }
  33123. bool ComboBox::keyStateChanged()
  33124. {
  33125. // only forward key events that aren't used by this component
  33126. return KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  33127. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  33128. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  33129. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey);
  33130. }
  33131. void ComboBox::focusGained (FocusChangeType)
  33132. {
  33133. repaint();
  33134. }
  33135. void ComboBox::focusLost (FocusChangeType)
  33136. {
  33137. repaint();
  33138. }
  33139. void ComboBox::labelTextChanged (Label*)
  33140. {
  33141. triggerAsyncUpdate();
  33142. }
  33143. void ComboBox::showPopup()
  33144. {
  33145. if (! menuActive)
  33146. {
  33147. const int currentId = getSelectedId();
  33148. ComponentDeletionWatcher deletionWatcher (this);
  33149. PopupMenu menu;
  33150. menu.setLookAndFeel (&getLookAndFeel());
  33151. for (int i = 0; i < items.size(); ++i)
  33152. {
  33153. const ItemInfo* const item = items.getUnchecked(i);
  33154. if (item->isSeparator())
  33155. menu.addSeparator();
  33156. else if (item->isHeading)
  33157. menu.addSectionHeader (item->name);
  33158. else
  33159. menu.addItem (item->itemId, item->name,
  33160. item->isEnabled, item->itemId == currentId);
  33161. }
  33162. if (items.size() == 0)
  33163. menu.addItem (1, noChoicesMessage, false);
  33164. const int itemHeight = jlimit (12, 24, getHeight());
  33165. menuActive = true;
  33166. const int resultId = menu.showAt (this, currentId,
  33167. getWidth(), 1, itemHeight);
  33168. if (deletionWatcher.hasBeenDeleted())
  33169. return;
  33170. menuActive = false;
  33171. if (resultId != 0)
  33172. setSelectedId (resultId);
  33173. }
  33174. }
  33175. void ComboBox::mouseDown (const MouseEvent& e)
  33176. {
  33177. beginDragAutoRepeat (300);
  33178. isButtonDown = isEnabled();
  33179. if (isButtonDown
  33180. && (e.eventComponent == this || ! label->isEditable()))
  33181. {
  33182. showPopup();
  33183. }
  33184. }
  33185. void ComboBox::mouseDrag (const MouseEvent& e)
  33186. {
  33187. beginDragAutoRepeat (50);
  33188. if (isButtonDown && ! e.mouseWasClicked())
  33189. showPopup();
  33190. }
  33191. void ComboBox::mouseUp (const MouseEvent& e2)
  33192. {
  33193. if (isButtonDown)
  33194. {
  33195. isButtonDown = false;
  33196. repaint();
  33197. const MouseEvent e (e2.getEventRelativeTo (this));
  33198. if (reallyContains (e.x, e.y, true)
  33199. && (e2.eventComponent == this || ! label->isEditable()))
  33200. {
  33201. showPopup();
  33202. }
  33203. }
  33204. }
  33205. END_JUCE_NAMESPACE
  33206. /********* End of inlined file: juce_ComboBox.cpp *********/
  33207. /********* Start of inlined file: juce_Label.cpp *********/
  33208. BEGIN_JUCE_NAMESPACE
  33209. Label::Label (const String& componentName,
  33210. const String& labelText)
  33211. : Component (componentName),
  33212. text (labelText),
  33213. font (15.0f),
  33214. justification (Justification::centredLeft),
  33215. editor (0),
  33216. listeners (2),
  33217. ownerComponent (0),
  33218. deletionWatcher (0),
  33219. horizontalBorderSize (3),
  33220. verticalBorderSize (1),
  33221. editSingleClick (false),
  33222. editDoubleClick (false),
  33223. lossOfFocusDiscardsChanges (false)
  33224. {
  33225. setColour (TextEditor::textColourId, Colours::black);
  33226. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  33227. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  33228. }
  33229. Label::~Label()
  33230. {
  33231. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33232. ownerComponent->removeComponentListener (this);
  33233. deleteAndZero (deletionWatcher);
  33234. if (editor != 0)
  33235. delete editor;
  33236. }
  33237. void Label::setText (const String& newText,
  33238. const bool broadcastChangeMessage)
  33239. {
  33240. hideEditor (true);
  33241. if (text != newText)
  33242. {
  33243. text = newText;
  33244. if (broadcastChangeMessage)
  33245. triggerAsyncUpdate();
  33246. repaint();
  33247. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33248. componentMovedOrResized (*ownerComponent, true, true);
  33249. }
  33250. }
  33251. const String Label::getText (const bool returnActiveEditorContents) const throw()
  33252. {
  33253. return (returnActiveEditorContents && isBeingEdited())
  33254. ? editor->getText()
  33255. : text;
  33256. }
  33257. void Label::setFont (const Font& newFont) throw()
  33258. {
  33259. font = newFont;
  33260. repaint();
  33261. }
  33262. const Font& Label::getFont() const throw()
  33263. {
  33264. return font;
  33265. }
  33266. void Label::setEditable (const bool editOnSingleClick,
  33267. const bool editOnDoubleClick,
  33268. const bool lossOfFocusDiscardsChanges_) throw()
  33269. {
  33270. editSingleClick = editOnSingleClick;
  33271. editDoubleClick = editOnDoubleClick;
  33272. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  33273. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  33274. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  33275. }
  33276. void Label::setJustificationType (const Justification& justification_) throw()
  33277. {
  33278. justification = justification_;
  33279. repaint();
  33280. }
  33281. void Label::setBorderSize (int h, int v)
  33282. {
  33283. horizontalBorderSize = h;
  33284. verticalBorderSize = v;
  33285. repaint();
  33286. }
  33287. void Label::attachToComponent (Component* owner,
  33288. const bool onLeft)
  33289. {
  33290. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33291. ownerComponent->removeComponentListener (this);
  33292. deleteAndZero (deletionWatcher);
  33293. ownerComponent = owner;
  33294. leftOfOwnerComp = onLeft;
  33295. if (ownerComponent != 0)
  33296. {
  33297. deletionWatcher = new ComponentDeletionWatcher (owner);
  33298. setVisible (owner->isVisible());
  33299. ownerComponent->addComponentListener (this);
  33300. componentParentHierarchyChanged (*ownerComponent);
  33301. componentMovedOrResized (*ownerComponent, true, true);
  33302. }
  33303. }
  33304. void Label::componentMovedOrResized (Component& component,
  33305. bool /*wasMoved*/,
  33306. bool /*wasResized*/)
  33307. {
  33308. if (leftOfOwnerComp)
  33309. {
  33310. setSize (jmin (getFont().getStringWidth (text) + 8, component.getX()),
  33311. component.getHeight());
  33312. setTopRightPosition (component.getX(), component.getY());
  33313. }
  33314. else
  33315. {
  33316. setSize (component.getWidth(),
  33317. 8 + roundFloatToInt (getFont().getHeight()));
  33318. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  33319. }
  33320. }
  33321. void Label::componentParentHierarchyChanged (Component& component)
  33322. {
  33323. if (component.getParentComponent() != 0)
  33324. component.getParentComponent()->addChildComponent (this);
  33325. }
  33326. void Label::componentVisibilityChanged (Component& component)
  33327. {
  33328. setVisible (component.isVisible());
  33329. }
  33330. void Label::textWasEdited()
  33331. {
  33332. }
  33333. void Label::showEditor()
  33334. {
  33335. if (editor == 0)
  33336. {
  33337. addAndMakeVisible (editor = createEditorComponent());
  33338. editor->setText (getText());
  33339. editor->addListener (this);
  33340. editor->grabKeyboardFocus();
  33341. editor->setHighlightedRegion (0, text.length());
  33342. editor->addListener (this);
  33343. resized();
  33344. repaint();
  33345. enterModalState();
  33346. editor->grabKeyboardFocus();
  33347. }
  33348. }
  33349. bool Label::updateFromTextEditorContents()
  33350. {
  33351. jassert (editor != 0);
  33352. const String newText (editor->getText());
  33353. if (text != newText)
  33354. {
  33355. text = newText;
  33356. triggerAsyncUpdate();
  33357. repaint();
  33358. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33359. componentMovedOrResized (*ownerComponent, true, true);
  33360. return true;
  33361. }
  33362. return false;
  33363. }
  33364. void Label::hideEditor (const bool discardCurrentEditorContents)
  33365. {
  33366. if (editor != 0)
  33367. {
  33368. const bool changed = (! discardCurrentEditorContents)
  33369. && updateFromTextEditorContents();
  33370. deleteAndZero (editor);
  33371. repaint();
  33372. if (changed)
  33373. textWasEdited();
  33374. exitModalState (0);
  33375. }
  33376. }
  33377. void Label::inputAttemptWhenModal()
  33378. {
  33379. if (editor != 0)
  33380. {
  33381. if (lossOfFocusDiscardsChanges)
  33382. textEditorEscapeKeyPressed (*editor);
  33383. else
  33384. textEditorReturnKeyPressed (*editor);
  33385. }
  33386. }
  33387. bool Label::isBeingEdited() const throw()
  33388. {
  33389. return editor != 0;
  33390. }
  33391. TextEditor* Label::createEditorComponent()
  33392. {
  33393. TextEditor* const ed = new TextEditor (getName());
  33394. ed->setFont (font);
  33395. // copy these colours from our own settings..
  33396. const int cols[] = { TextEditor::backgroundColourId,
  33397. TextEditor::textColourId,
  33398. TextEditor::highlightColourId,
  33399. TextEditor::highlightedTextColourId,
  33400. TextEditor::caretColourId,
  33401. TextEditor::outlineColourId,
  33402. TextEditor::focusedOutlineColourId,
  33403. TextEditor::shadowColourId };
  33404. for (int i = 0; i < numElementsInArray (cols); ++i)
  33405. ed->setColour (cols[i], findColour (cols[i]));
  33406. return ed;
  33407. }
  33408. void Label::paint (Graphics& g)
  33409. {
  33410. g.fillAll (findColour (backgroundColourId));
  33411. if (editor == 0)
  33412. {
  33413. const float alpha = isEnabled() ? 1.0f : 0.5f;
  33414. g.setColour (findColour (textColourId).withMultipliedAlpha (alpha));
  33415. g.setFont (font);
  33416. g.drawFittedText (text,
  33417. horizontalBorderSize,
  33418. verticalBorderSize,
  33419. getWidth() - 2 * horizontalBorderSize,
  33420. getHeight() - 2 * verticalBorderSize,
  33421. justification,
  33422. jmax (1, (int) (getHeight() / font.getHeight())));
  33423. g.setColour (findColour (outlineColourId).withMultipliedAlpha (alpha));
  33424. g.drawRect (0, 0, getWidth(), getHeight());
  33425. }
  33426. else if (isEnabled())
  33427. {
  33428. g.setColour (editor->findColour (TextEditor::backgroundColourId)
  33429. .overlaidWith (findColour (outlineColourId)));
  33430. g.drawRect (0, 0, getWidth(), getHeight());
  33431. }
  33432. }
  33433. void Label::mouseUp (const MouseEvent& e)
  33434. {
  33435. if (editSingleClick
  33436. && e.mouseWasClicked()
  33437. && contains (e.x, e.y)
  33438. && ! e.mods.isPopupMenu())
  33439. {
  33440. showEditor();
  33441. }
  33442. }
  33443. void Label::mouseDoubleClick (const MouseEvent& e)
  33444. {
  33445. if (editDoubleClick && ! e.mods.isPopupMenu())
  33446. showEditor();
  33447. }
  33448. void Label::resized()
  33449. {
  33450. if (editor != 0)
  33451. editor->setBoundsInset (BorderSize (0));
  33452. }
  33453. void Label::focusGained (FocusChangeType cause)
  33454. {
  33455. if (editSingleClick && cause == focusChangedByTabKey)
  33456. showEditor();
  33457. }
  33458. void Label::enablementChanged()
  33459. {
  33460. repaint();
  33461. }
  33462. void Label::colourChanged()
  33463. {
  33464. repaint();
  33465. }
  33466. // We'll use a custom focus traverser here to make sure focus goes from the
  33467. // text editor to another component rather than back to the label itself.
  33468. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  33469. {
  33470. public:
  33471. LabelKeyboardFocusTraverser() {}
  33472. Component* getNextComponent (Component* current)
  33473. {
  33474. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  33475. ? current->getParentComponent() : current);
  33476. }
  33477. Component* getPreviousComponent (Component* current)
  33478. {
  33479. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  33480. ? current->getParentComponent() : current);
  33481. }
  33482. };
  33483. KeyboardFocusTraverser* Label::createFocusTraverser()
  33484. {
  33485. return new LabelKeyboardFocusTraverser();
  33486. }
  33487. void Label::addListener (LabelListener* const listener) throw()
  33488. {
  33489. jassert (listener != 0);
  33490. if (listener != 0)
  33491. listeners.add (listener);
  33492. }
  33493. void Label::removeListener (LabelListener* const listener) throw()
  33494. {
  33495. listeners.removeValue (listener);
  33496. }
  33497. void Label::handleAsyncUpdate()
  33498. {
  33499. for (int i = listeners.size(); --i >= 0;)
  33500. {
  33501. ((LabelListener*) listeners.getUnchecked (i))->labelTextChanged (this);
  33502. i = jmin (i, listeners.size());
  33503. }
  33504. }
  33505. void Label::textEditorTextChanged (TextEditor& ed)
  33506. {
  33507. if (editor != 0)
  33508. {
  33509. jassert (&ed == editor);
  33510. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  33511. {
  33512. if (lossOfFocusDiscardsChanges)
  33513. textEditorEscapeKeyPressed (ed);
  33514. else
  33515. textEditorReturnKeyPressed (ed);
  33516. }
  33517. }
  33518. }
  33519. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  33520. {
  33521. if (editor != 0)
  33522. {
  33523. jassert (&ed == editor);
  33524. (void) ed;
  33525. const bool changed = updateFromTextEditorContents();
  33526. hideEditor (true);
  33527. if (changed)
  33528. textWasEdited();
  33529. }
  33530. }
  33531. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  33532. {
  33533. if (editor != 0)
  33534. {
  33535. jassert (&ed == editor);
  33536. (void) ed;
  33537. editor->setText (text, false);
  33538. hideEditor (true);
  33539. }
  33540. }
  33541. void Label::textEditorFocusLost (TextEditor& ed)
  33542. {
  33543. textEditorTextChanged (ed);
  33544. }
  33545. END_JUCE_NAMESPACE
  33546. /********* End of inlined file: juce_Label.cpp *********/
  33547. /********* Start of inlined file: juce_ListBox.cpp *********/
  33548. BEGIN_JUCE_NAMESPACE
  33549. class ListBoxRowComponent : public Component
  33550. {
  33551. public:
  33552. ListBoxRowComponent (ListBox& owner_)
  33553. : owner (owner_),
  33554. row (-1),
  33555. selected (false),
  33556. isDragging (false)
  33557. {
  33558. }
  33559. ~ListBoxRowComponent()
  33560. {
  33561. deleteAllChildren();
  33562. }
  33563. void paint (Graphics& g)
  33564. {
  33565. if (owner.getModel() != 0)
  33566. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  33567. }
  33568. void update (const int row_, const bool selected_)
  33569. {
  33570. if (row != row_ || selected != selected_)
  33571. {
  33572. repaint();
  33573. row = row_;
  33574. selected = selected_;
  33575. }
  33576. if (owner.getModel() != 0)
  33577. {
  33578. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  33579. if (customComp != 0)
  33580. {
  33581. addAndMakeVisible (customComp);
  33582. customComp->setBounds (0, 0, getWidth(), getHeight());
  33583. for (int i = getNumChildComponents(); --i >= 0;)
  33584. if (getChildComponent (i) != customComp)
  33585. delete getChildComponent (i);
  33586. }
  33587. else
  33588. {
  33589. deleteAllChildren();
  33590. }
  33591. }
  33592. }
  33593. void mouseDown (const MouseEvent& e)
  33594. {
  33595. isDragging = false;
  33596. selectRowOnMouseUp = false;
  33597. if (isEnabled())
  33598. {
  33599. if (! selected)
  33600. {
  33601. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  33602. if (owner.getModel() != 0)
  33603. owner.getModel()->listBoxItemClicked (row, e);
  33604. }
  33605. else
  33606. {
  33607. selectRowOnMouseUp = true;
  33608. }
  33609. }
  33610. }
  33611. void mouseUp (const MouseEvent& e)
  33612. {
  33613. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  33614. {
  33615. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  33616. if (owner.getModel() != 0)
  33617. owner.getModel()->listBoxItemClicked (row, e);
  33618. }
  33619. }
  33620. void mouseDoubleClick (const MouseEvent& e)
  33621. {
  33622. if (owner.getModel() != 0 && isEnabled())
  33623. owner.getModel()->listBoxItemDoubleClicked (row, e);
  33624. }
  33625. void mouseDrag (const MouseEvent& e)
  33626. {
  33627. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  33628. {
  33629. const SparseSet <int> selectedRows (owner.getSelectedRows());
  33630. if (selectedRows.size() > 0)
  33631. {
  33632. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  33633. if (dragDescription.isNotEmpty())
  33634. {
  33635. isDragging = true;
  33636. DragAndDropContainer* const dragContainer
  33637. = DragAndDropContainer::findParentDragContainerFor (this);
  33638. if (dragContainer != 0)
  33639. {
  33640. Image* dragImage = owner.createSnapshotOfSelectedRows();
  33641. dragImage->multiplyAllAlphas (0.6f);
  33642. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  33643. }
  33644. else
  33645. {
  33646. // to be able to do a drag-and-drop operation, the listbox needs to
  33647. // be inside a component which is also a DragAndDropContainer.
  33648. jassertfalse
  33649. }
  33650. }
  33651. }
  33652. }
  33653. }
  33654. void resized()
  33655. {
  33656. if (getNumChildComponents() > 0)
  33657. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  33658. }
  33659. juce_UseDebuggingNewOperator
  33660. bool neededFlag;
  33661. private:
  33662. ListBox& owner;
  33663. int row;
  33664. bool selected, isDragging, selectRowOnMouseUp;
  33665. ListBoxRowComponent (const ListBoxRowComponent&);
  33666. const ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  33667. };
  33668. class ListViewport : public Viewport
  33669. {
  33670. public:
  33671. int firstIndex, firstWholeIndex, lastWholeIndex;
  33672. bool hasUpdated;
  33673. ListViewport (ListBox& owner_)
  33674. : owner (owner_)
  33675. {
  33676. setWantsKeyboardFocus (false);
  33677. setViewedComponent (new Component());
  33678. getViewedComponent()->addMouseListener (this, false);
  33679. getViewedComponent()->setWantsKeyboardFocus (false);
  33680. }
  33681. ~ListViewport()
  33682. {
  33683. getViewedComponent()->removeMouseListener (this);
  33684. getViewedComponent()->deleteAllChildren();
  33685. }
  33686. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  33687. {
  33688. return (ListBoxRowComponent*) getViewedComponent()
  33689. ->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents()));
  33690. }
  33691. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  33692. {
  33693. const int index = getIndexOfChildComponent (rowComponent);
  33694. const int num = getViewedComponent()->getNumChildComponents();
  33695. for (int i = num; --i >= 0;)
  33696. if (((firstIndex + i) % jmax (1, num)) == index)
  33697. return firstIndex + i;
  33698. return -1;
  33699. }
  33700. Component* getComponentForRowIfOnscreen (const int row) const throw()
  33701. {
  33702. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  33703. ? getComponentForRow (row) : 0;
  33704. }
  33705. void visibleAreaChanged (int, int, int, int)
  33706. {
  33707. updateVisibleArea (true);
  33708. if (owner.getModel() != 0)
  33709. owner.getModel()->listWasScrolled();
  33710. }
  33711. void updateVisibleArea (const bool makeSureItUpdatesContent)
  33712. {
  33713. hasUpdated = false;
  33714. const int newX = getViewedComponent()->getX();
  33715. int newY = getViewedComponent()->getY();
  33716. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  33717. const int newH = owner.totalItems * owner.getRowHeight();
  33718. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  33719. newY = getMaximumVisibleHeight() - newH;
  33720. getViewedComponent()->setBounds (newX, newY, newW, newH);
  33721. if (makeSureItUpdatesContent && ! hasUpdated)
  33722. updateContents();
  33723. }
  33724. void updateContents()
  33725. {
  33726. hasUpdated = true;
  33727. const int rowHeight = owner.getRowHeight();
  33728. if (rowHeight > 0)
  33729. {
  33730. const int y = getViewPositionY();
  33731. const int w = getViewedComponent()->getWidth();
  33732. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  33733. while (numNeeded > getViewedComponent()->getNumChildComponents())
  33734. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  33735. jassert (numNeeded >= 0);
  33736. while (numNeeded < getViewedComponent()->getNumChildComponents())
  33737. {
  33738. Component* const rowToRemove
  33739. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  33740. delete rowToRemove;
  33741. }
  33742. firstIndex = y / rowHeight;
  33743. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  33744. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  33745. for (int i = 0; i < numNeeded; ++i)
  33746. {
  33747. const int row = i + firstIndex;
  33748. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  33749. if (rowComp != 0)
  33750. {
  33751. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  33752. rowComp->update (row, owner.isRowSelected (row));
  33753. }
  33754. }
  33755. }
  33756. if (owner.headerComponent != 0)
  33757. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  33758. owner.outlineThickness,
  33759. jmax (owner.getWidth() - owner.outlineThickness * 2,
  33760. getViewedComponent()->getWidth()),
  33761. owner.headerComponent->getHeight());
  33762. }
  33763. void paint (Graphics& g)
  33764. {
  33765. if (isOpaque())
  33766. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  33767. }
  33768. bool keyPressed (const KeyPress& key)
  33769. {
  33770. if (key.isKeyCode (KeyPress::upKey)
  33771. || key.isKeyCode (KeyPress::downKey)
  33772. || key.isKeyCode (KeyPress::pageUpKey)
  33773. || key.isKeyCode (KeyPress::pageDownKey)
  33774. || key.isKeyCode (KeyPress::homeKey)
  33775. || key.isKeyCode (KeyPress::endKey))
  33776. {
  33777. // we want to avoid these keypresses going to the viewport, and instead allow
  33778. // them to pass up to our listbox..
  33779. return false;
  33780. }
  33781. return Viewport::keyPressed (key);
  33782. }
  33783. juce_UseDebuggingNewOperator
  33784. private:
  33785. ListBox& owner;
  33786. ListViewport (const ListViewport&);
  33787. const ListViewport& operator= (const ListViewport&);
  33788. };
  33789. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  33790. : Component (name),
  33791. model (model_),
  33792. headerComponent (0),
  33793. totalItems (0),
  33794. rowHeight (22),
  33795. minimumRowWidth (0),
  33796. outlineThickness (0),
  33797. lastRowSelected (-1),
  33798. mouseMoveSelects (false),
  33799. multipleSelection (false),
  33800. hasDoneInitialUpdate (false)
  33801. {
  33802. addAndMakeVisible (viewport = new ListViewport (*this));
  33803. setWantsKeyboardFocus (true);
  33804. }
  33805. ListBox::~ListBox()
  33806. {
  33807. deleteAllChildren();
  33808. }
  33809. void ListBox::setModel (ListBoxModel* const newModel)
  33810. {
  33811. if (model != newModel)
  33812. {
  33813. model = newModel;
  33814. updateContent();
  33815. }
  33816. }
  33817. void ListBox::setMultipleSelectionEnabled (bool b)
  33818. {
  33819. multipleSelection = b;
  33820. }
  33821. void ListBox::setMouseMoveSelectsRows (bool b)
  33822. {
  33823. mouseMoveSelects = b;
  33824. if (b)
  33825. addMouseListener (this, true);
  33826. }
  33827. void ListBox::paint (Graphics& g)
  33828. {
  33829. if (! hasDoneInitialUpdate)
  33830. updateContent();
  33831. g.fillAll (findColour (backgroundColourId));
  33832. }
  33833. void ListBox::paintOverChildren (Graphics& g)
  33834. {
  33835. if (outlineThickness > 0)
  33836. {
  33837. g.setColour (findColour (outlineColourId));
  33838. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  33839. }
  33840. }
  33841. void ListBox::resized()
  33842. {
  33843. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  33844. outlineThickness,
  33845. outlineThickness,
  33846. outlineThickness));
  33847. viewport->setSingleStepSizes (20, getRowHeight());
  33848. viewport->updateVisibleArea (false);
  33849. }
  33850. void ListBox::visibilityChanged()
  33851. {
  33852. viewport->updateVisibleArea (true);
  33853. }
  33854. Viewport* ListBox::getViewport() const throw()
  33855. {
  33856. return viewport;
  33857. }
  33858. void ListBox::updateContent()
  33859. {
  33860. hasDoneInitialUpdate = true;
  33861. totalItems = (model != 0) ? model->getNumRows() : 0;
  33862. bool selectionChanged = false;
  33863. if (selected [selected.size() - 1] >= totalItems)
  33864. {
  33865. selected.removeRange (totalItems, INT_MAX - totalItems);
  33866. lastRowSelected = getSelectedRow (0);
  33867. selectionChanged = true;
  33868. }
  33869. viewport->updateVisibleArea (isVisible());
  33870. viewport->resized();
  33871. if (selectionChanged && model != 0)
  33872. model->selectedRowsChanged (lastRowSelected);
  33873. }
  33874. void ListBox::selectRow (const int row,
  33875. bool dontScroll,
  33876. bool deselectOthersFirst)
  33877. {
  33878. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  33879. }
  33880. void ListBox::selectRowInternal (const int row,
  33881. bool dontScroll,
  33882. bool deselectOthersFirst,
  33883. bool isMouseClick)
  33884. {
  33885. if (! multipleSelection)
  33886. deselectOthersFirst = true;
  33887. if ((! isRowSelected (row))
  33888. || (deselectOthersFirst && getNumSelectedRows() > 1))
  33889. {
  33890. if (((unsigned int) row) < (unsigned int) totalItems)
  33891. {
  33892. if (deselectOthersFirst)
  33893. selected.clear();
  33894. selected.addRange (row, 1);
  33895. if (getHeight() == 0 || getWidth() == 0)
  33896. dontScroll = true;
  33897. viewport->hasUpdated = false;
  33898. if (row < viewport->firstWholeIndex && ! dontScroll)
  33899. {
  33900. viewport->setViewPosition (viewport->getViewPositionX(),
  33901. row * getRowHeight());
  33902. }
  33903. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  33904. {
  33905. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  33906. if (row >= lastRowSelected + rowsOnScreen
  33907. && rowsOnScreen < totalItems - 1
  33908. && ! isMouseClick)
  33909. {
  33910. viewport->setViewPosition (viewport->getViewPositionX(),
  33911. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  33912. * getRowHeight());
  33913. }
  33914. else
  33915. {
  33916. viewport->setViewPosition (viewport->getViewPositionX(),
  33917. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  33918. }
  33919. }
  33920. if (! viewport->hasUpdated)
  33921. viewport->updateContents();
  33922. lastRowSelected = row;
  33923. model->selectedRowsChanged (row);
  33924. }
  33925. else
  33926. {
  33927. if (deselectOthersFirst)
  33928. deselectAllRows();
  33929. }
  33930. }
  33931. }
  33932. void ListBox::deselectRow (const int row)
  33933. {
  33934. if (selected.contains (row))
  33935. {
  33936. selected.removeRange (row, 1);
  33937. if (row == lastRowSelected)
  33938. lastRowSelected = getSelectedRow (0);
  33939. viewport->updateContents();
  33940. model->selectedRowsChanged (lastRowSelected);
  33941. }
  33942. }
  33943. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  33944. const bool sendNotificationEventToModel)
  33945. {
  33946. selected = setOfRowsToBeSelected;
  33947. selected.removeRange (totalItems, INT_MAX - totalItems);
  33948. if (! isRowSelected (lastRowSelected))
  33949. lastRowSelected = getSelectedRow (0);
  33950. viewport->updateContents();
  33951. if ((model != 0) && sendNotificationEventToModel)
  33952. model->selectedRowsChanged (lastRowSelected);
  33953. }
  33954. const SparseSet<int> ListBox::getSelectedRows() const
  33955. {
  33956. return selected;
  33957. }
  33958. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  33959. {
  33960. if (multipleSelection && (firstRow != lastRow))
  33961. {
  33962. const int numRows = totalItems - 1;
  33963. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  33964. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  33965. selected.addRange (jmin (firstRow, lastRow),
  33966. abs (firstRow - lastRow) + 1);
  33967. selected.removeRange (lastRow, 1);
  33968. }
  33969. selectRowInternal (lastRow, false, false, true);
  33970. }
  33971. void ListBox::flipRowSelection (const int row)
  33972. {
  33973. if (isRowSelected (row))
  33974. deselectRow (row);
  33975. else
  33976. selectRowInternal (row, false, false, true);
  33977. }
  33978. void ListBox::deselectAllRows()
  33979. {
  33980. if (! selected.isEmpty())
  33981. {
  33982. selected.clear();
  33983. lastRowSelected = -1;
  33984. viewport->updateContents();
  33985. if (model != 0)
  33986. model->selectedRowsChanged (lastRowSelected);
  33987. }
  33988. }
  33989. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  33990. const ModifierKeys& mods)
  33991. {
  33992. if (multipleSelection && mods.isCommandDown())
  33993. {
  33994. flipRowSelection (row);
  33995. }
  33996. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  33997. {
  33998. selectRangeOfRows (lastRowSelected, row);
  33999. }
  34000. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  34001. {
  34002. selectRowInternal (row, false, true, true);
  34003. }
  34004. }
  34005. int ListBox::getNumSelectedRows() const
  34006. {
  34007. return selected.size();
  34008. }
  34009. int ListBox::getSelectedRow (const int index) const
  34010. {
  34011. return (((unsigned int) index) < (unsigned int) selected.size())
  34012. ? selected [index] : -1;
  34013. }
  34014. bool ListBox::isRowSelected (const int row) const
  34015. {
  34016. return selected.contains (row);
  34017. }
  34018. int ListBox::getLastRowSelected() const
  34019. {
  34020. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  34021. }
  34022. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  34023. {
  34024. if (((unsigned int) x) < (unsigned int) getWidth())
  34025. {
  34026. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  34027. if (((unsigned int) row) < (unsigned int) totalItems)
  34028. return row;
  34029. }
  34030. return -1;
  34031. }
  34032. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  34033. {
  34034. if (((unsigned int) x) < (unsigned int) getWidth())
  34035. {
  34036. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  34037. return jlimit (0, totalItems, row);
  34038. }
  34039. return -1;
  34040. }
  34041. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  34042. {
  34043. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  34044. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  34045. }
  34046. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  34047. {
  34048. return viewport->getRowNumberOfComponent (rowComponent);
  34049. }
  34050. const Rectangle ListBox::getRowPosition (const int rowNumber,
  34051. const bool relativeToComponentTopLeft) const throw()
  34052. {
  34053. const int rowHeight = getRowHeight();
  34054. int y = viewport->getY() + rowHeight * rowNumber;
  34055. if (relativeToComponentTopLeft)
  34056. y -= viewport->getViewPositionY();
  34057. return Rectangle (viewport->getX(), y,
  34058. viewport->getViewedComponent()->getWidth(), rowHeight);
  34059. }
  34060. void ListBox::setVerticalPosition (const double proportion)
  34061. {
  34062. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  34063. viewport->setViewPosition (viewport->getViewPositionX(),
  34064. jmax (0, roundDoubleToInt (proportion * offscreen)));
  34065. }
  34066. double ListBox::getVerticalPosition() const
  34067. {
  34068. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  34069. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  34070. : 0;
  34071. }
  34072. int ListBox::getVisibleRowWidth() const throw()
  34073. {
  34074. return viewport->getViewWidth();
  34075. }
  34076. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  34077. {
  34078. if (row < viewport->firstWholeIndex)
  34079. {
  34080. viewport->setViewPosition (viewport->getViewPositionX(),
  34081. row * getRowHeight());
  34082. }
  34083. else if (row >= viewport->lastWholeIndex)
  34084. {
  34085. viewport->setViewPosition (viewport->getViewPositionX(),
  34086. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  34087. }
  34088. }
  34089. bool ListBox::keyPressed (const KeyPress& key)
  34090. {
  34091. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  34092. const bool multiple = multipleSelection
  34093. && (lastRowSelected >= 0)
  34094. && (key.getModifiers().isShiftDown()
  34095. || key.getModifiers().isCtrlDown()
  34096. || key.getModifiers().isCommandDown());
  34097. if (key.isKeyCode (KeyPress::upKey))
  34098. {
  34099. if (multiple)
  34100. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  34101. else
  34102. selectRow (jmax (0, lastRowSelected - 1));
  34103. }
  34104. else if (key.isKeyCode (KeyPress::returnKey)
  34105. && isRowSelected (lastRowSelected))
  34106. {
  34107. if (model != 0)
  34108. model->returnKeyPressed (lastRowSelected);
  34109. }
  34110. else if (key.isKeyCode (KeyPress::pageUpKey))
  34111. {
  34112. if (multiple)
  34113. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  34114. else
  34115. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  34116. }
  34117. else if (key.isKeyCode (KeyPress::pageDownKey))
  34118. {
  34119. if (multiple)
  34120. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  34121. else
  34122. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  34123. }
  34124. else if (key.isKeyCode (KeyPress::homeKey))
  34125. {
  34126. if (multiple && key.getModifiers().isShiftDown())
  34127. selectRangeOfRows (lastRowSelected, 0);
  34128. else
  34129. selectRow (0);
  34130. }
  34131. else if (key.isKeyCode (KeyPress::endKey))
  34132. {
  34133. if (multiple && key.getModifiers().isShiftDown())
  34134. selectRangeOfRows (lastRowSelected, totalItems - 1);
  34135. else
  34136. selectRow (totalItems - 1);
  34137. }
  34138. else if (key.isKeyCode (KeyPress::downKey))
  34139. {
  34140. if (multiple)
  34141. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  34142. else
  34143. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  34144. }
  34145. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  34146. && isRowSelected (lastRowSelected))
  34147. {
  34148. if (model != 0)
  34149. model->deleteKeyPressed (lastRowSelected);
  34150. }
  34151. else if (multiple && key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  34152. {
  34153. selectRangeOfRows (0, INT_MAX);
  34154. }
  34155. else
  34156. {
  34157. return false;
  34158. }
  34159. return true;
  34160. }
  34161. bool ListBox::keyStateChanged()
  34162. {
  34163. return KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  34164. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  34165. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  34166. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  34167. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  34168. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  34169. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey);
  34170. }
  34171. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  34172. {
  34173. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  34174. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  34175. }
  34176. void ListBox::mouseMove (const MouseEvent& e)
  34177. {
  34178. if (mouseMoveSelects)
  34179. {
  34180. const MouseEvent e2 (e.getEventRelativeTo (this));
  34181. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  34182. lastMouseX = e2.x;
  34183. lastMouseY = e2.y;
  34184. }
  34185. }
  34186. void ListBox::mouseExit (const MouseEvent& e)
  34187. {
  34188. mouseMove (e);
  34189. }
  34190. void ListBox::mouseUp (const MouseEvent& e)
  34191. {
  34192. if (e.mouseWasClicked() && model != 0)
  34193. model->backgroundClicked();
  34194. }
  34195. void ListBox::setRowHeight (const int newHeight)
  34196. {
  34197. rowHeight = jmax (1, newHeight);
  34198. viewport->setSingleStepSizes (20, rowHeight);
  34199. updateContent();
  34200. }
  34201. int ListBox::getNumRowsOnScreen() const throw()
  34202. {
  34203. return viewport->getMaximumVisibleHeight() / rowHeight;
  34204. }
  34205. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  34206. {
  34207. minimumRowWidth = newMinimumWidth;
  34208. updateContent();
  34209. }
  34210. int ListBox::getVisibleContentWidth() const throw()
  34211. {
  34212. return viewport->getMaximumVisibleWidth();
  34213. }
  34214. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  34215. {
  34216. return viewport->getVerticalScrollBar();
  34217. }
  34218. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  34219. {
  34220. return viewport->getHorizontalScrollBar();
  34221. }
  34222. void ListBox::colourChanged()
  34223. {
  34224. setOpaque (findColour (backgroundColourId).isOpaque());
  34225. viewport->setOpaque (isOpaque());
  34226. repaint();
  34227. }
  34228. void ListBox::setOutlineThickness (const int outlineThickness_)
  34229. {
  34230. outlineThickness = outlineThickness_;
  34231. resized();
  34232. }
  34233. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  34234. {
  34235. if (headerComponent != newHeaderComponent)
  34236. {
  34237. if (headerComponent != 0)
  34238. delete headerComponent;
  34239. headerComponent = newHeaderComponent;
  34240. addAndMakeVisible (newHeaderComponent);
  34241. ListBox::resized();
  34242. }
  34243. }
  34244. void ListBox::repaintRow (const int rowNumber) throw()
  34245. {
  34246. const Rectangle r (getRowPosition (rowNumber, true));
  34247. repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  34248. }
  34249. Image* ListBox::createSnapshotOfSelectedRows()
  34250. {
  34251. Image* snapshot = new Image (Image::ARGB, getWidth(), getHeight(), true);
  34252. Graphics g (*snapshot);
  34253. const int firstRow = getRowContainingPosition (0, 0);
  34254. for (int i = getNumRowsOnScreen() + 2; --i >= 0;)
  34255. {
  34256. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  34257. if (rowComp != 0 && isRowSelected (firstRow + i))
  34258. {
  34259. g.saveState();
  34260. int x = 0, y = 0;
  34261. rowComp->relativePositionToOtherComponent (this, x, y);
  34262. g.setOrigin (x, y);
  34263. g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight());
  34264. rowComp->paintEntireComponent (g);
  34265. g.restoreState();
  34266. }
  34267. }
  34268. return snapshot;
  34269. }
  34270. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  34271. {
  34272. (void) existingComponentToUpdate;
  34273. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  34274. return 0;
  34275. }
  34276. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  34277. {
  34278. }
  34279. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  34280. {
  34281. }
  34282. void ListBoxModel::backgroundClicked()
  34283. {
  34284. }
  34285. void ListBoxModel::selectedRowsChanged (int)
  34286. {
  34287. }
  34288. void ListBoxModel::deleteKeyPressed (int)
  34289. {
  34290. }
  34291. void ListBoxModel::returnKeyPressed (int)
  34292. {
  34293. }
  34294. void ListBoxModel::listWasScrolled()
  34295. {
  34296. }
  34297. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  34298. {
  34299. return String::empty;
  34300. }
  34301. END_JUCE_NAMESPACE
  34302. /********* End of inlined file: juce_ListBox.cpp *********/
  34303. /********* Start of inlined file: juce_ProgressBar.cpp *********/
  34304. BEGIN_JUCE_NAMESPACE
  34305. ProgressBar::ProgressBar (double& progress_)
  34306. : progress (progress_),
  34307. displayPercentage (true)
  34308. {
  34309. currentValue = jlimit (0.0, 1.0, progress);
  34310. }
  34311. ProgressBar::~ProgressBar()
  34312. {
  34313. }
  34314. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  34315. {
  34316. displayPercentage = shouldDisplayPercentage;
  34317. repaint();
  34318. }
  34319. void ProgressBar::setTextToDisplay (const String& text)
  34320. {
  34321. displayPercentage = false;
  34322. displayedMessage = text;
  34323. }
  34324. void ProgressBar::lookAndFeelChanged()
  34325. {
  34326. setOpaque (findColour (backgroundColourId).isOpaque());
  34327. }
  34328. void ProgressBar::colourChanged()
  34329. {
  34330. lookAndFeelChanged();
  34331. }
  34332. void ProgressBar::paint (Graphics& g)
  34333. {
  34334. String text;
  34335. if (displayPercentage)
  34336. {
  34337. if (currentValue >= 0 && currentValue <= 1.0)
  34338. text << roundDoubleToInt (currentValue * 100.0) << T("%");
  34339. }
  34340. else
  34341. {
  34342. text = displayedMessage;
  34343. }
  34344. getLookAndFeel().drawProgressBar (g, *this,
  34345. getWidth(), getHeight(),
  34346. currentValue, text);
  34347. }
  34348. void ProgressBar::visibilityChanged()
  34349. {
  34350. if (isVisible())
  34351. startTimer (30);
  34352. else
  34353. stopTimer();
  34354. }
  34355. void ProgressBar::timerCallback()
  34356. {
  34357. double newProgress = progress;
  34358. if (currentValue != newProgress
  34359. || newProgress < 0 || newProgress >= 1.0
  34360. || currentMessage != displayedMessage)
  34361. {
  34362. if (currentValue < newProgress
  34363. && newProgress >= 0 && newProgress < 1.0
  34364. && currentValue >= 0 && newProgress < 1.0)
  34365. {
  34366. newProgress = jmin (currentValue + 0.02, newProgress);
  34367. }
  34368. currentValue = newProgress;
  34369. currentMessage = displayedMessage;
  34370. repaint();
  34371. }
  34372. }
  34373. END_JUCE_NAMESPACE
  34374. /********* End of inlined file: juce_ProgressBar.cpp *********/
  34375. /********* Start of inlined file: juce_Slider.cpp *********/
  34376. BEGIN_JUCE_NAMESPACE
  34377. class SliderPopupDisplayComponent : public BubbleComponent
  34378. {
  34379. public:
  34380. SliderPopupDisplayComponent (Slider* const owner_)
  34381. : owner (owner_),
  34382. font (15.0f, Font::bold)
  34383. {
  34384. setAlwaysOnTop (true);
  34385. }
  34386. ~SliderPopupDisplayComponent()
  34387. {
  34388. }
  34389. void paintContent (Graphics& g, int w, int h)
  34390. {
  34391. g.setFont (font);
  34392. g.setColour (Colours::black);
  34393. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  34394. }
  34395. void getContentSize (int& w, int& h)
  34396. {
  34397. w = font.getStringWidth (text) + 18;
  34398. h = (int) (font.getHeight() * 1.6f);
  34399. }
  34400. void updatePosition (const String& newText)
  34401. {
  34402. if (text != newText)
  34403. {
  34404. text = newText;
  34405. repaint();
  34406. }
  34407. BubbleComponent::setPosition (owner);
  34408. }
  34409. juce_UseDebuggingNewOperator
  34410. private:
  34411. Slider* owner;
  34412. Font font;
  34413. String text;
  34414. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  34415. const SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  34416. };
  34417. Slider::Slider (const String& name)
  34418. : Component (name),
  34419. listeners (2),
  34420. currentValue (0.0),
  34421. valueMin (0.0),
  34422. valueMax (0.0),
  34423. minimum (0),
  34424. maximum (10),
  34425. interval (0),
  34426. skewFactor (1.0),
  34427. velocityModeSensitivity (1.0),
  34428. velocityModeOffset (0.0),
  34429. velocityModeThreshold (1),
  34430. rotaryStart (float_Pi * 1.2f),
  34431. rotaryEnd (float_Pi * 2.8f),
  34432. numDecimalPlaces (7),
  34433. sliderRegionStart (0),
  34434. sliderRegionSize (1),
  34435. sliderBeingDragged (-1),
  34436. pixelsForFullDragExtent (250),
  34437. style (LinearHorizontal),
  34438. textBoxPos (TextBoxLeft),
  34439. textBoxWidth (80),
  34440. textBoxHeight (20),
  34441. incDecButtonMode (incDecButtonsNotDraggable),
  34442. editableText (true),
  34443. doubleClickToValue (false),
  34444. isVelocityBased (false),
  34445. userKeyOverridesVelocity (true),
  34446. rotaryStop (true),
  34447. incDecButtonsSideBySide (false),
  34448. sendChangeOnlyOnRelease (false),
  34449. popupDisplayEnabled (false),
  34450. menuEnabled (false),
  34451. menuShown (false),
  34452. scrollWheelEnabled (true),
  34453. snapsToMousePos (true),
  34454. valueBox (0),
  34455. incButton (0),
  34456. decButton (0),
  34457. popupDisplay (0),
  34458. parentForPopupDisplay (0)
  34459. {
  34460. setWantsKeyboardFocus (false);
  34461. setRepaintsOnMouseActivity (true);
  34462. lookAndFeelChanged();
  34463. updateText();
  34464. }
  34465. Slider::~Slider()
  34466. {
  34467. deleteAndZero (popupDisplay);
  34468. deleteAllChildren();
  34469. }
  34470. void Slider::handleAsyncUpdate()
  34471. {
  34472. cancelPendingUpdate();
  34473. for (int i = listeners.size(); --i >= 0;)
  34474. {
  34475. ((SliderListener*) listeners.getUnchecked (i))->sliderValueChanged (this);
  34476. i = jmin (i, listeners.size());
  34477. }
  34478. }
  34479. void Slider::sendDragStart()
  34480. {
  34481. startedDragging();
  34482. for (int i = listeners.size(); --i >= 0;)
  34483. {
  34484. ((SliderListener*) listeners.getUnchecked (i))->sliderDragStarted (this);
  34485. i = jmin (i, listeners.size());
  34486. }
  34487. }
  34488. void Slider::sendDragEnd()
  34489. {
  34490. stoppedDragging();
  34491. sliderBeingDragged = -1;
  34492. for (int i = listeners.size(); --i >= 0;)
  34493. {
  34494. ((SliderListener*) listeners.getUnchecked (i))->sliderDragEnded (this);
  34495. i = jmin (i, listeners.size());
  34496. }
  34497. }
  34498. void Slider::addListener (SliderListener* const listener) throw()
  34499. {
  34500. jassert (listener != 0);
  34501. if (listener != 0)
  34502. listeners.add (listener);
  34503. }
  34504. void Slider::removeListener (SliderListener* const listener) throw()
  34505. {
  34506. listeners.removeValue (listener);
  34507. }
  34508. void Slider::setSliderStyle (const SliderStyle newStyle)
  34509. {
  34510. if (style != newStyle)
  34511. {
  34512. style = newStyle;
  34513. repaint();
  34514. lookAndFeelChanged();
  34515. }
  34516. }
  34517. void Slider::setRotaryParameters (const float startAngleRadians,
  34518. const float endAngleRadians,
  34519. const bool stopAtEnd)
  34520. {
  34521. // make sure the values are sensible..
  34522. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  34523. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  34524. jassert (rotaryStart < rotaryEnd);
  34525. rotaryStart = startAngleRadians;
  34526. rotaryEnd = endAngleRadians;
  34527. rotaryStop = stopAtEnd;
  34528. }
  34529. void Slider::setVelocityBasedMode (const bool velBased) throw()
  34530. {
  34531. isVelocityBased = velBased;
  34532. }
  34533. void Slider::setVelocityModeParameters (const double sensitivity,
  34534. const int threshold,
  34535. const double offset,
  34536. const bool userCanPressKeyToSwapMode) throw()
  34537. {
  34538. jassert (threshold >= 0);
  34539. jassert (sensitivity > 0);
  34540. jassert (offset >= 0);
  34541. velocityModeSensitivity = sensitivity;
  34542. velocityModeOffset = offset;
  34543. velocityModeThreshold = threshold;
  34544. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  34545. }
  34546. void Slider::setSkewFactor (const double factor) throw()
  34547. {
  34548. skewFactor = factor;
  34549. }
  34550. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw()
  34551. {
  34552. if (maximum > minimum)
  34553. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  34554. / (maximum - minimum));
  34555. }
  34556. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  34557. {
  34558. jassert (distanceForFullScaleDrag > 0);
  34559. pixelsForFullDragExtent = distanceForFullScaleDrag;
  34560. }
  34561. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  34562. {
  34563. if (incDecButtonMode != mode)
  34564. {
  34565. incDecButtonMode = mode;
  34566. lookAndFeelChanged();
  34567. }
  34568. }
  34569. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  34570. const bool isReadOnly,
  34571. const int textEntryBoxWidth,
  34572. const int textEntryBoxHeight)
  34573. {
  34574. textBoxPos = newPosition;
  34575. editableText = ! isReadOnly;
  34576. textBoxWidth = textEntryBoxWidth;
  34577. textBoxHeight = textEntryBoxHeight;
  34578. repaint();
  34579. lookAndFeelChanged();
  34580. }
  34581. void Slider::setTextBoxIsEditable (const bool shouldBeEditable) throw()
  34582. {
  34583. editableText = shouldBeEditable;
  34584. if (valueBox != 0)
  34585. valueBox->setEditable (shouldBeEditable && isEnabled());
  34586. }
  34587. void Slider::showTextBox()
  34588. {
  34589. jassert (editableText); // this should probably be avoided in read-only sliders.
  34590. if (valueBox != 0)
  34591. valueBox->showEditor();
  34592. }
  34593. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  34594. {
  34595. if (valueBox != 0)
  34596. {
  34597. valueBox->hideEditor (discardCurrentEditorContents);
  34598. if (discardCurrentEditorContents)
  34599. updateText();
  34600. }
  34601. }
  34602. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw()
  34603. {
  34604. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  34605. }
  34606. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw()
  34607. {
  34608. snapsToMousePos = shouldSnapToMouse;
  34609. }
  34610. void Slider::setPopupDisplayEnabled (const bool enabled,
  34611. Component* const parentComponentToUse) throw()
  34612. {
  34613. popupDisplayEnabled = enabled;
  34614. parentForPopupDisplay = parentComponentToUse;
  34615. }
  34616. void Slider::colourChanged()
  34617. {
  34618. lookAndFeelChanged();
  34619. }
  34620. void Slider::lookAndFeelChanged()
  34621. {
  34622. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  34623. : getTextFromValue (currentValue));
  34624. deleteAllChildren();
  34625. valueBox = 0;
  34626. LookAndFeel& lf = getLookAndFeel();
  34627. if (textBoxPos != NoTextBox)
  34628. {
  34629. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  34630. valueBox->setWantsKeyboardFocus (false);
  34631. valueBox->setText (previousTextBoxContent, false);
  34632. valueBox->setEditable (editableText && isEnabled());
  34633. valueBox->addListener (this);
  34634. if (style == LinearBar)
  34635. valueBox->addMouseListener (this, false);
  34636. }
  34637. if (style == IncDecButtons)
  34638. {
  34639. addAndMakeVisible (incButton = lf.createSliderButton (true));
  34640. incButton->addButtonListener (this);
  34641. addAndMakeVisible (decButton = lf.createSliderButton (false));
  34642. decButton->addButtonListener (this);
  34643. if (incDecButtonMode != incDecButtonsNotDraggable)
  34644. {
  34645. incButton->addMouseListener (this, false);
  34646. decButton->addMouseListener (this, false);
  34647. }
  34648. else
  34649. {
  34650. incButton->setRepeatSpeed (300, 100, 20);
  34651. incButton->addMouseListener (decButton, false);
  34652. decButton->setRepeatSpeed (300, 100, 20);
  34653. decButton->addMouseListener (incButton, false);
  34654. }
  34655. }
  34656. setComponentEffect (lf.getSliderEffect());
  34657. resized();
  34658. repaint();
  34659. }
  34660. void Slider::setRange (const double newMin,
  34661. const double newMax,
  34662. const double newInt)
  34663. {
  34664. if (minimum != newMin
  34665. || maximum != newMax
  34666. || interval != newInt)
  34667. {
  34668. minimum = newMin;
  34669. maximum = newMax;
  34670. interval = newInt;
  34671. // figure out the number of DPs needed to display all values at this
  34672. // interval setting.
  34673. numDecimalPlaces = 7;
  34674. if (newInt != 0)
  34675. {
  34676. int v = abs ((int) (newInt * 10000000));
  34677. while ((v % 10) == 0)
  34678. {
  34679. --numDecimalPlaces;
  34680. v /= 10;
  34681. }
  34682. }
  34683. // keep the current values inside the new range..
  34684. if (style != TwoValueHorizontal && style != TwoValueVertical)
  34685. {
  34686. setValue (currentValue, false, false);
  34687. }
  34688. else
  34689. {
  34690. setMinValue (getMinValue(), false, false);
  34691. setMaxValue (getMaxValue(), false, false);
  34692. }
  34693. updateText();
  34694. }
  34695. }
  34696. void Slider::triggerChangeMessage (const bool synchronous)
  34697. {
  34698. if (synchronous)
  34699. handleAsyncUpdate();
  34700. else
  34701. triggerAsyncUpdate();
  34702. valueChanged();
  34703. }
  34704. double Slider::getValue() const throw()
  34705. {
  34706. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  34707. // methods to get the two values.
  34708. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  34709. return currentValue;
  34710. }
  34711. void Slider::setValue (double newValue,
  34712. const bool sendUpdateMessage,
  34713. const bool sendMessageSynchronously)
  34714. {
  34715. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  34716. // methods to set the two values.
  34717. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  34718. newValue = constrainedValue (newValue);
  34719. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  34720. {
  34721. jassert (valueMin <= valueMax);
  34722. newValue = jlimit (valueMin, valueMax, newValue);
  34723. }
  34724. if (currentValue != newValue)
  34725. {
  34726. if (valueBox != 0)
  34727. valueBox->hideEditor (true);
  34728. currentValue = newValue;
  34729. updateText();
  34730. repaint();
  34731. if (popupDisplay != 0)
  34732. {
  34733. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (currentValue));
  34734. popupDisplay->repaint();
  34735. }
  34736. if (sendUpdateMessage)
  34737. triggerChangeMessage (sendMessageSynchronously);
  34738. }
  34739. }
  34740. double Slider::getMinValue() const throw()
  34741. {
  34742. // The minimum value only applies to sliders that are in two- or three-value mode.
  34743. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34744. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34745. return valueMin;
  34746. }
  34747. double Slider::getMaxValue() const throw()
  34748. {
  34749. // The maximum value only applies to sliders that are in two- or three-value mode.
  34750. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34751. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34752. return valueMax;
  34753. }
  34754. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously)
  34755. {
  34756. // The minimum value only applies to sliders that are in two- or three-value mode.
  34757. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34758. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34759. newValue = constrainedValue (newValue);
  34760. if (style == TwoValueHorizontal || style == TwoValueVertical)
  34761. newValue = jmin (valueMax, newValue);
  34762. else
  34763. newValue = jmin (currentValue, newValue);
  34764. if (valueMin != newValue)
  34765. {
  34766. valueMin = newValue;
  34767. repaint();
  34768. if (popupDisplay != 0)
  34769. {
  34770. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMin));
  34771. popupDisplay->repaint();
  34772. }
  34773. if (sendUpdateMessage)
  34774. triggerChangeMessage (sendMessageSynchronously);
  34775. }
  34776. }
  34777. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously)
  34778. {
  34779. // The maximum value only applies to sliders that are in two- or three-value mode.
  34780. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34781. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34782. newValue = constrainedValue (newValue);
  34783. if (style == TwoValueHorizontal || style == TwoValueVertical)
  34784. newValue = jmax (valueMin, newValue);
  34785. else
  34786. newValue = jmax (currentValue, newValue);
  34787. if (valueMax != newValue)
  34788. {
  34789. valueMax = newValue;
  34790. repaint();
  34791. if (popupDisplay != 0)
  34792. {
  34793. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMax));
  34794. popupDisplay->repaint();
  34795. }
  34796. if (sendUpdateMessage)
  34797. triggerChangeMessage (sendMessageSynchronously);
  34798. }
  34799. }
  34800. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  34801. const double valueToSetOnDoubleClick) throw()
  34802. {
  34803. doubleClickToValue = isDoubleClickEnabled;
  34804. doubleClickReturnValue = valueToSetOnDoubleClick;
  34805. }
  34806. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const throw()
  34807. {
  34808. isEnabled_ = doubleClickToValue;
  34809. return doubleClickReturnValue;
  34810. }
  34811. void Slider::updateText()
  34812. {
  34813. if (valueBox != 0)
  34814. valueBox->setText (getTextFromValue (currentValue), false);
  34815. }
  34816. void Slider::setTextValueSuffix (const String& suffix)
  34817. {
  34818. if (textSuffix != suffix)
  34819. {
  34820. textSuffix = suffix;
  34821. updateText();
  34822. }
  34823. }
  34824. const String Slider::getTextFromValue (double v)
  34825. {
  34826. if (numDecimalPlaces > 0)
  34827. return String (v, numDecimalPlaces) + textSuffix;
  34828. else
  34829. return String (roundDoubleToInt (v)) + textSuffix;
  34830. }
  34831. double Slider::getValueFromText (const String& text)
  34832. {
  34833. String t (text.trimStart());
  34834. if (t.endsWith (textSuffix))
  34835. t = t.substring (0, t.length() - textSuffix.length());
  34836. while (t.startsWithChar (T('+')))
  34837. t = t.substring (1).trimStart();
  34838. return t.initialSectionContainingOnly (T("0123456789.,-"))
  34839. .getDoubleValue();
  34840. }
  34841. double Slider::proportionOfLengthToValue (double proportion)
  34842. {
  34843. if (skewFactor != 1.0 && proportion > 0.0)
  34844. proportion = exp (log (proportion) / skewFactor);
  34845. return minimum + (maximum - minimum) * proportion;
  34846. }
  34847. double Slider::valueToProportionOfLength (double value)
  34848. {
  34849. const double n = (value - minimum) / (maximum - minimum);
  34850. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  34851. }
  34852. double Slider::snapValue (double attemptedValue, const bool)
  34853. {
  34854. return attemptedValue;
  34855. }
  34856. void Slider::startedDragging()
  34857. {
  34858. }
  34859. void Slider::stoppedDragging()
  34860. {
  34861. }
  34862. void Slider::valueChanged()
  34863. {
  34864. }
  34865. void Slider::enablementChanged()
  34866. {
  34867. repaint();
  34868. }
  34869. void Slider::setPopupMenuEnabled (const bool menuEnabled_) throw()
  34870. {
  34871. menuEnabled = menuEnabled_;
  34872. }
  34873. void Slider::setScrollWheelEnabled (const bool enabled) throw()
  34874. {
  34875. scrollWheelEnabled = enabled;
  34876. }
  34877. void Slider::labelTextChanged (Label* label)
  34878. {
  34879. const double newValue = snapValue (getValueFromText (label->getText()), false);
  34880. if (getValue() != newValue)
  34881. {
  34882. sendDragStart();
  34883. setValue (newValue, true, true);
  34884. sendDragEnd();
  34885. }
  34886. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  34887. }
  34888. void Slider::buttonClicked (Button* button)
  34889. {
  34890. if (style == IncDecButtons)
  34891. {
  34892. sendDragStart();
  34893. if (button == incButton)
  34894. setValue (snapValue (getValue() + interval, false), true, true);
  34895. else if (button == decButton)
  34896. setValue (snapValue (getValue() - interval, false), true, true);
  34897. sendDragEnd();
  34898. }
  34899. }
  34900. double Slider::constrainedValue (double value) const throw()
  34901. {
  34902. if (interval > 0)
  34903. value = minimum + interval * floor ((value - minimum) / interval + 0.5);
  34904. if (value <= minimum || maximum <= minimum)
  34905. value = minimum;
  34906. else if (value >= maximum)
  34907. value = maximum;
  34908. return value;
  34909. }
  34910. float Slider::getLinearSliderPos (const double value)
  34911. {
  34912. double sliderPosProportional;
  34913. if (maximum > minimum)
  34914. {
  34915. if (value < minimum)
  34916. {
  34917. sliderPosProportional = 0.0;
  34918. }
  34919. else if (value > maximum)
  34920. {
  34921. sliderPosProportional = 1.0;
  34922. }
  34923. else
  34924. {
  34925. sliderPosProportional = valueToProportionOfLength (value);
  34926. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  34927. }
  34928. }
  34929. else
  34930. {
  34931. sliderPosProportional = 0.5;
  34932. }
  34933. if (style == LinearVertical || style == IncDecButtons)
  34934. sliderPosProportional = 1.0 - sliderPosProportional;
  34935. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  34936. }
  34937. bool Slider::isHorizontal() const throw()
  34938. {
  34939. return style == LinearHorizontal
  34940. || style == LinearBar
  34941. || style == TwoValueHorizontal
  34942. || style == ThreeValueHorizontal;
  34943. }
  34944. bool Slider::isVertical() const throw()
  34945. {
  34946. return style == LinearVertical
  34947. || style == TwoValueVertical
  34948. || style == ThreeValueVertical;
  34949. }
  34950. bool Slider::incDecDragDirectionIsHorizontal() const throw()
  34951. {
  34952. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  34953. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  34954. }
  34955. float Slider::getPositionOfValue (const double value)
  34956. {
  34957. if (isHorizontal() || isVertical())
  34958. {
  34959. return getLinearSliderPos (value);
  34960. }
  34961. else
  34962. {
  34963. jassertfalse // not a valid call on a slider that doesn't work linearly!
  34964. return 0.0f;
  34965. }
  34966. }
  34967. void Slider::paint (Graphics& g)
  34968. {
  34969. if (style != IncDecButtons)
  34970. {
  34971. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  34972. {
  34973. const float sliderPos = (float) valueToProportionOfLength (currentValue);
  34974. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  34975. getLookAndFeel().drawRotarySlider (g,
  34976. sliderRect.getX(),
  34977. sliderRect.getY(),
  34978. sliderRect.getWidth(),
  34979. sliderRect.getHeight(),
  34980. sliderPos,
  34981. rotaryStart, rotaryEnd,
  34982. *this);
  34983. }
  34984. else
  34985. {
  34986. getLookAndFeel().drawLinearSlider (g,
  34987. sliderRect.getX(),
  34988. sliderRect.getY(),
  34989. sliderRect.getWidth(),
  34990. sliderRect.getHeight(),
  34991. getLinearSliderPos (currentValue),
  34992. getLinearSliderPos (valueMin),
  34993. getLinearSliderPos (valueMax),
  34994. style,
  34995. *this);
  34996. }
  34997. if (style == LinearBar && valueBox == 0)
  34998. {
  34999. g.setColour (findColour (Slider::textBoxOutlineColourId));
  35000. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  35001. }
  35002. }
  35003. }
  35004. void Slider::resized()
  35005. {
  35006. int minXSpace = 0;
  35007. int minYSpace = 0;
  35008. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  35009. minXSpace = 30;
  35010. else
  35011. minYSpace = 15;
  35012. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  35013. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  35014. if (style == LinearBar)
  35015. {
  35016. if (valueBox != 0)
  35017. valueBox->setBounds (0, 0, getWidth(), getHeight());
  35018. }
  35019. else
  35020. {
  35021. if (textBoxPos == NoTextBox)
  35022. {
  35023. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  35024. }
  35025. else if (textBoxPos == TextBoxLeft)
  35026. {
  35027. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  35028. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  35029. }
  35030. else if (textBoxPos == TextBoxRight)
  35031. {
  35032. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  35033. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  35034. }
  35035. else if (textBoxPos == TextBoxAbove)
  35036. {
  35037. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  35038. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  35039. }
  35040. else if (textBoxPos == TextBoxBelow)
  35041. {
  35042. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  35043. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  35044. }
  35045. }
  35046. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  35047. if (style == LinearBar)
  35048. {
  35049. const int barIndent = 1;
  35050. sliderRegionStart = barIndent;
  35051. sliderRegionSize = getWidth() - barIndent * 2;
  35052. sliderRect.setBounds (sliderRegionStart, barIndent,
  35053. sliderRegionSize, getHeight() - barIndent * 2);
  35054. }
  35055. else if (isHorizontal())
  35056. {
  35057. sliderRegionStart = sliderRect.getX() + indent;
  35058. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  35059. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  35060. sliderRegionSize, sliderRect.getHeight());
  35061. }
  35062. else if (isVertical())
  35063. {
  35064. sliderRegionStart = sliderRect.getY() + indent;
  35065. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  35066. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  35067. sliderRect.getWidth(), sliderRegionSize);
  35068. }
  35069. else
  35070. {
  35071. sliderRegionStart = 0;
  35072. sliderRegionSize = 100;
  35073. }
  35074. if (style == IncDecButtons)
  35075. {
  35076. Rectangle buttonRect (sliderRect);
  35077. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  35078. buttonRect.expand (-2, 0);
  35079. else
  35080. buttonRect.expand (0, -2);
  35081. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  35082. if (incDecButtonsSideBySide)
  35083. {
  35084. decButton->setBounds (buttonRect.getX(),
  35085. buttonRect.getY(),
  35086. buttonRect.getWidth() / 2,
  35087. buttonRect.getHeight());
  35088. decButton->setConnectedEdges (Button::ConnectedOnRight);
  35089. incButton->setBounds (buttonRect.getCentreX(),
  35090. buttonRect.getY(),
  35091. buttonRect.getWidth() / 2,
  35092. buttonRect.getHeight());
  35093. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  35094. }
  35095. else
  35096. {
  35097. incButton->setBounds (buttonRect.getX(),
  35098. buttonRect.getY(),
  35099. buttonRect.getWidth(),
  35100. buttonRect.getHeight() / 2);
  35101. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  35102. decButton->setBounds (buttonRect.getX(),
  35103. buttonRect.getCentreY(),
  35104. buttonRect.getWidth(),
  35105. buttonRect.getHeight() / 2);
  35106. decButton->setConnectedEdges (Button::ConnectedOnTop);
  35107. }
  35108. }
  35109. }
  35110. void Slider::focusOfChildComponentChanged (FocusChangeType)
  35111. {
  35112. repaint();
  35113. }
  35114. void Slider::mouseDown (const MouseEvent& e)
  35115. {
  35116. mouseWasHidden = false;
  35117. incDecDragged = false;
  35118. if (isEnabled())
  35119. {
  35120. if (e.mods.isPopupMenu() && menuEnabled)
  35121. {
  35122. menuShown = true;
  35123. PopupMenu m;
  35124. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  35125. m.addSeparator();
  35126. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  35127. {
  35128. PopupMenu rotaryMenu;
  35129. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  35130. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  35131. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  35132. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  35133. }
  35134. const int r = m.show();
  35135. if (r == 1)
  35136. {
  35137. setVelocityBasedMode (! isVelocityBased);
  35138. }
  35139. else if (r == 2)
  35140. {
  35141. setSliderStyle (Rotary);
  35142. }
  35143. else if (r == 3)
  35144. {
  35145. setSliderStyle (RotaryHorizontalDrag);
  35146. }
  35147. else if (r == 4)
  35148. {
  35149. setSliderStyle (RotaryVerticalDrag);
  35150. }
  35151. }
  35152. else if (maximum > minimum)
  35153. {
  35154. menuShown = false;
  35155. if (valueBox != 0)
  35156. valueBox->hideEditor (true);
  35157. sliderBeingDragged = 0;
  35158. if (style == TwoValueHorizontal
  35159. || style == TwoValueVertical
  35160. || style == ThreeValueHorizontal
  35161. || style == ThreeValueVertical)
  35162. {
  35163. const float mousePos = (float) (isVertical() ? e.y : e.x);
  35164. const float normalPosDistance = fabsf (getLinearSliderPos (currentValue) - mousePos);
  35165. const float minPosDistance = fabsf (getLinearSliderPos (valueMin) - 0.1f - mousePos);
  35166. const float maxPosDistance = fabsf (getLinearSliderPos (valueMax) + 0.1f - mousePos);
  35167. if (style == TwoValueHorizontal || style == TwoValueVertical)
  35168. {
  35169. if (maxPosDistance <= minPosDistance)
  35170. sliderBeingDragged = 2;
  35171. else
  35172. sliderBeingDragged = 1;
  35173. }
  35174. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  35175. {
  35176. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  35177. sliderBeingDragged = 1;
  35178. else if (normalPosDistance >= maxPosDistance)
  35179. sliderBeingDragged = 2;
  35180. }
  35181. }
  35182. minMaxDiff = valueMax - valueMin;
  35183. mouseXWhenLastDragged = e.x;
  35184. mouseYWhenLastDragged = e.y;
  35185. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  35186. * valueToProportionOfLength (currentValue);
  35187. if (sliderBeingDragged == 2)
  35188. valueWhenLastDragged = valueMax;
  35189. else if (sliderBeingDragged == 1)
  35190. valueWhenLastDragged = valueMin;
  35191. else
  35192. valueWhenLastDragged = currentValue;
  35193. valueOnMouseDown = valueWhenLastDragged;
  35194. if (popupDisplayEnabled)
  35195. {
  35196. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  35197. popupDisplay = popup;
  35198. if (parentForPopupDisplay != 0)
  35199. {
  35200. parentForPopupDisplay->addChildComponent (popup);
  35201. }
  35202. else
  35203. {
  35204. popup->addToDesktop (0);
  35205. }
  35206. popup->setVisible (true);
  35207. }
  35208. sendDragStart();
  35209. mouseDrag (e);
  35210. }
  35211. }
  35212. }
  35213. void Slider::mouseUp (const MouseEvent&)
  35214. {
  35215. if (isEnabled()
  35216. && (! menuShown)
  35217. && (maximum > minimum)
  35218. && (style != IncDecButtons || incDecDragged))
  35219. {
  35220. restoreMouseIfHidden();
  35221. if (sendChangeOnlyOnRelease && valueOnMouseDown != currentValue)
  35222. triggerChangeMessage (false);
  35223. sendDragEnd();
  35224. deleteAndZero (popupDisplay);
  35225. if (style == IncDecButtons)
  35226. {
  35227. incButton->setState (Button::buttonNormal);
  35228. decButton->setState (Button::buttonNormal);
  35229. }
  35230. }
  35231. }
  35232. void Slider::restoreMouseIfHidden()
  35233. {
  35234. if (mouseWasHidden)
  35235. {
  35236. mouseWasHidden = false;
  35237. Component* c = Component::getComponentUnderMouse();
  35238. if (c == 0)
  35239. c = this;
  35240. c->enableUnboundedMouseMovement (false);
  35241. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  35242. : ((sliderBeingDragged == 1) ? getMinValue()
  35243. : currentValue);
  35244. const int pixelPos = (int) getLinearSliderPos (pos);
  35245. int x = isHorizontal() ? pixelPos : (getWidth() / 2);
  35246. int y = isVertical() ? pixelPos : (getHeight() / 2);
  35247. relativePositionToGlobal (x, y);
  35248. Desktop::setMousePosition (x, y);
  35249. }
  35250. }
  35251. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  35252. {
  35253. if (isEnabled()
  35254. && style != IncDecButtons
  35255. && style != Rotary
  35256. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  35257. {
  35258. restoreMouseIfHidden();
  35259. }
  35260. }
  35261. static double smallestAngleBetween (double a1, double a2)
  35262. {
  35263. return jmin (fabs (a1 - a2),
  35264. fabs (a1 + double_Pi * 2.0 - a2),
  35265. fabs (a2 + double_Pi * 2.0 - a1));
  35266. }
  35267. void Slider::mouseDrag (const MouseEvent& e)
  35268. {
  35269. if (isEnabled()
  35270. && (! menuShown)
  35271. && (maximum > minimum))
  35272. {
  35273. if (style == Rotary)
  35274. {
  35275. int dx = e.x - sliderRect.getCentreX();
  35276. int dy = e.y - sliderRect.getCentreY();
  35277. if (dx * dx + dy * dy > 25)
  35278. {
  35279. double angle = atan2 ((double) dx, (double) -dy);
  35280. while (angle < 0.0)
  35281. angle += double_Pi * 2.0;
  35282. if (rotaryStop && ! e.mouseWasClicked())
  35283. {
  35284. if (fabs (angle - lastAngle) > double_Pi)
  35285. {
  35286. if (angle >= lastAngle)
  35287. angle -= double_Pi * 2.0;
  35288. else
  35289. angle += double_Pi * 2.0;
  35290. }
  35291. if (angle >= lastAngle)
  35292. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  35293. else
  35294. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  35295. }
  35296. else
  35297. {
  35298. while (angle < rotaryStart)
  35299. angle += double_Pi * 2.0;
  35300. if (angle > rotaryEnd)
  35301. {
  35302. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  35303. angle = rotaryStart;
  35304. else
  35305. angle = rotaryEnd;
  35306. }
  35307. }
  35308. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  35309. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  35310. lastAngle = angle;
  35311. }
  35312. }
  35313. else
  35314. {
  35315. if (style == LinearBar && e.mouseWasClicked()
  35316. && valueBox != 0 && valueBox->isEditable())
  35317. return;
  35318. if (style == IncDecButtons)
  35319. {
  35320. if (! incDecDragged)
  35321. incDecDragged = e.getDistanceFromDragStart() > 10 && ! e.mouseWasClicked();
  35322. if (! incDecDragged)
  35323. return;
  35324. }
  35325. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  35326. : false))
  35327. || ((maximum - minimum) / sliderRegionSize < interval))
  35328. {
  35329. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  35330. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  35331. if (style == RotaryHorizontalDrag
  35332. || style == RotaryVerticalDrag
  35333. || style == IncDecButtons
  35334. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  35335. && ! snapsToMousePos))
  35336. {
  35337. const int mouseDiff = (style == RotaryHorizontalDrag
  35338. || style == LinearHorizontal
  35339. || style == LinearBar
  35340. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  35341. ? e.getDistanceFromDragStartX()
  35342. : -e.getDistanceFromDragStartY();
  35343. double newPos = valueToProportionOfLength (valueOnMouseDown)
  35344. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  35345. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  35346. if (style == IncDecButtons)
  35347. {
  35348. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  35349. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  35350. }
  35351. }
  35352. else
  35353. {
  35354. if (style == LinearVertical)
  35355. scaledMousePos = 1.0 - scaledMousePos;
  35356. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  35357. }
  35358. }
  35359. else
  35360. {
  35361. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  35362. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  35363. ? e.x - mouseXWhenLastDragged
  35364. : e.y - mouseYWhenLastDragged;
  35365. const double maxSpeed = jmax (200, sliderRegionSize);
  35366. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  35367. if (speed != 0)
  35368. {
  35369. speed = 0.2 * velocityModeSensitivity
  35370. * (1.0 + sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  35371. + jmax (0.0, (double) (speed - velocityModeThreshold))
  35372. / maxSpeed))));
  35373. if (mouseDiff < 0)
  35374. speed = -speed;
  35375. if (style == LinearVertical || style == RotaryVerticalDrag
  35376. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  35377. speed = -speed;
  35378. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  35379. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  35380. e.originalComponent->enableUnboundedMouseMovement (true, false);
  35381. mouseWasHidden = true;
  35382. }
  35383. }
  35384. }
  35385. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  35386. if (sliderBeingDragged == 0)
  35387. {
  35388. setValue (snapValue (valueWhenLastDragged, true),
  35389. ! sendChangeOnlyOnRelease, true);
  35390. }
  35391. else if (sliderBeingDragged == 1)
  35392. {
  35393. setMinValue (snapValue (valueWhenLastDragged, true),
  35394. ! sendChangeOnlyOnRelease, false);
  35395. if (e.mods.isShiftDown())
  35396. setMaxValue (getMinValue() + minMaxDiff, false);
  35397. else
  35398. minMaxDiff = valueMax - valueMin;
  35399. }
  35400. else
  35401. {
  35402. jassert (sliderBeingDragged == 2);
  35403. setMaxValue (snapValue (valueWhenLastDragged, true),
  35404. ! sendChangeOnlyOnRelease, false);
  35405. if (e.mods.isShiftDown())
  35406. setMinValue (getMaxValue() - minMaxDiff, false);
  35407. else
  35408. minMaxDiff = valueMax - valueMin;
  35409. }
  35410. mouseXWhenLastDragged = e.x;
  35411. mouseYWhenLastDragged = e.y;
  35412. }
  35413. }
  35414. void Slider::mouseDoubleClick (const MouseEvent&)
  35415. {
  35416. if (doubleClickToValue
  35417. && isEnabled()
  35418. && style != IncDecButtons
  35419. && minimum <= doubleClickReturnValue
  35420. && maximum >= doubleClickReturnValue)
  35421. {
  35422. sendDragStart();
  35423. setValue (doubleClickReturnValue, true, true);
  35424. sendDragEnd();
  35425. }
  35426. }
  35427. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  35428. {
  35429. if (scrollWheelEnabled && isEnabled()
  35430. && style != TwoValueHorizontal
  35431. && style != TwoValueVertical)
  35432. {
  35433. if (maximum > minimum && ! isMouseButtonDownAnywhere())
  35434. {
  35435. if (valueBox != 0)
  35436. valueBox->hideEditor (false);
  35437. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  35438. const double currentPos = valueToProportionOfLength (currentValue);
  35439. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  35440. double delta = (newValue != currentValue)
  35441. ? jmax (fabs (newValue - currentValue), interval) : 0;
  35442. if (currentValue > newValue)
  35443. delta = -delta;
  35444. sendDragStart();
  35445. setValue (snapValue (currentValue + delta, false), true, true);
  35446. sendDragEnd();
  35447. }
  35448. }
  35449. else
  35450. {
  35451. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  35452. }
  35453. }
  35454. void SliderListener::sliderDragStarted (Slider*)
  35455. {
  35456. }
  35457. void SliderListener::sliderDragEnded (Slider*)
  35458. {
  35459. }
  35460. END_JUCE_NAMESPACE
  35461. /********* End of inlined file: juce_Slider.cpp *********/
  35462. /********* Start of inlined file: juce_TableHeaderComponent.cpp *********/
  35463. BEGIN_JUCE_NAMESPACE
  35464. class DragOverlayComp : public Component
  35465. {
  35466. public:
  35467. DragOverlayComp (Image* const image_)
  35468. : image (image_)
  35469. {
  35470. image->multiplyAllAlphas (0.8f);
  35471. setAlwaysOnTop (true);
  35472. }
  35473. ~DragOverlayComp()
  35474. {
  35475. delete image;
  35476. }
  35477. void paint (Graphics& g)
  35478. {
  35479. g.drawImageAt (image, 0, 0);
  35480. }
  35481. private:
  35482. Image* image;
  35483. DragOverlayComp (const DragOverlayComp&);
  35484. const DragOverlayComp& operator= (const DragOverlayComp&);
  35485. };
  35486. TableHeaderComponent::TableHeaderComponent()
  35487. : listeners (2),
  35488. dragOverlayComp (0),
  35489. columnsChanged (false),
  35490. columnsResized (false),
  35491. sortChanged (false),
  35492. menuActive (true),
  35493. stretchToFit (false),
  35494. columnIdBeingResized (0),
  35495. columnIdBeingDragged (0),
  35496. columnIdUnderMouse (0),
  35497. lastDeliberateWidth (0)
  35498. {
  35499. }
  35500. TableHeaderComponent::~TableHeaderComponent()
  35501. {
  35502. delete dragOverlayComp;
  35503. }
  35504. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  35505. {
  35506. menuActive = hasMenu;
  35507. }
  35508. bool TableHeaderComponent::isPopupMenuActive() const throw() { return menuActive; }
  35509. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const throw()
  35510. {
  35511. if (onlyCountVisibleColumns)
  35512. {
  35513. int num = 0;
  35514. for (int i = columns.size(); --i >= 0;)
  35515. if (columns.getUnchecked(i)->isVisible())
  35516. ++num;
  35517. return num;
  35518. }
  35519. else
  35520. {
  35521. return columns.size();
  35522. }
  35523. }
  35524. const String TableHeaderComponent::getColumnName (const int columnId) const throw()
  35525. {
  35526. const ColumnInfo* const ci = getInfoForId (columnId);
  35527. return ci != 0 ? ci->name : String::empty;
  35528. }
  35529. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  35530. {
  35531. ColumnInfo* const ci = getInfoForId (columnId);
  35532. if (ci != 0 && ci->name != newName)
  35533. {
  35534. ci->name = newName;
  35535. sendColumnsChanged();
  35536. }
  35537. }
  35538. void TableHeaderComponent::addColumn (const String& columnName,
  35539. const int columnId,
  35540. const int width,
  35541. const int minimumWidth,
  35542. const int maximumWidth,
  35543. const int propertyFlags,
  35544. const int insertIndex)
  35545. {
  35546. // can't have a duplicate or null ID!
  35547. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  35548. jassert (width > 0);
  35549. ColumnInfo* const ci = new ColumnInfo();
  35550. ci->name = columnName;
  35551. ci->id = columnId;
  35552. ci->width = width;
  35553. ci->lastDeliberateWidth = width;
  35554. ci->minimumWidth = minimumWidth;
  35555. ci->maximumWidth = maximumWidth;
  35556. if (ci->maximumWidth < 0)
  35557. ci->maximumWidth = INT_MAX;
  35558. jassert (ci->maximumWidth >= ci->minimumWidth);
  35559. ci->propertyFlags = propertyFlags;
  35560. columns.insert (insertIndex, ci);
  35561. sendColumnsChanged();
  35562. }
  35563. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  35564. {
  35565. const int index = getIndexOfColumnId (columnIdToRemove, false);
  35566. if (index >= 0)
  35567. {
  35568. columns.remove (index);
  35569. sortChanged = true;
  35570. sendColumnsChanged();
  35571. }
  35572. }
  35573. void TableHeaderComponent::removeAllColumns()
  35574. {
  35575. if (columns.size() > 0)
  35576. {
  35577. columns.clear();
  35578. sendColumnsChanged();
  35579. }
  35580. }
  35581. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  35582. {
  35583. const int currentIndex = getIndexOfColumnId (columnId, false);
  35584. newIndex = visibleIndexToTotalIndex (newIndex);
  35585. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  35586. {
  35587. columns.move (currentIndex, newIndex);
  35588. sendColumnsChanged();
  35589. }
  35590. }
  35591. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  35592. {
  35593. ColumnInfo* const ci = getInfoForId (columnId);
  35594. if (ci != 0 && ci->width != newWidth)
  35595. {
  35596. const int numColumns = getNumColumns (true);
  35597. ci->lastDeliberateWidth = ci->width
  35598. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  35599. if (stretchToFit)
  35600. {
  35601. const int index = getIndexOfColumnId (columnId, true) + 1;
  35602. if (((unsigned int) index) < (unsigned int) numColumns)
  35603. {
  35604. const int x = getColumnPosition (index).getX();
  35605. if (lastDeliberateWidth == 0)
  35606. lastDeliberateWidth = getTotalWidth();
  35607. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  35608. }
  35609. }
  35610. repaint();
  35611. columnsResized = true;
  35612. triggerAsyncUpdate();
  35613. }
  35614. }
  35615. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw()
  35616. {
  35617. int n = 0;
  35618. for (int i = 0; i < columns.size(); ++i)
  35619. {
  35620. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  35621. {
  35622. if (columns.getUnchecked(i)->id == columnId)
  35623. return n;
  35624. ++n;
  35625. }
  35626. }
  35627. return -1;
  35628. }
  35629. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw()
  35630. {
  35631. if (onlyCountVisibleColumns)
  35632. index = visibleIndexToTotalIndex (index);
  35633. const ColumnInfo* const ci = columns [index];
  35634. return (ci != 0) ? ci->id : 0;
  35635. }
  35636. const Rectangle TableHeaderComponent::getColumnPosition (const int index) const throw()
  35637. {
  35638. int x = 0, width = 0, n = 0;
  35639. for (int i = 0; i < columns.size(); ++i)
  35640. {
  35641. x += width;
  35642. if (columns.getUnchecked(i)->isVisible())
  35643. {
  35644. width = columns.getUnchecked(i)->width;
  35645. if (n++ == index)
  35646. break;
  35647. }
  35648. else
  35649. {
  35650. width = 0;
  35651. }
  35652. }
  35653. return Rectangle (x, 0, width, getHeight());
  35654. }
  35655. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const throw()
  35656. {
  35657. if (xToFind >= 0)
  35658. {
  35659. int x = 0;
  35660. for (int i = 0; i < columns.size(); ++i)
  35661. {
  35662. const ColumnInfo* const ci = columns.getUnchecked(i);
  35663. if (ci->isVisible())
  35664. {
  35665. x += ci->width;
  35666. if (xToFind < x)
  35667. return ci->id;
  35668. }
  35669. }
  35670. }
  35671. return 0;
  35672. }
  35673. int TableHeaderComponent::getTotalWidth() const throw()
  35674. {
  35675. int w = 0;
  35676. for (int i = columns.size(); --i >= 0;)
  35677. if (columns.getUnchecked(i)->isVisible())
  35678. w += columns.getUnchecked(i)->width;
  35679. return w;
  35680. }
  35681. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  35682. {
  35683. stretchToFit = shouldStretchToFit;
  35684. lastDeliberateWidth = getTotalWidth();
  35685. resized();
  35686. }
  35687. bool TableHeaderComponent::isStretchToFitActive() const throw()
  35688. {
  35689. return stretchToFit;
  35690. }
  35691. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  35692. {
  35693. if (stretchToFit && getWidth() > 0
  35694. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  35695. {
  35696. lastDeliberateWidth = targetTotalWidth;
  35697. resizeColumnsToFit (0, targetTotalWidth);
  35698. }
  35699. }
  35700. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  35701. {
  35702. targetTotalWidth = jmax (targetTotalWidth, 0);
  35703. StretchableObjectResizer sor;
  35704. int i;
  35705. for (i = firstColumnIndex; i < columns.size(); ++i)
  35706. {
  35707. ColumnInfo* const ci = columns.getUnchecked(i);
  35708. if (ci->isVisible())
  35709. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  35710. }
  35711. sor.resizeToFit (targetTotalWidth);
  35712. int visIndex = 0;
  35713. for (i = firstColumnIndex; i < columns.size(); ++i)
  35714. {
  35715. ColumnInfo* const ci = columns.getUnchecked(i);
  35716. if (ci->isVisible())
  35717. {
  35718. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  35719. (int) floor (sor.getItemSize (visIndex++)));
  35720. if (newWidth != ci->width)
  35721. {
  35722. ci->width = newWidth;
  35723. repaint();
  35724. columnsResized = true;
  35725. triggerAsyncUpdate();
  35726. }
  35727. }
  35728. }
  35729. }
  35730. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  35731. {
  35732. ColumnInfo* const ci = getInfoForId (columnId);
  35733. if (ci != 0 && shouldBeVisible != ci->isVisible())
  35734. {
  35735. if (shouldBeVisible)
  35736. ci->propertyFlags |= visible;
  35737. else
  35738. ci->propertyFlags &= ~visible;
  35739. sendColumnsChanged();
  35740. resized();
  35741. }
  35742. }
  35743. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  35744. {
  35745. const ColumnInfo* const ci = getInfoForId (columnId);
  35746. return ci != 0 && ci->isVisible();
  35747. }
  35748. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  35749. {
  35750. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  35751. {
  35752. for (int i = columns.size(); --i >= 0;)
  35753. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  35754. ColumnInfo* const ci = getInfoForId (columnId);
  35755. if (ci != 0)
  35756. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  35757. reSortTable();
  35758. }
  35759. }
  35760. int TableHeaderComponent::getSortColumnId() const throw()
  35761. {
  35762. for (int i = columns.size(); --i >= 0;)
  35763. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  35764. return columns.getUnchecked(i)->id;
  35765. return 0;
  35766. }
  35767. bool TableHeaderComponent::isSortedForwards() const throw()
  35768. {
  35769. for (int i = columns.size(); --i >= 0;)
  35770. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  35771. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  35772. return true;
  35773. }
  35774. void TableHeaderComponent::reSortTable()
  35775. {
  35776. sortChanged = true;
  35777. repaint();
  35778. triggerAsyncUpdate();
  35779. }
  35780. const String TableHeaderComponent::toString() const
  35781. {
  35782. String s;
  35783. XmlElement doc (T("TABLELAYOUT"));
  35784. doc.setAttribute (T("sortedCol"), getSortColumnId());
  35785. doc.setAttribute (T("sortForwards"), isSortedForwards());
  35786. for (int i = 0; i < columns.size(); ++i)
  35787. {
  35788. const ColumnInfo* const ci = columns.getUnchecked (i);
  35789. XmlElement* const e = new XmlElement (T("COLUMN"));
  35790. doc.addChildElement (e);
  35791. e->setAttribute (T("id"), ci->id);
  35792. e->setAttribute (T("visible"), ci->isVisible());
  35793. e->setAttribute (T("width"), ci->width);
  35794. }
  35795. return doc.createDocument (String::empty, true, false);
  35796. }
  35797. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  35798. {
  35799. XmlDocument doc (storedVersion);
  35800. XmlElement* const storedXml = doc.getDocumentElement();
  35801. int index = 0;
  35802. if (storedXml != 0 && storedXml->hasTagName (T("TABLELAYOUT")))
  35803. {
  35804. forEachXmlChildElement (*storedXml, col)
  35805. {
  35806. const int tabId = col->getIntAttribute (T("id"));
  35807. ColumnInfo* const ci = getInfoForId (tabId);
  35808. if (ci != 0)
  35809. {
  35810. columns.move (columns.indexOf (ci), index);
  35811. ci->width = col->getIntAttribute (T("width"));
  35812. setColumnVisible (tabId, col->getBoolAttribute (T("visible")));
  35813. }
  35814. ++index;
  35815. }
  35816. columnsResized = true;
  35817. sendColumnsChanged();
  35818. setSortColumnId (storedXml->getIntAttribute (T("sortedCol")),
  35819. storedXml->getBoolAttribute (T("sortForwards"), true));
  35820. }
  35821. delete storedXml;
  35822. }
  35823. void TableHeaderComponent::addListener (TableHeaderListener* const newListener) throw()
  35824. {
  35825. listeners.addIfNotAlreadyThere (newListener);
  35826. }
  35827. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove) throw()
  35828. {
  35829. listeners.removeValue (listenerToRemove);
  35830. }
  35831. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  35832. {
  35833. const ColumnInfo* const ci = getInfoForId (columnId);
  35834. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  35835. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  35836. }
  35837. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  35838. {
  35839. for (int i = 0; i < columns.size(); ++i)
  35840. {
  35841. const ColumnInfo* const ci = columns.getUnchecked(i);
  35842. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  35843. menu.addItem (ci->id, ci->name,
  35844. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  35845. isColumnVisible (ci->id));
  35846. }
  35847. }
  35848. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  35849. {
  35850. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  35851. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  35852. }
  35853. void TableHeaderComponent::paint (Graphics& g)
  35854. {
  35855. LookAndFeel& lf = getLookAndFeel();
  35856. lf.drawTableHeaderBackground (g, *this);
  35857. const Rectangle clip (g.getClipBounds());
  35858. int x = 0;
  35859. for (int i = 0; i < columns.size(); ++i)
  35860. {
  35861. const ColumnInfo* const ci = columns.getUnchecked(i);
  35862. if (ci->isVisible())
  35863. {
  35864. if (x + ci->width > clip.getX()
  35865. && (ci->id != columnIdBeingDragged
  35866. || dragOverlayComp == 0
  35867. || ! dragOverlayComp->isVisible()))
  35868. {
  35869. g.saveState();
  35870. g.setOrigin (x, 0);
  35871. g.reduceClipRegion (0, 0, ci->width, getHeight());
  35872. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  35873. ci->id == columnIdUnderMouse,
  35874. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  35875. ci->propertyFlags);
  35876. g.restoreState();
  35877. }
  35878. x += ci->width;
  35879. if (x >= clip.getRight())
  35880. break;
  35881. }
  35882. }
  35883. }
  35884. void TableHeaderComponent::resized()
  35885. {
  35886. }
  35887. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  35888. {
  35889. updateColumnUnderMouse (e.x, e.y);
  35890. }
  35891. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  35892. {
  35893. updateColumnUnderMouse (e.x, e.y);
  35894. }
  35895. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  35896. {
  35897. updateColumnUnderMouse (e.x, e.y);
  35898. }
  35899. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  35900. {
  35901. repaint();
  35902. columnIdBeingResized = 0;
  35903. columnIdBeingDragged = 0;
  35904. if (columnIdUnderMouse != 0)
  35905. {
  35906. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  35907. if (e.mods.isPopupMenu())
  35908. columnClicked (columnIdUnderMouse, e.mods);
  35909. }
  35910. if (menuActive && e.mods.isPopupMenu())
  35911. showColumnChooserMenu (columnIdUnderMouse);
  35912. }
  35913. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  35914. {
  35915. if (columnIdBeingResized == 0
  35916. && columnIdBeingDragged == 0
  35917. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  35918. {
  35919. deleteAndZero (dragOverlayComp);
  35920. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  35921. if (columnIdBeingResized != 0)
  35922. {
  35923. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  35924. initialColumnWidth = ci->width;
  35925. }
  35926. else
  35927. {
  35928. beginDrag (e);
  35929. }
  35930. }
  35931. if (columnIdBeingResized != 0)
  35932. {
  35933. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  35934. if (ci != 0)
  35935. {
  35936. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  35937. initialColumnWidth + e.getDistanceFromDragStartX());
  35938. if (stretchToFit)
  35939. {
  35940. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  35941. int minWidthOnRight = 0;
  35942. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  35943. if (columns.getUnchecked (i)->isVisible())
  35944. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  35945. const Rectangle currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  35946. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  35947. }
  35948. setColumnWidth (columnIdBeingResized, w);
  35949. }
  35950. }
  35951. else if (columnIdBeingDragged != 0)
  35952. {
  35953. if (e.y >= -50 && e.y < getHeight() + 50)
  35954. {
  35955. beginDrag (e);
  35956. if (dragOverlayComp != 0)
  35957. {
  35958. dragOverlayComp->setVisible (true);
  35959. dragOverlayComp->setBounds (jlimit (0,
  35960. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  35961. e.x - draggingColumnOffset),
  35962. 0,
  35963. dragOverlayComp->getWidth(),
  35964. getHeight());
  35965. for (int i = columns.size(); --i >= 0;)
  35966. {
  35967. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  35968. int newIndex = currentIndex;
  35969. if (newIndex > 0)
  35970. {
  35971. // if the previous column isn't draggable, we can't move our column
  35972. // past it, because that'd change the undraggable column's position..
  35973. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  35974. if ((previous->propertyFlags & draggable) != 0)
  35975. {
  35976. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  35977. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  35978. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  35979. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  35980. {
  35981. --newIndex;
  35982. }
  35983. }
  35984. }
  35985. if (newIndex < columns.size() - 1)
  35986. {
  35987. // if the next column isn't draggable, we can't move our column
  35988. // past it, because that'd change the undraggable column's position..
  35989. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  35990. if ((nextCol->propertyFlags & draggable) != 0)
  35991. {
  35992. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  35993. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  35994. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  35995. > abs (dragOverlayComp->getRight() - rightOfNext))
  35996. {
  35997. ++newIndex;
  35998. }
  35999. }
  36000. }
  36001. if (newIndex != currentIndex)
  36002. moveColumn (columnIdBeingDragged, newIndex);
  36003. else
  36004. break;
  36005. }
  36006. }
  36007. }
  36008. else
  36009. {
  36010. endDrag (draggingColumnOriginalIndex);
  36011. }
  36012. }
  36013. }
  36014. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  36015. {
  36016. if (columnIdBeingDragged == 0)
  36017. {
  36018. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  36019. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  36020. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  36021. {
  36022. columnIdBeingDragged = 0;
  36023. }
  36024. else
  36025. {
  36026. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  36027. const Rectangle columnRect (getColumnPosition (draggingColumnOriginalIndex));
  36028. const int temp = columnIdBeingDragged;
  36029. columnIdBeingDragged = 0;
  36030. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  36031. columnIdBeingDragged = temp;
  36032. dragOverlayComp->setBounds (columnRect);
  36033. for (int i = listeners.size(); --i >= 0;)
  36034. {
  36035. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  36036. i = jmin (i, listeners.size() - 1);
  36037. }
  36038. }
  36039. }
  36040. }
  36041. void TableHeaderComponent::endDrag (const int finalIndex)
  36042. {
  36043. if (columnIdBeingDragged != 0)
  36044. {
  36045. moveColumn (columnIdBeingDragged, finalIndex);
  36046. columnIdBeingDragged = 0;
  36047. repaint();
  36048. for (int i = listeners.size(); --i >= 0;)
  36049. {
  36050. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  36051. i = jmin (i, listeners.size() - 1);
  36052. }
  36053. }
  36054. }
  36055. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  36056. {
  36057. mouseDrag (e);
  36058. for (int i = columns.size(); --i >= 0;)
  36059. if (columns.getUnchecked (i)->isVisible())
  36060. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  36061. columnIdBeingResized = 0;
  36062. repaint();
  36063. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  36064. updateColumnUnderMouse (e.x, e.y);
  36065. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  36066. columnClicked (columnIdUnderMouse, e.mods);
  36067. deleteAndZero (dragOverlayComp);
  36068. }
  36069. const MouseCursor TableHeaderComponent::getMouseCursor()
  36070. {
  36071. int x, y;
  36072. getMouseXYRelative (x, y);
  36073. if (columnIdBeingResized != 0 || (getResizeDraggerAt (x) != 0 && ! isMouseButtonDown()))
  36074. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  36075. return Component::getMouseCursor();
  36076. }
  36077. bool TableHeaderComponent::ColumnInfo::isVisible() const throw()
  36078. {
  36079. return (propertyFlags & TableHeaderComponent::visible) != 0;
  36080. }
  36081. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const throw()
  36082. {
  36083. for (int i = columns.size(); --i >= 0;)
  36084. if (columns.getUnchecked(i)->id == id)
  36085. return columns.getUnchecked(i);
  36086. return 0;
  36087. }
  36088. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const throw()
  36089. {
  36090. int n = 0;
  36091. for (int i = 0; i < columns.size(); ++i)
  36092. {
  36093. if (columns.getUnchecked(i)->isVisible())
  36094. {
  36095. if (n == visibleIndex)
  36096. return i;
  36097. ++n;
  36098. }
  36099. }
  36100. return -1;
  36101. }
  36102. void TableHeaderComponent::sendColumnsChanged()
  36103. {
  36104. if (stretchToFit && lastDeliberateWidth > 0)
  36105. resizeAllColumnsToFit (lastDeliberateWidth);
  36106. repaint();
  36107. columnsChanged = true;
  36108. triggerAsyncUpdate();
  36109. }
  36110. void TableHeaderComponent::handleAsyncUpdate()
  36111. {
  36112. const bool changed = columnsChanged || sortChanged;
  36113. const bool sized = columnsResized || changed;
  36114. const bool sorted = sortChanged;
  36115. columnsChanged = false;
  36116. columnsResized = false;
  36117. sortChanged = false;
  36118. if (sorted)
  36119. {
  36120. for (int i = listeners.size(); --i >= 0;)
  36121. {
  36122. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  36123. i = jmin (i, listeners.size() - 1);
  36124. }
  36125. }
  36126. if (changed)
  36127. {
  36128. for (int i = listeners.size(); --i >= 0;)
  36129. {
  36130. listeners.getUnchecked(i)->tableColumnsChanged (this);
  36131. i = jmin (i, listeners.size() - 1);
  36132. }
  36133. }
  36134. if (sized)
  36135. {
  36136. for (int i = listeners.size(); --i >= 0;)
  36137. {
  36138. listeners.getUnchecked(i)->tableColumnsResized (this);
  36139. i = jmin (i, listeners.size() - 1);
  36140. }
  36141. }
  36142. }
  36143. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const throw()
  36144. {
  36145. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  36146. {
  36147. const int draggableDistance = 3;
  36148. int x = 0;
  36149. for (int i = 0; i < columns.size(); ++i)
  36150. {
  36151. const ColumnInfo* const ci = columns.getUnchecked(i);
  36152. if (ci->isVisible())
  36153. {
  36154. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  36155. && (ci->propertyFlags & resizable) != 0)
  36156. return ci->id;
  36157. x += ci->width;
  36158. }
  36159. }
  36160. }
  36161. return 0;
  36162. }
  36163. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  36164. {
  36165. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  36166. ? getColumnIdAtX (x) : 0;
  36167. if (newCol != columnIdUnderMouse)
  36168. {
  36169. columnIdUnderMouse = newCol;
  36170. repaint();
  36171. }
  36172. }
  36173. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  36174. {
  36175. PopupMenu m;
  36176. addMenuItems (m, columnIdClicked);
  36177. if (m.getNumItems() > 0)
  36178. {
  36179. const int result = m.show();
  36180. if (result != 0)
  36181. reactToMenuItem (result, columnIdClicked);
  36182. }
  36183. }
  36184. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  36185. {
  36186. }
  36187. END_JUCE_NAMESPACE
  36188. /********* End of inlined file: juce_TableHeaderComponent.cpp *********/
  36189. /********* Start of inlined file: juce_TableListBox.cpp *********/
  36190. BEGIN_JUCE_NAMESPACE
  36191. static const tchar* const tableColumnPropertyTag = T("_tableColumnID");
  36192. class TableListRowComp : public Component
  36193. {
  36194. public:
  36195. TableListRowComp (TableListBox& owner_)
  36196. : owner (owner_),
  36197. row (-1),
  36198. isSelected (false)
  36199. {
  36200. }
  36201. ~TableListRowComp()
  36202. {
  36203. deleteAllChildren();
  36204. }
  36205. void paint (Graphics& g)
  36206. {
  36207. TableListBoxModel* const model = owner.getModel();
  36208. if (model != 0)
  36209. {
  36210. const TableHeaderComponent* const header = owner.getHeader();
  36211. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  36212. const int numColumns = header->getNumColumns (true);
  36213. for (int i = 0; i < numColumns; ++i)
  36214. {
  36215. if (! columnsWithComponents [i])
  36216. {
  36217. const int columnId = header->getColumnIdOfIndex (i, true);
  36218. Rectangle columnRect (header->getColumnPosition (i));
  36219. columnRect.setSize (columnRect.getWidth(), getHeight());
  36220. g.saveState();
  36221. g.reduceClipRegion (columnRect);
  36222. g.setOrigin (columnRect.getX(), 0);
  36223. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  36224. g.restoreState();
  36225. }
  36226. }
  36227. }
  36228. }
  36229. void update (const int newRow, const bool isNowSelected)
  36230. {
  36231. if (newRow != row || isNowSelected != isSelected)
  36232. {
  36233. row = newRow;
  36234. isSelected = isNowSelected;
  36235. repaint();
  36236. }
  36237. if (row < owner.getNumRows())
  36238. {
  36239. jassert (row >= 0);
  36240. const tchar* const tagPropertyName = T("_tableLastUseNum");
  36241. const int newTag = Random::getSystemRandom().nextInt();
  36242. const TableHeaderComponent* const header = owner.getHeader();
  36243. const int numColumns = header->getNumColumns (true);
  36244. int i;
  36245. columnsWithComponents.clear();
  36246. if (owner.getModel() != 0)
  36247. {
  36248. for (i = 0; i < numColumns; ++i)
  36249. {
  36250. const int columnId = header->getColumnIdOfIndex (i, true);
  36251. Component* const newComp
  36252. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  36253. findChildComponentForColumn (columnId));
  36254. if (newComp != 0)
  36255. {
  36256. addAndMakeVisible (newComp);
  36257. newComp->setComponentProperty (tagPropertyName, newTag);
  36258. newComp->setComponentProperty (tableColumnPropertyTag, columnId);
  36259. const Rectangle columnRect (header->getColumnPosition (i));
  36260. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  36261. columnsWithComponents.setBit (i);
  36262. }
  36263. }
  36264. }
  36265. for (i = getNumChildComponents(); --i >= 0;)
  36266. {
  36267. Component* const c = getChildComponent (i);
  36268. if (c->getComponentPropertyInt (tagPropertyName, false, 0) != newTag)
  36269. delete c;
  36270. }
  36271. }
  36272. else
  36273. {
  36274. columnsWithComponents.clear();
  36275. deleteAllChildren();
  36276. }
  36277. }
  36278. void resized()
  36279. {
  36280. for (int i = getNumChildComponents(); --i >= 0;)
  36281. {
  36282. Component* const c = getChildComponent (i);
  36283. const int columnId = c->getComponentPropertyInt (tableColumnPropertyTag, false, 0);
  36284. if (columnId != 0)
  36285. {
  36286. const Rectangle columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  36287. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  36288. }
  36289. }
  36290. }
  36291. void mouseDown (const MouseEvent& e)
  36292. {
  36293. isDragging = false;
  36294. selectRowOnMouseUp = false;
  36295. if (isEnabled())
  36296. {
  36297. if (! isSelected)
  36298. {
  36299. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  36300. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  36301. if (columnId != 0 && owner.getModel() != 0)
  36302. owner.getModel()->cellClicked (row, columnId, e);
  36303. }
  36304. else
  36305. {
  36306. selectRowOnMouseUp = true;
  36307. }
  36308. }
  36309. }
  36310. void mouseDrag (const MouseEvent& e)
  36311. {
  36312. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  36313. {
  36314. const SparseSet <int> selectedRows (owner.getSelectedRows());
  36315. if (selectedRows.size() > 0)
  36316. {
  36317. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  36318. if (dragDescription.isNotEmpty())
  36319. {
  36320. isDragging = true;
  36321. DragAndDropContainer* const dragContainer
  36322. = DragAndDropContainer::findParentDragContainerFor (this);
  36323. if (dragContainer != 0)
  36324. {
  36325. Image* dragImage = owner.createSnapshotOfSelectedRows();
  36326. dragImage->multiplyAllAlphas (0.6f);
  36327. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  36328. }
  36329. else
  36330. {
  36331. // to be able to do a drag-and-drop operation, the listbox needs to
  36332. // be inside a component which is also a DragAndDropContainer.
  36333. jassertfalse
  36334. }
  36335. }
  36336. }
  36337. }
  36338. }
  36339. void mouseUp (const MouseEvent& e)
  36340. {
  36341. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  36342. {
  36343. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  36344. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  36345. if (columnId != 0 && owner.getModel() != 0)
  36346. owner.getModel()->cellClicked (row, columnId, e);
  36347. }
  36348. }
  36349. void mouseDoubleClick (const MouseEvent& e)
  36350. {
  36351. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  36352. if (columnId != 0 && owner.getModel() != 0)
  36353. owner.getModel()->cellDoubleClicked (row, columnId, e);
  36354. }
  36355. juce_UseDebuggingNewOperator
  36356. private:
  36357. TableListBox& owner;
  36358. int row;
  36359. bool isSelected, isDragging, selectRowOnMouseUp;
  36360. BitArray columnsWithComponents;
  36361. Component* findChildComponentForColumn (const int columnId) const
  36362. {
  36363. for (int i = getNumChildComponents(); --i >= 0;)
  36364. {
  36365. Component* const c = getChildComponent (i);
  36366. if (c->getComponentPropertyInt (tableColumnPropertyTag, false, 0) == columnId)
  36367. return c;
  36368. }
  36369. return 0;
  36370. }
  36371. TableListRowComp (const TableListRowComp&);
  36372. const TableListRowComp& operator= (const TableListRowComp&);
  36373. };
  36374. class TableListBoxHeader : public TableHeaderComponent
  36375. {
  36376. public:
  36377. TableListBoxHeader (TableListBox& owner_)
  36378. : owner (owner_)
  36379. {
  36380. }
  36381. ~TableListBoxHeader()
  36382. {
  36383. }
  36384. void addMenuItems (PopupMenu& menu, const int columnIdClicked)
  36385. {
  36386. if (owner.isAutoSizeMenuOptionShown())
  36387. {
  36388. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  36389. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  36390. menu.addSeparator();
  36391. }
  36392. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  36393. }
  36394. void reactToMenuItem (const int menuReturnId, const int columnIdClicked)
  36395. {
  36396. if (menuReturnId == 0xf836743)
  36397. {
  36398. owner.autoSizeColumn (columnIdClicked);
  36399. }
  36400. else if (menuReturnId == 0xf836744)
  36401. {
  36402. owner.autoSizeAllColumns();
  36403. }
  36404. else
  36405. {
  36406. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  36407. }
  36408. }
  36409. juce_UseDebuggingNewOperator
  36410. private:
  36411. TableListBox& owner;
  36412. TableListBoxHeader (const TableListBoxHeader&);
  36413. const TableListBoxHeader& operator= (const TableListBoxHeader&);
  36414. };
  36415. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  36416. : ListBox (name, 0),
  36417. model (model_),
  36418. autoSizeOptionsShown (true)
  36419. {
  36420. ListBox::model = this;
  36421. header = new TableListBoxHeader (*this);
  36422. header->setSize (100, 28);
  36423. header->addListener (this);
  36424. setHeaderComponent (header);
  36425. }
  36426. TableListBox::~TableListBox()
  36427. {
  36428. deleteAllChildren();
  36429. }
  36430. void TableListBox::setModel (TableListBoxModel* const newModel)
  36431. {
  36432. if (model != newModel)
  36433. {
  36434. model = newModel;
  36435. updateContent();
  36436. }
  36437. }
  36438. int TableListBox::getHeaderHeight() const throw()
  36439. {
  36440. return header->getHeight();
  36441. }
  36442. void TableListBox::setHeaderHeight (const int newHeight)
  36443. {
  36444. header->setSize (header->getWidth(), newHeight);
  36445. resized();
  36446. }
  36447. void TableListBox::autoSizeColumn (const int columnId)
  36448. {
  36449. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  36450. if (width > 0)
  36451. header->setColumnWidth (columnId, width);
  36452. }
  36453. void TableListBox::autoSizeAllColumns()
  36454. {
  36455. for (int i = 0; i < header->getNumColumns (true); ++i)
  36456. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  36457. }
  36458. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  36459. {
  36460. autoSizeOptionsShown = shouldBeShown;
  36461. }
  36462. bool TableListBox::isAutoSizeMenuOptionShown() const throw()
  36463. {
  36464. return autoSizeOptionsShown;
  36465. }
  36466. const Rectangle TableListBox::getCellPosition (const int columnId,
  36467. const int rowNumber,
  36468. const bool relativeToComponentTopLeft) const
  36469. {
  36470. Rectangle headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  36471. if (relativeToComponentTopLeft)
  36472. headerCell.translate (header->getX(), 0);
  36473. const Rectangle row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  36474. return Rectangle (headerCell.getX(), row.getY(),
  36475. headerCell.getWidth(), row.getHeight());
  36476. }
  36477. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  36478. {
  36479. ScrollBar* const scrollbar = getHorizontalScrollBar();
  36480. if (scrollbar != 0)
  36481. {
  36482. const Rectangle pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  36483. double x = scrollbar->getCurrentRangeStart();
  36484. const double w = scrollbar->getCurrentRangeSize();
  36485. if (pos.getX() < x)
  36486. x = pos.getX();
  36487. else if (pos.getRight() > x + w)
  36488. x += jmax (0.0, pos.getRight() - (x + w));
  36489. scrollbar->setCurrentRangeStart (x);
  36490. }
  36491. }
  36492. int TableListBox::getNumRows()
  36493. {
  36494. return model != 0 ? model->getNumRows() : 0;
  36495. }
  36496. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  36497. {
  36498. }
  36499. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate)
  36500. {
  36501. if (existingComponentToUpdate == 0)
  36502. existingComponentToUpdate = new TableListRowComp (*this);
  36503. ((TableListRowComp*) existingComponentToUpdate)->update (rowNumber, isRowSelected);
  36504. return existingComponentToUpdate;
  36505. }
  36506. void TableListBox::selectedRowsChanged (int row)
  36507. {
  36508. if (model != 0)
  36509. model->selectedRowsChanged (row);
  36510. }
  36511. void TableListBox::deleteKeyPressed (int row)
  36512. {
  36513. if (model != 0)
  36514. model->deleteKeyPressed (row);
  36515. }
  36516. void TableListBox::returnKeyPressed (int row)
  36517. {
  36518. if (model != 0)
  36519. model->returnKeyPressed (row);
  36520. }
  36521. void TableListBox::backgroundClicked()
  36522. {
  36523. if (model != 0)
  36524. model->backgroundClicked();
  36525. }
  36526. void TableListBox::listWasScrolled()
  36527. {
  36528. if (model != 0)
  36529. model->listWasScrolled();
  36530. }
  36531. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  36532. {
  36533. setMinimumContentWidth (header->getTotalWidth());
  36534. repaint();
  36535. updateColumnComponents();
  36536. }
  36537. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  36538. {
  36539. setMinimumContentWidth (header->getTotalWidth());
  36540. repaint();
  36541. updateColumnComponents();
  36542. }
  36543. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  36544. {
  36545. if (model != 0)
  36546. model->sortOrderChanged (header->getSortColumnId(),
  36547. header->isSortedForwards());
  36548. }
  36549. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  36550. {
  36551. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  36552. repaint();
  36553. }
  36554. void TableListBox::resized()
  36555. {
  36556. ListBox::resized();
  36557. header->resizeAllColumnsToFit (getVisibleContentWidth());
  36558. setMinimumContentWidth (header->getTotalWidth());
  36559. }
  36560. void TableListBox::updateColumnComponents() const
  36561. {
  36562. const int firstRow = getRowContainingPosition (0, 0);
  36563. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  36564. {
  36565. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  36566. if (rowComp != 0)
  36567. rowComp->resized();
  36568. }
  36569. }
  36570. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  36571. {
  36572. }
  36573. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  36574. {
  36575. }
  36576. void TableListBoxModel::backgroundClicked()
  36577. {
  36578. }
  36579. void TableListBoxModel::sortOrderChanged (int, const bool)
  36580. {
  36581. }
  36582. int TableListBoxModel::getColumnAutoSizeWidth (int)
  36583. {
  36584. return 0;
  36585. }
  36586. void TableListBoxModel::selectedRowsChanged (int)
  36587. {
  36588. }
  36589. void TableListBoxModel::deleteKeyPressed (int)
  36590. {
  36591. }
  36592. void TableListBoxModel::returnKeyPressed (int)
  36593. {
  36594. }
  36595. void TableListBoxModel::listWasScrolled()
  36596. {
  36597. }
  36598. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  36599. {
  36600. return String::empty;
  36601. }
  36602. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  36603. {
  36604. (void) existingComponentToUpdate;
  36605. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  36606. return 0;
  36607. }
  36608. END_JUCE_NAMESPACE
  36609. /********* End of inlined file: juce_TableListBox.cpp *********/
  36610. /********* Start of inlined file: juce_TextEditor.cpp *********/
  36611. BEGIN_JUCE_NAMESPACE
  36612. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  36613. // a word or space that can't be broken down any further
  36614. struct TextAtom
  36615. {
  36616. String atomText;
  36617. float width;
  36618. uint16 numChars;
  36619. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (atomText[0]); }
  36620. bool isNewLine() const throw() { return atomText[0] == T('\r') || atomText[0] == T('\n'); }
  36621. const String getText (const tchar passwordCharacter) const throw()
  36622. {
  36623. if (passwordCharacter == 0)
  36624. return atomText;
  36625. else
  36626. return String::repeatedString (String::charToString (passwordCharacter),
  36627. atomText.length());
  36628. }
  36629. const String getTrimmedText (const tchar passwordCharacter) const throw()
  36630. {
  36631. if (passwordCharacter == 0)
  36632. return atomText.substring (0, numChars);
  36633. else if (isNewLine())
  36634. return String::empty;
  36635. else
  36636. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  36637. }
  36638. };
  36639. // a run of text with a single font and colour
  36640. class UniformTextSection
  36641. {
  36642. public:
  36643. UniformTextSection (const String& text,
  36644. const Font& font_,
  36645. const Colour& colour_,
  36646. const tchar passwordCharacter) throw()
  36647. : font (font_),
  36648. colour (colour_),
  36649. atoms (64)
  36650. {
  36651. initialiseAtoms (text, passwordCharacter);
  36652. }
  36653. UniformTextSection (const UniformTextSection& other) throw()
  36654. : font (other.font),
  36655. colour (other.colour),
  36656. atoms (64)
  36657. {
  36658. for (int i = 0; i < other.atoms.size(); ++i)
  36659. atoms.add (new TextAtom (*(const TextAtom*) other.atoms.getUnchecked(i)));
  36660. }
  36661. ~UniformTextSection() throw()
  36662. {
  36663. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  36664. }
  36665. void clear() throw()
  36666. {
  36667. for (int i = atoms.size(); --i >= 0;)
  36668. {
  36669. TextAtom* const atom = getAtom(i);
  36670. delete atom;
  36671. }
  36672. atoms.clear();
  36673. }
  36674. int getNumAtoms() const throw()
  36675. {
  36676. return atoms.size();
  36677. }
  36678. TextAtom* getAtom (const int index) const throw()
  36679. {
  36680. return (TextAtom*) atoms.getUnchecked (index);
  36681. }
  36682. void append (const UniformTextSection& other, const tchar passwordCharacter) throw()
  36683. {
  36684. if (other.atoms.size() > 0)
  36685. {
  36686. TextAtom* const lastAtom = (TextAtom*) atoms.getLast();
  36687. int i = 0;
  36688. if (lastAtom != 0)
  36689. {
  36690. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  36691. {
  36692. TextAtom* const first = other.getAtom(0);
  36693. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  36694. {
  36695. lastAtom->atomText += first->atomText;
  36696. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  36697. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  36698. delete first;
  36699. ++i;
  36700. }
  36701. }
  36702. }
  36703. while (i < other.atoms.size())
  36704. {
  36705. atoms.add (other.getAtom(i));
  36706. ++i;
  36707. }
  36708. }
  36709. }
  36710. UniformTextSection* split (const int indexToBreakAt,
  36711. const tchar passwordCharacter) throw()
  36712. {
  36713. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  36714. font, colour,
  36715. passwordCharacter);
  36716. int index = 0;
  36717. for (int i = 0; i < atoms.size(); ++i)
  36718. {
  36719. TextAtom* const atom = getAtom(i);
  36720. const int nextIndex = index + atom->numChars;
  36721. if (index == indexToBreakAt)
  36722. {
  36723. int j;
  36724. for (j = i; j < atoms.size(); ++j)
  36725. section2->atoms.add (getAtom (j));
  36726. for (j = atoms.size(); --j >= i;)
  36727. atoms.remove (j);
  36728. break;
  36729. }
  36730. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  36731. {
  36732. TextAtom* const secondAtom = new TextAtom();
  36733. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  36734. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  36735. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  36736. section2->atoms.add (secondAtom);
  36737. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  36738. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  36739. atom->numChars = (uint16) (indexToBreakAt - index);
  36740. int j;
  36741. for (j = i + 1; j < atoms.size(); ++j)
  36742. section2->atoms.add (getAtom (j));
  36743. for (j = atoms.size(); --j > i;)
  36744. atoms.remove (j);
  36745. break;
  36746. }
  36747. index = nextIndex;
  36748. }
  36749. return section2;
  36750. }
  36751. const String getAllText() const throw()
  36752. {
  36753. String s;
  36754. s.preallocateStorage (getTotalLength());
  36755. tchar* endOfString = (tchar*) &(s[0]);
  36756. for (int i = 0; i < atoms.size(); ++i)
  36757. {
  36758. const TextAtom* const atom = getAtom(i);
  36759. memcpy (endOfString, &(atom->atomText[0]), atom->numChars * sizeof (tchar));
  36760. endOfString += atom->numChars;
  36761. }
  36762. *endOfString = 0;
  36763. jassert ((endOfString - (tchar*) &(s[0])) <= getTotalLength());
  36764. return s;
  36765. }
  36766. const String getTextSubstring (const int startCharacter,
  36767. const int endCharacter) const throw()
  36768. {
  36769. int index = 0;
  36770. int totalLen = 0;
  36771. int i;
  36772. for (i = 0; i < atoms.size(); ++i)
  36773. {
  36774. const TextAtom* const atom = getAtom (i);
  36775. const int nextIndex = index + atom->numChars;
  36776. if (startCharacter < nextIndex)
  36777. {
  36778. if (endCharacter <= index)
  36779. break;
  36780. const int start = jmax (0, startCharacter - index);
  36781. const int end = jmin (endCharacter - index, atom->numChars);
  36782. jassert (end >= start);
  36783. totalLen += end - start;
  36784. }
  36785. index = nextIndex;
  36786. }
  36787. String s;
  36788. s.preallocateStorage (totalLen + 1);
  36789. tchar* psz = (tchar*) (const tchar*) s;
  36790. index = 0;
  36791. for (i = 0; i < atoms.size(); ++i)
  36792. {
  36793. const TextAtom* const atom = getAtom (i);
  36794. const int nextIndex = index + atom->numChars;
  36795. if (startCharacter < nextIndex)
  36796. {
  36797. if (endCharacter <= index)
  36798. break;
  36799. const int start = jmax (0, startCharacter - index);
  36800. const int len = jmin (endCharacter - index, atom->numChars) - start;
  36801. memcpy (psz, ((const tchar*) atom->atomText) + start, len * sizeof (tchar));
  36802. psz += len;
  36803. *psz = 0;
  36804. }
  36805. index = nextIndex;
  36806. }
  36807. return s;
  36808. }
  36809. int getTotalLength() const throw()
  36810. {
  36811. int c = 0;
  36812. for (int i = atoms.size(); --i >= 0;)
  36813. c += getAtom(i)->numChars;
  36814. return c;
  36815. }
  36816. void setFont (const Font& newFont,
  36817. const tchar passwordCharacter) throw()
  36818. {
  36819. if (font != newFont)
  36820. {
  36821. font = newFont;
  36822. for (int i = atoms.size(); --i >= 0;)
  36823. {
  36824. TextAtom* const atom = (TextAtom*) atoms.getUnchecked(i);
  36825. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  36826. }
  36827. }
  36828. }
  36829. juce_UseDebuggingNewOperator
  36830. Font font;
  36831. Colour colour;
  36832. private:
  36833. VoidArray atoms;
  36834. void initialiseAtoms (const String& textToParse,
  36835. const tchar passwordCharacter) throw()
  36836. {
  36837. int i = 0;
  36838. const int len = textToParse.length();
  36839. const tchar* const text = (const tchar*) textToParse;
  36840. while (i < len)
  36841. {
  36842. int start = i;
  36843. // create a whitespace atom unless it starts with non-ws
  36844. if (CharacterFunctions::isWhitespace (text[i])
  36845. && text[i] != T('\r')
  36846. && text[i] != T('\n'))
  36847. {
  36848. while (i < len
  36849. && CharacterFunctions::isWhitespace (text[i])
  36850. && text[i] != T('\r')
  36851. && text[i] != T('\n'))
  36852. {
  36853. ++i;
  36854. }
  36855. }
  36856. else
  36857. {
  36858. if (text[i] == T('\r'))
  36859. {
  36860. ++i;
  36861. if ((i < len) && (text[i] == T('\n')))
  36862. {
  36863. ++start;
  36864. ++i;
  36865. }
  36866. }
  36867. else if (text[i] == T('\n'))
  36868. {
  36869. ++i;
  36870. }
  36871. else
  36872. {
  36873. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  36874. ++i;
  36875. }
  36876. }
  36877. TextAtom* const atom = new TextAtom();
  36878. atom->atomText = String (text + start, i - start);
  36879. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  36880. atom->numChars = (uint16) (i - start);
  36881. atoms.add (atom);
  36882. }
  36883. }
  36884. const UniformTextSection& operator= (const UniformTextSection& other);
  36885. };
  36886. class TextEditorIterator
  36887. {
  36888. public:
  36889. TextEditorIterator (const VoidArray& sections_,
  36890. const float wordWrapWidth_,
  36891. const tchar passwordCharacter_) throw()
  36892. : indexInText (0),
  36893. lineY (0),
  36894. lineHeight (0),
  36895. maxDescent (0),
  36896. atomX (0),
  36897. atomRight (0),
  36898. atom (0),
  36899. currentSection (0),
  36900. sections (sections_),
  36901. sectionIndex (0),
  36902. atomIndex (0),
  36903. wordWrapWidth (wordWrapWidth_),
  36904. passwordCharacter (passwordCharacter_)
  36905. {
  36906. jassert (wordWrapWidth_ > 0);
  36907. if (sections.size() > 0)
  36908. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  36909. if (currentSection != 0)
  36910. {
  36911. lineHeight = currentSection->font.getHeight();
  36912. maxDescent = currentSection->font.getDescent();
  36913. }
  36914. }
  36915. TextEditorIterator (const TextEditorIterator& other) throw()
  36916. : indexInText (other.indexInText),
  36917. lineY (other.lineY),
  36918. lineHeight (other.lineHeight),
  36919. maxDescent (other.maxDescent),
  36920. atomX (other.atomX),
  36921. atomRight (other.atomRight),
  36922. atom (other.atom),
  36923. currentSection (other.currentSection),
  36924. sections (other.sections),
  36925. sectionIndex (other.sectionIndex),
  36926. atomIndex (other.atomIndex),
  36927. wordWrapWidth (other.wordWrapWidth),
  36928. passwordCharacter (other.passwordCharacter),
  36929. tempAtom (other.tempAtom)
  36930. {
  36931. }
  36932. ~TextEditorIterator() throw()
  36933. {
  36934. }
  36935. bool next() throw()
  36936. {
  36937. if (atom == &tempAtom)
  36938. {
  36939. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  36940. if (numRemaining > 0)
  36941. {
  36942. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  36943. atomX = 0;
  36944. if (tempAtom.numChars > 0)
  36945. lineY += lineHeight;
  36946. indexInText += tempAtom.numChars;
  36947. GlyphArrangement g;
  36948. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  36949. int split;
  36950. for (split = 0; split < g.getNumGlyphs(); ++split)
  36951. if (SHOULD_WRAP (g.getGlyph (split).getRight(), wordWrapWidth))
  36952. break;
  36953. if (split > 0 && split <= numRemaining)
  36954. {
  36955. tempAtom.numChars = (uint16) split;
  36956. tempAtom.width = g.getGlyph (split - 1).getRight();
  36957. atomRight = atomX + tempAtom.width;
  36958. return true;
  36959. }
  36960. }
  36961. }
  36962. bool forceNewLine = false;
  36963. if (sectionIndex >= sections.size())
  36964. {
  36965. moveToEndOfLastAtom();
  36966. return false;
  36967. }
  36968. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  36969. {
  36970. if (atomIndex >= currentSection->getNumAtoms())
  36971. {
  36972. if (++sectionIndex >= sections.size())
  36973. {
  36974. moveToEndOfLastAtom();
  36975. return false;
  36976. }
  36977. atomIndex = 0;
  36978. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  36979. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  36980. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  36981. }
  36982. else
  36983. {
  36984. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  36985. if (! lastAtom->isWhitespace())
  36986. {
  36987. // handle the case where the last atom in a section is actually part of the same
  36988. // word as the first atom of the next section...
  36989. float right = atomRight + lastAtom->width;
  36990. float lineHeight2 = lineHeight;
  36991. float maxDescent2 = maxDescent;
  36992. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  36993. {
  36994. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked (section);
  36995. if (s->getNumAtoms() == 0)
  36996. break;
  36997. const TextAtom* const nextAtom = s->getAtom (0);
  36998. if (nextAtom->isWhitespace())
  36999. break;
  37000. right += nextAtom->width;
  37001. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  37002. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  37003. if (SHOULD_WRAP (right, wordWrapWidth))
  37004. {
  37005. lineHeight = lineHeight2;
  37006. maxDescent = maxDescent2;
  37007. forceNewLine = true;
  37008. break;
  37009. }
  37010. if (s->getNumAtoms() > 1)
  37011. break;
  37012. }
  37013. }
  37014. }
  37015. }
  37016. if (atom != 0)
  37017. {
  37018. atomX = atomRight;
  37019. indexInText += atom->numChars;
  37020. if (atom->isNewLine())
  37021. {
  37022. atomX = 0;
  37023. lineY += lineHeight;
  37024. }
  37025. }
  37026. atom = currentSection->getAtom (atomIndex);
  37027. atomRight = atomX + atom->width;
  37028. ++atomIndex;
  37029. if (SHOULD_WRAP (atomRight, wordWrapWidth) || forceNewLine)
  37030. {
  37031. if (atom->isWhitespace())
  37032. {
  37033. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  37034. atomRight = jmin (atomRight, wordWrapWidth);
  37035. }
  37036. else
  37037. {
  37038. return wrapCurrentAtom();
  37039. }
  37040. }
  37041. return true;
  37042. }
  37043. bool wrapCurrentAtom() throw()
  37044. {
  37045. atomRight = atom->width;
  37046. if (SHOULD_WRAP (atomRight, wordWrapWidth)) // atom too big to fit on a line, so break it up..
  37047. {
  37048. tempAtom = *atom;
  37049. tempAtom.width = 0;
  37050. tempAtom.numChars = 0;
  37051. atom = &tempAtom;
  37052. if (atomX > 0)
  37053. {
  37054. atomX = 0;
  37055. lineY += lineHeight;
  37056. }
  37057. return next();
  37058. }
  37059. atomX = 0;
  37060. lineY += lineHeight;
  37061. return true;
  37062. }
  37063. void draw (Graphics& g, const UniformTextSection*& lastSection) const throw()
  37064. {
  37065. if (passwordCharacter != 0 || ! atom->isWhitespace())
  37066. {
  37067. if (lastSection != currentSection)
  37068. {
  37069. lastSection = currentSection;
  37070. g.setColour (currentSection->colour);
  37071. g.setFont (currentSection->font);
  37072. }
  37073. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  37074. GlyphArrangement ga;
  37075. ga.addLineOfText (currentSection->font,
  37076. atom->getTrimmedText (passwordCharacter),
  37077. atomX,
  37078. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  37079. ga.draw (g);
  37080. }
  37081. }
  37082. void drawSelection (Graphics& g,
  37083. const int selectionStart,
  37084. const int selectionEnd) const throw()
  37085. {
  37086. const int startX = roundFloatToInt (indexToX (selectionStart));
  37087. const int endX = roundFloatToInt (indexToX (selectionEnd));
  37088. const int y = roundFloatToInt (lineY);
  37089. const int nextY = roundFloatToInt (lineY + lineHeight);
  37090. g.fillRect (startX, y, endX - startX, nextY - y);
  37091. }
  37092. void drawSelectedText (Graphics& g,
  37093. const int selectionStart,
  37094. const int selectionEnd,
  37095. const Colour& selectedTextColour) const throw()
  37096. {
  37097. if (passwordCharacter != 0 || ! atom->isWhitespace())
  37098. {
  37099. GlyphArrangement ga;
  37100. ga.addLineOfText (currentSection->font,
  37101. atom->getTrimmedText (passwordCharacter),
  37102. atomX,
  37103. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  37104. if (selectionEnd < indexInText + atom->numChars)
  37105. {
  37106. GlyphArrangement ga2 (ga);
  37107. ga2.removeRangeOfGlyphs (0, selectionEnd - indexInText);
  37108. ga.removeRangeOfGlyphs (selectionEnd - indexInText, -1);
  37109. g.setColour (currentSection->colour);
  37110. ga2.draw (g);
  37111. }
  37112. if (selectionStart > indexInText)
  37113. {
  37114. GlyphArrangement ga2 (ga);
  37115. ga2.removeRangeOfGlyphs (selectionStart - indexInText, -1);
  37116. ga.removeRangeOfGlyphs (0, selectionStart - indexInText);
  37117. g.setColour (currentSection->colour);
  37118. ga2.draw (g);
  37119. }
  37120. g.setColour (selectedTextColour);
  37121. ga.draw (g);
  37122. }
  37123. }
  37124. float indexToX (const int indexToFind) const throw()
  37125. {
  37126. if (indexToFind <= indexInText)
  37127. return atomX;
  37128. if (indexToFind >= indexInText + atom->numChars)
  37129. return atomRight;
  37130. GlyphArrangement g;
  37131. g.addLineOfText (currentSection->font,
  37132. atom->getText (passwordCharacter),
  37133. atomX, 0.0f);
  37134. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  37135. }
  37136. int xToIndex (const float xToFind) const throw()
  37137. {
  37138. if (xToFind <= atomX || atom->isNewLine())
  37139. return indexInText;
  37140. if (xToFind >= atomRight)
  37141. return indexInText + atom->numChars;
  37142. GlyphArrangement g;
  37143. g.addLineOfText (currentSection->font,
  37144. atom->getText (passwordCharacter),
  37145. atomX, 0.0f);
  37146. int j;
  37147. for (j = 0; j < atom->numChars; ++j)
  37148. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  37149. break;
  37150. return indexInText + j;
  37151. }
  37152. void updateLineHeight() throw()
  37153. {
  37154. float x = atomRight;
  37155. int tempSectionIndex = sectionIndex;
  37156. int tempAtomIndex = atomIndex;
  37157. const UniformTextSection* currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  37158. while (! SHOULD_WRAP (x, wordWrapWidth))
  37159. {
  37160. if (tempSectionIndex >= sections.size())
  37161. break;
  37162. bool checkSize = false;
  37163. if (tempAtomIndex >= currentSection->getNumAtoms())
  37164. {
  37165. if (++tempSectionIndex >= sections.size())
  37166. break;
  37167. tempAtomIndex = 0;
  37168. currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  37169. checkSize = true;
  37170. }
  37171. const TextAtom* const atom = currentSection->getAtom (tempAtomIndex);
  37172. if (atom == 0)
  37173. break;
  37174. x += atom->width;
  37175. if (SHOULD_WRAP (x, wordWrapWidth) || atom->isNewLine())
  37176. break;
  37177. if (checkSize)
  37178. {
  37179. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  37180. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  37181. }
  37182. ++tempAtomIndex;
  37183. }
  37184. }
  37185. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_) throw()
  37186. {
  37187. while (next())
  37188. {
  37189. if (indexInText + atom->numChars >= index)
  37190. {
  37191. updateLineHeight();
  37192. if (indexInText + atom->numChars > index)
  37193. {
  37194. cx = indexToX (index);
  37195. cy = lineY;
  37196. lineHeight_ = lineHeight;
  37197. return true;
  37198. }
  37199. }
  37200. }
  37201. cx = atomX;
  37202. cy = lineY;
  37203. lineHeight_ = lineHeight;
  37204. return false;
  37205. }
  37206. juce_UseDebuggingNewOperator
  37207. int indexInText;
  37208. float lineY, lineHeight, maxDescent;
  37209. float atomX, atomRight;
  37210. const TextAtom* atom;
  37211. const UniformTextSection* currentSection;
  37212. private:
  37213. const VoidArray& sections;
  37214. int sectionIndex, atomIndex;
  37215. const float wordWrapWidth;
  37216. const tchar passwordCharacter;
  37217. TextAtom tempAtom;
  37218. const TextEditorIterator& operator= (const TextEditorIterator&);
  37219. void moveToEndOfLastAtom() throw()
  37220. {
  37221. if (atom != 0)
  37222. {
  37223. atomX = atomRight;
  37224. if (atom->isNewLine())
  37225. {
  37226. atomX = 0.0f;
  37227. lineY += lineHeight;
  37228. }
  37229. }
  37230. }
  37231. };
  37232. class TextEditorInsertAction : public UndoableAction
  37233. {
  37234. TextEditor& owner;
  37235. const String text;
  37236. const int insertIndex, oldCaretPos, newCaretPos;
  37237. const Font font;
  37238. const Colour colour;
  37239. TextEditorInsertAction (const TextEditorInsertAction&);
  37240. const TextEditorInsertAction& operator= (const TextEditorInsertAction&);
  37241. public:
  37242. TextEditorInsertAction (TextEditor& owner_,
  37243. const String& text_,
  37244. const int insertIndex_,
  37245. const Font& font_,
  37246. const Colour& colour_,
  37247. const int oldCaretPos_,
  37248. const int newCaretPos_) throw()
  37249. : owner (owner_),
  37250. text (text_),
  37251. insertIndex (insertIndex_),
  37252. oldCaretPos (oldCaretPos_),
  37253. newCaretPos (newCaretPos_),
  37254. font (font_),
  37255. colour (colour_)
  37256. {
  37257. }
  37258. ~TextEditorInsertAction()
  37259. {
  37260. }
  37261. bool perform()
  37262. {
  37263. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  37264. return true;
  37265. }
  37266. bool undo()
  37267. {
  37268. owner.remove (insertIndex, insertIndex + text.length(), 0, oldCaretPos);
  37269. return true;
  37270. }
  37271. int getSizeInUnits()
  37272. {
  37273. return text.length() + 16;
  37274. }
  37275. };
  37276. class TextEditorRemoveAction : public UndoableAction
  37277. {
  37278. TextEditor& owner;
  37279. const int startIndex, endIndex, oldCaretPos, newCaretPos;
  37280. VoidArray removedSections;
  37281. TextEditorRemoveAction (const TextEditorRemoveAction&);
  37282. const TextEditorRemoveAction& operator= (const TextEditorRemoveAction&);
  37283. public:
  37284. TextEditorRemoveAction (TextEditor& owner_,
  37285. const int startIndex_,
  37286. const int endIndex_,
  37287. const int oldCaretPos_,
  37288. const int newCaretPos_,
  37289. const VoidArray& removedSections_) throw()
  37290. : owner (owner_),
  37291. startIndex (startIndex_),
  37292. endIndex (endIndex_),
  37293. oldCaretPos (oldCaretPos_),
  37294. newCaretPos (newCaretPos_),
  37295. removedSections (removedSections_)
  37296. {
  37297. }
  37298. ~TextEditorRemoveAction()
  37299. {
  37300. for (int i = removedSections.size(); --i >= 0;)
  37301. {
  37302. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  37303. section->clear();
  37304. delete section;
  37305. }
  37306. }
  37307. bool perform()
  37308. {
  37309. owner.remove (startIndex, endIndex, 0, newCaretPos);
  37310. return true;
  37311. }
  37312. bool undo()
  37313. {
  37314. owner.reinsert (startIndex, removedSections);
  37315. owner.moveCursorTo (oldCaretPos, false);
  37316. return true;
  37317. }
  37318. int getSizeInUnits()
  37319. {
  37320. int n = 0;
  37321. for (int i = removedSections.size(); --i >= 0;)
  37322. {
  37323. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  37324. n += section->getTotalLength();
  37325. }
  37326. return n + 16;
  37327. }
  37328. };
  37329. class TextHolderComponent : public Component,
  37330. public Timer
  37331. {
  37332. TextEditor* const owner;
  37333. TextHolderComponent (const TextHolderComponent&);
  37334. const TextHolderComponent& operator= (const TextHolderComponent&);
  37335. public:
  37336. TextHolderComponent (TextEditor* const owner_)
  37337. : owner (owner_)
  37338. {
  37339. setWantsKeyboardFocus (false);
  37340. setInterceptsMouseClicks (false, true);
  37341. }
  37342. ~TextHolderComponent()
  37343. {
  37344. }
  37345. void paint (Graphics& g)
  37346. {
  37347. owner->drawContent (g);
  37348. }
  37349. void timerCallback()
  37350. {
  37351. owner->timerCallbackInt();
  37352. }
  37353. const MouseCursor getMouseCursor()
  37354. {
  37355. return owner->getMouseCursor();
  37356. }
  37357. };
  37358. class TextEditorViewport : public Viewport
  37359. {
  37360. TextEditor* const owner;
  37361. float lastWordWrapWidth;
  37362. TextEditorViewport (const TextEditorViewport&);
  37363. const TextEditorViewport& operator= (const TextEditorViewport&);
  37364. public:
  37365. TextEditorViewport (TextEditor* const owner_)
  37366. : owner (owner_),
  37367. lastWordWrapWidth (0)
  37368. {
  37369. }
  37370. ~TextEditorViewport()
  37371. {
  37372. }
  37373. void visibleAreaChanged (int, int, int, int)
  37374. {
  37375. const float wordWrapWidth = owner->getWordWrapWidth();
  37376. if (wordWrapWidth != lastWordWrapWidth)
  37377. {
  37378. lastWordWrapWidth = wordWrapWidth;
  37379. owner->updateTextHolderSize();
  37380. }
  37381. }
  37382. };
  37383. const int flashSpeedIntervalMs = 380;
  37384. const int textChangeMessageId = 0x10003001;
  37385. const int returnKeyMessageId = 0x10003002;
  37386. const int escapeKeyMessageId = 0x10003003;
  37387. const int focusLossMessageId = 0x10003004;
  37388. TextEditor::TextEditor (const String& name,
  37389. const tchar passwordCharacter_)
  37390. : Component (name),
  37391. borderSize (1, 1, 1, 3),
  37392. readOnly (false),
  37393. multiline (false),
  37394. wordWrap (false),
  37395. returnKeyStartsNewLine (false),
  37396. caretVisible (true),
  37397. popupMenuEnabled (true),
  37398. selectAllTextWhenFocused (false),
  37399. scrollbarVisible (true),
  37400. wasFocused (false),
  37401. caretFlashState (true),
  37402. keepCursorOnScreen (true),
  37403. tabKeyUsed (false),
  37404. menuActive (false),
  37405. cursorX (0),
  37406. cursorY (0),
  37407. cursorHeight (0),
  37408. maxTextLength (0),
  37409. selectionStart (0),
  37410. selectionEnd (0),
  37411. leftIndent (4),
  37412. topIndent (4),
  37413. lastTransactionTime (0),
  37414. currentFont (14.0f),
  37415. totalNumChars (0),
  37416. caretPosition (0),
  37417. sections (8),
  37418. passwordCharacter (passwordCharacter_),
  37419. dragType (notDragging),
  37420. listeners (2)
  37421. {
  37422. setOpaque (true);
  37423. addAndMakeVisible (viewport = new TextEditorViewport (this));
  37424. viewport->setViewedComponent (textHolder = new TextHolderComponent (this));
  37425. viewport->setWantsKeyboardFocus (false);
  37426. viewport->setScrollBarsShown (false, false);
  37427. setMouseCursor (MouseCursor::IBeamCursor);
  37428. setWantsKeyboardFocus (true);
  37429. }
  37430. TextEditor::~TextEditor()
  37431. {
  37432. clearInternal (0);
  37433. delete viewport;
  37434. }
  37435. void TextEditor::newTransaction() throw()
  37436. {
  37437. lastTransactionTime = Time::getApproximateMillisecondCounter();
  37438. undoManager.beginNewTransaction();
  37439. }
  37440. void TextEditor::doUndoRedo (const bool isRedo)
  37441. {
  37442. if (! isReadOnly())
  37443. {
  37444. if ((isRedo) ? undoManager.redo()
  37445. : undoManager.undo())
  37446. {
  37447. scrollToMakeSureCursorIsVisible();
  37448. repaint();
  37449. textChanged();
  37450. }
  37451. }
  37452. }
  37453. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  37454. const bool shouldWordWrap)
  37455. {
  37456. multiline = shouldBeMultiLine;
  37457. wordWrap = shouldWordWrap && shouldBeMultiLine;
  37458. setScrollbarsShown (scrollbarVisible);
  37459. viewport->setViewPosition (0, 0);
  37460. resized();
  37461. scrollToMakeSureCursorIsVisible();
  37462. }
  37463. bool TextEditor::isMultiLine() const throw()
  37464. {
  37465. return multiline;
  37466. }
  37467. void TextEditor::setScrollbarsShown (bool enabled) throw()
  37468. {
  37469. scrollbarVisible = enabled;
  37470. enabled = enabled && isMultiLine();
  37471. viewport->setScrollBarsShown (enabled, enabled);
  37472. }
  37473. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  37474. {
  37475. readOnly = shouldBeReadOnly;
  37476. enablementChanged();
  37477. }
  37478. bool TextEditor::isReadOnly() const throw()
  37479. {
  37480. return readOnly || ! isEnabled();
  37481. }
  37482. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  37483. {
  37484. returnKeyStartsNewLine = shouldStartNewLine;
  37485. }
  37486. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw()
  37487. {
  37488. tabKeyUsed = shouldTabKeyBeUsed;
  37489. }
  37490. void TextEditor::setPopupMenuEnabled (const bool b) throw()
  37491. {
  37492. popupMenuEnabled = b;
  37493. }
  37494. void TextEditor::setSelectAllWhenFocused (const bool b) throw()
  37495. {
  37496. selectAllTextWhenFocused = b;
  37497. }
  37498. const Font TextEditor::getFont() const throw()
  37499. {
  37500. return currentFont;
  37501. }
  37502. void TextEditor::setFont (const Font& newFont) throw()
  37503. {
  37504. currentFont = newFont;
  37505. scrollToMakeSureCursorIsVisible();
  37506. }
  37507. void TextEditor::applyFontToAllText (const Font& newFont)
  37508. {
  37509. currentFont = newFont;
  37510. const Colour overallColour (findColour (textColourId));
  37511. for (int i = sections.size(); --i >= 0;)
  37512. {
  37513. UniformTextSection* const uts = (UniformTextSection*) sections.getUnchecked(i);
  37514. uts->setFont (newFont, passwordCharacter);
  37515. uts->colour = overallColour;
  37516. }
  37517. coalesceSimilarSections();
  37518. updateTextHolderSize();
  37519. scrollToMakeSureCursorIsVisible();
  37520. repaint();
  37521. }
  37522. void TextEditor::colourChanged()
  37523. {
  37524. setOpaque (findColour (backgroundColourId).isOpaque());
  37525. repaint();
  37526. }
  37527. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible) throw()
  37528. {
  37529. caretVisible = shouldCaretBeVisible;
  37530. if (shouldCaretBeVisible)
  37531. textHolder->startTimer (flashSpeedIntervalMs);
  37532. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  37533. : MouseCursor::NormalCursor);
  37534. }
  37535. void TextEditor::setInputRestrictions (const int maxLen,
  37536. const String& chars) throw()
  37537. {
  37538. maxTextLength = jmax (0, maxLen);
  37539. allowedCharacters = chars;
  37540. }
  37541. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw()
  37542. {
  37543. textToShowWhenEmpty = text;
  37544. colourForTextWhenEmpty = colourToUse;
  37545. }
  37546. void TextEditor::setPasswordCharacter (const tchar newPasswordCharacter) throw()
  37547. {
  37548. if (passwordCharacter != newPasswordCharacter)
  37549. {
  37550. passwordCharacter = newPasswordCharacter;
  37551. resized();
  37552. repaint();
  37553. }
  37554. }
  37555. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  37556. {
  37557. viewport->setScrollBarThickness (newThicknessPixels);
  37558. }
  37559. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  37560. {
  37561. viewport->setScrollBarButtonVisibility (buttonsVisible);
  37562. }
  37563. void TextEditor::clear()
  37564. {
  37565. clearInternal (0);
  37566. updateTextHolderSize();
  37567. undoManager.clearUndoHistory();
  37568. }
  37569. void TextEditor::setText (const String& newText,
  37570. const bool sendTextChangeMessage)
  37571. {
  37572. const int newLength = newText.length();
  37573. if (newLength != getTotalNumChars() || getText() != newText)
  37574. {
  37575. const int oldCursorPos = caretPosition;
  37576. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  37577. clearInternal (0);
  37578. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  37579. // if you're adding text with line-feeds to a single-line text editor, it
  37580. // ain't gonna look right!
  37581. jassert (multiline || ! newText.containsAnyOf (T("\r\n")));
  37582. if (cursorWasAtEnd && ! isMultiLine())
  37583. moveCursorTo (getTotalNumChars(), false);
  37584. else
  37585. moveCursorTo (oldCursorPos, false);
  37586. if (sendTextChangeMessage)
  37587. textChanged();
  37588. repaint();
  37589. }
  37590. updateTextHolderSize();
  37591. scrollToMakeSureCursorIsVisible();
  37592. undoManager.clearUndoHistory();
  37593. }
  37594. void TextEditor::textChanged() throw()
  37595. {
  37596. updateTextHolderSize();
  37597. postCommandMessage (textChangeMessageId);
  37598. }
  37599. void TextEditor::returnPressed()
  37600. {
  37601. postCommandMessage (returnKeyMessageId);
  37602. }
  37603. void TextEditor::escapePressed()
  37604. {
  37605. postCommandMessage (escapeKeyMessageId);
  37606. }
  37607. void TextEditor::addListener (TextEditorListener* const newListener) throw()
  37608. {
  37609. jassert (newListener != 0)
  37610. if (newListener != 0)
  37611. listeners.add (newListener);
  37612. }
  37613. void TextEditor::removeListener (TextEditorListener* const listenerToRemove) throw()
  37614. {
  37615. listeners.removeValue (listenerToRemove);
  37616. }
  37617. void TextEditor::timerCallbackInt()
  37618. {
  37619. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  37620. if (caretFlashState != newState)
  37621. {
  37622. caretFlashState = newState;
  37623. if (caretFlashState)
  37624. wasFocused = true;
  37625. if (caretVisible
  37626. && hasKeyboardFocus (false)
  37627. && ! isReadOnly())
  37628. {
  37629. repaintCaret();
  37630. }
  37631. }
  37632. const unsigned int now = Time::getApproximateMillisecondCounter();
  37633. if (now > lastTransactionTime + 200)
  37634. newTransaction();
  37635. }
  37636. void TextEditor::repaintCaret()
  37637. {
  37638. if (! findColour (caretColourId).isTransparent())
  37639. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundFloatToInt (cursorX) - 1,
  37640. borderSize.getTop() + textHolder->getY() + topIndent + roundFloatToInt (cursorY) - 1,
  37641. 4,
  37642. roundFloatToInt (cursorHeight) + 2);
  37643. }
  37644. void TextEditor::repaintText (int textStartIndex, int textEndIndex)
  37645. {
  37646. if (textStartIndex > textEndIndex && textEndIndex > 0)
  37647. swapVariables (textStartIndex, textEndIndex);
  37648. float x = 0, y = 0, lh = currentFont.getHeight();
  37649. const float wordWrapWidth = getWordWrapWidth();
  37650. if (wordWrapWidth > 0)
  37651. {
  37652. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  37653. i.getCharPosition (textStartIndex, x, y, lh);
  37654. const int y1 = (int) y;
  37655. int y2;
  37656. if (textEndIndex >= 0)
  37657. {
  37658. i.getCharPosition (textEndIndex, x, y, lh);
  37659. y2 = (int) (y + lh * 2.0f);
  37660. }
  37661. else
  37662. {
  37663. y2 = textHolder->getHeight();
  37664. }
  37665. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  37666. }
  37667. }
  37668. void TextEditor::moveCaret (int newCaretPos) throw()
  37669. {
  37670. if (newCaretPos < 0)
  37671. newCaretPos = 0;
  37672. else if (newCaretPos > getTotalNumChars())
  37673. newCaretPos = getTotalNumChars();
  37674. if (newCaretPos != getCaretPosition())
  37675. {
  37676. repaintCaret();
  37677. caretFlashState = true;
  37678. caretPosition = newCaretPos;
  37679. textHolder->startTimer (flashSpeedIntervalMs);
  37680. scrollToMakeSureCursorIsVisible();
  37681. repaintCaret();
  37682. }
  37683. }
  37684. void TextEditor::setCaretPosition (const int newIndex) throw()
  37685. {
  37686. moveCursorTo (newIndex, false);
  37687. }
  37688. int TextEditor::getCaretPosition() const throw()
  37689. {
  37690. return caretPosition;
  37691. }
  37692. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  37693. const int desiredCaretY) throw()
  37694. {
  37695. updateCaretPosition();
  37696. int vx = roundFloatToInt (cursorX) - desiredCaretX;
  37697. int vy = roundFloatToInt (cursorY) - desiredCaretY;
  37698. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  37699. {
  37700. vx += desiredCaretX - proportionOfWidth (0.2f);
  37701. }
  37702. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  37703. {
  37704. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  37705. }
  37706. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  37707. if (! isMultiLine())
  37708. {
  37709. vy = viewport->getViewPositionY();
  37710. }
  37711. else
  37712. {
  37713. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  37714. const int curH = roundFloatToInt (cursorHeight);
  37715. if (desiredCaretY < 0)
  37716. {
  37717. vy = jmax (0, desiredCaretY + vy);
  37718. }
  37719. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  37720. {
  37721. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  37722. }
  37723. }
  37724. viewport->setViewPosition (vx, vy);
  37725. }
  37726. const Rectangle TextEditor::getCaretRectangle() throw()
  37727. {
  37728. updateCaretPosition();
  37729. return Rectangle (roundFloatToInt (cursorX) - viewport->getX(),
  37730. roundFloatToInt (cursorY) - viewport->getY(),
  37731. 1, roundFloatToInt (cursorHeight));
  37732. }
  37733. float TextEditor::getWordWrapWidth() const throw()
  37734. {
  37735. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  37736. : 1.0e10f;
  37737. }
  37738. void TextEditor::updateTextHolderSize() throw()
  37739. {
  37740. const float wordWrapWidth = getWordWrapWidth();
  37741. if (wordWrapWidth > 0)
  37742. {
  37743. float maxWidth = 0.0f;
  37744. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  37745. while (i.next())
  37746. maxWidth = jmax (maxWidth, i.atomRight);
  37747. const int w = leftIndent + roundFloatToInt (maxWidth);
  37748. const int h = topIndent + roundFloatToInt (jmax (i.lineY + i.lineHeight,
  37749. currentFont.getHeight()));
  37750. textHolder->setSize (w + 1, h + 1);
  37751. }
  37752. }
  37753. int TextEditor::getTextWidth() const throw()
  37754. {
  37755. return textHolder->getWidth();
  37756. }
  37757. int TextEditor::getTextHeight() const throw()
  37758. {
  37759. return textHolder->getHeight();
  37760. }
  37761. void TextEditor::setIndents (const int newLeftIndent,
  37762. const int newTopIndent) throw()
  37763. {
  37764. leftIndent = newLeftIndent;
  37765. topIndent = newTopIndent;
  37766. }
  37767. void TextEditor::setBorder (const BorderSize& border) throw()
  37768. {
  37769. borderSize = border;
  37770. resized();
  37771. }
  37772. const BorderSize TextEditor::getBorder() const throw()
  37773. {
  37774. return borderSize;
  37775. }
  37776. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor) throw()
  37777. {
  37778. keepCursorOnScreen = shouldScrollToShowCursor;
  37779. }
  37780. void TextEditor::updateCaretPosition() throw()
  37781. {
  37782. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  37783. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  37784. }
  37785. void TextEditor::scrollToMakeSureCursorIsVisible() throw()
  37786. {
  37787. updateCaretPosition();
  37788. if (keepCursorOnScreen)
  37789. {
  37790. int x = viewport->getViewPositionX();
  37791. int y = viewport->getViewPositionY();
  37792. const int relativeCursorX = roundFloatToInt (cursorX) - x;
  37793. const int relativeCursorY = roundFloatToInt (cursorY) - y;
  37794. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  37795. {
  37796. x += relativeCursorX - proportionOfWidth (0.2f);
  37797. }
  37798. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  37799. {
  37800. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  37801. }
  37802. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  37803. if (! isMultiLine())
  37804. {
  37805. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  37806. }
  37807. else
  37808. {
  37809. const int curH = roundFloatToInt (cursorHeight);
  37810. if (relativeCursorY < 0)
  37811. {
  37812. y = jmax (0, relativeCursorY + y);
  37813. }
  37814. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  37815. {
  37816. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  37817. }
  37818. }
  37819. viewport->setViewPosition (x, y);
  37820. }
  37821. }
  37822. void TextEditor::moveCursorTo (const int newPosition,
  37823. const bool isSelecting) throw()
  37824. {
  37825. if (isSelecting)
  37826. {
  37827. moveCaret (newPosition);
  37828. const int oldSelStart = selectionStart;
  37829. const int oldSelEnd = selectionEnd;
  37830. if (dragType == notDragging)
  37831. {
  37832. if (abs (getCaretPosition() - selectionStart) < abs (getCaretPosition() - selectionEnd))
  37833. dragType = draggingSelectionStart;
  37834. else
  37835. dragType = draggingSelectionEnd;
  37836. }
  37837. if (dragType == draggingSelectionStart)
  37838. {
  37839. selectionStart = getCaretPosition();
  37840. if (selectionEnd < selectionStart)
  37841. {
  37842. swapVariables (selectionStart, selectionEnd);
  37843. dragType = draggingSelectionEnd;
  37844. }
  37845. }
  37846. else
  37847. {
  37848. selectionEnd = getCaretPosition();
  37849. if (selectionEnd < selectionStart)
  37850. {
  37851. swapVariables (selectionStart, selectionEnd);
  37852. dragType = draggingSelectionStart;
  37853. }
  37854. }
  37855. jassert (selectionStart <= selectionEnd);
  37856. jassert (oldSelStart <= oldSelEnd);
  37857. repaintText (jmin (oldSelStart, selectionStart),
  37858. jmax (oldSelEnd, selectionEnd));
  37859. }
  37860. else
  37861. {
  37862. dragType = notDragging;
  37863. if (selectionEnd > selectionStart)
  37864. repaintText (selectionStart, selectionEnd);
  37865. moveCaret (newPosition);
  37866. selectionStart = getCaretPosition();
  37867. selectionEnd = getCaretPosition();
  37868. }
  37869. }
  37870. int TextEditor::getTextIndexAt (const int x,
  37871. const int y) throw()
  37872. {
  37873. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  37874. (float) (y + viewport->getViewPositionY() - topIndent));
  37875. }
  37876. void TextEditor::insertTextAtCursor (String newText)
  37877. {
  37878. if (allowedCharacters.isNotEmpty())
  37879. newText = newText.retainCharacters (allowedCharacters);
  37880. if (! isMultiLine())
  37881. newText = newText.replaceCharacters (T("\r\n"), T(" "));
  37882. else
  37883. newText = newText.replace (T("\r\n"), T("\n"));
  37884. const int newCaretPos = selectionStart + newText.length();
  37885. const int insertIndex = selectionStart;
  37886. remove (selectionStart, selectionEnd,
  37887. &undoManager,
  37888. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  37889. if (maxTextLength > 0)
  37890. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  37891. if (newText.isNotEmpty())
  37892. insert (newText,
  37893. insertIndex,
  37894. currentFont,
  37895. findColour (textColourId),
  37896. &undoManager,
  37897. newCaretPos);
  37898. textChanged();
  37899. }
  37900. void TextEditor::setHighlightedRegion (int startPos, int numChars) throw()
  37901. {
  37902. moveCursorTo (startPos, false);
  37903. moveCursorTo (startPos + numChars, true);
  37904. }
  37905. void TextEditor::copy()
  37906. {
  37907. const String selection (getTextSubstring (selectionStart, selectionEnd));
  37908. if (selection.isNotEmpty())
  37909. SystemClipboard::copyTextToClipboard (selection);
  37910. }
  37911. void TextEditor::paste()
  37912. {
  37913. if (! isReadOnly())
  37914. {
  37915. const String clip (SystemClipboard::getTextFromClipboard());
  37916. if (clip.isNotEmpty())
  37917. insertTextAtCursor (clip);
  37918. }
  37919. }
  37920. void TextEditor::cut()
  37921. {
  37922. if (! isReadOnly())
  37923. {
  37924. moveCaret (selectionEnd);
  37925. insertTextAtCursor (String::empty);
  37926. }
  37927. }
  37928. void TextEditor::drawContent (Graphics& g)
  37929. {
  37930. const float wordWrapWidth = getWordWrapWidth();
  37931. if (wordWrapWidth > 0)
  37932. {
  37933. g.setOrigin (leftIndent, topIndent);
  37934. const Rectangle clip (g.getClipBounds());
  37935. Colour selectedTextColour;
  37936. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  37937. while (i.lineY + 200.0 < clip.getY() && i.next())
  37938. {}
  37939. if (selectionStart < selectionEnd)
  37940. {
  37941. g.setColour (findColour (highlightColourId)
  37942. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  37943. selectedTextColour = findColour (highlightedTextColourId);
  37944. TextEditorIterator i2 (i);
  37945. while (i2.next() && i2.lineY < clip.getBottom())
  37946. {
  37947. i2.updateLineHeight();
  37948. if (i2.lineY + i2.lineHeight >= clip.getY()
  37949. && selectionEnd >= i2.indexInText
  37950. && selectionStart <= i2.indexInText + i2.atom->numChars)
  37951. {
  37952. i2.drawSelection (g, selectionStart, selectionEnd);
  37953. }
  37954. }
  37955. }
  37956. const UniformTextSection* lastSection = 0;
  37957. while (i.next() && i.lineY < clip.getBottom())
  37958. {
  37959. i.updateLineHeight();
  37960. if (i.lineY + i.lineHeight >= clip.getY())
  37961. {
  37962. if (selectionEnd >= i.indexInText
  37963. && selectionStart <= i.indexInText + i.atom->numChars)
  37964. {
  37965. i.drawSelectedText (g, selectionStart, selectionEnd, selectedTextColour);
  37966. lastSection = 0;
  37967. }
  37968. else
  37969. {
  37970. i.draw (g, lastSection);
  37971. }
  37972. }
  37973. }
  37974. }
  37975. }
  37976. void TextEditor::paint (Graphics& g)
  37977. {
  37978. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  37979. }
  37980. void TextEditor::paintOverChildren (Graphics& g)
  37981. {
  37982. if (caretFlashState
  37983. && hasKeyboardFocus (false)
  37984. && caretVisible
  37985. && ! isReadOnly())
  37986. {
  37987. g.setColour (findColour (caretColourId));
  37988. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  37989. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  37990. 2.0f, cursorHeight);
  37991. }
  37992. if (textToShowWhenEmpty.isNotEmpty()
  37993. && (! hasKeyboardFocus (false))
  37994. && getTotalNumChars() == 0)
  37995. {
  37996. g.setColour (colourForTextWhenEmpty);
  37997. g.setFont (getFont());
  37998. if (isMultiLine())
  37999. {
  38000. g.drawText (textToShowWhenEmpty,
  38001. 0, 0, getWidth(), getHeight(),
  38002. Justification::centred, true);
  38003. }
  38004. else
  38005. {
  38006. g.drawText (textToShowWhenEmpty,
  38007. leftIndent, topIndent,
  38008. viewport->getWidth() - leftIndent,
  38009. viewport->getHeight() - topIndent,
  38010. Justification::centredLeft, true);
  38011. }
  38012. }
  38013. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  38014. }
  38015. void TextEditor::mouseDown (const MouseEvent& e)
  38016. {
  38017. beginDragAutoRepeat (100);
  38018. newTransaction();
  38019. if (wasFocused || ! selectAllTextWhenFocused)
  38020. {
  38021. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  38022. {
  38023. moveCursorTo (getTextIndexAt (e.x, e.y),
  38024. e.mods.isShiftDown());
  38025. }
  38026. else
  38027. {
  38028. PopupMenu m;
  38029. addPopupMenuItems (m, &e);
  38030. menuActive = true;
  38031. const int result = m.show();
  38032. menuActive = false;
  38033. if (result != 0)
  38034. performPopupMenuAction (result);
  38035. }
  38036. }
  38037. }
  38038. void TextEditor::mouseDrag (const MouseEvent& e)
  38039. {
  38040. if (wasFocused || ! selectAllTextWhenFocused)
  38041. {
  38042. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  38043. {
  38044. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  38045. }
  38046. }
  38047. }
  38048. void TextEditor::mouseUp (const MouseEvent& e)
  38049. {
  38050. newTransaction();
  38051. textHolder->startTimer (flashSpeedIntervalMs);
  38052. if (wasFocused || ! selectAllTextWhenFocused)
  38053. {
  38054. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  38055. {
  38056. moveCaret (getTextIndexAt (e.x, e.y));
  38057. }
  38058. }
  38059. wasFocused = true;
  38060. }
  38061. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  38062. {
  38063. int tokenEnd = getTextIndexAt (e.x, e.y);
  38064. int tokenStart = tokenEnd;
  38065. if (e.getNumberOfClicks() > 3)
  38066. {
  38067. tokenStart = 0;
  38068. tokenEnd = getTotalNumChars();
  38069. }
  38070. else
  38071. {
  38072. const String t (getText());
  38073. const int totalLength = getTotalNumChars();
  38074. while (tokenEnd < totalLength)
  38075. {
  38076. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  38077. ++tokenEnd;
  38078. else
  38079. break;
  38080. }
  38081. tokenStart = tokenEnd;
  38082. while (tokenStart > 0)
  38083. {
  38084. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  38085. --tokenStart;
  38086. else
  38087. break;
  38088. }
  38089. if (e.getNumberOfClicks() > 2)
  38090. {
  38091. while (tokenEnd < totalLength)
  38092. {
  38093. if (t [tokenEnd] != T('\r') && t [tokenEnd] != T('\n'))
  38094. ++tokenEnd;
  38095. else
  38096. break;
  38097. }
  38098. while (tokenStart > 0)
  38099. {
  38100. if (t [tokenStart - 1] != T('\r') && t [tokenStart - 1] != T('\n'))
  38101. --tokenStart;
  38102. else
  38103. break;
  38104. }
  38105. }
  38106. }
  38107. moveCursorTo (tokenEnd, false);
  38108. moveCursorTo (tokenStart, true);
  38109. }
  38110. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  38111. {
  38112. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  38113. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  38114. }
  38115. bool TextEditor::keyPressed (const KeyPress& key)
  38116. {
  38117. if (isReadOnly() && key != KeyPress (T('c'), ModifierKeys::commandModifier, 0))
  38118. return false;
  38119. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  38120. if (key.isKeyCode (KeyPress::leftKey)
  38121. || key.isKeyCode (KeyPress::upKey))
  38122. {
  38123. newTransaction();
  38124. int newPos;
  38125. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  38126. newPos = indexAtPosition (cursorX, cursorY - 1);
  38127. else if (moveInWholeWordSteps)
  38128. newPos = findWordBreakBefore (getCaretPosition());
  38129. else
  38130. newPos = getCaretPosition() - 1;
  38131. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  38132. }
  38133. else if (key.isKeyCode (KeyPress::rightKey)
  38134. || key.isKeyCode (KeyPress::downKey))
  38135. {
  38136. newTransaction();
  38137. int newPos;
  38138. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  38139. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  38140. else if (moveInWholeWordSteps)
  38141. newPos = findWordBreakAfter (getCaretPosition());
  38142. else
  38143. newPos = getCaretPosition() + 1;
  38144. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  38145. }
  38146. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  38147. {
  38148. newTransaction();
  38149. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  38150. key.getModifiers().isShiftDown());
  38151. }
  38152. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  38153. {
  38154. newTransaction();
  38155. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  38156. key.getModifiers().isShiftDown());
  38157. }
  38158. else if (key.isKeyCode (KeyPress::homeKey))
  38159. {
  38160. newTransaction();
  38161. if (isMultiLine() && ! moveInWholeWordSteps)
  38162. moveCursorTo (indexAtPosition (0.0f, cursorY),
  38163. key.getModifiers().isShiftDown());
  38164. else
  38165. moveCursorTo (0, key.getModifiers().isShiftDown());
  38166. }
  38167. else if (key.isKeyCode (KeyPress::endKey))
  38168. {
  38169. newTransaction();
  38170. if (isMultiLine() && ! moveInWholeWordSteps)
  38171. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  38172. key.getModifiers().isShiftDown());
  38173. else
  38174. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  38175. }
  38176. else if (key.isKeyCode (KeyPress::backspaceKey))
  38177. {
  38178. if (moveInWholeWordSteps)
  38179. {
  38180. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  38181. }
  38182. else
  38183. {
  38184. if (selectionStart == selectionEnd && selectionStart > 0)
  38185. --selectionStart;
  38186. }
  38187. cut();
  38188. }
  38189. else if (key.isKeyCode (KeyPress::deleteKey))
  38190. {
  38191. if (key.getModifiers().isShiftDown())
  38192. copy();
  38193. if (selectionStart == selectionEnd
  38194. && selectionEnd < getTotalNumChars())
  38195. {
  38196. ++selectionEnd;
  38197. }
  38198. cut();
  38199. }
  38200. else if (key == KeyPress (T('c'), ModifierKeys::commandModifier, 0)
  38201. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  38202. {
  38203. newTransaction();
  38204. copy();
  38205. }
  38206. else if (key == KeyPress (T('x'), ModifierKeys::commandModifier, 0))
  38207. {
  38208. newTransaction();
  38209. copy();
  38210. cut();
  38211. }
  38212. else if (key == KeyPress (T('v'), ModifierKeys::commandModifier, 0)
  38213. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  38214. {
  38215. newTransaction();
  38216. paste();
  38217. }
  38218. else if (key == KeyPress (T('z'), ModifierKeys::commandModifier, 0))
  38219. {
  38220. newTransaction();
  38221. doUndoRedo (false);
  38222. }
  38223. else if (key == KeyPress (T('y'), ModifierKeys::commandModifier, 0))
  38224. {
  38225. newTransaction();
  38226. doUndoRedo (true);
  38227. }
  38228. else if (key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  38229. {
  38230. newTransaction();
  38231. moveCursorTo (getTotalNumChars(), false);
  38232. moveCursorTo (0, true);
  38233. }
  38234. else if (key == KeyPress::returnKey)
  38235. {
  38236. newTransaction();
  38237. if (returnKeyStartsNewLine)
  38238. insertTextAtCursor (T("\n"));
  38239. else
  38240. returnPressed();
  38241. }
  38242. else if (key.isKeyCode (KeyPress::escapeKey))
  38243. {
  38244. newTransaction();
  38245. moveCursorTo (getCaretPosition(), false);
  38246. escapePressed();
  38247. }
  38248. else if (key.getTextCharacter() >= ' '
  38249. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  38250. {
  38251. insertTextAtCursor (String::charToString (key.getTextCharacter()));
  38252. lastTransactionTime = Time::getApproximateMillisecondCounter();
  38253. }
  38254. else
  38255. {
  38256. return false;
  38257. }
  38258. return true;
  38259. }
  38260. bool TextEditor::keyStateChanged()
  38261. {
  38262. // (overridden to avoid forwarding key events to the parent)
  38263. return true;
  38264. }
  38265. const int baseMenuItemID = 0x7fff0000;
  38266. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  38267. {
  38268. const bool writable = ! isReadOnly();
  38269. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  38270. m.addItem (baseMenuItemID + 2, TRANS("copy"), selectionStart < selectionEnd);
  38271. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  38272. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  38273. m.addSeparator();
  38274. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  38275. m.addSeparator();
  38276. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  38277. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  38278. }
  38279. void TextEditor::performPopupMenuAction (const int menuItemID)
  38280. {
  38281. switch (menuItemID)
  38282. {
  38283. case baseMenuItemID + 1:
  38284. copy();
  38285. cut();
  38286. break;
  38287. case baseMenuItemID + 2:
  38288. copy();
  38289. break;
  38290. case baseMenuItemID + 3:
  38291. paste();
  38292. break;
  38293. case baseMenuItemID + 4:
  38294. cut();
  38295. break;
  38296. case baseMenuItemID + 5:
  38297. moveCursorTo (getTotalNumChars(), false);
  38298. moveCursorTo (0, true);
  38299. break;
  38300. case baseMenuItemID + 6:
  38301. doUndoRedo (false);
  38302. break;
  38303. case baseMenuItemID + 7:
  38304. doUndoRedo (true);
  38305. break;
  38306. default:
  38307. break;
  38308. }
  38309. }
  38310. void TextEditor::focusGained (FocusChangeType)
  38311. {
  38312. newTransaction();
  38313. caretFlashState = true;
  38314. if (selectAllTextWhenFocused)
  38315. {
  38316. moveCursorTo (0, false);
  38317. moveCursorTo (getTotalNumChars(), true);
  38318. }
  38319. repaint();
  38320. if (caretVisible)
  38321. textHolder->startTimer (flashSpeedIntervalMs);
  38322. ComponentPeer* const peer = getPeer();
  38323. if (peer != 0)
  38324. peer->textInputRequired (getScreenX() - peer->getScreenX(),
  38325. getScreenY() - peer->getScreenY());
  38326. }
  38327. void TextEditor::focusLost (FocusChangeType)
  38328. {
  38329. newTransaction();
  38330. wasFocused = false;
  38331. textHolder->stopTimer();
  38332. caretFlashState = false;
  38333. postCommandMessage (focusLossMessageId);
  38334. repaint();
  38335. }
  38336. void TextEditor::resized()
  38337. {
  38338. viewport->setBoundsInset (borderSize);
  38339. viewport->setSingleStepSizes (16, roundFloatToInt (currentFont.getHeight()));
  38340. updateTextHolderSize();
  38341. if (! isMultiLine())
  38342. {
  38343. scrollToMakeSureCursorIsVisible();
  38344. }
  38345. else
  38346. {
  38347. updateCaretPosition();
  38348. }
  38349. }
  38350. void TextEditor::handleCommandMessage (const int commandId)
  38351. {
  38352. const ComponentDeletionWatcher deletionChecker (this);
  38353. for (int i = listeners.size(); --i >= 0;)
  38354. {
  38355. TextEditorListener* const tl = (TextEditorListener*) listeners [i];
  38356. if (tl != 0)
  38357. {
  38358. switch (commandId)
  38359. {
  38360. case textChangeMessageId:
  38361. tl->textEditorTextChanged (*this);
  38362. break;
  38363. case returnKeyMessageId:
  38364. tl->textEditorReturnKeyPressed (*this);
  38365. break;
  38366. case escapeKeyMessageId:
  38367. tl->textEditorEscapeKeyPressed (*this);
  38368. break;
  38369. case focusLossMessageId:
  38370. tl->textEditorFocusLost (*this);
  38371. break;
  38372. default:
  38373. jassertfalse
  38374. break;
  38375. }
  38376. if (i > 0 && deletionChecker.hasBeenDeleted())
  38377. return;
  38378. }
  38379. }
  38380. }
  38381. void TextEditor::enablementChanged()
  38382. {
  38383. setMouseCursor (MouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  38384. : MouseCursor::IBeamCursor));
  38385. repaint();
  38386. }
  38387. void TextEditor::clearInternal (UndoManager* const um) throw()
  38388. {
  38389. remove (0, getTotalNumChars(), um, caretPosition);
  38390. }
  38391. void TextEditor::insert (const String& text,
  38392. const int insertIndex,
  38393. const Font& font,
  38394. const Colour& colour,
  38395. UndoManager* const um,
  38396. const int caretPositionToMoveTo) throw()
  38397. {
  38398. if (text.isNotEmpty())
  38399. {
  38400. if (um != 0)
  38401. {
  38402. um->perform (new TextEditorInsertAction (*this,
  38403. text,
  38404. insertIndex,
  38405. font,
  38406. colour,
  38407. caretPosition,
  38408. caretPositionToMoveTo));
  38409. }
  38410. else
  38411. {
  38412. repaintText (insertIndex, -1); // must do this before and after changing the data, in case
  38413. // a line gets moved due to word wrap
  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. sections.insert (i, new UniformTextSection (text,
  38422. font, colour,
  38423. passwordCharacter));
  38424. break;
  38425. }
  38426. else if (insertIndex > index && insertIndex < nextIndex)
  38427. {
  38428. splitSection (i, insertIndex - index);
  38429. sections.insert (i + 1, new UniformTextSection (text,
  38430. font, colour,
  38431. passwordCharacter));
  38432. break;
  38433. }
  38434. index = nextIndex;
  38435. }
  38436. if (nextIndex == insertIndex)
  38437. sections.add (new UniformTextSection (text,
  38438. font, colour,
  38439. passwordCharacter));
  38440. coalesceSimilarSections();
  38441. totalNumChars = -1;
  38442. moveCursorTo (caretPositionToMoveTo, false);
  38443. repaintText (insertIndex, -1);
  38444. }
  38445. }
  38446. }
  38447. void TextEditor::reinsert (const int insertIndex,
  38448. const VoidArray& sectionsToInsert) throw()
  38449. {
  38450. int index = 0;
  38451. int nextIndex = 0;
  38452. for (int i = 0; i < sections.size(); ++i)
  38453. {
  38454. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  38455. if (insertIndex == index)
  38456. {
  38457. for (int j = sectionsToInsert.size(); --j >= 0;)
  38458. sections.insert (i, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  38459. break;
  38460. }
  38461. else if (insertIndex > index && insertIndex < nextIndex)
  38462. {
  38463. splitSection (i, insertIndex - index);
  38464. for (int j = sectionsToInsert.size(); --j >= 0;)
  38465. sections.insert (i + 1, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  38466. break;
  38467. }
  38468. index = nextIndex;
  38469. }
  38470. if (nextIndex == insertIndex)
  38471. {
  38472. for (int j = 0; j < sectionsToInsert.size(); ++j)
  38473. sections.add (new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  38474. }
  38475. coalesceSimilarSections();
  38476. totalNumChars = -1;
  38477. }
  38478. void TextEditor::remove (const int startIndex,
  38479. int endIndex,
  38480. UndoManager* const um,
  38481. const int caretPositionToMoveTo) throw()
  38482. {
  38483. if (endIndex > startIndex)
  38484. {
  38485. int index = 0;
  38486. for (int i = 0; i < sections.size(); ++i)
  38487. {
  38488. const int nextIndex = index + ((UniformTextSection*) sections[i])->getTotalLength();
  38489. if (startIndex > index && startIndex < nextIndex)
  38490. {
  38491. splitSection (i, startIndex - index);
  38492. --i;
  38493. }
  38494. else if (endIndex > index && endIndex < nextIndex)
  38495. {
  38496. splitSection (i, endIndex - index);
  38497. --i;
  38498. }
  38499. else
  38500. {
  38501. index = nextIndex;
  38502. if (index > endIndex)
  38503. break;
  38504. }
  38505. }
  38506. index = 0;
  38507. if (um != 0)
  38508. {
  38509. VoidArray removedSections;
  38510. for (int i = 0; i < sections.size(); ++i)
  38511. {
  38512. if (endIndex <= startIndex)
  38513. break;
  38514. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  38515. const int nextIndex = index + section->getTotalLength();
  38516. if (startIndex <= index && endIndex >= nextIndex)
  38517. removedSections.add (new UniformTextSection (*section));
  38518. index = nextIndex;
  38519. }
  38520. um->perform (new TextEditorRemoveAction (*this,
  38521. startIndex,
  38522. endIndex,
  38523. caretPosition,
  38524. caretPositionToMoveTo,
  38525. removedSections));
  38526. }
  38527. else
  38528. {
  38529. for (int i = 0; i < sections.size(); ++i)
  38530. {
  38531. if (endIndex <= startIndex)
  38532. break;
  38533. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  38534. const int nextIndex = index + section->getTotalLength();
  38535. if (startIndex <= index && endIndex >= nextIndex)
  38536. {
  38537. sections.remove(i);
  38538. endIndex -= (nextIndex - index);
  38539. section->clear();
  38540. delete section;
  38541. --i;
  38542. }
  38543. else
  38544. {
  38545. index = nextIndex;
  38546. }
  38547. }
  38548. coalesceSimilarSections();
  38549. totalNumChars = -1;
  38550. moveCursorTo (caretPositionToMoveTo, false);
  38551. repaintText (startIndex, -1);
  38552. }
  38553. }
  38554. }
  38555. const String TextEditor::getText() const throw()
  38556. {
  38557. String t;
  38558. for (int i = 0; i < sections.size(); ++i)
  38559. t += ((const UniformTextSection*) sections.getUnchecked(i))->getAllText();
  38560. return t;
  38561. }
  38562. const String TextEditor::getTextSubstring (const int startCharacter, const int endCharacter) const throw()
  38563. {
  38564. String t;
  38565. int index = 0;
  38566. for (int i = 0; i < sections.size(); ++i)
  38567. {
  38568. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked(i);
  38569. const int nextIndex = index + s->getTotalLength();
  38570. if (startCharacter < nextIndex)
  38571. {
  38572. if (endCharacter <= index)
  38573. break;
  38574. const int start = jmax (index, startCharacter);
  38575. t += s->getTextSubstring (start - index, endCharacter - index);
  38576. }
  38577. index = nextIndex;
  38578. }
  38579. return t;
  38580. }
  38581. const String TextEditor::getHighlightedText() const throw()
  38582. {
  38583. return getTextSubstring (getHighlightedRegionStart(),
  38584. getHighlightedRegionStart() + getHighlightedRegionLength());
  38585. }
  38586. int TextEditor::getTotalNumChars() throw()
  38587. {
  38588. if (totalNumChars < 0)
  38589. {
  38590. totalNumChars = 0;
  38591. for (int i = sections.size(); --i >= 0;)
  38592. totalNumChars += ((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  38593. }
  38594. return totalNumChars;
  38595. }
  38596. bool TextEditor::isEmpty() const throw()
  38597. {
  38598. if (totalNumChars != 0)
  38599. {
  38600. for (int i = sections.size(); --i >= 0;)
  38601. if (((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength() > 0)
  38602. return false;
  38603. }
  38604. return true;
  38605. }
  38606. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const throw()
  38607. {
  38608. const float wordWrapWidth = getWordWrapWidth();
  38609. if (wordWrapWidth > 0 && sections.size() > 0)
  38610. {
  38611. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  38612. i.getCharPosition (index, cx, cy, lineHeight);
  38613. }
  38614. else
  38615. {
  38616. cx = cy = 0;
  38617. lineHeight = currentFont.getHeight();
  38618. }
  38619. }
  38620. int TextEditor::indexAtPosition (const float x, const float y) throw()
  38621. {
  38622. const float wordWrapWidth = getWordWrapWidth();
  38623. if (wordWrapWidth > 0)
  38624. {
  38625. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  38626. while (i.next())
  38627. {
  38628. if (i.lineY + getHeight() > y)
  38629. i.updateLineHeight();
  38630. if (i.lineY + i.lineHeight > y)
  38631. {
  38632. if (i.lineY > y)
  38633. return jmax (0, i.indexInText - 1);
  38634. if (i.atomX >= x)
  38635. return i.indexInText;
  38636. if (x < i.atomRight)
  38637. return i.xToIndex (x);
  38638. }
  38639. }
  38640. }
  38641. return getTotalNumChars();
  38642. }
  38643. static int getCharacterCategory (const tchar character) throw()
  38644. {
  38645. return CharacterFunctions::isLetterOrDigit (character)
  38646. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  38647. }
  38648. int TextEditor::findWordBreakAfter (const int position) const throw()
  38649. {
  38650. const String t (getTextSubstring (position, position + 512));
  38651. const int totalLength = t.length();
  38652. int i = 0;
  38653. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  38654. ++i;
  38655. const int type = getCharacterCategory (t[i]);
  38656. while (i < totalLength && type == getCharacterCategory (t[i]))
  38657. ++i;
  38658. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  38659. ++i;
  38660. return position + i;
  38661. }
  38662. int TextEditor::findWordBreakBefore (const int position) const throw()
  38663. {
  38664. if (position <= 0)
  38665. return 0;
  38666. const int startOfBuffer = jmax (0, position - 512);
  38667. const String t (getTextSubstring (startOfBuffer, position));
  38668. int i = position - startOfBuffer;
  38669. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  38670. --i;
  38671. if (i > 0)
  38672. {
  38673. const int type = getCharacterCategory (t [i - 1]);
  38674. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  38675. --i;
  38676. }
  38677. jassert (startOfBuffer + i >= 0);
  38678. return startOfBuffer + i;
  38679. }
  38680. void TextEditor::splitSection (const int sectionIndex,
  38681. const int charToSplitAt) throw()
  38682. {
  38683. jassert (sections[sectionIndex] != 0);
  38684. sections.insert (sectionIndex + 1,
  38685. ((UniformTextSection*) sections.getUnchecked (sectionIndex))
  38686. ->split (charToSplitAt, passwordCharacter));
  38687. }
  38688. void TextEditor::coalesceSimilarSections() throw()
  38689. {
  38690. for (int i = 0; i < sections.size() - 1; ++i)
  38691. {
  38692. UniformTextSection* const s1 = (UniformTextSection*) (sections.getUnchecked (i));
  38693. UniformTextSection* const s2 = (UniformTextSection*) (sections.getUnchecked (i + 1));
  38694. if (s1->font == s2->font
  38695. && s1->colour == s2->colour)
  38696. {
  38697. s1->append (*s2, passwordCharacter);
  38698. sections.remove (i + 1);
  38699. delete s2;
  38700. --i;
  38701. }
  38702. }
  38703. }
  38704. END_JUCE_NAMESPACE
  38705. /********* End of inlined file: juce_TextEditor.cpp *********/
  38706. /********* Start of inlined file: juce_Toolbar.cpp *********/
  38707. BEGIN_JUCE_NAMESPACE
  38708. const tchar* const Toolbar::toolbarDragDescriptor = T("_toolbarItem_");
  38709. class ToolbarSpacerComp : public ToolbarItemComponent
  38710. {
  38711. public:
  38712. ToolbarSpacerComp (const int itemId, const float fixedSize_, const bool drawBar_)
  38713. : ToolbarItemComponent (itemId, String::empty, false),
  38714. fixedSize (fixedSize_),
  38715. drawBar (drawBar_)
  38716. {
  38717. }
  38718. ~ToolbarSpacerComp()
  38719. {
  38720. }
  38721. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  38722. int& preferredSize, int& minSize, int& maxSize)
  38723. {
  38724. if (fixedSize <= 0)
  38725. {
  38726. preferredSize = toolbarThickness * 2;
  38727. minSize = 4;
  38728. maxSize = 32768;
  38729. }
  38730. else
  38731. {
  38732. maxSize = roundFloatToInt (toolbarThickness * fixedSize);
  38733. minSize = drawBar ? maxSize : jmin (4, maxSize);
  38734. preferredSize = maxSize;
  38735. if (getEditingMode() == editableOnPalette)
  38736. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  38737. }
  38738. return true;
  38739. }
  38740. void paintButtonArea (Graphics&, int, int, bool, bool)
  38741. {
  38742. }
  38743. void contentAreaChanged (const Rectangle&)
  38744. {
  38745. }
  38746. int getResizeOrder() const throw()
  38747. {
  38748. return fixedSize <= 0 ? 0 : 1;
  38749. }
  38750. void paint (Graphics& g)
  38751. {
  38752. const int w = getWidth();
  38753. const int h = getHeight();
  38754. if (drawBar)
  38755. {
  38756. g.setColour (findColour (Toolbar::separatorColourId, true));
  38757. const float thickness = 0.2f;
  38758. if (isToolbarVertical())
  38759. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  38760. else
  38761. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  38762. }
  38763. if (getEditingMode() != normalMode && ! drawBar)
  38764. {
  38765. g.setColour (findColour (Toolbar::separatorColourId, true));
  38766. const int indentX = jmin (2, (w - 3) / 2);
  38767. const int indentY = jmin (2, (h - 3) / 2);
  38768. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  38769. if (fixedSize <= 0)
  38770. {
  38771. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  38772. if (isToolbarVertical())
  38773. {
  38774. x1 = w * 0.5f;
  38775. y1 = h * 0.4f;
  38776. x2 = x1;
  38777. y2 = indentX * 2.0f;
  38778. x3 = x1;
  38779. y3 = h * 0.6f;
  38780. x4 = x1;
  38781. y4 = h - y2;
  38782. hw = w * 0.15f;
  38783. hl = w * 0.2f;
  38784. }
  38785. else
  38786. {
  38787. x1 = w * 0.4f;
  38788. y1 = h * 0.5f;
  38789. x2 = indentX * 2.0f;
  38790. y2 = y1;
  38791. x3 = w * 0.6f;
  38792. y3 = y1;
  38793. x4 = w - x2;
  38794. y4 = y1;
  38795. hw = h * 0.15f;
  38796. hl = h * 0.2f;
  38797. }
  38798. Path p;
  38799. p.addArrow (x1, y1, x2, y2, 1.5f, hw, hl);
  38800. p.addArrow (x3, y3, x4, y4, 1.5f, hw, hl);
  38801. g.fillPath (p);
  38802. }
  38803. }
  38804. }
  38805. juce_UseDebuggingNewOperator
  38806. private:
  38807. const float fixedSize;
  38808. const bool drawBar;
  38809. ToolbarSpacerComp (const ToolbarSpacerComp&);
  38810. const ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  38811. };
  38812. class MissingItemsComponent : public PopupMenuCustomComponent
  38813. {
  38814. public:
  38815. MissingItemsComponent (Toolbar& owner_, const int height_)
  38816. : PopupMenuCustomComponent (true),
  38817. owner (owner_),
  38818. height (height_)
  38819. {
  38820. for (int i = owner_.items.size(); --i >= 0;)
  38821. {
  38822. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  38823. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  38824. {
  38825. oldIndexes.insert (0, i);
  38826. addAndMakeVisible (tc, 0);
  38827. }
  38828. }
  38829. layout (400);
  38830. }
  38831. ~MissingItemsComponent()
  38832. {
  38833. // deleting the toolbar while its menu it open??
  38834. jassert (owner.isValidComponent());
  38835. for (int i = 0; i < getNumChildComponents(); ++i)
  38836. {
  38837. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  38838. if (tc != 0)
  38839. {
  38840. tc->setVisible (false);
  38841. const int index = oldIndexes.remove (i);
  38842. owner.addChildComponent (tc, index);
  38843. --i;
  38844. }
  38845. }
  38846. owner.resized();
  38847. }
  38848. void layout (const int preferredWidth)
  38849. {
  38850. const int indent = 8;
  38851. int x = indent;
  38852. int y = indent;
  38853. int maxX = 0;
  38854. for (int i = 0; i < getNumChildComponents(); ++i)
  38855. {
  38856. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  38857. if (tc != 0)
  38858. {
  38859. int preferredSize = 1, minSize = 1, maxSize = 1;
  38860. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  38861. {
  38862. if (x + preferredSize > preferredWidth && x > indent)
  38863. {
  38864. x = indent;
  38865. y += height;
  38866. }
  38867. tc->setBounds (x, y, preferredSize, height);
  38868. x += preferredSize;
  38869. maxX = jmax (maxX, x);
  38870. }
  38871. }
  38872. }
  38873. setSize (maxX + 8, y + height + 8);
  38874. }
  38875. void getIdealSize (int& idealWidth, int& idealHeight)
  38876. {
  38877. idealWidth = getWidth();
  38878. idealHeight = getHeight();
  38879. }
  38880. juce_UseDebuggingNewOperator
  38881. private:
  38882. Toolbar& owner;
  38883. const int height;
  38884. Array <int> oldIndexes;
  38885. MissingItemsComponent (const MissingItemsComponent&);
  38886. const MissingItemsComponent& operator= (const MissingItemsComponent&);
  38887. };
  38888. Toolbar::Toolbar()
  38889. : vertical (false),
  38890. isEditingActive (false),
  38891. toolbarStyle (Toolbar::iconsOnly)
  38892. {
  38893. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  38894. missingItemsButton->setAlwaysOnTop (true);
  38895. missingItemsButton->addButtonListener (this);
  38896. }
  38897. Toolbar::~Toolbar()
  38898. {
  38899. animator.cancelAllAnimations (true);
  38900. deleteAllChildren();
  38901. }
  38902. void Toolbar::setVertical (const bool shouldBeVertical)
  38903. {
  38904. if (vertical != shouldBeVertical)
  38905. {
  38906. vertical = shouldBeVertical;
  38907. resized();
  38908. }
  38909. }
  38910. void Toolbar::clear()
  38911. {
  38912. for (int i = items.size(); --i >= 0;)
  38913. {
  38914. ToolbarItemComponent* const tc = items.getUnchecked(i);
  38915. items.remove (i);
  38916. delete tc;
  38917. }
  38918. resized();
  38919. }
  38920. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  38921. {
  38922. if (itemId == ToolbarItemFactory::separatorBarId)
  38923. return new ToolbarSpacerComp (itemId, 0.1f, true);
  38924. else if (itemId == ToolbarItemFactory::spacerId)
  38925. return new ToolbarSpacerComp (itemId, 0.5f, false);
  38926. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  38927. return new ToolbarSpacerComp (itemId, 0, false);
  38928. return factory.createItem (itemId);
  38929. }
  38930. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  38931. const int itemId,
  38932. const int insertIndex)
  38933. {
  38934. // An ID can't be zero - this might indicate a mistake somewhere?
  38935. jassert (itemId != 0);
  38936. ToolbarItemComponent* const tc = createItem (factory, itemId);
  38937. if (tc != 0)
  38938. {
  38939. #ifdef JUCE_DEBUG
  38940. Array <int> allowedIds;
  38941. factory.getAllToolbarItemIds (allowedIds);
  38942. // If your factory can create an item for a given ID, it must also return
  38943. // that ID from its getAllToolbarItemIds() method!
  38944. jassert (allowedIds.contains (itemId));
  38945. #endif
  38946. items.insert (insertIndex, tc);
  38947. addAndMakeVisible (tc, insertIndex);
  38948. }
  38949. }
  38950. void Toolbar::addItem (ToolbarItemFactory& factory,
  38951. const int itemId,
  38952. const int insertIndex)
  38953. {
  38954. addItemInternal (factory, itemId, insertIndex);
  38955. resized();
  38956. }
  38957. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  38958. {
  38959. Array <int> ids;
  38960. factoryToUse.getDefaultItemSet (ids);
  38961. clear();
  38962. for (int i = 0; i < ids.size(); ++i)
  38963. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  38964. resized();
  38965. }
  38966. void Toolbar::removeToolbarItem (const int itemIndex)
  38967. {
  38968. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  38969. if (tc != 0)
  38970. {
  38971. items.removeValue (tc);
  38972. delete tc;
  38973. resized();
  38974. }
  38975. }
  38976. int Toolbar::getNumItems() const throw()
  38977. {
  38978. return items.size();
  38979. }
  38980. int Toolbar::getItemId (const int itemIndex) const throw()
  38981. {
  38982. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  38983. return tc != 0 ? tc->getItemId() : 0;
  38984. }
  38985. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  38986. {
  38987. return items [itemIndex];
  38988. }
  38989. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  38990. {
  38991. for (;;)
  38992. {
  38993. index += delta;
  38994. ToolbarItemComponent* const tc = getItemComponent (index);
  38995. if (tc == 0)
  38996. break;
  38997. if (tc->isActive)
  38998. return tc;
  38999. }
  39000. return 0;
  39001. }
  39002. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  39003. {
  39004. if (toolbarStyle != newStyle)
  39005. {
  39006. toolbarStyle = newStyle;
  39007. updateAllItemPositions (false);
  39008. }
  39009. }
  39010. const String Toolbar::toString() const
  39011. {
  39012. String s (T("TB:"));
  39013. for (int i = 0; i < getNumItems(); ++i)
  39014. s << getItemId(i) << T(' ');
  39015. return s.trimEnd();
  39016. }
  39017. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  39018. const String& savedVersion)
  39019. {
  39020. if (! savedVersion.startsWith (T("TB:")))
  39021. return false;
  39022. StringArray tokens;
  39023. tokens.addTokens (savedVersion.substring (3), false);
  39024. clear();
  39025. for (int i = 0; i < tokens.size(); ++i)
  39026. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  39027. resized();
  39028. return true;
  39029. }
  39030. void Toolbar::paint (Graphics& g)
  39031. {
  39032. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  39033. }
  39034. int Toolbar::getThickness() const throw()
  39035. {
  39036. return vertical ? getWidth() : getHeight();
  39037. }
  39038. int Toolbar::getLength() const throw()
  39039. {
  39040. return vertical ? getHeight() : getWidth();
  39041. }
  39042. void Toolbar::setEditingActive (const bool active)
  39043. {
  39044. if (isEditingActive != active)
  39045. {
  39046. isEditingActive = active;
  39047. updateAllItemPositions (false);
  39048. }
  39049. }
  39050. void Toolbar::resized()
  39051. {
  39052. updateAllItemPositions (false);
  39053. }
  39054. void Toolbar::updateAllItemPositions (const bool animate)
  39055. {
  39056. if (getWidth() > 0 && getHeight() > 0)
  39057. {
  39058. StretchableObjectResizer resizer;
  39059. int i;
  39060. for (i = 0; i < items.size(); ++i)
  39061. {
  39062. ToolbarItemComponent* const tc = items.getUnchecked(i);
  39063. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  39064. : ToolbarItemComponent::normalMode);
  39065. tc->setStyle (toolbarStyle);
  39066. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  39067. int preferredSize = 1, minSize = 1, maxSize = 1;
  39068. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  39069. preferredSize, minSize, maxSize))
  39070. {
  39071. tc->isActive = true;
  39072. resizer.addItem (preferredSize, minSize, maxSize,
  39073. spacer != 0 ? spacer->getResizeOrder() : 2);
  39074. }
  39075. else
  39076. {
  39077. tc->isActive = false;
  39078. tc->setVisible (false);
  39079. }
  39080. }
  39081. resizer.resizeToFit (getLength());
  39082. int totalLength = 0;
  39083. for (i = 0; i < resizer.getNumItems(); ++i)
  39084. totalLength += (int) resizer.getItemSize (i);
  39085. const bool itemsOffTheEnd = totalLength > getLength();
  39086. const int extrasButtonSize = getThickness() / 2;
  39087. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  39088. missingItemsButton->setVisible (itemsOffTheEnd);
  39089. missingItemsButton->setEnabled (! isEditingActive);
  39090. if (vertical)
  39091. missingItemsButton->setCentrePosition (getWidth() / 2,
  39092. getHeight() - 4 - extrasButtonSize / 2);
  39093. else
  39094. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  39095. getHeight() / 2);
  39096. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  39097. : missingItemsButton->getX()) - 4
  39098. : getLength();
  39099. int pos = 0, activeIndex = 0;
  39100. for (i = 0; i < items.size(); ++i)
  39101. {
  39102. ToolbarItemComponent* const tc = items.getUnchecked(i);
  39103. if (tc->isActive)
  39104. {
  39105. const int size = (int) resizer.getItemSize (activeIndex++);
  39106. Rectangle newBounds;
  39107. if (vertical)
  39108. newBounds.setBounds (0, pos, getWidth(), size);
  39109. else
  39110. newBounds.setBounds (pos, 0, size, getHeight());
  39111. if (animate)
  39112. {
  39113. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  39114. }
  39115. else
  39116. {
  39117. animator.cancelAnimation (tc, false);
  39118. tc->setBounds (newBounds);
  39119. }
  39120. pos += size;
  39121. tc->setVisible (pos <= maxLength
  39122. && ((! tc->isBeingDragged)
  39123. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  39124. }
  39125. }
  39126. }
  39127. }
  39128. void Toolbar::buttonClicked (Button*)
  39129. {
  39130. jassert (missingItemsButton->isShowing());
  39131. if (missingItemsButton->isShowing())
  39132. {
  39133. PopupMenu m;
  39134. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  39135. m.showAt (missingItemsButton);
  39136. }
  39137. }
  39138. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  39139. Component* /*sourceComponent*/)
  39140. {
  39141. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  39142. }
  39143. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  39144. {
  39145. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  39146. if (tc != 0)
  39147. {
  39148. if (getNumItems() == 0)
  39149. {
  39150. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  39151. {
  39152. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  39153. if (palette != 0)
  39154. palette->replaceComponent (tc);
  39155. }
  39156. else
  39157. {
  39158. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  39159. }
  39160. items.add (tc);
  39161. addChildComponent (tc);
  39162. updateAllItemPositions (false);
  39163. }
  39164. else
  39165. {
  39166. for (int i = getNumItems(); --i >= 0;)
  39167. {
  39168. int currentIndex = getIndexOfChildComponent (tc);
  39169. if (currentIndex < 0)
  39170. {
  39171. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  39172. {
  39173. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  39174. if (palette != 0)
  39175. palette->replaceComponent (tc);
  39176. }
  39177. else
  39178. {
  39179. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  39180. }
  39181. items.add (tc);
  39182. addChildComponent (tc);
  39183. currentIndex = getIndexOfChildComponent (tc);
  39184. updateAllItemPositions (true);
  39185. }
  39186. int newIndex = currentIndex;
  39187. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  39188. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  39189. const Rectangle current (animator.getComponentDestination (getChildComponent (newIndex)));
  39190. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  39191. if (prev != 0)
  39192. {
  39193. const Rectangle previousPos (animator.getComponentDestination (prev));
  39194. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  39195. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  39196. {
  39197. newIndex = getIndexOfChildComponent (prev);
  39198. }
  39199. }
  39200. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  39201. if (next != 0)
  39202. {
  39203. const Rectangle nextPos (animator.getComponentDestination (next));
  39204. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  39205. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  39206. {
  39207. newIndex = getIndexOfChildComponent (next) + 1;
  39208. }
  39209. }
  39210. if (newIndex != currentIndex)
  39211. {
  39212. items.removeValue (tc);
  39213. removeChildComponent (tc);
  39214. addChildComponent (tc, newIndex);
  39215. items.insert (newIndex, tc);
  39216. updateAllItemPositions (true);
  39217. }
  39218. else
  39219. {
  39220. break;
  39221. }
  39222. }
  39223. }
  39224. }
  39225. }
  39226. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  39227. {
  39228. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  39229. if (tc != 0)
  39230. {
  39231. if (isParentOf (tc))
  39232. {
  39233. items.removeValue (tc);
  39234. removeChildComponent (tc);
  39235. updateAllItemPositions (true);
  39236. }
  39237. }
  39238. }
  39239. void Toolbar::itemDropped (const String&, Component*, int, int)
  39240. {
  39241. }
  39242. void Toolbar::mouseDown (const MouseEvent& e)
  39243. {
  39244. if (e.mods.isPopupMenu())
  39245. {
  39246. }
  39247. }
  39248. class ToolbarCustomisationDialog : public DialogWindow
  39249. {
  39250. public:
  39251. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  39252. Toolbar* const toolbar_,
  39253. const int optionFlags)
  39254. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  39255. toolbar (toolbar_)
  39256. {
  39257. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  39258. setResizable (true, true);
  39259. setResizeLimits (400, 300, 1500, 1000);
  39260. positionNearBar();
  39261. }
  39262. ~ToolbarCustomisationDialog()
  39263. {
  39264. setContentComponent (0, true);
  39265. }
  39266. void closeButtonPressed()
  39267. {
  39268. setVisible (false);
  39269. }
  39270. bool canModalEventBeSentToComponent (const Component* comp)
  39271. {
  39272. return toolbar->isParentOf (comp);
  39273. }
  39274. void positionNearBar()
  39275. {
  39276. const Rectangle screenSize (toolbar->getParentMonitorArea());
  39277. const int tbx = toolbar->getScreenX();
  39278. const int tby = toolbar->getScreenY();
  39279. const int gap = 8;
  39280. int x, y;
  39281. if (toolbar->isVertical())
  39282. {
  39283. y = tby;
  39284. if (tbx > screenSize.getCentreX())
  39285. x = tbx - getWidth() - gap;
  39286. else
  39287. x = tbx + toolbar->getWidth() + gap;
  39288. }
  39289. else
  39290. {
  39291. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  39292. if (tby > screenSize.getCentreY())
  39293. y = tby - getHeight() - gap;
  39294. else
  39295. y = tby + toolbar->getHeight() + gap;
  39296. }
  39297. setTopLeftPosition (x, y);
  39298. }
  39299. private:
  39300. Toolbar* const toolbar;
  39301. class CustomiserPanel : public Component,
  39302. private ComboBoxListener,
  39303. private ButtonListener
  39304. {
  39305. public:
  39306. CustomiserPanel (ToolbarItemFactory& factory_,
  39307. Toolbar* const toolbar_,
  39308. const int optionFlags)
  39309. : factory (factory_),
  39310. toolbar (toolbar_),
  39311. styleBox (0),
  39312. defaultButton (0)
  39313. {
  39314. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  39315. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  39316. | Toolbar::allowIconsWithTextChoice
  39317. | Toolbar::allowTextOnlyChoice)) != 0)
  39318. {
  39319. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  39320. styleBox->setEditableText (false);
  39321. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  39322. styleBox->addItem (TRANS("Show icons only"), 1);
  39323. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  39324. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  39325. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  39326. styleBox->addItem (TRANS("Show descriptions only"), 3);
  39327. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  39328. styleBox->setSelectedId (1);
  39329. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  39330. styleBox->setSelectedId (2);
  39331. else if (toolbar_->getStyle() == Toolbar::textOnly)
  39332. styleBox->setSelectedId (3);
  39333. styleBox->addListener (this);
  39334. }
  39335. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  39336. {
  39337. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  39338. defaultButton->addButtonListener (this);
  39339. }
  39340. addAndMakeVisible (instructions = new Label (String::empty,
  39341. 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.")));
  39342. instructions->setFont (Font (13.0f));
  39343. setSize (500, 300);
  39344. }
  39345. ~CustomiserPanel()
  39346. {
  39347. deleteAllChildren();
  39348. }
  39349. void comboBoxChanged (ComboBox*)
  39350. {
  39351. if (styleBox->getSelectedId() == 1)
  39352. toolbar->setStyle (Toolbar::iconsOnly);
  39353. else if (styleBox->getSelectedId() == 2)
  39354. toolbar->setStyle (Toolbar::iconsWithText);
  39355. else if (styleBox->getSelectedId() == 3)
  39356. toolbar->setStyle (Toolbar::textOnly);
  39357. palette->resized(); // to make it update the styles
  39358. }
  39359. void buttonClicked (Button*)
  39360. {
  39361. toolbar->addDefaultItems (factory);
  39362. }
  39363. void paint (Graphics& g)
  39364. {
  39365. Colour background;
  39366. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  39367. if (dw != 0)
  39368. background = dw->getBackgroundColour();
  39369. g.setColour (background.contrasting().withAlpha (0.3f));
  39370. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  39371. }
  39372. void resized()
  39373. {
  39374. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  39375. if (styleBox != 0)
  39376. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  39377. if (defaultButton != 0)
  39378. {
  39379. defaultButton->changeWidthToFitText (22);
  39380. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  39381. }
  39382. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  39383. }
  39384. private:
  39385. ToolbarItemFactory& factory;
  39386. Toolbar* const toolbar;
  39387. Label* instructions;
  39388. ToolbarItemPalette* palette;
  39389. ComboBox* styleBox;
  39390. TextButton* defaultButton;
  39391. };
  39392. };
  39393. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  39394. {
  39395. setEditingActive (true);
  39396. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  39397. dw.runModalLoop();
  39398. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  39399. setEditingActive (false);
  39400. }
  39401. END_JUCE_NAMESPACE
  39402. /********* End of inlined file: juce_Toolbar.cpp *********/
  39403. /********* Start of inlined file: juce_ToolbarItemComponent.cpp *********/
  39404. BEGIN_JUCE_NAMESPACE
  39405. ToolbarItemFactory::ToolbarItemFactory()
  39406. {
  39407. }
  39408. ToolbarItemFactory::~ToolbarItemFactory()
  39409. {
  39410. }
  39411. class ItemDragAndDropOverlayComponent : public Component
  39412. {
  39413. public:
  39414. ItemDragAndDropOverlayComponent()
  39415. : isDragging (false)
  39416. {
  39417. setAlwaysOnTop (true);
  39418. setRepaintsOnMouseActivity (true);
  39419. setMouseCursor (MouseCursor::DraggingHandCursor);
  39420. }
  39421. ~ItemDragAndDropOverlayComponent()
  39422. {
  39423. }
  39424. void paint (Graphics& g)
  39425. {
  39426. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39427. if (isMouseOverOrDragging()
  39428. && tc != 0
  39429. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  39430. {
  39431. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  39432. g.drawRect (0, 0, getWidth(), getHeight(),
  39433. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  39434. }
  39435. }
  39436. void mouseDown (const MouseEvent& e)
  39437. {
  39438. isDragging = false;
  39439. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39440. if (tc != 0)
  39441. {
  39442. tc->dragOffsetX = e.x;
  39443. tc->dragOffsetY = e.y;
  39444. }
  39445. }
  39446. void mouseDrag (const MouseEvent& e)
  39447. {
  39448. if (! (isDragging || e.mouseWasClicked()))
  39449. {
  39450. isDragging = true;
  39451. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  39452. if (dnd != 0)
  39453. {
  39454. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), 0, true);
  39455. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39456. if (tc != 0)
  39457. {
  39458. tc->isBeingDragged = true;
  39459. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  39460. tc->setVisible (false);
  39461. }
  39462. }
  39463. }
  39464. }
  39465. void mouseUp (const MouseEvent&)
  39466. {
  39467. isDragging = false;
  39468. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39469. if (tc != 0)
  39470. {
  39471. tc->isBeingDragged = false;
  39472. Toolbar* const tb = tc->getToolbar();
  39473. if (tb != 0)
  39474. tb->updateAllItemPositions (true);
  39475. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  39476. delete tc;
  39477. }
  39478. }
  39479. void parentSizeChanged()
  39480. {
  39481. setBounds (0, 0, getParentWidth(), getParentHeight());
  39482. }
  39483. juce_UseDebuggingNewOperator
  39484. private:
  39485. bool isDragging;
  39486. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  39487. const ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  39488. };
  39489. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  39490. const String& labelText,
  39491. const bool isBeingUsedAsAButton_)
  39492. : Button (labelText),
  39493. itemId (itemId_),
  39494. mode (normalMode),
  39495. toolbarStyle (Toolbar::iconsOnly),
  39496. overlayComp (0),
  39497. dragOffsetX (0),
  39498. dragOffsetY (0),
  39499. isActive (true),
  39500. isBeingDragged (false),
  39501. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  39502. {
  39503. // Your item ID can't be 0!
  39504. jassert (itemId_ != 0);
  39505. }
  39506. ToolbarItemComponent::~ToolbarItemComponent()
  39507. {
  39508. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  39509. delete overlayComp;
  39510. }
  39511. Toolbar* ToolbarItemComponent::getToolbar() const
  39512. {
  39513. return dynamic_cast <Toolbar*> (getParentComponent());
  39514. }
  39515. bool ToolbarItemComponent::isToolbarVertical() const
  39516. {
  39517. const Toolbar* const t = getToolbar();
  39518. return t != 0 && t->isVertical();
  39519. }
  39520. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  39521. {
  39522. if (toolbarStyle != newStyle)
  39523. {
  39524. toolbarStyle = newStyle;
  39525. repaint();
  39526. resized();
  39527. }
  39528. }
  39529. void ToolbarItemComponent::paintButton (Graphics& g, bool isMouseOver, bool isMouseDown)
  39530. {
  39531. if (isBeingUsedAsAButton)
  39532. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  39533. isMouseOver, isMouseDown, *this);
  39534. if (toolbarStyle != Toolbar::iconsOnly)
  39535. {
  39536. const int indent = contentArea.getX();
  39537. int y = indent;
  39538. int h = getHeight() - indent * 2;
  39539. if (toolbarStyle == Toolbar::iconsWithText)
  39540. {
  39541. y = contentArea.getBottom() + indent / 2;
  39542. h -= contentArea.getHeight();
  39543. }
  39544. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  39545. getButtonText(), *this);
  39546. }
  39547. if (! contentArea.isEmpty())
  39548. {
  39549. g.saveState();
  39550. g.setOrigin (contentArea.getX(), contentArea.getY());
  39551. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  39552. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), isMouseOver, isMouseDown);
  39553. g.restoreState();
  39554. }
  39555. }
  39556. void ToolbarItemComponent::resized()
  39557. {
  39558. if (toolbarStyle != Toolbar::textOnly)
  39559. {
  39560. const int indent = jmin (proportionOfWidth (0.08f),
  39561. proportionOfHeight (0.08f));
  39562. contentArea = Rectangle (indent, indent,
  39563. getWidth() - indent * 2,
  39564. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  39565. : (getHeight() - indent * 2));
  39566. }
  39567. else
  39568. {
  39569. contentArea = Rectangle();
  39570. }
  39571. contentAreaChanged (contentArea);
  39572. }
  39573. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  39574. {
  39575. if (mode != newMode)
  39576. {
  39577. mode = newMode;
  39578. repaint();
  39579. if (mode == normalMode)
  39580. {
  39581. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  39582. delete overlayComp;
  39583. overlayComp = 0;
  39584. }
  39585. else if (overlayComp == 0)
  39586. {
  39587. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  39588. overlayComp->parentSizeChanged();
  39589. }
  39590. resized();
  39591. }
  39592. }
  39593. END_JUCE_NAMESPACE
  39594. /********* End of inlined file: juce_ToolbarItemComponent.cpp *********/
  39595. /********* Start of inlined file: juce_ToolbarItemPalette.cpp *********/
  39596. BEGIN_JUCE_NAMESPACE
  39597. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  39598. Toolbar* const toolbar_)
  39599. : factory (factory_),
  39600. toolbar (toolbar_)
  39601. {
  39602. Component* const itemHolder = new Component();
  39603. Array <int> allIds;
  39604. factory_.getAllToolbarItemIds (allIds);
  39605. for (int i = 0; i < allIds.size(); ++i)
  39606. {
  39607. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  39608. jassert (tc != 0);
  39609. if (tc != 0)
  39610. {
  39611. itemHolder->addAndMakeVisible (tc);
  39612. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  39613. }
  39614. }
  39615. viewport = new Viewport();
  39616. viewport->setViewedComponent (itemHolder);
  39617. addAndMakeVisible (viewport);
  39618. }
  39619. ToolbarItemPalette::~ToolbarItemPalette()
  39620. {
  39621. viewport->getViewedComponent()->deleteAllChildren();
  39622. deleteAllChildren();
  39623. }
  39624. void ToolbarItemPalette::resized()
  39625. {
  39626. viewport->setBoundsInset (BorderSize (1));
  39627. Component* const itemHolder = viewport->getViewedComponent();
  39628. const int indent = 8;
  39629. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  39630. const int height = toolbar->getThickness();
  39631. int x = indent;
  39632. int y = indent;
  39633. int maxX = 0;
  39634. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  39635. {
  39636. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  39637. if (tc != 0)
  39638. {
  39639. tc->setStyle (toolbar->getStyle());
  39640. int preferredSize = 1, minSize = 1, maxSize = 1;
  39641. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  39642. {
  39643. if (x + preferredSize > preferredWidth && x > indent)
  39644. {
  39645. x = indent;
  39646. y += height;
  39647. }
  39648. tc->setBounds (x, y, preferredSize, height);
  39649. x += preferredSize + 8;
  39650. maxX = jmax (maxX, x);
  39651. }
  39652. }
  39653. }
  39654. itemHolder->setSize (maxX, y + height + 8);
  39655. }
  39656. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  39657. {
  39658. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  39659. jassert (tc != 0);
  39660. if (tc != 0)
  39661. {
  39662. tc->setBounds (comp->getBounds());
  39663. tc->setStyle (toolbar->getStyle());
  39664. tc->setEditingMode (comp->getEditingMode());
  39665. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  39666. }
  39667. }
  39668. END_JUCE_NAMESPACE
  39669. /********* End of inlined file: juce_ToolbarItemPalette.cpp *********/
  39670. /********* Start of inlined file: juce_TreeView.cpp *********/
  39671. BEGIN_JUCE_NAMESPACE
  39672. class TreeViewContentComponent : public Component
  39673. {
  39674. public:
  39675. TreeViewContentComponent (TreeView* const owner_)
  39676. : owner (owner_),
  39677. isDragging (false)
  39678. {
  39679. }
  39680. ~TreeViewContentComponent()
  39681. {
  39682. deleteAllChildren();
  39683. }
  39684. void mouseDown (const MouseEvent& e)
  39685. {
  39686. isDragging = false;
  39687. needSelectionOnMouseUp = false;
  39688. Rectangle pos;
  39689. TreeViewItem* const item = findItemAt (e.y, pos);
  39690. if (item != 0 && e.x >= pos.getX())
  39691. {
  39692. if (! owner->isMultiSelectEnabled())
  39693. item->setSelected (true, true);
  39694. else if (item->isSelected())
  39695. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  39696. else
  39697. selectBasedOnModifiers (item, e.mods);
  39698. MouseEvent e2 (e);
  39699. e2.x -= pos.getX();
  39700. e2.y -= pos.getY();
  39701. item->itemClicked (e2);
  39702. }
  39703. }
  39704. void mouseUp (const MouseEvent& e)
  39705. {
  39706. Rectangle pos;
  39707. TreeViewItem* const item = findItemAt (e.y, pos);
  39708. if (item != 0 && e.mouseWasClicked())
  39709. {
  39710. if (needSelectionOnMouseUp)
  39711. {
  39712. selectBasedOnModifiers (item, e.mods);
  39713. }
  39714. else if (e.mouseWasClicked())
  39715. {
  39716. if (e.x >= pos.getX() - owner->getIndentSize()
  39717. && e.x < pos.getX())
  39718. {
  39719. item->setOpen (! item->isOpen());
  39720. }
  39721. }
  39722. }
  39723. }
  39724. void mouseDoubleClick (const MouseEvent& e)
  39725. {
  39726. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  39727. {
  39728. Rectangle pos;
  39729. TreeViewItem* const item = findItemAt (e.y, pos);
  39730. if (item != 0 && e.x >= pos.getX())
  39731. {
  39732. MouseEvent e2 (e);
  39733. e2.x -= pos.getX();
  39734. e2.y -= pos.getY();
  39735. item->itemDoubleClicked (e2);
  39736. }
  39737. }
  39738. }
  39739. void mouseDrag (const MouseEvent& e)
  39740. {
  39741. if (isEnabled() && ! (e.mouseWasClicked() || isDragging))
  39742. {
  39743. isDragging = true;
  39744. Rectangle pos;
  39745. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  39746. if (item != 0 && e.getMouseDownX() >= pos.getX())
  39747. {
  39748. const String dragDescription (item->getDragSourceDescription());
  39749. if (dragDescription.isNotEmpty())
  39750. {
  39751. DragAndDropContainer* const dragContainer
  39752. = DragAndDropContainer::findParentDragContainerFor (this);
  39753. if (dragContainer != 0)
  39754. {
  39755. pos.setSize (pos.getWidth(), item->itemHeight);
  39756. Image* dragImage = Component::createComponentSnapshot (pos, true);
  39757. dragImage->multiplyAllAlphas (0.6f);
  39758. dragContainer->startDragging (dragDescription, owner, dragImage, true);
  39759. }
  39760. else
  39761. {
  39762. // to be able to do a drag-and-drop operation, the treeview needs to
  39763. // be inside a component which is also a DragAndDropContainer.
  39764. jassertfalse
  39765. }
  39766. }
  39767. }
  39768. }
  39769. }
  39770. void paint (Graphics& g);
  39771. TreeViewItem* findItemAt (int y, Rectangle& itemPosition) const;
  39772. void updateComponents()
  39773. {
  39774. int xAdjust = 0, yAdjust = 0;
  39775. if ((! owner->rootItemVisible) && owner->rootItem != 0)
  39776. {
  39777. yAdjust = owner->rootItem->itemHeight;
  39778. xAdjust = owner->getIndentSize();
  39779. }
  39780. const int visibleTop = -getY();
  39781. const int visibleBottom = visibleTop + getParentHeight();
  39782. BitArray itemsToKeep;
  39783. TreeViewItem* item = owner->rootItem;
  39784. int y = -yAdjust;
  39785. while (item != 0 && y < visibleBottom)
  39786. {
  39787. y += item->itemHeight;
  39788. if (y >= visibleTop)
  39789. {
  39790. const int index = rowComponentIds.indexOf (item->uid);
  39791. if (index < 0)
  39792. {
  39793. Component* const comp = item->createItemComponent();
  39794. if (comp != 0)
  39795. {
  39796. addAndMakeVisible (comp);
  39797. itemsToKeep.setBit (rowComponentItems.size());
  39798. rowComponentItems.add (item);
  39799. rowComponentIds.add (item->uid);
  39800. rowComponents.add (comp);
  39801. }
  39802. }
  39803. else
  39804. {
  39805. itemsToKeep.setBit (index);
  39806. }
  39807. }
  39808. item = item->getNextVisibleItem (true);
  39809. }
  39810. for (int i = rowComponentItems.size(); --i >= 0;)
  39811. {
  39812. Component* const comp = (Component*) (rowComponents.getUnchecked(i));
  39813. bool keep = false;
  39814. if ((itemsToKeep[i] || (comp == Component::getComponentUnderMouse() && comp->isMouseButtonDown()))
  39815. && isParentOf (comp))
  39816. {
  39817. if (itemsToKeep[i])
  39818. {
  39819. const TreeViewItem* const item = (TreeViewItem*) rowComponentItems.getUnchecked(i);
  39820. Rectangle pos (item->getItemPosition (false));
  39821. pos.translate (-xAdjust, -yAdjust);
  39822. pos.setSize (pos.getWidth() + xAdjust, item->itemHeight);
  39823. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  39824. {
  39825. keep = true;
  39826. comp->setBounds (pos);
  39827. }
  39828. }
  39829. else
  39830. {
  39831. comp->setSize (0, 0);
  39832. }
  39833. }
  39834. if (! keep)
  39835. {
  39836. delete comp;
  39837. rowComponents.remove (i);
  39838. rowComponentIds.remove (i);
  39839. rowComponentItems.remove (i);
  39840. }
  39841. }
  39842. }
  39843. void resized()
  39844. {
  39845. owner->itemsChanged();
  39846. }
  39847. juce_UseDebuggingNewOperator
  39848. private:
  39849. TreeView* const owner;
  39850. VoidArray rowComponentItems;
  39851. Array <int> rowComponentIds;
  39852. VoidArray rowComponents;
  39853. bool isDragging, needSelectionOnMouseUp;
  39854. TreeViewContentComponent (const TreeViewContentComponent&);
  39855. const TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  39856. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  39857. {
  39858. TreeViewItem* firstSelected = 0;
  39859. if (modifiers.isShiftDown() && ((firstSelected = owner->getSelectedItem (0)) != 0))
  39860. {
  39861. TreeViewItem* const lastSelected = owner->getSelectedItem (owner->getNumSelectedItems() - 1);
  39862. jassert (lastSelected != 0);
  39863. int rowStart = firstSelected->getRowNumberInTree();
  39864. int rowEnd = lastSelected->getRowNumberInTree();
  39865. if (rowStart > rowEnd)
  39866. swapVariables (rowStart, rowEnd);
  39867. int ourRow = item->getRowNumberInTree();
  39868. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  39869. if (ourRow > otherEnd)
  39870. swapVariables (ourRow, otherEnd);
  39871. for (int i = ourRow; i <= otherEnd; ++i)
  39872. owner->getItemOnRow (i)->setSelected (true, false);
  39873. }
  39874. else
  39875. {
  39876. const bool cmd = modifiers.isCommandDown();
  39877. item->setSelected ((! cmd) || (! item->isSelected()), ! cmd);
  39878. }
  39879. }
  39880. };
  39881. class TreeViewport : public Viewport
  39882. {
  39883. public:
  39884. TreeViewport() throw() {}
  39885. ~TreeViewport() throw() {}
  39886. void updateComponents()
  39887. {
  39888. if (getViewedComponent() != 0)
  39889. ((TreeViewContentComponent*) getViewedComponent())->updateComponents();
  39890. repaint();
  39891. }
  39892. void visibleAreaChanged (int, int, int, int)
  39893. {
  39894. updateComponents();
  39895. }
  39896. juce_UseDebuggingNewOperator
  39897. private:
  39898. TreeViewport (const TreeViewport&);
  39899. const TreeViewport& operator= (const TreeViewport&);
  39900. };
  39901. TreeView::TreeView (const String& componentName)
  39902. : Component (componentName),
  39903. rootItem (0),
  39904. indentSize (24),
  39905. defaultOpenness (false),
  39906. needsRecalculating (true),
  39907. rootItemVisible (true),
  39908. multiSelectEnabled (false)
  39909. {
  39910. addAndMakeVisible (viewport = new TreeViewport());
  39911. viewport->setViewedComponent (new TreeViewContentComponent (this));
  39912. viewport->setWantsKeyboardFocus (false);
  39913. setWantsKeyboardFocus (true);
  39914. }
  39915. TreeView::~TreeView()
  39916. {
  39917. if (rootItem != 0)
  39918. rootItem->setOwnerView (0);
  39919. deleteAllChildren();
  39920. }
  39921. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  39922. {
  39923. if (rootItem != newRootItem)
  39924. {
  39925. if (newRootItem != 0)
  39926. {
  39927. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  39928. if (newRootItem->ownerView != 0)
  39929. newRootItem->ownerView->setRootItem (0);
  39930. }
  39931. if (rootItem != 0)
  39932. rootItem->setOwnerView (0);
  39933. rootItem = newRootItem;
  39934. if (newRootItem != 0)
  39935. newRootItem->setOwnerView (this);
  39936. needsRecalculating = true;
  39937. handleAsyncUpdate();
  39938. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  39939. {
  39940. rootItem->setOpen (false); // force a re-open
  39941. rootItem->setOpen (true);
  39942. }
  39943. }
  39944. }
  39945. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  39946. {
  39947. rootItemVisible = shouldBeVisible;
  39948. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  39949. {
  39950. rootItem->setOpen (false); // force a re-open
  39951. rootItem->setOpen (true);
  39952. }
  39953. itemsChanged();
  39954. }
  39955. void TreeView::colourChanged()
  39956. {
  39957. setOpaque (findColour (backgroundColourId).isOpaque());
  39958. repaint();
  39959. }
  39960. void TreeView::setIndentSize (const int newIndentSize)
  39961. {
  39962. if (indentSize != newIndentSize)
  39963. {
  39964. indentSize = newIndentSize;
  39965. resized();
  39966. }
  39967. }
  39968. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  39969. {
  39970. if (defaultOpenness != isOpenByDefault)
  39971. {
  39972. defaultOpenness = isOpenByDefault;
  39973. itemsChanged();
  39974. }
  39975. }
  39976. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  39977. {
  39978. multiSelectEnabled = canMultiSelect;
  39979. }
  39980. void TreeView::clearSelectedItems()
  39981. {
  39982. if (rootItem != 0)
  39983. rootItem->deselectAllRecursively();
  39984. }
  39985. int TreeView::getNumSelectedItems() const throw()
  39986. {
  39987. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  39988. }
  39989. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  39990. {
  39991. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  39992. }
  39993. int TreeView::getNumRowsInTree() const
  39994. {
  39995. if (rootItem != 0)
  39996. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  39997. return 0;
  39998. }
  39999. TreeViewItem* TreeView::getItemOnRow (int index) const
  40000. {
  40001. if (! rootItemVisible)
  40002. ++index;
  40003. if (rootItem != 0 && index >= 0)
  40004. return rootItem->getItemOnRow (index);
  40005. return 0;
  40006. }
  40007. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  40008. {
  40009. XmlElement* e = 0;
  40010. if (rootItem != 0)
  40011. {
  40012. e = rootItem->createXmlOpenness();
  40013. if (e != 0 && alsoIncludeScrollPosition)
  40014. e->setAttribute (T("scrollPos"), viewport->getViewPositionY());
  40015. }
  40016. return e;
  40017. }
  40018. void TreeView::restoreOpennessState (const XmlElement& newState)
  40019. {
  40020. if (rootItem != 0)
  40021. {
  40022. rootItem->restoreFromXml (newState);
  40023. if (newState.hasAttribute (T("scrollPos")))
  40024. viewport->setViewPosition (viewport->getViewPositionX(),
  40025. newState.getIntAttribute (T("scrollPos")));
  40026. }
  40027. }
  40028. void TreeView::paint (Graphics& g)
  40029. {
  40030. g.fillAll (findColour (backgroundColourId));
  40031. }
  40032. void TreeView::resized()
  40033. {
  40034. viewport->setBounds (0, 0, getWidth(), getHeight());
  40035. itemsChanged();
  40036. }
  40037. void TreeView::moveSelectedRow (int delta)
  40038. {
  40039. int rowSelected = 0;
  40040. TreeViewItem* const firstSelected = getSelectedItem (0);
  40041. if (firstSelected != 0)
  40042. rowSelected = firstSelected->getRowNumberInTree();
  40043. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  40044. TreeViewItem* item = getItemOnRow (rowSelected);
  40045. if (item != 0)
  40046. {
  40047. item->setSelected (true, true);
  40048. scrollToKeepItemVisible (item);
  40049. }
  40050. }
  40051. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  40052. {
  40053. if (item != 0 && item->ownerView == this)
  40054. {
  40055. handleAsyncUpdate();
  40056. item = item->getDeepestOpenParentItem();
  40057. int y = item->y;
  40058. if (! rootItemVisible)
  40059. y -= rootItem->itemHeight;
  40060. int viewTop = viewport->getViewPositionY();
  40061. if (y < viewTop)
  40062. {
  40063. viewport->setViewPosition (viewport->getViewPositionX(), y);
  40064. }
  40065. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  40066. {
  40067. viewport->setViewPosition (viewport->getViewPositionX(),
  40068. (y + item->itemHeight) - viewport->getViewHeight());
  40069. }
  40070. }
  40071. }
  40072. bool TreeView::keyPressed (const KeyPress& key)
  40073. {
  40074. if (key.isKeyCode (KeyPress::upKey))
  40075. {
  40076. moveSelectedRow (-1);
  40077. }
  40078. else if (key.isKeyCode (KeyPress::downKey))
  40079. {
  40080. moveSelectedRow (1);
  40081. }
  40082. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  40083. {
  40084. if (rootItem != 0)
  40085. {
  40086. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  40087. if (key.isKeyCode (KeyPress::pageUpKey))
  40088. rowsOnScreen = -rowsOnScreen;
  40089. moveSelectedRow (rowsOnScreen);
  40090. }
  40091. }
  40092. else if (key.isKeyCode (KeyPress::homeKey))
  40093. {
  40094. moveSelectedRow (-0x3fffffff);
  40095. }
  40096. else if (key.isKeyCode (KeyPress::endKey))
  40097. {
  40098. moveSelectedRow (0x3fffffff);
  40099. }
  40100. else if (key.isKeyCode (KeyPress::returnKey))
  40101. {
  40102. TreeViewItem* const firstSelected = getSelectedItem (0);
  40103. if (firstSelected != 0)
  40104. firstSelected->setOpen (! firstSelected->isOpen());
  40105. }
  40106. else if (key.isKeyCode (KeyPress::leftKey))
  40107. {
  40108. TreeViewItem* const firstSelected = getSelectedItem (0);
  40109. if (firstSelected != 0)
  40110. {
  40111. if (firstSelected->isOpen())
  40112. {
  40113. firstSelected->setOpen (false);
  40114. }
  40115. else
  40116. {
  40117. TreeViewItem* parent = firstSelected->parentItem;
  40118. if ((! rootItemVisible) && parent == rootItem)
  40119. parent = 0;
  40120. if (parent != 0)
  40121. {
  40122. parent->setSelected (true, true);
  40123. scrollToKeepItemVisible (parent);
  40124. }
  40125. }
  40126. }
  40127. }
  40128. else if (key.isKeyCode (KeyPress::rightKey))
  40129. {
  40130. TreeViewItem* const firstSelected = getSelectedItem (0);
  40131. if (firstSelected != 0)
  40132. {
  40133. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  40134. moveSelectedRow (1);
  40135. else
  40136. firstSelected->setOpen (true);
  40137. }
  40138. }
  40139. else
  40140. {
  40141. return false;
  40142. }
  40143. return true;
  40144. }
  40145. void TreeView::itemsChanged() throw()
  40146. {
  40147. needsRecalculating = true;
  40148. repaint();
  40149. triggerAsyncUpdate();
  40150. }
  40151. void TreeView::handleAsyncUpdate()
  40152. {
  40153. if (needsRecalculating)
  40154. {
  40155. needsRecalculating = false;
  40156. const ScopedLock sl (nodeAlterationLock);
  40157. if (rootItem != 0)
  40158. rootItem->updatePositions (0);
  40159. ((TreeViewport*) viewport)->updateComponents();
  40160. if (rootItem != 0)
  40161. {
  40162. viewport->getViewedComponent()
  40163. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  40164. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  40165. }
  40166. else
  40167. {
  40168. viewport->getViewedComponent()->setSize (0, 0);
  40169. }
  40170. }
  40171. }
  40172. void TreeViewContentComponent::paint (Graphics& g)
  40173. {
  40174. if (owner->rootItem != 0)
  40175. {
  40176. owner->handleAsyncUpdate();
  40177. int w = getWidth();
  40178. if (! owner->rootItemVisible)
  40179. {
  40180. const int indentWidth = owner->getIndentSize();
  40181. g.setOrigin (-indentWidth, -owner->rootItem->itemHeight);
  40182. w += indentWidth;
  40183. }
  40184. owner->rootItem->paintRecursively (g, w);
  40185. }
  40186. }
  40187. TreeViewItem* TreeViewContentComponent::findItemAt (int y, Rectangle& itemPosition) const
  40188. {
  40189. if (owner->rootItem != 0)
  40190. {
  40191. owner->handleAsyncUpdate();
  40192. if (! owner->rootItemVisible)
  40193. y += owner->rootItem->itemHeight;
  40194. TreeViewItem* const ti = owner->rootItem->findItemRecursively (y);
  40195. if (ti != 0)
  40196. {
  40197. itemPosition = ti->getItemPosition (false);
  40198. if (! owner->rootItemVisible)
  40199. itemPosition.translate (-owner->getIndentSize(),
  40200. -owner->rootItem->itemHeight);
  40201. }
  40202. return ti;
  40203. }
  40204. return 0;
  40205. }
  40206. #define opennessDefault 0
  40207. #define opennessClosed 1
  40208. #define opennessOpen 2
  40209. TreeViewItem::TreeViewItem()
  40210. : ownerView (0),
  40211. parentItem (0),
  40212. subItems (8),
  40213. y (0),
  40214. itemHeight (0),
  40215. totalHeight (0),
  40216. selected (false),
  40217. redrawNeeded (true),
  40218. drawLinesInside (true),
  40219. openness (opennessDefault)
  40220. {
  40221. static int nextUID = 0;
  40222. uid = nextUID++;
  40223. }
  40224. TreeViewItem::~TreeViewItem()
  40225. {
  40226. }
  40227. const String TreeViewItem::getUniqueName() const
  40228. {
  40229. return String::empty;
  40230. }
  40231. void TreeViewItem::itemOpennessChanged (bool)
  40232. {
  40233. }
  40234. int TreeViewItem::getNumSubItems() const throw()
  40235. {
  40236. return subItems.size();
  40237. }
  40238. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  40239. {
  40240. return subItems [index];
  40241. }
  40242. void TreeViewItem::clearSubItems()
  40243. {
  40244. if (subItems.size() > 0)
  40245. {
  40246. if (ownerView != 0)
  40247. {
  40248. const ScopedLock sl (ownerView->nodeAlterationLock);
  40249. subItems.clear();
  40250. treeHasChanged();
  40251. }
  40252. else
  40253. {
  40254. subItems.clear();
  40255. }
  40256. }
  40257. }
  40258. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  40259. {
  40260. if (newItem != 0)
  40261. {
  40262. newItem->parentItem = this;
  40263. newItem->setOwnerView (ownerView);
  40264. newItem->y = 0;
  40265. newItem->itemHeight = newItem->getItemHeight();
  40266. newItem->totalHeight = 0;
  40267. newItem->itemWidth = newItem->getItemWidth();
  40268. newItem->totalWidth = 0;
  40269. if (ownerView != 0)
  40270. {
  40271. const ScopedLock sl (ownerView->nodeAlterationLock);
  40272. subItems.insert (insertPosition, newItem);
  40273. treeHasChanged();
  40274. if (newItem->isOpen())
  40275. newItem->itemOpennessChanged (true);
  40276. }
  40277. else
  40278. {
  40279. subItems.insert (insertPosition, newItem);
  40280. if (newItem->isOpen())
  40281. newItem->itemOpennessChanged (true);
  40282. }
  40283. }
  40284. }
  40285. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  40286. {
  40287. if (ownerView != 0)
  40288. ownerView->nodeAlterationLock.enter();
  40289. if (((unsigned int) index) < (unsigned int) subItems.size())
  40290. {
  40291. subItems.remove (index, deleteItem);
  40292. treeHasChanged();
  40293. }
  40294. if (ownerView != 0)
  40295. ownerView->nodeAlterationLock.exit();
  40296. }
  40297. bool TreeViewItem::isOpen() const throw()
  40298. {
  40299. if (openness == opennessDefault)
  40300. return ownerView != 0 && ownerView->defaultOpenness;
  40301. else
  40302. return openness == opennessOpen;
  40303. }
  40304. void TreeViewItem::setOpen (const bool shouldBeOpen)
  40305. {
  40306. if (isOpen() != shouldBeOpen)
  40307. {
  40308. openness = shouldBeOpen ? opennessOpen
  40309. : opennessClosed;
  40310. treeHasChanged();
  40311. itemOpennessChanged (isOpen());
  40312. }
  40313. }
  40314. bool TreeViewItem::isSelected() const throw()
  40315. {
  40316. return selected;
  40317. }
  40318. void TreeViewItem::deselectAllRecursively()
  40319. {
  40320. setSelected (false, false);
  40321. for (int i = 0; i < subItems.size(); ++i)
  40322. subItems.getUnchecked(i)->deselectAllRecursively();
  40323. }
  40324. void TreeViewItem::setSelected (const bool shouldBeSelected,
  40325. const bool deselectOtherItemsFirst)
  40326. {
  40327. if (deselectOtherItemsFirst)
  40328. getTopLevelItem()->deselectAllRecursively();
  40329. if (shouldBeSelected != selected)
  40330. {
  40331. selected = shouldBeSelected;
  40332. if (ownerView != 0)
  40333. ownerView->repaint();
  40334. itemSelectionChanged (shouldBeSelected);
  40335. }
  40336. }
  40337. void TreeViewItem::paintItem (Graphics&, int, int)
  40338. {
  40339. }
  40340. void TreeViewItem::itemClicked (const MouseEvent&)
  40341. {
  40342. }
  40343. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  40344. {
  40345. if (mightContainSubItems())
  40346. setOpen (! isOpen());
  40347. }
  40348. void TreeViewItem::itemSelectionChanged (bool)
  40349. {
  40350. }
  40351. const String TreeViewItem::getDragSourceDescription()
  40352. {
  40353. return String::empty;
  40354. }
  40355. const Rectangle TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  40356. {
  40357. const int indentX = getIndentX();
  40358. int width = itemWidth;
  40359. if (ownerView != 0 && width < 0)
  40360. width = ownerView->viewport->getViewWidth() - indentX;
  40361. Rectangle r (indentX, y, jmax (0, width), totalHeight);
  40362. if (relativeToTreeViewTopLeft)
  40363. r.setPosition (r.getX() - ownerView->viewport->getViewPositionX(),
  40364. r.getY() - ownerView->viewport->getViewPositionY());
  40365. return r;
  40366. }
  40367. void TreeViewItem::treeHasChanged() const throw()
  40368. {
  40369. if (ownerView != 0)
  40370. ownerView->itemsChanged();
  40371. }
  40372. void TreeViewItem::updatePositions (int newY)
  40373. {
  40374. y = newY;
  40375. itemHeight = getItemHeight();
  40376. totalHeight = itemHeight;
  40377. itemWidth = getItemWidth();
  40378. totalWidth = jmax (itemWidth, 0);
  40379. if (isOpen())
  40380. {
  40381. const int ourIndent = getIndentX();
  40382. newY += totalHeight;
  40383. for (int i = 0; i < subItems.size(); ++i)
  40384. {
  40385. TreeViewItem* const ti = subItems.getUnchecked(i);
  40386. ti->updatePositions (newY);
  40387. newY += ti->totalHeight;
  40388. totalHeight += ti->totalHeight;
  40389. totalWidth = jmax (totalWidth, ti->totalWidth + ourIndent);
  40390. }
  40391. }
  40392. }
  40393. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  40394. {
  40395. TreeViewItem* result = this;
  40396. TreeViewItem* item = this;
  40397. while (item->parentItem != 0)
  40398. {
  40399. item = item->parentItem;
  40400. if (! item->isOpen())
  40401. result = item;
  40402. }
  40403. return result;
  40404. }
  40405. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  40406. {
  40407. ownerView = newOwner;
  40408. for (int i = subItems.size(); --i >= 0;)
  40409. subItems.getUnchecked(i)->setOwnerView (newOwner);
  40410. }
  40411. int TreeViewItem::getIndentX() const throw()
  40412. {
  40413. const int indentWidth = ownerView->getIndentSize();
  40414. int x = indentWidth;
  40415. TreeViewItem* p = parentItem;
  40416. while (p != 0)
  40417. {
  40418. x += indentWidth;
  40419. p = p->parentItem;
  40420. }
  40421. return x;
  40422. }
  40423. void TreeViewItem::paintRecursively (Graphics& g, int width)
  40424. {
  40425. jassert (ownerView != 0);
  40426. if (ownerView == 0)
  40427. return;
  40428. const int indent = getIndentX();
  40429. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  40430. g.setColour (ownerView->findColour (TreeView::linesColourId));
  40431. const float halfH = itemHeight * 0.5f;
  40432. int depth = 0;
  40433. TreeViewItem* p = parentItem;
  40434. while (p != 0)
  40435. {
  40436. ++depth;
  40437. p = p->parentItem;
  40438. }
  40439. const int indentWidth = ownerView->getIndentSize();
  40440. float x = (depth + 0.5f) * indentWidth;
  40441. if (x > 0)
  40442. {
  40443. if (depth >= 0)
  40444. {
  40445. if (parentItem != 0 && parentItem->drawLinesInside)
  40446. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  40447. if ((parentItem != 0 && parentItem->drawLinesInside)
  40448. || (parentItem == 0 && drawLinesInside))
  40449. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  40450. }
  40451. p = parentItem;
  40452. int d = depth;
  40453. while (p != 0 && --d >= 0)
  40454. {
  40455. x -= (float) indentWidth;
  40456. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  40457. && ! p->isLastOfSiblings())
  40458. {
  40459. g.drawLine (x, 0, x, (float) itemHeight);
  40460. }
  40461. p = p->parentItem;
  40462. }
  40463. if (mightContainSubItems())
  40464. {
  40465. ownerView->getLookAndFeel()
  40466. .drawTreeviewPlusMinusBox (g,
  40467. depth * indentWidth, 0,
  40468. indentWidth, itemHeight,
  40469. ! isOpen());
  40470. }
  40471. }
  40472. {
  40473. g.saveState();
  40474. g.setOrigin (indent, 0);
  40475. if (g.reduceClipRegion (0, 0, itemW, itemHeight))
  40476. paintItem (g, itemW, itemHeight);
  40477. g.restoreState();
  40478. }
  40479. if (isOpen())
  40480. {
  40481. const Rectangle clip (g.getClipBounds());
  40482. for (int i = 0; i < subItems.size(); ++i)
  40483. {
  40484. TreeViewItem* const ti = subItems.getUnchecked(i);
  40485. const int relY = ti->y - y;
  40486. if (relY >= clip.getBottom())
  40487. break;
  40488. if (relY + ti->totalHeight >= clip.getY())
  40489. {
  40490. g.saveState();
  40491. g.setOrigin (0, relY);
  40492. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  40493. ti->paintRecursively (g, width);
  40494. g.restoreState();
  40495. }
  40496. }
  40497. }
  40498. }
  40499. bool TreeViewItem::isLastOfSiblings() const throw()
  40500. {
  40501. return parentItem == 0
  40502. || parentItem->subItems.getLast() == this;
  40503. }
  40504. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  40505. {
  40506. return (parentItem == 0) ? this
  40507. : parentItem->getTopLevelItem();
  40508. }
  40509. int TreeViewItem::getNumRows() const throw()
  40510. {
  40511. int num = 1;
  40512. if (isOpen())
  40513. {
  40514. for (int i = subItems.size(); --i >= 0;)
  40515. num += subItems.getUnchecked(i)->getNumRows();
  40516. }
  40517. return num;
  40518. }
  40519. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  40520. {
  40521. if (index == 0)
  40522. return this;
  40523. if (index > 0 && isOpen())
  40524. {
  40525. --index;
  40526. for (int i = 0; i < subItems.size(); ++i)
  40527. {
  40528. TreeViewItem* const item = subItems.getUnchecked(i);
  40529. if (index == 0)
  40530. return item;
  40531. const int numRows = item->getNumRows();
  40532. if (numRows > index)
  40533. return item->getItemOnRow (index);
  40534. index -= numRows;
  40535. }
  40536. }
  40537. return 0;
  40538. }
  40539. TreeViewItem* TreeViewItem::findItemRecursively (int y) throw()
  40540. {
  40541. if (((unsigned int) y) < (unsigned int) totalHeight)
  40542. {
  40543. const int h = itemHeight;
  40544. if (y < h)
  40545. return this;
  40546. if (isOpen())
  40547. {
  40548. y -= h;
  40549. for (int i = 0; i < subItems.size(); ++i)
  40550. {
  40551. TreeViewItem* const ti = subItems.getUnchecked(i);
  40552. if (ti->totalHeight >= y)
  40553. return ti->findItemRecursively (y);
  40554. y -= ti->totalHeight;
  40555. }
  40556. }
  40557. }
  40558. return 0;
  40559. }
  40560. int TreeViewItem::countSelectedItemsRecursively() const throw()
  40561. {
  40562. int total = 0;
  40563. if (isSelected())
  40564. ++total;
  40565. for (int i = subItems.size(); --i >= 0;)
  40566. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  40567. return total;
  40568. }
  40569. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  40570. {
  40571. if (isSelected())
  40572. {
  40573. if (index == 0)
  40574. return this;
  40575. --index;
  40576. }
  40577. if (index >= 0)
  40578. {
  40579. for (int i = 0; i < subItems.size(); ++i)
  40580. {
  40581. TreeViewItem* const item = subItems.getUnchecked(i);
  40582. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  40583. if (found != 0)
  40584. return found;
  40585. index -= item->countSelectedItemsRecursively();
  40586. }
  40587. }
  40588. return 0;
  40589. }
  40590. int TreeViewItem::getRowNumberInTree() const throw()
  40591. {
  40592. if (parentItem != 0 && ownerView != 0)
  40593. {
  40594. int n = 1 + parentItem->getRowNumberInTree();
  40595. int ourIndex = parentItem->subItems.indexOf (this);
  40596. jassert (ourIndex >= 0);
  40597. while (--ourIndex >= 0)
  40598. n += parentItem->subItems [ourIndex]->getNumRows();
  40599. if (parentItem->parentItem == 0
  40600. && ! ownerView->rootItemVisible)
  40601. --n;
  40602. return n;
  40603. }
  40604. else
  40605. {
  40606. return 0;
  40607. }
  40608. }
  40609. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  40610. {
  40611. drawLinesInside = drawLines;
  40612. }
  40613. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  40614. {
  40615. if (recurse && isOpen() && subItems.size() > 0)
  40616. return subItems [0];
  40617. if (parentItem != 0)
  40618. {
  40619. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  40620. if (nextIndex >= parentItem->subItems.size())
  40621. return parentItem->getNextVisibleItem (false);
  40622. return parentItem->subItems [nextIndex];
  40623. }
  40624. return 0;
  40625. }
  40626. void TreeViewItem::restoreFromXml (const XmlElement& e)
  40627. {
  40628. if (e.hasTagName (T("CLOSED")))
  40629. {
  40630. setOpen (false);
  40631. }
  40632. else if (e.hasTagName (T("OPEN")))
  40633. {
  40634. setOpen (true);
  40635. forEachXmlChildElement (e, n)
  40636. {
  40637. const String id (n->getStringAttribute (T("id")));
  40638. for (int i = 0; i < subItems.size(); ++i)
  40639. {
  40640. TreeViewItem* const ti = subItems.getUnchecked(i);
  40641. if (ti->getUniqueName() == id)
  40642. {
  40643. ti->restoreFromXml (*n);
  40644. break;
  40645. }
  40646. }
  40647. }
  40648. }
  40649. }
  40650. XmlElement* TreeViewItem::createXmlOpenness() const
  40651. {
  40652. if (openness != opennessDefault)
  40653. {
  40654. const String name (getUniqueName());
  40655. if (name.isNotEmpty())
  40656. {
  40657. XmlElement* e;
  40658. if (isOpen())
  40659. {
  40660. e = new XmlElement (T("OPEN"));
  40661. for (int i = 0; i < subItems.size(); ++i)
  40662. e->addChildElement (subItems.getUnchecked(i)->createXmlOpenness());
  40663. }
  40664. else
  40665. {
  40666. e = new XmlElement (T("CLOSED"));
  40667. }
  40668. e->setAttribute (T("id"), name);
  40669. return e;
  40670. }
  40671. else
  40672. {
  40673. // trying to save the openness for an element that has no name - this won't
  40674. // work because it needs the names to identify what to open.
  40675. jassertfalse
  40676. }
  40677. }
  40678. return 0;
  40679. }
  40680. END_JUCE_NAMESPACE
  40681. /********* End of inlined file: juce_TreeView.cpp *********/
  40682. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  40683. BEGIN_JUCE_NAMESPACE
  40684. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  40685. : fileList (listToShow),
  40686. listeners (2)
  40687. {
  40688. }
  40689. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  40690. {
  40691. }
  40692. FileBrowserListener::~FileBrowserListener()
  40693. {
  40694. }
  40695. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener) throw()
  40696. {
  40697. jassert (listener != 0);
  40698. if (listener != 0)
  40699. listeners.add (listener);
  40700. }
  40701. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener) throw()
  40702. {
  40703. listeners.removeValue (listener);
  40704. }
  40705. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  40706. {
  40707. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  40708. for (int i = listeners.size(); --i >= 0;)
  40709. {
  40710. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  40711. if (deletionWatcher.hasBeenDeleted())
  40712. return;
  40713. i = jmin (i, listeners.size() - 1);
  40714. }
  40715. }
  40716. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  40717. {
  40718. if (fileList.getDirectory().exists())
  40719. {
  40720. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  40721. for (int i = listeners.size(); --i >= 0;)
  40722. {
  40723. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (file, e);
  40724. if (deletionWatcher.hasBeenDeleted())
  40725. return;
  40726. i = jmin (i, listeners.size() - 1);
  40727. }
  40728. }
  40729. }
  40730. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  40731. {
  40732. if (fileList.getDirectory().exists())
  40733. {
  40734. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  40735. for (int i = listeners.size(); --i >= 0;)
  40736. {
  40737. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (file);
  40738. if (deletionWatcher.hasBeenDeleted())
  40739. return;
  40740. i = jmin (i, listeners.size() - 1);
  40741. }
  40742. }
  40743. }
  40744. END_JUCE_NAMESPACE
  40745. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  40746. /********* Start of inlined file: juce_DirectoryContentsList.cpp *********/
  40747. BEGIN_JUCE_NAMESPACE
  40748. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  40749. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  40750. Time* creationTime, bool* isReadOnly) throw();
  40751. bool juce_findFileNext (void* handle, String& resultFile,
  40752. bool* isDirectory, bool* isHidden, int64* fileSize,
  40753. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  40754. void juce_findFileClose (void* handle) throw();
  40755. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  40756. TimeSliceThread& thread_)
  40757. : fileFilter (fileFilter_),
  40758. thread (thread_),
  40759. includeDirectories (false),
  40760. includeFiles (false),
  40761. ignoreHiddenFiles (true),
  40762. fileFindHandle (0),
  40763. shouldStop (true)
  40764. {
  40765. }
  40766. DirectoryContentsList::~DirectoryContentsList()
  40767. {
  40768. clear();
  40769. }
  40770. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  40771. {
  40772. ignoreHiddenFiles = shouldIgnoreHiddenFiles;
  40773. }
  40774. const File& DirectoryContentsList::getDirectory() const throw()
  40775. {
  40776. return root;
  40777. }
  40778. void DirectoryContentsList::setDirectory (const File& directory,
  40779. const bool includeDirectories_,
  40780. const bool includeFiles_)
  40781. {
  40782. if (directory != root
  40783. || includeDirectories != includeDirectories_
  40784. || includeFiles != includeFiles_)
  40785. {
  40786. clear();
  40787. root = directory;
  40788. includeDirectories = includeDirectories_;
  40789. includeFiles = includeFiles_;
  40790. refresh();
  40791. }
  40792. }
  40793. void DirectoryContentsList::clear()
  40794. {
  40795. shouldStop = true;
  40796. thread.removeTimeSliceClient (this);
  40797. if (fileFindHandle != 0)
  40798. {
  40799. juce_findFileClose (fileFindHandle);
  40800. fileFindHandle = 0;
  40801. }
  40802. if (files.size() > 0)
  40803. {
  40804. files.clear();
  40805. changed();
  40806. }
  40807. }
  40808. void DirectoryContentsList::refresh()
  40809. {
  40810. clear();
  40811. if (root.isDirectory())
  40812. {
  40813. String fileFound;
  40814. bool fileFoundIsDir, isHidden, isReadOnly;
  40815. int64 fileSize;
  40816. Time modTime, creationTime;
  40817. String path (root.getFullPathName());
  40818. if (! path.endsWithChar (File::separator))
  40819. path += File::separator;
  40820. jassert (fileFindHandle == 0);
  40821. fileFindHandle = juce_findFileStart (path, T("*"), fileFound,
  40822. &fileFoundIsDir,
  40823. &isHidden,
  40824. &fileSize,
  40825. &modTime,
  40826. &creationTime,
  40827. &isReadOnly);
  40828. if (fileFindHandle != 0 && fileFound.isNotEmpty())
  40829. {
  40830. if (addFile (fileFound, fileFoundIsDir, isHidden,
  40831. fileSize, modTime, creationTime, isReadOnly))
  40832. {
  40833. changed();
  40834. }
  40835. }
  40836. shouldStop = false;
  40837. thread.addTimeSliceClient (this);
  40838. }
  40839. }
  40840. int DirectoryContentsList::getNumFiles() const
  40841. {
  40842. return files.size();
  40843. }
  40844. bool DirectoryContentsList::getFileInfo (const int index,
  40845. FileInfo& result) const
  40846. {
  40847. const ScopedLock sl (fileListLock);
  40848. const FileInfo* const info = files [index];
  40849. if (info != 0)
  40850. {
  40851. result = *info;
  40852. return true;
  40853. }
  40854. return false;
  40855. }
  40856. const File DirectoryContentsList::getFile (const int index) const
  40857. {
  40858. const ScopedLock sl (fileListLock);
  40859. const FileInfo* const info = files [index];
  40860. if (info != 0)
  40861. return root.getChildFile (info->filename);
  40862. return File::nonexistent;
  40863. }
  40864. bool DirectoryContentsList::isStillLoading() const
  40865. {
  40866. return fileFindHandle != 0;
  40867. }
  40868. void DirectoryContentsList::changed()
  40869. {
  40870. sendChangeMessage (this);
  40871. }
  40872. bool DirectoryContentsList::useTimeSlice()
  40873. {
  40874. const uint32 startTime = Time::getApproximateMillisecondCounter();
  40875. bool hasChanged = false;
  40876. for (int i = 100; --i >= 0;)
  40877. {
  40878. if (! checkNextFile (hasChanged))
  40879. {
  40880. if (hasChanged)
  40881. changed();
  40882. return false;
  40883. }
  40884. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  40885. break;
  40886. }
  40887. if (hasChanged)
  40888. changed();
  40889. return true;
  40890. }
  40891. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  40892. {
  40893. if (fileFindHandle != 0)
  40894. {
  40895. String fileFound;
  40896. bool fileFoundIsDir, isHidden, isReadOnly;
  40897. int64 fileSize;
  40898. Time modTime, creationTime;
  40899. if (juce_findFileNext (fileFindHandle, fileFound,
  40900. &fileFoundIsDir, &isHidden,
  40901. &fileSize,
  40902. &modTime,
  40903. &creationTime,
  40904. &isReadOnly))
  40905. {
  40906. if (addFile (fileFound, fileFoundIsDir, isHidden, fileSize,
  40907. modTime, creationTime, isReadOnly))
  40908. {
  40909. hasChanged = true;
  40910. }
  40911. return true;
  40912. }
  40913. else
  40914. {
  40915. juce_findFileClose (fileFindHandle);
  40916. fileFindHandle = 0;
  40917. }
  40918. }
  40919. return false;
  40920. }
  40921. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  40922. const DirectoryContentsList::FileInfo* const second) throw()
  40923. {
  40924. #if JUCE_WIN32
  40925. if (first->isDirectory != second->isDirectory)
  40926. return first->isDirectory ? -1 : 1;
  40927. #endif
  40928. return first->filename.compareIgnoreCase (second->filename);
  40929. }
  40930. bool DirectoryContentsList::addFile (const String& filename,
  40931. const bool isDir,
  40932. const bool isHidden,
  40933. const int64 fileSize,
  40934. const Time& modTime,
  40935. const Time& creationTime,
  40936. const bool isReadOnly)
  40937. {
  40938. if (filename == T("..")
  40939. || filename == T(".")
  40940. || (ignoreHiddenFiles && isHidden))
  40941. return false;
  40942. const File file (root.getChildFile (filename));
  40943. if (((isDir && includeDirectories) || ((! isDir) && includeFiles))
  40944. && (fileFilter == 0
  40945. || ((! isDir) && fileFilter->isFileSuitable (file))
  40946. || (isDir && fileFilter->isDirectorySuitable (file))))
  40947. {
  40948. FileInfo* const info = new FileInfo();
  40949. info->filename = filename;
  40950. info->fileSize = fileSize;
  40951. info->modificationTime = modTime;
  40952. info->creationTime = creationTime;
  40953. info->isDirectory = isDir;
  40954. info->isReadOnly = isReadOnly;
  40955. const ScopedLock sl (fileListLock);
  40956. for (int i = files.size(); --i >= 0;)
  40957. {
  40958. if (files.getUnchecked(i)->filename == info->filename)
  40959. {
  40960. delete info;
  40961. return false;
  40962. }
  40963. }
  40964. files.addSorted (*this, info);
  40965. return true;
  40966. }
  40967. return false;
  40968. }
  40969. END_JUCE_NAMESPACE
  40970. /********* End of inlined file: juce_DirectoryContentsList.cpp *********/
  40971. /********* Start of inlined file: juce_FileBrowserComponent.cpp *********/
  40972. BEGIN_JUCE_NAMESPACE
  40973. class DirectoriesOnlyFilter : public FileFilter
  40974. {
  40975. public:
  40976. DirectoriesOnlyFilter() : FileFilter (String::empty) {}
  40977. bool isFileSuitable (const File&) const { return false; }
  40978. bool isDirectorySuitable (const File&) const { return true; }
  40979. };
  40980. FileBrowserComponent::FileBrowserComponent (FileChooserMode mode_,
  40981. const File& initialFileOrDirectory,
  40982. const FileFilter* fileFilter,
  40983. FilePreviewComponent* previewComp_,
  40984. const bool useTreeView,
  40985. const bool filenameTextBoxIsReadOnly)
  40986. : directoriesOnlyFilter (0),
  40987. mode (mode_),
  40988. listeners (2),
  40989. previewComp (previewComp_),
  40990. thread ("Juce FileBrowser")
  40991. {
  40992. String filename;
  40993. if (initialFileOrDirectory == File::nonexistent)
  40994. {
  40995. currentRoot = File::getCurrentWorkingDirectory();
  40996. }
  40997. else if (initialFileOrDirectory.isDirectory())
  40998. {
  40999. currentRoot = initialFileOrDirectory;
  41000. }
  41001. else
  41002. {
  41003. currentRoot = initialFileOrDirectory.getParentDirectory();
  41004. filename = initialFileOrDirectory.getFileName();
  41005. }
  41006. if (mode_ == chooseDirectoryMode)
  41007. fileFilter = directoriesOnlyFilter = new DirectoriesOnlyFilter();
  41008. fileList = new DirectoryContentsList (fileFilter, thread);
  41009. if (useTreeView)
  41010. {
  41011. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  41012. addAndMakeVisible (tree);
  41013. fileListComponent = tree;
  41014. }
  41015. else
  41016. {
  41017. FileListComponent* const list = new FileListComponent (*fileList);
  41018. list->setOutlineThickness (1);
  41019. addAndMakeVisible (list);
  41020. fileListComponent = list;
  41021. }
  41022. fileListComponent->addListener (this);
  41023. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  41024. currentPathBox->setEditableText (true);
  41025. StringArray rootNames, rootPaths;
  41026. const BitArray separators (getRoots (rootNames, rootPaths));
  41027. for (int i = 0; i < rootNames.size(); ++i)
  41028. {
  41029. if (separators [i])
  41030. currentPathBox->addSeparator();
  41031. currentPathBox->addItem (rootNames[i], i + 1);
  41032. }
  41033. currentPathBox->addSeparator();
  41034. currentPathBox->addListener (this);
  41035. addAndMakeVisible (filenameBox = new TextEditor());
  41036. filenameBox->setMultiLine (false);
  41037. filenameBox->setSelectAllWhenFocused (true);
  41038. filenameBox->setText (filename, false);
  41039. filenameBox->addListener (this);
  41040. filenameBox->setReadOnly (filenameTextBoxIsReadOnly);
  41041. Label* label = new Label ("f", (mode == chooseDirectoryMode) ? TRANS("folder:")
  41042. : TRANS("file:"));
  41043. addAndMakeVisible (label);
  41044. label->attachToComponent (filenameBox, true);
  41045. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  41046. goUpButton->addButtonListener (this);
  41047. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  41048. if (previewComp != 0)
  41049. addAndMakeVisible (previewComp);
  41050. setRoot (currentRoot);
  41051. thread.startThread (4);
  41052. }
  41053. FileBrowserComponent::~FileBrowserComponent()
  41054. {
  41055. if (previewComp != 0)
  41056. removeChildComponent (previewComp);
  41057. deleteAllChildren();
  41058. deleteAndZero (fileList);
  41059. delete directoriesOnlyFilter;
  41060. thread.stopThread (10000);
  41061. }
  41062. void FileBrowserComponent::addListener (FileBrowserListener* const newListener) throw()
  41063. {
  41064. jassert (newListener != 0)
  41065. if (newListener != 0)
  41066. listeners.add (newListener);
  41067. }
  41068. void FileBrowserComponent::removeListener (FileBrowserListener* const listener) throw()
  41069. {
  41070. listeners.removeValue (listener);
  41071. }
  41072. const File FileBrowserComponent::getCurrentFile() const throw()
  41073. {
  41074. return currentRoot.getChildFile (filenameBox->getText());
  41075. }
  41076. bool FileBrowserComponent::currentFileIsValid() const
  41077. {
  41078. if (mode == saveFileMode)
  41079. return ! getCurrentFile().isDirectory();
  41080. else if (mode == loadFileMode)
  41081. return getCurrentFile().existsAsFile();
  41082. else if (mode == chooseDirectoryMode)
  41083. return getCurrentFile().isDirectory();
  41084. jassertfalse
  41085. return false;
  41086. }
  41087. const File FileBrowserComponent::getRoot() const
  41088. {
  41089. return currentRoot;
  41090. }
  41091. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  41092. {
  41093. if (currentRoot != newRootDirectory)
  41094. {
  41095. fileListComponent->scrollToTop();
  41096. if (mode == chooseDirectoryMode)
  41097. filenameBox->setText (String::empty, false);
  41098. String path (newRootDirectory.getFullPathName());
  41099. if (path.isEmpty())
  41100. path += File::separator;
  41101. StringArray rootNames, rootPaths;
  41102. getRoots (rootNames, rootPaths);
  41103. if (! rootPaths.contains (path, true))
  41104. {
  41105. bool alreadyListed = false;
  41106. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  41107. {
  41108. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  41109. {
  41110. alreadyListed = true;
  41111. break;
  41112. }
  41113. }
  41114. if (! alreadyListed)
  41115. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  41116. }
  41117. }
  41118. currentRoot = newRootDirectory;
  41119. fileList->setDirectory (currentRoot, true, true);
  41120. String currentRootName (currentRoot.getFullPathName());
  41121. if (currentRootName.isEmpty())
  41122. currentRootName += File::separator;
  41123. currentPathBox->setText (currentRootName, true);
  41124. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  41125. && currentRoot.getParentDirectory() != currentRoot);
  41126. }
  41127. void FileBrowserComponent::goUp()
  41128. {
  41129. setRoot (getRoot().getParentDirectory());
  41130. }
  41131. void FileBrowserComponent::refresh()
  41132. {
  41133. fileList->refresh();
  41134. }
  41135. const String FileBrowserComponent::getActionVerb() const
  41136. {
  41137. return (mode == chooseDirectoryMode) ? TRANS("Choose")
  41138. : ((mode == saveFileMode) ? TRANS("Save") : TRANS("Open"));
  41139. }
  41140. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  41141. {
  41142. return previewComp;
  41143. }
  41144. void FileBrowserComponent::resized()
  41145. {
  41146. getLookAndFeel()
  41147. .layoutFileBrowserComponent (*this, fileListComponent,
  41148. previewComp, currentPathBox,
  41149. filenameBox, goUpButton);
  41150. }
  41151. void FileBrowserComponent::sendListenerChangeMessage()
  41152. {
  41153. ComponentDeletionWatcher deletionWatcher (this);
  41154. if (previewComp != 0)
  41155. previewComp->selectedFileChanged (getCurrentFile());
  41156. jassert (! deletionWatcher.hasBeenDeleted());
  41157. for (int i = listeners.size(); --i >= 0;)
  41158. {
  41159. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  41160. if (deletionWatcher.hasBeenDeleted())
  41161. return;
  41162. i = jmin (i, listeners.size() - 1);
  41163. }
  41164. }
  41165. void FileBrowserComponent::selectionChanged()
  41166. {
  41167. const File selected (fileListComponent->getSelectedFile());
  41168. if ((mode == chooseDirectoryMode && selected.isDirectory())
  41169. || selected.existsAsFile())
  41170. {
  41171. filenameBox->setText (selected.getRelativePathFrom (getRoot()), false);
  41172. }
  41173. sendListenerChangeMessage();
  41174. }
  41175. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  41176. {
  41177. ComponentDeletionWatcher deletionWatcher (this);
  41178. for (int i = listeners.size(); --i >= 0;)
  41179. {
  41180. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (f, e);
  41181. if (deletionWatcher.hasBeenDeleted())
  41182. return;
  41183. i = jmin (i, listeners.size() - 1);
  41184. }
  41185. }
  41186. void FileBrowserComponent::fileDoubleClicked (const File& f)
  41187. {
  41188. if (f.isDirectory())
  41189. {
  41190. setRoot (f);
  41191. }
  41192. else
  41193. {
  41194. ComponentDeletionWatcher deletionWatcher (this);
  41195. for (int i = listeners.size(); --i >= 0;)
  41196. {
  41197. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (f);
  41198. if (deletionWatcher.hasBeenDeleted())
  41199. return;
  41200. i = jmin (i, listeners.size() - 1);
  41201. }
  41202. }
  41203. }
  41204. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  41205. {
  41206. sendListenerChangeMessage();
  41207. }
  41208. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  41209. {
  41210. if (filenameBox->getText().containsChar (File::separator))
  41211. {
  41212. const File f (currentRoot.getChildFile (filenameBox->getText()));
  41213. if (f.isDirectory())
  41214. {
  41215. setRoot (f);
  41216. filenameBox->setText (String::empty);
  41217. }
  41218. else
  41219. {
  41220. setRoot (f.getParentDirectory());
  41221. filenameBox->setText (f.getFileName());
  41222. }
  41223. }
  41224. else
  41225. {
  41226. fileDoubleClicked (getCurrentFile());
  41227. }
  41228. }
  41229. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  41230. {
  41231. }
  41232. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  41233. {
  41234. if (mode != saveFileMode)
  41235. selectionChanged();
  41236. }
  41237. void FileBrowserComponent::buttonClicked (Button*)
  41238. {
  41239. goUp();
  41240. }
  41241. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  41242. {
  41243. const String newText (currentPathBox->getText().trim().unquoted());
  41244. if (newText.isNotEmpty())
  41245. {
  41246. const int index = currentPathBox->getSelectedId() - 1;
  41247. StringArray rootNames, rootPaths;
  41248. getRoots (rootNames, rootPaths);
  41249. if (rootPaths [index].isNotEmpty())
  41250. {
  41251. setRoot (File (rootPaths [index]));
  41252. }
  41253. else
  41254. {
  41255. File f (newText);
  41256. for (;;)
  41257. {
  41258. if (f.isDirectory())
  41259. {
  41260. setRoot (f);
  41261. break;
  41262. }
  41263. if (f.getParentDirectory() == f)
  41264. break;
  41265. f = f.getParentDirectory();
  41266. }
  41267. }
  41268. }
  41269. }
  41270. const BitArray FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  41271. {
  41272. BitArray separators;
  41273. #if JUCE_WIN32
  41274. OwnedArray<File> roots;
  41275. File::findFileSystemRoots (roots);
  41276. rootPaths.clear();
  41277. for (int i = 0; i < roots.size(); ++i)
  41278. {
  41279. const File* const drive = roots.getUnchecked(i);
  41280. String name (drive->getFullPathName());
  41281. rootPaths.add (name);
  41282. if (drive->isOnHardDisk())
  41283. {
  41284. String volume (drive->getVolumeLabel());
  41285. if (volume.isEmpty())
  41286. volume = TRANS("Hard Drive");
  41287. name << " [" << drive->getVolumeLabel() << ']';
  41288. }
  41289. else if (drive->isOnCDRomDrive())
  41290. {
  41291. name << TRANS(" [CD/DVD drive]");
  41292. }
  41293. rootNames.add (name);
  41294. }
  41295. separators.setBit (rootPaths.size());
  41296. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  41297. rootNames.add ("Documents");
  41298. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  41299. rootNames.add ("Desktop");
  41300. #endif
  41301. #if JUCE_MAC
  41302. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  41303. rootNames.add ("Home folder");
  41304. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  41305. rootNames.add ("Documents");
  41306. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  41307. rootNames.add ("Desktop");
  41308. separators.setBit (rootPaths.size());
  41309. OwnedArray <File> volumes;
  41310. File vol ("/Volumes");
  41311. vol.findChildFiles (volumes, File::findDirectories, false);
  41312. for (int i = 0; i < volumes.size(); ++i)
  41313. {
  41314. const File* const volume = volumes.getUnchecked(i);
  41315. if (volume->isDirectory() && ! volume->getFileName().startsWithChar (T('.')))
  41316. {
  41317. rootPaths.add (volume->getFullPathName());
  41318. rootNames.add (volume->getFileName());
  41319. }
  41320. }
  41321. #endif
  41322. #if JUCE_LINUX
  41323. rootPaths.add ("/");
  41324. rootNames.add ("/");
  41325. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  41326. rootNames.add ("Home folder");
  41327. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  41328. rootNames.add ("Desktop");
  41329. #endif
  41330. return separators;
  41331. }
  41332. END_JUCE_NAMESPACE
  41333. /********* End of inlined file: juce_FileBrowserComponent.cpp *********/
  41334. /********* Start of inlined file: juce_FileChooser.cpp *********/
  41335. BEGIN_JUCE_NAMESPACE
  41336. FileChooser::FileChooser (const String& chooserBoxTitle,
  41337. const File& currentFileOrDirectory,
  41338. const String& fileFilters,
  41339. const bool useNativeDialogBox_)
  41340. : title (chooserBoxTitle),
  41341. filters (fileFilters),
  41342. startingFile (currentFileOrDirectory),
  41343. useNativeDialogBox (useNativeDialogBox_)
  41344. {
  41345. #if JUCE_LINUX
  41346. useNativeDialogBox = false;
  41347. #endif
  41348. if (fileFilters.trim().isEmpty())
  41349. filters = T("*");
  41350. }
  41351. FileChooser::~FileChooser()
  41352. {
  41353. }
  41354. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  41355. {
  41356. return showDialog (false, false, false, false, previewComponent);
  41357. }
  41358. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  41359. {
  41360. return showDialog (false, false, false, true, previewComponent);
  41361. }
  41362. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  41363. {
  41364. return showDialog (false, true, warnAboutOverwritingExistingFiles, false, 0);
  41365. }
  41366. bool FileChooser::browseForDirectory()
  41367. {
  41368. return showDialog (true, false, false, false, 0);
  41369. }
  41370. const File FileChooser::getResult() const
  41371. {
  41372. // if you've used a multiple-file select, you should use the getResults() method
  41373. // to retrieve all the files that were chosen.
  41374. jassert (results.size() <= 1);
  41375. const File* const f = results.getFirst();
  41376. if (f != 0)
  41377. return *f;
  41378. return File::nonexistent;
  41379. }
  41380. const OwnedArray <File>& FileChooser::getResults() const
  41381. {
  41382. return results;
  41383. }
  41384. bool FileChooser::showDialog (const bool isDirectory,
  41385. const bool isSave,
  41386. const bool warnAboutOverwritingExistingFiles,
  41387. const bool selectMultipleFiles,
  41388. FilePreviewComponent* const previewComponent)
  41389. {
  41390. ComponentDeletionWatcher* currentlyFocusedChecker = 0;
  41391. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  41392. if (currentlyFocused != 0)
  41393. currentlyFocusedChecker = new ComponentDeletionWatcher (currentlyFocused);
  41394. results.clear();
  41395. // the preview component needs to be the right size before you pass it in here..
  41396. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  41397. && previewComponent->getHeight() > 10));
  41398. #if JUCE_WIN32
  41399. if (useNativeDialogBox)
  41400. #else
  41401. if (useNativeDialogBox && (previewComponent == 0))
  41402. #endif
  41403. {
  41404. showPlatformDialog (results, title, startingFile, filters,
  41405. isDirectory, isSave,
  41406. warnAboutOverwritingExistingFiles,
  41407. selectMultipleFiles,
  41408. previewComponent);
  41409. }
  41410. else
  41411. {
  41412. jassert (! selectMultipleFiles); // not yet implemented for juce dialogs!
  41413. WildcardFileFilter wildcard (filters, String::empty);
  41414. FileBrowserComponent browserComponent (isDirectory ? FileBrowserComponent::chooseDirectoryMode
  41415. : (isSave ? FileBrowserComponent::saveFileMode
  41416. : FileBrowserComponent::loadFileMode),
  41417. startingFile, &wildcard, previewComponent);
  41418. FileChooserDialogBox box (title, String::empty,
  41419. browserComponent,
  41420. warnAboutOverwritingExistingFiles,
  41421. browserComponent.findColour (AlertWindow::backgroundColourId));
  41422. if (box.show())
  41423. results.add (new File (browserComponent.getCurrentFile()));
  41424. }
  41425. if (currentlyFocused != 0 && ! currentlyFocusedChecker->hasBeenDeleted())
  41426. currentlyFocused->grabKeyboardFocus();
  41427. delete currentlyFocusedChecker;
  41428. return results.size() > 0;
  41429. }
  41430. FilePreviewComponent::FilePreviewComponent()
  41431. {
  41432. }
  41433. FilePreviewComponent::~FilePreviewComponent()
  41434. {
  41435. }
  41436. END_JUCE_NAMESPACE
  41437. /********* End of inlined file: juce_FileChooser.cpp *********/
  41438. /********* Start of inlined file: juce_FileChooserDialogBox.cpp *********/
  41439. BEGIN_JUCE_NAMESPACE
  41440. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  41441. const String& instructions,
  41442. FileBrowserComponent& chooserComponent,
  41443. const bool warnAboutOverwritingExistingFiles_,
  41444. const Colour& backgroundColour)
  41445. : ResizableWindow (name, backgroundColour, true),
  41446. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  41447. {
  41448. content = new ContentComponent();
  41449. content->setName (name);
  41450. content->instructions = instructions;
  41451. content->chooserComponent = &chooserComponent;
  41452. content->addAndMakeVisible (&chooserComponent);
  41453. content->okButton = new TextButton (chooserComponent.getActionVerb());
  41454. content->addAndMakeVisible (content->okButton);
  41455. content->okButton->addButtonListener (this);
  41456. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  41457. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  41458. content->cancelButton = new TextButton (TRANS("Cancel"));
  41459. content->addAndMakeVisible (content->cancelButton);
  41460. content->cancelButton->addButtonListener (this);
  41461. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  41462. setContentComponent (content);
  41463. setResizable (true, true);
  41464. setResizeLimits (300, 300, 1200, 1000);
  41465. content->chooserComponent->addListener (this);
  41466. }
  41467. FileChooserDialogBox::~FileChooserDialogBox()
  41468. {
  41469. content->chooserComponent->removeListener (this);
  41470. }
  41471. bool FileChooserDialogBox::show (int w, int h)
  41472. {
  41473. if (w <= 0)
  41474. {
  41475. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  41476. if (previewComp != 0)
  41477. w = 400 + previewComp->getWidth();
  41478. else
  41479. w = 600;
  41480. }
  41481. if (h <= 0)
  41482. h = 500;
  41483. centreWithSize (w, h);
  41484. const bool ok = (runModalLoop() != 0);
  41485. setVisible (false);
  41486. return ok;
  41487. }
  41488. void FileChooserDialogBox::buttonClicked (Button* button)
  41489. {
  41490. if (button == content->okButton)
  41491. {
  41492. if (warnAboutOverwritingExistingFiles
  41493. && content->chooserComponent->getMode() == FileBrowserComponent::saveFileMode
  41494. && content->chooserComponent->getCurrentFile().exists())
  41495. {
  41496. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  41497. TRANS("File already exists"),
  41498. TRANS("There's already a file called:\n\n")
  41499. + content->chooserComponent->getCurrentFile().getFullPathName()
  41500. + T("\n\nAre you sure you want to overwrite it?"),
  41501. TRANS("overwrite"),
  41502. TRANS("cancel")))
  41503. {
  41504. return;
  41505. }
  41506. }
  41507. exitModalState (1);
  41508. }
  41509. else if (button == content->cancelButton)
  41510. closeButtonPressed();
  41511. }
  41512. void FileChooserDialogBox::closeButtonPressed()
  41513. {
  41514. setVisible (false);
  41515. }
  41516. void FileChooserDialogBox::selectionChanged()
  41517. {
  41518. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  41519. }
  41520. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  41521. {
  41522. }
  41523. void FileChooserDialogBox::fileDoubleClicked (const File&)
  41524. {
  41525. selectionChanged();
  41526. content->okButton->triggerClick();
  41527. }
  41528. FileChooserDialogBox::ContentComponent::ContentComponent()
  41529. {
  41530. setInterceptsMouseClicks (false, true);
  41531. }
  41532. FileChooserDialogBox::ContentComponent::~ContentComponent()
  41533. {
  41534. delete okButton;
  41535. delete cancelButton;
  41536. }
  41537. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  41538. {
  41539. g.setColour (Colours::black);
  41540. text.draw (g);
  41541. }
  41542. void FileChooserDialogBox::ContentComponent::resized()
  41543. {
  41544. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  41545. float left, top, right, bottom;
  41546. text.getBoundingBox (0, text.getNumGlyphs(), left, top, right, bottom, false);
  41547. const int y = roundFloatToInt (bottom) + 10;
  41548. const int buttonHeight = 26;
  41549. const int buttonY = getHeight() - buttonHeight - 8;
  41550. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  41551. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  41552. proportionOfWidth (0.2f), buttonHeight);
  41553. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  41554. proportionOfWidth (0.2f), buttonHeight);
  41555. }
  41556. END_JUCE_NAMESPACE
  41557. /********* End of inlined file: juce_FileChooserDialogBox.cpp *********/
  41558. /********* Start of inlined file: juce_FileFilter.cpp *********/
  41559. BEGIN_JUCE_NAMESPACE
  41560. FileFilter::FileFilter (const String& filterDescription)
  41561. : description (filterDescription)
  41562. {
  41563. }
  41564. FileFilter::~FileFilter()
  41565. {
  41566. }
  41567. const String& FileFilter::getDescription() const throw()
  41568. {
  41569. return description;
  41570. }
  41571. END_JUCE_NAMESPACE
  41572. /********* End of inlined file: juce_FileFilter.cpp *********/
  41573. /********* Start of inlined file: juce_FileListComponent.cpp *********/
  41574. BEGIN_JUCE_NAMESPACE
  41575. Image* juce_createIconForFile (const File& file);
  41576. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  41577. : ListBox (String::empty, 0),
  41578. DirectoryContentsDisplayComponent (listToShow)
  41579. {
  41580. setModel (this);
  41581. fileList.addChangeListener (this);
  41582. }
  41583. FileListComponent::~FileListComponent()
  41584. {
  41585. fileList.removeChangeListener (this);
  41586. deleteAllChildren();
  41587. }
  41588. const File FileListComponent::getSelectedFile() const
  41589. {
  41590. return fileList.getFile (getSelectedRow());
  41591. }
  41592. void FileListComponent::scrollToTop()
  41593. {
  41594. getVerticalScrollBar()->setCurrentRangeStart (0);
  41595. }
  41596. void FileListComponent::changeListenerCallback (void*)
  41597. {
  41598. updateContent();
  41599. if (lastDirectory != fileList.getDirectory())
  41600. {
  41601. lastDirectory = fileList.getDirectory();
  41602. deselectAllRows();
  41603. }
  41604. }
  41605. class FileListItemComponent : public Component,
  41606. public TimeSliceClient,
  41607. public AsyncUpdater
  41608. {
  41609. public:
  41610. FileListItemComponent (FileListComponent& owner_,
  41611. TimeSliceThread& thread_) throw()
  41612. : owner (owner_),
  41613. thread (thread_),
  41614. icon (0)
  41615. {
  41616. }
  41617. ~FileListItemComponent() throw()
  41618. {
  41619. thread.removeTimeSliceClient (this);
  41620. clearIcon();
  41621. }
  41622. void paint (Graphics& g)
  41623. {
  41624. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  41625. file.getFileName(),
  41626. icon,
  41627. fileSize, modTime,
  41628. isDirectory, highlighted,
  41629. index);
  41630. }
  41631. void mouseDown (const MouseEvent& e)
  41632. {
  41633. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  41634. owner.sendMouseClickMessage (file, e);
  41635. }
  41636. void mouseDoubleClick (const MouseEvent&)
  41637. {
  41638. owner.sendDoubleClickMessage (file);
  41639. }
  41640. void update (const File& root,
  41641. const DirectoryContentsList::FileInfo* const fileInfo,
  41642. const int index_,
  41643. const bool highlighted_) throw()
  41644. {
  41645. thread.removeTimeSliceClient (this);
  41646. if (highlighted_ != highlighted
  41647. || index_ != index)
  41648. {
  41649. index = index_;
  41650. highlighted = highlighted_;
  41651. repaint();
  41652. }
  41653. File newFile;
  41654. String newFileSize;
  41655. String newModTime;
  41656. if (fileInfo != 0)
  41657. {
  41658. newFile = root.getChildFile (fileInfo->filename);
  41659. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  41660. newModTime = fileInfo->modificationTime.formatted (T("%d %b '%y %H:%M"));
  41661. }
  41662. if (newFile != file
  41663. || fileSize != newFileSize
  41664. || modTime != newModTime)
  41665. {
  41666. file = newFile;
  41667. fileSize = newFileSize;
  41668. modTime = newModTime;
  41669. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  41670. repaint();
  41671. clearIcon();
  41672. }
  41673. if (file != File::nonexistent
  41674. && icon == 0 && ! isDirectory)
  41675. {
  41676. updateIcon (true);
  41677. if (icon == 0)
  41678. thread.addTimeSliceClient (this);
  41679. }
  41680. }
  41681. bool useTimeSlice()
  41682. {
  41683. updateIcon (false);
  41684. return false;
  41685. }
  41686. void handleAsyncUpdate()
  41687. {
  41688. repaint();
  41689. }
  41690. juce_UseDebuggingNewOperator
  41691. private:
  41692. FileListComponent& owner;
  41693. TimeSliceThread& thread;
  41694. bool highlighted;
  41695. int index;
  41696. File file;
  41697. String fileSize;
  41698. String modTime;
  41699. Image* icon;
  41700. bool isDirectory;
  41701. void clearIcon() throw()
  41702. {
  41703. ImageCache::release (icon);
  41704. icon = 0;
  41705. }
  41706. void updateIcon (const bool onlyUpdateIfCached) throw()
  41707. {
  41708. if (icon == 0)
  41709. {
  41710. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  41711. Image* im = ImageCache::getFromHashCode (hashCode);
  41712. if (im == 0 && ! onlyUpdateIfCached)
  41713. {
  41714. im = juce_createIconForFile (file);
  41715. if (im != 0)
  41716. ImageCache::addImageToCache (im, hashCode);
  41717. }
  41718. if (im != 0)
  41719. {
  41720. icon = im;
  41721. triggerAsyncUpdate();
  41722. }
  41723. }
  41724. }
  41725. };
  41726. int FileListComponent::getNumRows()
  41727. {
  41728. return fileList.getNumFiles();
  41729. }
  41730. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  41731. {
  41732. }
  41733. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  41734. {
  41735. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  41736. if (comp == 0)
  41737. {
  41738. delete existingComponentToUpdate;
  41739. existingComponentToUpdate = comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  41740. }
  41741. DirectoryContentsList::FileInfo fileInfo;
  41742. if (fileList.getFileInfo (row, fileInfo))
  41743. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  41744. else
  41745. comp->update (fileList.getDirectory(), 0, row, isSelected);
  41746. return comp;
  41747. }
  41748. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  41749. {
  41750. sendSelectionChangeMessage();
  41751. }
  41752. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  41753. {
  41754. }
  41755. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  41756. {
  41757. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  41758. }
  41759. END_JUCE_NAMESPACE
  41760. /********* End of inlined file: juce_FileListComponent.cpp *********/
  41761. /********* Start of inlined file: juce_FilenameComponent.cpp *********/
  41762. BEGIN_JUCE_NAMESPACE
  41763. FilenameComponent::FilenameComponent (const String& name,
  41764. const File& currentFile,
  41765. const bool canEditFilename,
  41766. const bool isDirectory,
  41767. const bool isForSaving,
  41768. const String& fileBrowserWildcard,
  41769. const String& enforcedSuffix_,
  41770. const String& textWhenNothingSelected)
  41771. : Component (name),
  41772. maxRecentFiles (30),
  41773. isDir (isDirectory),
  41774. isSaving (isForSaving),
  41775. isFileDragOver (false),
  41776. wildcard (fileBrowserWildcard),
  41777. enforcedSuffix (enforcedSuffix_)
  41778. {
  41779. addAndMakeVisible (filenameBox = new ComboBox (T("fn")));
  41780. filenameBox->setEditableText (canEditFilename);
  41781. filenameBox->addListener (this);
  41782. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  41783. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  41784. browseButton = 0;
  41785. setBrowseButtonText (T("..."));
  41786. setCurrentFile (currentFile, true);
  41787. }
  41788. FilenameComponent::~FilenameComponent()
  41789. {
  41790. deleteAllChildren();
  41791. }
  41792. void FilenameComponent::paintOverChildren (Graphics& g)
  41793. {
  41794. if (isFileDragOver)
  41795. {
  41796. g.setColour (Colours::red.withAlpha (0.2f));
  41797. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  41798. }
  41799. }
  41800. void FilenameComponent::resized()
  41801. {
  41802. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  41803. }
  41804. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  41805. {
  41806. browseButtonText = newBrowseButtonText;
  41807. lookAndFeelChanged();
  41808. }
  41809. void FilenameComponent::lookAndFeelChanged()
  41810. {
  41811. deleteAndZero (browseButton);
  41812. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  41813. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  41814. resized();
  41815. browseButton->addButtonListener (this);
  41816. }
  41817. void FilenameComponent::setTooltip (const String& newTooltip)
  41818. {
  41819. SettableTooltipClient::setTooltip (newTooltip);
  41820. filenameBox->setTooltip (newTooltip);
  41821. }
  41822. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  41823. {
  41824. defaultBrowseFile = newDefaultDirectory;
  41825. }
  41826. void FilenameComponent::buttonClicked (Button*)
  41827. {
  41828. FileChooser fc (TRANS("Choose a new file"),
  41829. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  41830. : getCurrentFile(),
  41831. wildcard);
  41832. if (isDir ? fc.browseForDirectory()
  41833. : (isSaving ? fc.browseForFileToSave (false)
  41834. : fc.browseForFileToOpen()))
  41835. {
  41836. setCurrentFile (fc.getResult(), true);
  41837. }
  41838. }
  41839. void FilenameComponent::comboBoxChanged (ComboBox*)
  41840. {
  41841. setCurrentFile (getCurrentFile(), true);
  41842. }
  41843. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  41844. {
  41845. return true;
  41846. }
  41847. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  41848. {
  41849. isFileDragOver = false;
  41850. repaint();
  41851. const File f (filenames[0]);
  41852. if (f.exists() && (f.isDirectory() == isDir))
  41853. setCurrentFile (f, true);
  41854. }
  41855. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  41856. {
  41857. isFileDragOver = true;
  41858. repaint();
  41859. }
  41860. void FilenameComponent::fileDragExit (const StringArray&)
  41861. {
  41862. isFileDragOver = false;
  41863. repaint();
  41864. }
  41865. const File FilenameComponent::getCurrentFile() const
  41866. {
  41867. File f (filenameBox->getText());
  41868. if (enforcedSuffix.isNotEmpty())
  41869. f = f.withFileExtension (enforcedSuffix);
  41870. return f;
  41871. }
  41872. void FilenameComponent::setCurrentFile (File newFile,
  41873. const bool addToRecentlyUsedList,
  41874. const bool sendChangeNotification)
  41875. {
  41876. if (enforcedSuffix.isNotEmpty())
  41877. newFile = newFile.withFileExtension (enforcedSuffix);
  41878. if (newFile.getFullPathName() != lastFilename)
  41879. {
  41880. lastFilename = newFile.getFullPathName();
  41881. if (addToRecentlyUsedList)
  41882. addRecentlyUsedFile (newFile);
  41883. filenameBox->setText (lastFilename, true);
  41884. if (sendChangeNotification)
  41885. triggerAsyncUpdate();
  41886. }
  41887. }
  41888. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  41889. {
  41890. filenameBox->setEditableText (shouldBeEditable);
  41891. }
  41892. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  41893. {
  41894. StringArray names;
  41895. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  41896. names.add (filenameBox->getItemText (i));
  41897. return names;
  41898. }
  41899. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  41900. {
  41901. if (filenames != getRecentlyUsedFilenames())
  41902. {
  41903. filenameBox->clear();
  41904. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  41905. filenameBox->addItem (filenames[i], i + 1);
  41906. }
  41907. }
  41908. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  41909. {
  41910. maxRecentFiles = jmax (1, newMaximum);
  41911. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  41912. }
  41913. void FilenameComponent::addRecentlyUsedFile (const File& file)
  41914. {
  41915. StringArray files (getRecentlyUsedFilenames());
  41916. if (file.getFullPathName().isNotEmpty())
  41917. {
  41918. files.removeString (file.getFullPathName(), true);
  41919. files.insert (0, file.getFullPathName());
  41920. setRecentlyUsedFilenames (files);
  41921. }
  41922. }
  41923. void FilenameComponent::addListener (FilenameComponentListener* const listener) throw()
  41924. {
  41925. jassert (listener != 0);
  41926. if (listener != 0)
  41927. listeners.add (listener);
  41928. }
  41929. void FilenameComponent::removeListener (FilenameComponentListener* const listener) throw()
  41930. {
  41931. listeners.removeValue (listener);
  41932. }
  41933. void FilenameComponent::handleAsyncUpdate()
  41934. {
  41935. for (int i = listeners.size(); --i >= 0;)
  41936. {
  41937. ((FilenameComponentListener*) listeners.getUnchecked (i))->filenameComponentChanged (this);
  41938. i = jmin (i, listeners.size());
  41939. }
  41940. }
  41941. END_JUCE_NAMESPACE
  41942. /********* End of inlined file: juce_FilenameComponent.cpp *********/
  41943. /********* Start of inlined file: juce_FileSearchPathListComponent.cpp *********/
  41944. BEGIN_JUCE_NAMESPACE
  41945. FileSearchPathListComponent::FileSearchPathListComponent()
  41946. {
  41947. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  41948. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  41949. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  41950. listBox->setOutlineThickness (1);
  41951. addAndMakeVisible (addButton = new TextButton ("+"));
  41952. addButton->addButtonListener (this);
  41953. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  41954. addAndMakeVisible (removeButton = new TextButton ("-"));
  41955. removeButton->addButtonListener (this);
  41956. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  41957. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  41958. changeButton->addButtonListener (this);
  41959. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  41960. upButton->addButtonListener (this);
  41961. {
  41962. Path arrowPath;
  41963. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  41964. DrawablePath arrowImage;
  41965. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  41966. arrowImage.setPath (arrowPath);
  41967. ((DrawableButton*) upButton)->setImages (&arrowImage);
  41968. }
  41969. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  41970. downButton->addButtonListener (this);
  41971. {
  41972. Path arrowPath;
  41973. arrowPath.addArrow (50.0f, 0.0f, 50.0f, 100.0f, 40.0f, 100.0f, 50.0f);
  41974. DrawablePath arrowImage;
  41975. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  41976. arrowImage.setPath (arrowPath);
  41977. ((DrawableButton*) downButton)->setImages (&arrowImage);
  41978. }
  41979. updateButtons();
  41980. }
  41981. FileSearchPathListComponent::~FileSearchPathListComponent()
  41982. {
  41983. deleteAllChildren();
  41984. }
  41985. void FileSearchPathListComponent::updateButtons() throw()
  41986. {
  41987. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  41988. removeButton->setEnabled (anythingSelected);
  41989. changeButton->setEnabled (anythingSelected);
  41990. upButton->setEnabled (anythingSelected);
  41991. downButton->setEnabled (anythingSelected);
  41992. }
  41993. void FileSearchPathListComponent::changed() throw()
  41994. {
  41995. listBox->updateContent();
  41996. listBox->repaint();
  41997. updateButtons();
  41998. }
  41999. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  42000. {
  42001. if (newPath.toString() != path.toString())
  42002. {
  42003. path = newPath;
  42004. changed();
  42005. }
  42006. }
  42007. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  42008. {
  42009. defaultBrowseTarget = newDefaultDirectory;
  42010. }
  42011. int FileSearchPathListComponent::getNumRows()
  42012. {
  42013. return path.getNumPaths();
  42014. }
  42015. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  42016. {
  42017. if (rowIsSelected)
  42018. g.fillAll (findColour (TextEditor::highlightColourId));
  42019. g.setColour (findColour (ListBox::textColourId));
  42020. Font f (height * 0.7f);
  42021. f.setHorizontalScale (0.9f);
  42022. g.setFont (f);
  42023. g.drawText (path [rowNumber].getFullPathName(),
  42024. 4, 0, width - 6, height,
  42025. Justification::centredLeft, true);
  42026. }
  42027. void FileSearchPathListComponent::deleteKeyPressed (int row)
  42028. {
  42029. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  42030. {
  42031. path.remove (row);
  42032. changed();
  42033. }
  42034. }
  42035. void FileSearchPathListComponent::returnKeyPressed (int row)
  42036. {
  42037. FileChooser chooser (TRANS("Change folder..."), path [row], T("*"));
  42038. if (chooser.browseForDirectory())
  42039. {
  42040. path.remove (row);
  42041. path.add (chooser.getResult(), row);
  42042. changed();
  42043. }
  42044. }
  42045. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  42046. {
  42047. returnKeyPressed (row);
  42048. }
  42049. void FileSearchPathListComponent::selectedRowsChanged (int)
  42050. {
  42051. updateButtons();
  42052. }
  42053. void FileSearchPathListComponent::paint (Graphics& g)
  42054. {
  42055. g.fillAll (findColour (backgroundColourId));
  42056. }
  42057. void FileSearchPathListComponent::resized()
  42058. {
  42059. const int buttonH = 22;
  42060. const int buttonY = getHeight() - buttonH - 4;
  42061. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  42062. addButton->setBounds (2, buttonY, buttonH, buttonH);
  42063. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  42064. ((TextButton*) changeButton)->changeWidthToFitText (buttonH);
  42065. downButton->setSize (buttonH * 2, buttonH);
  42066. upButton->setSize (buttonH * 2, buttonH);
  42067. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  42068. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  42069. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  42070. }
  42071. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  42072. {
  42073. return true;
  42074. }
  42075. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  42076. {
  42077. for (int i = filenames.size(); --i >= 0;)
  42078. {
  42079. const File f (filenames[i]);
  42080. if (f.isDirectory())
  42081. {
  42082. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  42083. path.add (f, row);
  42084. changed();
  42085. }
  42086. }
  42087. }
  42088. void FileSearchPathListComponent::buttonClicked (Button* button)
  42089. {
  42090. const int currentRow = listBox->getSelectedRow();
  42091. if (button == removeButton)
  42092. {
  42093. deleteKeyPressed (currentRow);
  42094. }
  42095. else if (button == addButton)
  42096. {
  42097. File start (defaultBrowseTarget);
  42098. if (start == File::nonexistent)
  42099. start = path [0];
  42100. if (start == File::nonexistent)
  42101. start = File::getCurrentWorkingDirectory();
  42102. FileChooser chooser (TRANS("Add a folder..."), start, T("*"));
  42103. if (chooser.browseForDirectory())
  42104. {
  42105. path.add (chooser.getResult(), currentRow);
  42106. }
  42107. }
  42108. else if (button == changeButton)
  42109. {
  42110. returnKeyPressed (currentRow);
  42111. }
  42112. else if (button == upButton)
  42113. {
  42114. if (currentRow > 0 && currentRow < path.getNumPaths())
  42115. {
  42116. const File f (path[currentRow]);
  42117. path.remove (currentRow);
  42118. path.add (f, currentRow - 1);
  42119. listBox->selectRow (currentRow - 1);
  42120. }
  42121. }
  42122. else if (button == downButton)
  42123. {
  42124. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  42125. {
  42126. const File f (path[currentRow]);
  42127. path.remove (currentRow);
  42128. path.add (f, currentRow + 1);
  42129. listBox->selectRow (currentRow + 1);
  42130. }
  42131. }
  42132. changed();
  42133. }
  42134. END_JUCE_NAMESPACE
  42135. /********* End of inlined file: juce_FileSearchPathListComponent.cpp *********/
  42136. /********* Start of inlined file: juce_FileTreeComponent.cpp *********/
  42137. BEGIN_JUCE_NAMESPACE
  42138. Image* juce_createIconForFile (const File& file);
  42139. class FileListTreeItem : public TreeViewItem,
  42140. public TimeSliceClient,
  42141. public AsyncUpdater,
  42142. public ChangeListener
  42143. {
  42144. public:
  42145. FileListTreeItem (FileTreeComponent& owner_,
  42146. DirectoryContentsList* const parentContentsList_,
  42147. const int indexInContentsList_,
  42148. const File& file_,
  42149. TimeSliceThread& thread_) throw()
  42150. : file (file_),
  42151. owner (owner_),
  42152. parentContentsList (parentContentsList_),
  42153. indexInContentsList (indexInContentsList_),
  42154. subContentsList (0),
  42155. canDeleteSubContentsList (false),
  42156. thread (thread_),
  42157. icon (0)
  42158. {
  42159. DirectoryContentsList::FileInfo fileInfo;
  42160. if (parentContentsList_ != 0
  42161. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  42162. {
  42163. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  42164. modTime = fileInfo.modificationTime.formatted (T("%d %b '%y %H:%M"));
  42165. isDirectory = fileInfo.isDirectory;
  42166. }
  42167. else
  42168. {
  42169. isDirectory = true;
  42170. }
  42171. }
  42172. ~FileListTreeItem() throw()
  42173. {
  42174. thread.removeTimeSliceClient (this);
  42175. clearSubItems();
  42176. ImageCache::release (icon);
  42177. if (canDeleteSubContentsList)
  42178. delete subContentsList;
  42179. }
  42180. bool mightContainSubItems() { return isDirectory; }
  42181. const String getUniqueName() const { return file.getFullPathName(); }
  42182. int getItemHeight() const { return 22; }
  42183. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  42184. void itemOpennessChanged (bool isNowOpen)
  42185. {
  42186. if (isNowOpen)
  42187. {
  42188. clearSubItems();
  42189. isDirectory = file.isDirectory();
  42190. if (isDirectory)
  42191. {
  42192. if (subContentsList == 0)
  42193. {
  42194. jassert (parentContentsList != 0);
  42195. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  42196. l->setDirectory (file, true, true);
  42197. setSubContentsList (l);
  42198. canDeleteSubContentsList = true;
  42199. }
  42200. changeListenerCallback (0);
  42201. }
  42202. }
  42203. }
  42204. void setSubContentsList (DirectoryContentsList* newList) throw()
  42205. {
  42206. jassert (subContentsList == 0);
  42207. subContentsList = newList;
  42208. newList->addChangeListener (this);
  42209. }
  42210. void changeListenerCallback (void*)
  42211. {
  42212. clearSubItems();
  42213. if (isOpen() && subContentsList != 0)
  42214. {
  42215. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  42216. {
  42217. FileListTreeItem* const item
  42218. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  42219. addSubItem (item);
  42220. }
  42221. }
  42222. }
  42223. void paintItem (Graphics& g, int width, int height)
  42224. {
  42225. if (file != File::nonexistent && ! isDirectory)
  42226. {
  42227. updateIcon (true);
  42228. if (icon == 0)
  42229. thread.addTimeSliceClient (this);
  42230. }
  42231. owner.getLookAndFeel()
  42232. .drawFileBrowserRow (g, width, height,
  42233. file.getFileName(),
  42234. icon,
  42235. fileSize, modTime,
  42236. isDirectory, isSelected(),
  42237. indexInContentsList);
  42238. }
  42239. void itemClicked (const MouseEvent& e)
  42240. {
  42241. owner.sendMouseClickMessage (file, e);
  42242. }
  42243. void itemDoubleClicked (const MouseEvent& e)
  42244. {
  42245. TreeViewItem::itemDoubleClicked (e);
  42246. owner.sendDoubleClickMessage (file);
  42247. }
  42248. void itemSelectionChanged (bool)
  42249. {
  42250. owner.sendSelectionChangeMessage();
  42251. }
  42252. bool useTimeSlice()
  42253. {
  42254. updateIcon (false);
  42255. thread.removeTimeSliceClient (this);
  42256. return false;
  42257. }
  42258. void handleAsyncUpdate()
  42259. {
  42260. owner.repaint();
  42261. }
  42262. const File file;
  42263. juce_UseDebuggingNewOperator
  42264. private:
  42265. FileTreeComponent& owner;
  42266. DirectoryContentsList* parentContentsList;
  42267. int indexInContentsList;
  42268. DirectoryContentsList* subContentsList;
  42269. bool isDirectory, canDeleteSubContentsList;
  42270. TimeSliceThread& thread;
  42271. Image* icon;
  42272. String fileSize;
  42273. String modTime;
  42274. void updateIcon (const bool onlyUpdateIfCached) throw()
  42275. {
  42276. if (icon == 0)
  42277. {
  42278. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  42279. Image* im = ImageCache::getFromHashCode (hashCode);
  42280. if (im == 0 && ! onlyUpdateIfCached)
  42281. {
  42282. im = juce_createIconForFile (file);
  42283. if (im != 0)
  42284. ImageCache::addImageToCache (im, hashCode);
  42285. }
  42286. if (im != 0)
  42287. {
  42288. icon = im;
  42289. triggerAsyncUpdate();
  42290. }
  42291. }
  42292. }
  42293. };
  42294. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  42295. : DirectoryContentsDisplayComponent (listToShow)
  42296. {
  42297. FileListTreeItem* const root
  42298. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  42299. listToShow.getTimeSliceThread());
  42300. root->setSubContentsList (&listToShow);
  42301. setRootItemVisible (false);
  42302. setRootItem (root);
  42303. }
  42304. FileTreeComponent::~FileTreeComponent()
  42305. {
  42306. TreeViewItem* const root = getRootItem();
  42307. setRootItem (0);
  42308. delete root;
  42309. }
  42310. const File FileTreeComponent::getSelectedFile() const
  42311. {
  42312. return getSelectedFile (0);
  42313. }
  42314. const File FileTreeComponent::getSelectedFile (const int index) const throw()
  42315. {
  42316. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  42317. if (item != 0)
  42318. return item->file;
  42319. return File::nonexistent;
  42320. }
  42321. void FileTreeComponent::scrollToTop()
  42322. {
  42323. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  42324. }
  42325. void FileTreeComponent::setDragAndDropDescription (const String& description) throw()
  42326. {
  42327. dragAndDropDescription = description;
  42328. }
  42329. END_JUCE_NAMESPACE
  42330. /********* End of inlined file: juce_FileTreeComponent.cpp *********/
  42331. /********* Start of inlined file: juce_ImagePreviewComponent.cpp *********/
  42332. BEGIN_JUCE_NAMESPACE
  42333. ImagePreviewComponent::ImagePreviewComponent()
  42334. : currentThumbnail (0)
  42335. {
  42336. }
  42337. ImagePreviewComponent::~ImagePreviewComponent()
  42338. {
  42339. delete currentThumbnail;
  42340. }
  42341. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  42342. {
  42343. const int availableW = proportionOfWidth (0.97f);
  42344. const int availableH = getHeight() - 13 * 4;
  42345. const double scale = jmin (1.0,
  42346. availableW / (double) w,
  42347. availableH / (double) h);
  42348. w = roundDoubleToInt (scale * w);
  42349. h = roundDoubleToInt (scale * h);
  42350. }
  42351. void ImagePreviewComponent::selectedFileChanged (const File& file)
  42352. {
  42353. if (fileToLoad != file)
  42354. {
  42355. fileToLoad = file;
  42356. startTimer (100);
  42357. }
  42358. }
  42359. void ImagePreviewComponent::timerCallback()
  42360. {
  42361. stopTimer();
  42362. deleteAndZero (currentThumbnail);
  42363. currentDetails = String::empty;
  42364. repaint();
  42365. FileInputStream* const in = fileToLoad.createInputStream();
  42366. if (in != 0)
  42367. {
  42368. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  42369. if (format != 0)
  42370. {
  42371. currentThumbnail = format->decodeImage (*in);
  42372. if (currentThumbnail != 0)
  42373. {
  42374. int w = currentThumbnail->getWidth();
  42375. int h = currentThumbnail->getHeight();
  42376. currentDetails
  42377. << fileToLoad.getFileName() << "\n"
  42378. << format->getFormatName() << "\n"
  42379. << w << " x " << h << " pixels\n"
  42380. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  42381. getThumbSize (w, h);
  42382. Image* const reduced = currentThumbnail->createCopy (w, h);
  42383. delete currentThumbnail;
  42384. currentThumbnail = reduced;
  42385. }
  42386. }
  42387. delete in;
  42388. }
  42389. }
  42390. void ImagePreviewComponent::paint (Graphics& g)
  42391. {
  42392. if (currentThumbnail != 0)
  42393. {
  42394. g.setFont (13.0f);
  42395. int w = currentThumbnail->getWidth();
  42396. int h = currentThumbnail->getHeight();
  42397. getThumbSize (w, h);
  42398. const int numLines = 4;
  42399. const int totalH = 13 * numLines + h + 4;
  42400. const int y = (getHeight() - totalH) / 2;
  42401. g.drawImageWithin (currentThumbnail,
  42402. (getWidth() - w) / 2, y, w, h,
  42403. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  42404. false);
  42405. g.drawFittedText (currentDetails,
  42406. 0, y + h + 4, getWidth(), 100,
  42407. Justification::centredTop, numLines);
  42408. }
  42409. }
  42410. END_JUCE_NAMESPACE
  42411. /********* End of inlined file: juce_ImagePreviewComponent.cpp *********/
  42412. /********* Start of inlined file: juce_WildcardFileFilter.cpp *********/
  42413. BEGIN_JUCE_NAMESPACE
  42414. WildcardFileFilter::WildcardFileFilter (const String& wildcardPatterns,
  42415. const String& description)
  42416. : FileFilter (description.isEmpty() ? wildcardPatterns
  42417. : (description + T(" (") + wildcardPatterns + T(")")))
  42418. {
  42419. wildcards.addTokens (wildcardPatterns.toLowerCase(), T(";,"), T("\"'"));
  42420. wildcards.trim();
  42421. wildcards.removeEmptyStrings();
  42422. // special case for *.*, because people use it to mean "any file", but it
  42423. // would actually ignore files with no extension.
  42424. for (int i = wildcards.size(); --i >= 0;)
  42425. if (wildcards[i] == T("*.*"))
  42426. wildcards.set (i, T("*"));
  42427. }
  42428. WildcardFileFilter::~WildcardFileFilter()
  42429. {
  42430. }
  42431. bool WildcardFileFilter::isFileSuitable (const File& file) const
  42432. {
  42433. const String filename (file.getFileName());
  42434. for (int i = wildcards.size(); --i >= 0;)
  42435. if (filename.matchesWildcard (wildcards[i], true))
  42436. return true;
  42437. return false;
  42438. }
  42439. bool WildcardFileFilter::isDirectorySuitable (const File&) const
  42440. {
  42441. return true;
  42442. }
  42443. END_JUCE_NAMESPACE
  42444. /********* End of inlined file: juce_WildcardFileFilter.cpp *********/
  42445. /********* Start of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  42446. BEGIN_JUCE_NAMESPACE
  42447. KeyboardFocusTraverser::KeyboardFocusTraverser()
  42448. {
  42449. }
  42450. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  42451. {
  42452. }
  42453. // This will sort a set of components, so that they are ordered in terms of
  42454. // left-to-right and then top-to-bottom.
  42455. class ScreenPositionComparator
  42456. {
  42457. public:
  42458. ScreenPositionComparator() {}
  42459. static int compareElements (const Component* const first, const Component* const second) throw()
  42460. {
  42461. int explicitOrder1 = first->getExplicitFocusOrder();
  42462. if (explicitOrder1 <= 0)
  42463. explicitOrder1 = INT_MAX / 2;
  42464. int explicitOrder2 = second->getExplicitFocusOrder();
  42465. if (explicitOrder2 <= 0)
  42466. explicitOrder2 = INT_MAX / 2;
  42467. if (explicitOrder1 != explicitOrder2)
  42468. return explicitOrder1 - explicitOrder2;
  42469. const int diff = first->getY() - second->getY();
  42470. return (diff == 0) ? first->getX() - second->getX()
  42471. : diff;
  42472. }
  42473. };
  42474. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  42475. {
  42476. if (parent->getNumChildComponents() > 0)
  42477. {
  42478. Array <Component*> localComps;
  42479. ScreenPositionComparator comparator;
  42480. int i;
  42481. for (i = parent->getNumChildComponents(); --i >= 0;)
  42482. {
  42483. Component* const c = parent->getChildComponent (i);
  42484. if (c->isVisible() && c->isEnabled())
  42485. localComps.addSorted (comparator, c);
  42486. }
  42487. for (i = 0; i < localComps.size(); ++i)
  42488. {
  42489. Component* const c = localComps.getUnchecked (i);
  42490. if (c->getWantsKeyboardFocus())
  42491. comps.add (c);
  42492. if (! c->isFocusContainer())
  42493. findAllFocusableComponents (c, comps);
  42494. }
  42495. }
  42496. }
  42497. static Component* getIncrementedComponent (Component* const current, const int delta) throw()
  42498. {
  42499. Component* focusContainer = current->getParentComponent();
  42500. if (focusContainer != 0)
  42501. {
  42502. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  42503. focusContainer = focusContainer->getParentComponent();
  42504. if (focusContainer != 0)
  42505. {
  42506. Array <Component*> comps;
  42507. findAllFocusableComponents (focusContainer, comps);
  42508. if (comps.size() > 0)
  42509. {
  42510. const int index = comps.indexOf (current);
  42511. return comps [(index + comps.size() + delta) % comps.size()];
  42512. }
  42513. }
  42514. }
  42515. return 0;
  42516. }
  42517. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  42518. {
  42519. return getIncrementedComponent (current, 1);
  42520. }
  42521. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  42522. {
  42523. return getIncrementedComponent (current, -1);
  42524. }
  42525. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  42526. {
  42527. Array <Component*> comps;
  42528. if (parentComponent != 0)
  42529. findAllFocusableComponents (parentComponent, comps);
  42530. return comps.getFirst();
  42531. }
  42532. END_JUCE_NAMESPACE
  42533. /********* End of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  42534. /********* Start of inlined file: juce_KeyListener.cpp *********/
  42535. BEGIN_JUCE_NAMESPACE
  42536. bool KeyListener::keyStateChanged (Component*)
  42537. {
  42538. return false;
  42539. }
  42540. END_JUCE_NAMESPACE
  42541. /********* End of inlined file: juce_KeyListener.cpp *********/
  42542. /********* Start of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  42543. BEGIN_JUCE_NAMESPACE
  42544. // N.B. these two includes are put here deliberately to avoid problems with
  42545. // old GCCs failing on long include paths
  42546. const int maxKeys = 3;
  42547. class KeyMappingChangeButton : public Button
  42548. {
  42549. public:
  42550. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  42551. const CommandID commandID_,
  42552. const String& keyName,
  42553. const int keyNum_)
  42554. : Button (keyName),
  42555. owner (owner_),
  42556. commandID (commandID_),
  42557. keyNum (keyNum_)
  42558. {
  42559. setWantsKeyboardFocus (false);
  42560. setTriggeredOnMouseDown (keyNum >= 0);
  42561. if (keyNum_ < 0)
  42562. setTooltip (TRANS("adds a new key-mapping"));
  42563. else
  42564. setTooltip (TRANS("click to change this key-mapping"));
  42565. }
  42566. ~KeyMappingChangeButton()
  42567. {
  42568. }
  42569. void paintButton (Graphics& g, bool isOver, bool isDown)
  42570. {
  42571. if (keyNum >= 0)
  42572. {
  42573. if (isEnabled())
  42574. {
  42575. const float alpha = isDown ? 0.3f : (isOver ? 0.15f : 0.08f);
  42576. g.fillAll (owner->textColour.withAlpha (alpha));
  42577. g.setOpacity (0.3f);
  42578. g.drawBevel (0, 0, getWidth(), getHeight(), 2);
  42579. }
  42580. g.setColour (owner->textColour);
  42581. g.setFont (getHeight() * 0.6f);
  42582. g.drawFittedText (getName(),
  42583. 3, 0, getWidth() - 6, getHeight(),
  42584. Justification::centred, 1);
  42585. }
  42586. else
  42587. {
  42588. const float thickness = 7.0f;
  42589. const float indent = 22.0f;
  42590. Path p;
  42591. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  42592. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  42593. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  42594. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  42595. p.setUsingNonZeroWinding (false);
  42596. g.setColour (owner->textColour.withAlpha (isDown ? 0.7f : (isOver ? 0.5f : 0.3f)));
  42597. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, true));
  42598. }
  42599. if (hasKeyboardFocus (false))
  42600. {
  42601. g.setColour (owner->textColour.withAlpha (0.4f));
  42602. g.drawRect (0, 0, getWidth(), getHeight());
  42603. }
  42604. }
  42605. void clicked()
  42606. {
  42607. if (keyNum >= 0)
  42608. {
  42609. // existing key clicked..
  42610. PopupMenu m;
  42611. m.addItem (1, TRANS("change this key-mapping"));
  42612. m.addSeparator();
  42613. m.addItem (2, TRANS("remove this key-mapping"));
  42614. const int res = m.show();
  42615. if (res == 1)
  42616. {
  42617. owner->assignNewKey (commandID, keyNum);
  42618. }
  42619. else if (res == 2)
  42620. {
  42621. owner->getMappings()->removeKeyPress (commandID, keyNum);
  42622. }
  42623. }
  42624. else
  42625. {
  42626. // + button pressed..
  42627. owner->assignNewKey (commandID, -1);
  42628. }
  42629. }
  42630. void fitToContent (const int h) throw()
  42631. {
  42632. if (keyNum < 0)
  42633. {
  42634. setSize (h, h);
  42635. }
  42636. else
  42637. {
  42638. Font f (h * 0.6f);
  42639. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  42640. }
  42641. }
  42642. juce_UseDebuggingNewOperator
  42643. private:
  42644. KeyMappingEditorComponent* const owner;
  42645. const CommandID commandID;
  42646. const int keyNum;
  42647. KeyMappingChangeButton (const KeyMappingChangeButton&);
  42648. const KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  42649. };
  42650. class KeyMappingItemComponent : public Component
  42651. {
  42652. public:
  42653. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  42654. const CommandID commandID_)
  42655. : owner (owner_),
  42656. commandID (commandID_)
  42657. {
  42658. setInterceptsMouseClicks (false, true);
  42659. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  42660. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  42661. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  42662. {
  42663. KeyMappingChangeButton* const kb
  42664. = new KeyMappingChangeButton (owner_, commandID,
  42665. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  42666. kb->setEnabled (! isReadOnly);
  42667. addAndMakeVisible (kb);
  42668. }
  42669. KeyMappingChangeButton* const kb
  42670. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  42671. addChildComponent (kb);
  42672. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  42673. }
  42674. ~KeyMappingItemComponent()
  42675. {
  42676. deleteAllChildren();
  42677. }
  42678. void paint (Graphics& g)
  42679. {
  42680. g.setFont (getHeight() * 0.7f);
  42681. g.setColour (owner->textColour);
  42682. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  42683. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  42684. Justification::centredLeft, true);
  42685. }
  42686. void resized()
  42687. {
  42688. int x = getWidth() - 4;
  42689. for (int i = getNumChildComponents(); --i >= 0;)
  42690. {
  42691. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  42692. kb->fitToContent (getHeight() - 2);
  42693. kb->setTopRightPosition (x, 1);
  42694. x -= kb->getWidth() + 5;
  42695. }
  42696. }
  42697. juce_UseDebuggingNewOperator
  42698. private:
  42699. KeyMappingEditorComponent* const owner;
  42700. const CommandID commandID;
  42701. KeyMappingItemComponent (const KeyMappingItemComponent&);
  42702. const KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  42703. };
  42704. class KeyMappingTreeViewItem : public TreeViewItem
  42705. {
  42706. public:
  42707. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  42708. const CommandID commandID_)
  42709. : owner (owner_),
  42710. commandID (commandID_)
  42711. {
  42712. }
  42713. ~KeyMappingTreeViewItem()
  42714. {
  42715. }
  42716. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  42717. bool mightContainSubItems() { return false; }
  42718. int getItemHeight() const { return 20; }
  42719. Component* createItemComponent()
  42720. {
  42721. return new KeyMappingItemComponent (owner, commandID);
  42722. }
  42723. juce_UseDebuggingNewOperator
  42724. private:
  42725. KeyMappingEditorComponent* const owner;
  42726. const CommandID commandID;
  42727. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  42728. const KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  42729. };
  42730. class KeyCategoryTreeViewItem : public TreeViewItem
  42731. {
  42732. public:
  42733. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  42734. const String& name)
  42735. : owner (owner_),
  42736. categoryName (name)
  42737. {
  42738. }
  42739. ~KeyCategoryTreeViewItem()
  42740. {
  42741. }
  42742. const String getUniqueName() const { return categoryName + "_cat"; }
  42743. bool mightContainSubItems() { return true; }
  42744. int getItemHeight() const { return 28; }
  42745. void paintItem (Graphics& g, int width, int height)
  42746. {
  42747. g.setFont (height * 0.6f, Font::bold);
  42748. g.setColour (owner->textColour);
  42749. g.drawText (categoryName,
  42750. 2, 0, width - 2, height,
  42751. Justification::centredLeft, true);
  42752. }
  42753. void itemOpennessChanged (bool isNowOpen)
  42754. {
  42755. if (isNowOpen)
  42756. {
  42757. if (getNumSubItems() == 0)
  42758. {
  42759. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  42760. for (int i = 0; i < commands.size(); ++i)
  42761. {
  42762. if (owner->shouldCommandBeIncluded (commands[i]))
  42763. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  42764. }
  42765. }
  42766. }
  42767. else
  42768. {
  42769. clearSubItems();
  42770. }
  42771. }
  42772. juce_UseDebuggingNewOperator
  42773. private:
  42774. KeyMappingEditorComponent* owner;
  42775. String categoryName;
  42776. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  42777. const KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  42778. };
  42779. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  42780. const bool showResetToDefaultButton)
  42781. : mappings (mappingManager),
  42782. textColour (Colours::black)
  42783. {
  42784. jassert (mappingManager != 0); // can't be null!
  42785. mappingManager->addChangeListener (this);
  42786. setLinesDrawnForSubItems (false);
  42787. resetButton = 0;
  42788. if (showResetToDefaultButton)
  42789. {
  42790. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  42791. resetButton->addButtonListener (this);
  42792. }
  42793. addAndMakeVisible (tree = new TreeView());
  42794. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  42795. tree->setRootItemVisible (false);
  42796. tree->setDefaultOpenness (true);
  42797. tree->setRootItem (this);
  42798. }
  42799. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  42800. {
  42801. mappings->removeChangeListener (this);
  42802. deleteAllChildren();
  42803. }
  42804. bool KeyMappingEditorComponent::mightContainSubItems()
  42805. {
  42806. return true;
  42807. }
  42808. const String KeyMappingEditorComponent::getUniqueName() const
  42809. {
  42810. return T("keys");
  42811. }
  42812. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  42813. const Colour& textColour_)
  42814. {
  42815. backgroundColour = mainBackground;
  42816. textColour = textColour_;
  42817. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  42818. }
  42819. void KeyMappingEditorComponent::parentHierarchyChanged()
  42820. {
  42821. changeListenerCallback (0);
  42822. }
  42823. void KeyMappingEditorComponent::resized()
  42824. {
  42825. int h = getHeight();
  42826. if (resetButton != 0)
  42827. {
  42828. const int buttonHeight = 20;
  42829. h -= buttonHeight + 8;
  42830. int x = getWidth() - 8;
  42831. const int y = h + 6;
  42832. resetButton->changeWidthToFitText (buttonHeight);
  42833. resetButton->setTopRightPosition (x, y);
  42834. }
  42835. tree->setBounds (0, 0, getWidth(), h);
  42836. }
  42837. void KeyMappingEditorComponent::buttonClicked (Button* button)
  42838. {
  42839. if (button == resetButton)
  42840. {
  42841. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  42842. TRANS("Reset to defaults"),
  42843. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  42844. TRANS("Reset")))
  42845. {
  42846. mappings->resetToDefaultMappings();
  42847. }
  42848. }
  42849. }
  42850. void KeyMappingEditorComponent::changeListenerCallback (void*)
  42851. {
  42852. XmlElement* openness = tree->getOpennessState (true);
  42853. clearSubItems();
  42854. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  42855. for (int i = 0; i < categories.size(); ++i)
  42856. {
  42857. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  42858. int count = 0;
  42859. for (int j = 0; j < commands.size(); ++j)
  42860. if (shouldCommandBeIncluded (commands[j]))
  42861. ++count;
  42862. if (count > 0)
  42863. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  42864. }
  42865. if (openness != 0)
  42866. {
  42867. tree->restoreOpennessState (*openness);
  42868. delete openness;
  42869. }
  42870. }
  42871. class KeyEntryWindow : public AlertWindow
  42872. {
  42873. public:
  42874. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  42875. : AlertWindow (TRANS("New key-mapping"),
  42876. TRANS("Please press a key combination now..."),
  42877. AlertWindow::NoIcon),
  42878. owner (owner_)
  42879. {
  42880. addButton (TRANS("ok"), 1);
  42881. addButton (TRANS("cancel"), 0);
  42882. // (avoid return + escape keys getting processed by the buttons..)
  42883. for (int i = getNumChildComponents(); --i >= 0;)
  42884. getChildComponent (i)->setWantsKeyboardFocus (false);
  42885. setWantsKeyboardFocus (true);
  42886. grabKeyboardFocus();
  42887. }
  42888. ~KeyEntryWindow()
  42889. {
  42890. }
  42891. bool keyPressed (const KeyPress& key)
  42892. {
  42893. lastPress = key;
  42894. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  42895. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  42896. if (previousCommand != 0)
  42897. {
  42898. message << "\n\n"
  42899. << TRANS("(Currently assigned to \"")
  42900. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  42901. << "\")";
  42902. }
  42903. setMessage (message);
  42904. return true;
  42905. }
  42906. bool keyStateChanged()
  42907. {
  42908. return true;
  42909. }
  42910. KeyPress lastPress;
  42911. juce_UseDebuggingNewOperator
  42912. private:
  42913. KeyMappingEditorComponent* owner;
  42914. KeyEntryWindow (const KeyEntryWindow&);
  42915. const KeyEntryWindow& operator= (const KeyEntryWindow&);
  42916. };
  42917. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  42918. {
  42919. KeyEntryWindow entryWindow (this);
  42920. if (entryWindow.runModalLoop() != 0)
  42921. {
  42922. entryWindow.setVisible (false);
  42923. if (entryWindow.lastPress.isValid())
  42924. {
  42925. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  42926. if (previousCommand != 0)
  42927. {
  42928. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  42929. TRANS("Change key-mapping"),
  42930. TRANS("This key is already assigned to the command \"")
  42931. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  42932. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  42933. TRANS("re-assign"),
  42934. TRANS("cancel")))
  42935. {
  42936. return;
  42937. }
  42938. }
  42939. mappings->removeKeyPress (entryWindow.lastPress);
  42940. if (index >= 0)
  42941. mappings->removeKeyPress (commandID, index);
  42942. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  42943. }
  42944. }
  42945. }
  42946. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  42947. {
  42948. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  42949. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  42950. }
  42951. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  42952. {
  42953. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  42954. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  42955. }
  42956. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  42957. {
  42958. return key.getTextDescription();
  42959. }
  42960. END_JUCE_NAMESPACE
  42961. /********* End of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  42962. /********* Start of inlined file: juce_KeyPress.cpp *********/
  42963. BEGIN_JUCE_NAMESPACE
  42964. KeyPress::KeyPress() throw()
  42965. : keyCode (0),
  42966. mods (0),
  42967. textCharacter (0)
  42968. {
  42969. }
  42970. KeyPress::KeyPress (const int keyCode_,
  42971. const ModifierKeys& mods_,
  42972. const juce_wchar textCharacter_) throw()
  42973. : keyCode (keyCode_),
  42974. mods (mods_),
  42975. textCharacter (textCharacter_)
  42976. {
  42977. }
  42978. KeyPress::KeyPress (const int keyCode_) throw()
  42979. : keyCode (keyCode_),
  42980. textCharacter (0)
  42981. {
  42982. }
  42983. KeyPress::KeyPress (const KeyPress& other) throw()
  42984. : keyCode (other.keyCode),
  42985. mods (other.mods),
  42986. textCharacter (other.textCharacter)
  42987. {
  42988. }
  42989. const KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  42990. {
  42991. keyCode = other.keyCode;
  42992. mods = other.mods;
  42993. textCharacter = other.textCharacter;
  42994. return *this;
  42995. }
  42996. bool KeyPress::operator== (const KeyPress& other) const throw()
  42997. {
  42998. return mods.getRawFlags() == other.mods.getRawFlags()
  42999. && (textCharacter == other.textCharacter
  43000. || textCharacter == 0
  43001. || other.textCharacter == 0)
  43002. && (keyCode == other.keyCode
  43003. || (keyCode < 256
  43004. && other.keyCode < 256
  43005. && CharacterFunctions::toLowerCase ((tchar) keyCode)
  43006. == CharacterFunctions::toLowerCase ((tchar) other.keyCode)));
  43007. }
  43008. bool KeyPress::operator!= (const KeyPress& other) const throw()
  43009. {
  43010. return ! operator== (other);
  43011. }
  43012. bool KeyPress::isCurrentlyDown() const throw()
  43013. {
  43014. return isKeyCurrentlyDown (keyCode)
  43015. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  43016. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  43017. }
  43018. struct KeyNameAndCode
  43019. {
  43020. const char* name;
  43021. int code;
  43022. };
  43023. static const KeyNameAndCode keyNameTranslations[] =
  43024. {
  43025. { "spacebar", KeyPress::spaceKey },
  43026. { "return", KeyPress::returnKey },
  43027. { "escape", KeyPress::escapeKey },
  43028. { "backspace", KeyPress::backspaceKey },
  43029. { "cursor left", KeyPress::leftKey },
  43030. { "cursor right", KeyPress::rightKey },
  43031. { "cursor up", KeyPress::upKey },
  43032. { "cursor down", KeyPress::downKey },
  43033. { "page up", KeyPress::pageUpKey },
  43034. { "page down", KeyPress::pageDownKey },
  43035. { "home", KeyPress::homeKey },
  43036. { "end", KeyPress::endKey },
  43037. { "delete", KeyPress::deleteKey },
  43038. { "insert", KeyPress::insertKey },
  43039. { "tab", KeyPress::tabKey },
  43040. { "play", KeyPress::playKey },
  43041. { "stop", KeyPress::stopKey },
  43042. { "fast forward", KeyPress::fastForwardKey },
  43043. { "rewind", KeyPress::rewindKey }
  43044. };
  43045. static const tchar* const numberPadPrefix = T("numpad ");
  43046. const KeyPress KeyPress::createFromDescription (const String& desc) throw()
  43047. {
  43048. int modifiers = 0;
  43049. if (desc.containsWholeWordIgnoreCase (T("ctrl"))
  43050. || desc.containsWholeWordIgnoreCase (T("control"))
  43051. || desc.containsWholeWordIgnoreCase (T("ctl")))
  43052. modifiers |= ModifierKeys::ctrlModifier;
  43053. if (desc.containsWholeWordIgnoreCase (T("shift"))
  43054. || desc.containsWholeWordIgnoreCase (T("shft")))
  43055. modifiers |= ModifierKeys::shiftModifier;
  43056. if (desc.containsWholeWordIgnoreCase (T("alt"))
  43057. || desc.containsWholeWordIgnoreCase (T("option")))
  43058. modifiers |= ModifierKeys::altModifier;
  43059. if (desc.containsWholeWordIgnoreCase (T("command"))
  43060. || desc.containsWholeWordIgnoreCase (T("cmd")))
  43061. modifiers |= ModifierKeys::commandModifier;
  43062. int key = 0;
  43063. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  43064. {
  43065. if (desc.containsWholeWordIgnoreCase (String (keyNameTranslations[i].name)))
  43066. {
  43067. key = keyNameTranslations[i].code;
  43068. break;
  43069. }
  43070. }
  43071. if (key == 0)
  43072. {
  43073. // see if it's a numpad key..
  43074. if (desc.containsIgnoreCase (numberPadPrefix))
  43075. {
  43076. const tchar lastChar = desc.trimEnd().getLastCharacter();
  43077. if (lastChar >= T('0') && lastChar <= T('9'))
  43078. key = numberPad0 + lastChar - T('0');
  43079. else if (lastChar == T('+'))
  43080. key = numberPadAdd;
  43081. else if (lastChar == T('-'))
  43082. key = numberPadSubtract;
  43083. else if (lastChar == T('*'))
  43084. key = numberPadMultiply;
  43085. else if (lastChar == T('/'))
  43086. key = numberPadDivide;
  43087. else if (lastChar == T('.'))
  43088. key = numberPadDecimalPoint;
  43089. else if (lastChar == T('='))
  43090. key = numberPadEquals;
  43091. else if (desc.endsWith (T("separator")))
  43092. key = numberPadSeparator;
  43093. else if (desc.endsWith (T("delete")))
  43094. key = numberPadDelete;
  43095. }
  43096. if (key == 0)
  43097. {
  43098. // see if it's a function key..
  43099. for (int i = 1; i <= 12; ++i)
  43100. if (desc.containsWholeWordIgnoreCase (T("f") + String (i)))
  43101. key = F1Key + i - 1;
  43102. if (key == 0)
  43103. {
  43104. // give up and use the hex code..
  43105. const int hexCode = desc.fromFirstOccurrenceOf (T("#"), false, false)
  43106. .toLowerCase()
  43107. .retainCharacters (T("0123456789abcdef"))
  43108. .getHexValue32();
  43109. if (hexCode > 0)
  43110. key = hexCode;
  43111. else
  43112. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  43113. }
  43114. }
  43115. }
  43116. return KeyPress (key, ModifierKeys (modifiers), 0);
  43117. }
  43118. const String KeyPress::getTextDescription() const throw()
  43119. {
  43120. String desc;
  43121. if (keyCode > 0)
  43122. {
  43123. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  43124. // want to store it as being a slash, not shift+whatever.
  43125. if (textCharacter == T('/'))
  43126. return "/";
  43127. if (mods.isCtrlDown())
  43128. desc << "ctrl + ";
  43129. if (mods.isShiftDown())
  43130. desc << "shift + ";
  43131. #if JUCE_MAC
  43132. // only do this on the mac, because on Windows ctrl and command are the same,
  43133. // and this would get confusing
  43134. if (mods.isCommandDown())
  43135. desc << "command + ";
  43136. if (mods.isAltDown())
  43137. desc << "option + ";
  43138. #else
  43139. if (mods.isAltDown())
  43140. desc << "alt + ";
  43141. #endif
  43142. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  43143. if (keyCode == keyNameTranslations[i].code)
  43144. return desc + keyNameTranslations[i].name;
  43145. if (keyCode >= F1Key && keyCode <= F16Key)
  43146. desc << 'F' << (1 + keyCode - F1Key);
  43147. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  43148. desc << numberPadPrefix << (keyCode - numberPad0);
  43149. else if (keyCode >= 33 && keyCode < 176)
  43150. desc += CharacterFunctions::toUpperCase ((tchar) keyCode);
  43151. else if (keyCode == numberPadAdd)
  43152. desc << numberPadPrefix << '+';
  43153. else if (keyCode == numberPadSubtract)
  43154. desc << numberPadPrefix << '-';
  43155. else if (keyCode == numberPadMultiply)
  43156. desc << numberPadPrefix << '*';
  43157. else if (keyCode == numberPadDivide)
  43158. desc << numberPadPrefix << '/';
  43159. else if (keyCode == numberPadSeparator)
  43160. desc << numberPadPrefix << "separator";
  43161. else if (keyCode == numberPadDecimalPoint)
  43162. desc << numberPadPrefix << '.';
  43163. else if (keyCode == numberPadDelete)
  43164. desc << numberPadPrefix << "delete";
  43165. else
  43166. desc << '#' << String::toHexString (keyCode);
  43167. }
  43168. return desc;
  43169. }
  43170. END_JUCE_NAMESPACE
  43171. /********* End of inlined file: juce_KeyPress.cpp *********/
  43172. /********* Start of inlined file: juce_KeyPressMappingSet.cpp *********/
  43173. BEGIN_JUCE_NAMESPACE
  43174. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_) throw()
  43175. : commandManager (commandManager_)
  43176. {
  43177. // A manager is needed to get the descriptions of commands, and will be called when
  43178. // a command is invoked. So you can't leave this null..
  43179. jassert (commandManager_ != 0);
  43180. Desktop::getInstance().addFocusChangeListener (this);
  43181. }
  43182. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other) throw()
  43183. : commandManager (other.commandManager)
  43184. {
  43185. Desktop::getInstance().addFocusChangeListener (this);
  43186. }
  43187. KeyPressMappingSet::~KeyPressMappingSet()
  43188. {
  43189. Desktop::getInstance().removeFocusChangeListener (this);
  43190. }
  43191. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const throw()
  43192. {
  43193. for (int i = 0; i < mappings.size(); ++i)
  43194. if (mappings.getUnchecked(i)->commandID == commandID)
  43195. return mappings.getUnchecked (i)->keypresses;
  43196. return Array <KeyPress> ();
  43197. }
  43198. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  43199. const KeyPress& newKeyPress,
  43200. int insertIndex) throw()
  43201. {
  43202. if (findCommandForKeyPress (newKeyPress) != commandID)
  43203. {
  43204. removeKeyPress (newKeyPress);
  43205. if (newKeyPress.isValid())
  43206. {
  43207. for (int i = mappings.size(); --i >= 0;)
  43208. {
  43209. if (mappings.getUnchecked(i)->commandID == commandID)
  43210. {
  43211. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  43212. sendChangeMessage (this);
  43213. return;
  43214. }
  43215. }
  43216. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  43217. if (ci != 0)
  43218. {
  43219. CommandMapping* const cm = new CommandMapping();
  43220. cm->commandID = commandID;
  43221. cm->keypresses.add (newKeyPress);
  43222. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  43223. mappings.add (cm);
  43224. sendChangeMessage (this);
  43225. }
  43226. }
  43227. }
  43228. }
  43229. void KeyPressMappingSet::resetToDefaultMappings() throw()
  43230. {
  43231. mappings.clear();
  43232. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  43233. {
  43234. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  43235. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  43236. {
  43237. addKeyPress (ci->commandID,
  43238. ci->defaultKeypresses.getReference (j));
  43239. }
  43240. }
  43241. sendChangeMessage (this);
  43242. }
  43243. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID) throw()
  43244. {
  43245. clearAllKeyPresses (commandID);
  43246. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  43247. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  43248. {
  43249. addKeyPress (ci->commandID,
  43250. ci->defaultKeypresses.getReference (j));
  43251. }
  43252. }
  43253. void KeyPressMappingSet::clearAllKeyPresses() throw()
  43254. {
  43255. if (mappings.size() > 0)
  43256. {
  43257. sendChangeMessage (this);
  43258. mappings.clear();
  43259. }
  43260. }
  43261. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID) throw()
  43262. {
  43263. for (int i = mappings.size(); --i >= 0;)
  43264. {
  43265. if (mappings.getUnchecked(i)->commandID == commandID)
  43266. {
  43267. mappings.remove (i);
  43268. sendChangeMessage (this);
  43269. }
  43270. }
  43271. }
  43272. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress) throw()
  43273. {
  43274. if (keypress.isValid())
  43275. {
  43276. for (int i = mappings.size(); --i >= 0;)
  43277. {
  43278. CommandMapping* const cm = mappings.getUnchecked(i);
  43279. for (int j = cm->keypresses.size(); --j >= 0;)
  43280. {
  43281. if (keypress == cm->keypresses [j])
  43282. {
  43283. cm->keypresses.remove (j);
  43284. sendChangeMessage (this);
  43285. }
  43286. }
  43287. }
  43288. }
  43289. }
  43290. void KeyPressMappingSet::removeKeyPress (const CommandID commandID,
  43291. const int keyPressIndex) throw()
  43292. {
  43293. for (int i = mappings.size(); --i >= 0;)
  43294. {
  43295. if (mappings.getUnchecked(i)->commandID == commandID)
  43296. {
  43297. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  43298. sendChangeMessage (this);
  43299. break;
  43300. }
  43301. }
  43302. }
  43303. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  43304. {
  43305. for (int i = 0; i < mappings.size(); ++i)
  43306. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  43307. return mappings.getUnchecked(i)->commandID;
  43308. return 0;
  43309. }
  43310. bool KeyPressMappingSet::containsMapping (const CommandID commandID,
  43311. const KeyPress& keyPress) const throw()
  43312. {
  43313. for (int i = mappings.size(); --i >= 0;)
  43314. if (mappings.getUnchecked(i)->commandID == commandID)
  43315. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  43316. return false;
  43317. }
  43318. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  43319. const KeyPress& key,
  43320. const bool isKeyDown,
  43321. const int millisecsSinceKeyPressed,
  43322. Component* const originatingComponent) const
  43323. {
  43324. ApplicationCommandTarget::InvocationInfo info (commandID);
  43325. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  43326. info.isKeyDown = isKeyDown;
  43327. info.keyPress = key;
  43328. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  43329. info.originatingComponent = originatingComponent;
  43330. commandManager->invoke (info, false);
  43331. }
  43332. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  43333. {
  43334. if (xmlVersion.hasTagName (T("KEYMAPPINGS")))
  43335. {
  43336. if (xmlVersion.getBoolAttribute (T("basedOnDefaults"), true))
  43337. {
  43338. // if the XML was created as a set of differences from the default mappings,
  43339. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  43340. resetToDefaultMappings();
  43341. }
  43342. else
  43343. {
  43344. // if the XML was created calling createXml (false), then we need to clear all
  43345. // the keys and treat the xml as describing the entire set of mappings.
  43346. clearAllKeyPresses();
  43347. }
  43348. forEachXmlChildElement (xmlVersion, map)
  43349. {
  43350. const CommandID commandId = map->getStringAttribute (T("commandId")).getHexValue32();
  43351. if (commandId != 0)
  43352. {
  43353. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute (T("key"))));
  43354. if (map->hasTagName (T("MAPPING")))
  43355. {
  43356. addKeyPress (commandId, key);
  43357. }
  43358. else if (map->hasTagName (T("UNMAPPING")))
  43359. {
  43360. if (containsMapping (commandId, key))
  43361. removeKeyPress (key);
  43362. }
  43363. }
  43364. }
  43365. return true;
  43366. }
  43367. return false;
  43368. }
  43369. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  43370. {
  43371. KeyPressMappingSet* defaultSet = 0;
  43372. if (saveDifferencesFromDefaultSet)
  43373. {
  43374. defaultSet = new KeyPressMappingSet (commandManager);
  43375. defaultSet->resetToDefaultMappings();
  43376. }
  43377. XmlElement* const doc = new XmlElement (T("KEYMAPPINGS"));
  43378. doc->setAttribute (T("basedOnDefaults"), saveDifferencesFromDefaultSet);
  43379. int i;
  43380. for (i = 0; i < mappings.size(); ++i)
  43381. {
  43382. const CommandMapping* const cm = mappings.getUnchecked(i);
  43383. for (int j = 0; j < cm->keypresses.size(); ++j)
  43384. {
  43385. if (defaultSet == 0
  43386. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  43387. {
  43388. XmlElement* const map = new XmlElement (T("MAPPING"));
  43389. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  43390. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  43391. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  43392. doc->addChildElement (map);
  43393. }
  43394. }
  43395. }
  43396. if (defaultSet != 0)
  43397. {
  43398. for (i = 0; i < defaultSet->mappings.size(); ++i)
  43399. {
  43400. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  43401. for (int j = 0; j < cm->keypresses.size(); ++j)
  43402. {
  43403. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  43404. {
  43405. XmlElement* const map = new XmlElement (T("UNMAPPING"));
  43406. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  43407. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  43408. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  43409. doc->addChildElement (map);
  43410. }
  43411. }
  43412. }
  43413. delete defaultSet;
  43414. }
  43415. return doc;
  43416. }
  43417. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  43418. Component* originatingComponent)
  43419. {
  43420. bool used = false;
  43421. const CommandID commandID = findCommandForKeyPress (key);
  43422. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  43423. if (ci != 0
  43424. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  43425. {
  43426. ApplicationCommandInfo info (0);
  43427. if (commandManager->getTargetForCommand (commandID, info) != 0
  43428. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  43429. {
  43430. invokeCommand (commandID, key, true, 0, originatingComponent);
  43431. used = true;
  43432. }
  43433. else
  43434. {
  43435. if (originatingComponent != 0)
  43436. originatingComponent->getLookAndFeel().playAlertSound();
  43437. }
  43438. }
  43439. return used;
  43440. }
  43441. bool KeyPressMappingSet::keyStateChanged (Component* originatingComponent)
  43442. {
  43443. bool used = false;
  43444. const uint32 now = Time::getMillisecondCounter();
  43445. for (int i = mappings.size(); --i >= 0;)
  43446. {
  43447. CommandMapping* const cm = mappings.getUnchecked(i);
  43448. if (cm->wantsKeyUpDownCallbacks)
  43449. {
  43450. for (int j = cm->keypresses.size(); --j >= 0;)
  43451. {
  43452. const KeyPress key (cm->keypresses.getReference (j));
  43453. const bool isDown = key.isCurrentlyDown();
  43454. int keyPressEntryIndex = 0;
  43455. bool wasDown = false;
  43456. for (int k = keysDown.size(); --k >= 0;)
  43457. {
  43458. if (key == keysDown.getUnchecked(k)->key)
  43459. {
  43460. keyPressEntryIndex = k;
  43461. wasDown = true;
  43462. break;
  43463. }
  43464. }
  43465. if (isDown != wasDown)
  43466. {
  43467. int millisecs = 0;
  43468. if (isDown)
  43469. {
  43470. KeyPressTime* const k = new KeyPressTime();
  43471. k->key = key;
  43472. k->timeWhenPressed = now;
  43473. keysDown.add (k);
  43474. }
  43475. else
  43476. {
  43477. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  43478. if (now > pressTime)
  43479. millisecs = now - pressTime;
  43480. keysDown.remove (keyPressEntryIndex);
  43481. }
  43482. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  43483. used = true;
  43484. }
  43485. }
  43486. }
  43487. }
  43488. return used;
  43489. }
  43490. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  43491. {
  43492. if (focusedComponent != 0)
  43493. focusedComponent->keyStateChanged();
  43494. }
  43495. END_JUCE_NAMESPACE
  43496. /********* End of inlined file: juce_KeyPressMappingSet.cpp *********/
  43497. /********* Start of inlined file: juce_ModifierKeys.cpp *********/
  43498. BEGIN_JUCE_NAMESPACE
  43499. ModifierKeys::ModifierKeys (const int flags_) throw()
  43500. : flags (flags_)
  43501. {
  43502. }
  43503. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  43504. : flags (other.flags)
  43505. {
  43506. }
  43507. const ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  43508. {
  43509. flags = other.flags;
  43510. return *this;
  43511. }
  43512. int ModifierKeys::currentModifierFlags = 0;
  43513. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  43514. {
  43515. return ModifierKeys (currentModifierFlags);
  43516. }
  43517. END_JUCE_NAMESPACE
  43518. /********* End of inlined file: juce_ModifierKeys.cpp *********/
  43519. /********* Start of inlined file: juce_ComponentAnimator.cpp *********/
  43520. BEGIN_JUCE_NAMESPACE
  43521. struct AnimationTask
  43522. {
  43523. AnimationTask (Component* const comp)
  43524. : component (comp),
  43525. watcher (comp)
  43526. {
  43527. }
  43528. Component* component;
  43529. ComponentDeletionWatcher watcher;
  43530. Rectangle destination;
  43531. int msElapsed, msTotal;
  43532. double startSpeed, midSpeed, endSpeed, lastProgress;
  43533. double left, top, right, bottom;
  43534. bool useTimeslice (const int elapsed)
  43535. {
  43536. if (watcher.hasBeenDeleted())
  43537. return false;
  43538. msElapsed += elapsed;
  43539. double newProgress = msElapsed / (double) msTotal;
  43540. if (newProgress >= 0 && newProgress < 1.0)
  43541. {
  43542. newProgress = timeToDistance (newProgress);
  43543. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  43544. jassert (newProgress >= lastProgress);
  43545. lastProgress = newProgress;
  43546. left += (destination.getX() - left) * delta;
  43547. top += (destination.getY() - top) * delta;
  43548. right += (destination.getRight() - right) * delta;
  43549. bottom += (destination.getBottom() - bottom) * delta;
  43550. if (delta < 1.0)
  43551. {
  43552. const Rectangle newBounds (roundDoubleToInt (left),
  43553. roundDoubleToInt (top),
  43554. roundDoubleToInt (right - left),
  43555. roundDoubleToInt (bottom - top));
  43556. if (newBounds != destination)
  43557. {
  43558. component->setBounds (newBounds);
  43559. return true;
  43560. }
  43561. }
  43562. }
  43563. component->setBounds (destination);
  43564. return false;
  43565. }
  43566. void moveToFinalDestination()
  43567. {
  43568. if (! watcher.hasBeenDeleted())
  43569. component->setBounds (destination);
  43570. }
  43571. private:
  43572. inline double timeToDistance (const double time) const
  43573. {
  43574. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  43575. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  43576. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  43577. }
  43578. };
  43579. ComponentAnimator::ComponentAnimator()
  43580. : lastTime (0)
  43581. {
  43582. }
  43583. ComponentAnimator::~ComponentAnimator()
  43584. {
  43585. cancelAllAnimations (false);
  43586. jassert (tasks.size() == 0);
  43587. }
  43588. void* ComponentAnimator::findTaskFor (Component* const component) const
  43589. {
  43590. for (int i = tasks.size(); --i >= 0;)
  43591. if (component == ((AnimationTask*) tasks.getUnchecked(i))->component)
  43592. return tasks.getUnchecked(i);
  43593. return 0;
  43594. }
  43595. void ComponentAnimator::animateComponent (Component* const component,
  43596. const Rectangle& finalPosition,
  43597. const int millisecondsToSpendMoving,
  43598. const double startSpeed,
  43599. const double endSpeed)
  43600. {
  43601. if (component != 0)
  43602. {
  43603. AnimationTask* at = (AnimationTask*) findTaskFor (component);
  43604. if (at == 0)
  43605. {
  43606. at = new AnimationTask (component);
  43607. tasks.add (at);
  43608. }
  43609. at->msElapsed = 0;
  43610. at->lastProgress = 0;
  43611. at->msTotal = jmax (1, millisecondsToSpendMoving);
  43612. at->destination = finalPosition;
  43613. // the speeds must be 0 or greater!
  43614. jassert (startSpeed >= 0 && endSpeed >= 0)
  43615. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  43616. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  43617. at->midSpeed = invTotalDistance;
  43618. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  43619. at->left = component->getX();
  43620. at->top = component->getY();
  43621. at->right = component->getRight();
  43622. at->bottom = component->getBottom();
  43623. if (! isTimerRunning())
  43624. {
  43625. lastTime = Time::getMillisecondCounter();
  43626. startTimer (1000 / 50);
  43627. }
  43628. }
  43629. }
  43630. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  43631. {
  43632. for (int i = tasks.size(); --i >= 0;)
  43633. {
  43634. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  43635. if (moveComponentsToTheirFinalPositions)
  43636. at->moveToFinalDestination();
  43637. delete at;
  43638. tasks.remove (i);
  43639. }
  43640. }
  43641. void ComponentAnimator::cancelAnimation (Component* const component,
  43642. const bool moveComponentToItsFinalPosition)
  43643. {
  43644. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  43645. if (at != 0)
  43646. {
  43647. if (moveComponentToItsFinalPosition)
  43648. at->moveToFinalDestination();
  43649. tasks.removeValue (at);
  43650. delete at;
  43651. }
  43652. }
  43653. const Rectangle ComponentAnimator::getComponentDestination (Component* const component)
  43654. {
  43655. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  43656. if (at != 0)
  43657. return at->destination;
  43658. else if (component != 0)
  43659. return component->getBounds();
  43660. return Rectangle();
  43661. }
  43662. void ComponentAnimator::timerCallback()
  43663. {
  43664. const uint32 timeNow = Time::getMillisecondCounter();
  43665. if (lastTime == 0 || lastTime == timeNow)
  43666. lastTime = timeNow;
  43667. const int elapsed = timeNow - lastTime;
  43668. for (int i = tasks.size(); --i >= 0;)
  43669. {
  43670. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  43671. if (! at->useTimeslice (elapsed))
  43672. {
  43673. tasks.remove (i);
  43674. delete at;
  43675. }
  43676. }
  43677. lastTime = timeNow;
  43678. if (tasks.size() == 0)
  43679. stopTimer();
  43680. }
  43681. END_JUCE_NAMESPACE
  43682. /********* End of inlined file: juce_ComponentAnimator.cpp *********/
  43683. /********* Start of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  43684. BEGIN_JUCE_NAMESPACE
  43685. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  43686. : minW (0),
  43687. maxW (0x3fffffff),
  43688. minH (0),
  43689. maxH (0x3fffffff),
  43690. minOffTop (0),
  43691. minOffLeft (0),
  43692. minOffBottom (0),
  43693. minOffRight (0),
  43694. aspectRatio (0.0)
  43695. {
  43696. }
  43697. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  43698. {
  43699. }
  43700. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  43701. {
  43702. minW = minimumWidth;
  43703. }
  43704. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  43705. {
  43706. maxW = maximumWidth;
  43707. }
  43708. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  43709. {
  43710. minH = minimumHeight;
  43711. }
  43712. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  43713. {
  43714. maxH = maximumHeight;
  43715. }
  43716. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  43717. {
  43718. jassert (maxW >= minimumWidth);
  43719. jassert (maxH >= minimumHeight);
  43720. jassert (minimumWidth > 0 && minimumHeight > 0);
  43721. minW = minimumWidth;
  43722. minH = minimumHeight;
  43723. if (minW > maxW)
  43724. maxW = minW;
  43725. if (minH > maxH)
  43726. maxH = minH;
  43727. }
  43728. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  43729. {
  43730. jassert (maximumWidth >= minW);
  43731. jassert (maximumHeight >= minH);
  43732. jassert (maximumWidth > 0 && maximumHeight > 0);
  43733. maxW = jmax (minW, maximumWidth);
  43734. maxH = jmax (minH, maximumHeight);
  43735. }
  43736. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  43737. const int minimumHeight,
  43738. const int maximumWidth,
  43739. const int maximumHeight) throw()
  43740. {
  43741. jassert (maximumWidth >= minimumWidth);
  43742. jassert (maximumHeight >= minimumHeight);
  43743. jassert (maximumWidth > 0 && maximumHeight > 0);
  43744. jassert (minimumWidth > 0 && minimumHeight > 0);
  43745. minW = jmax (0, minimumWidth);
  43746. minH = jmax (0, minimumHeight);
  43747. maxW = jmax (minW, maximumWidth);
  43748. maxH = jmax (minH, maximumHeight);
  43749. }
  43750. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  43751. const int minimumWhenOffTheLeft,
  43752. const int minimumWhenOffTheBottom,
  43753. const int minimumWhenOffTheRight) throw()
  43754. {
  43755. minOffTop = minimumWhenOffTheTop;
  43756. minOffLeft = minimumWhenOffTheLeft;
  43757. minOffBottom = minimumWhenOffTheBottom;
  43758. minOffRight = minimumWhenOffTheRight;
  43759. }
  43760. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  43761. {
  43762. aspectRatio = jmax (0.0, widthOverHeight);
  43763. }
  43764. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  43765. {
  43766. return aspectRatio;
  43767. }
  43768. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  43769. int x, int y, int w, int h,
  43770. const bool isStretchingTop,
  43771. const bool isStretchingLeft,
  43772. const bool isStretchingBottom,
  43773. const bool isStretchingRight)
  43774. {
  43775. jassert (component != 0);
  43776. Rectangle limits;
  43777. Component* const p = component->getParentComponent();
  43778. if (p == 0)
  43779. limits = Desktop::getInstance().getAllMonitorDisplayAreas().getBounds();
  43780. else
  43781. limits.setSize (p->getWidth(), p->getHeight());
  43782. if (component->isOnDesktop())
  43783. {
  43784. ComponentPeer* const peer = component->getPeer();
  43785. const BorderSize border (peer->getFrameSize());
  43786. x -= border.getLeft();
  43787. y -= border.getTop();
  43788. w += border.getLeftAndRight();
  43789. h += border.getTopAndBottom();
  43790. checkBounds (x, y, w, h,
  43791. border.addedTo (component->getBounds()), limits,
  43792. isStretchingTop, isStretchingLeft,
  43793. isStretchingBottom, isStretchingRight);
  43794. x += border.getLeft();
  43795. y += border.getTop();
  43796. w -= border.getLeftAndRight();
  43797. h -= border.getTopAndBottom();
  43798. }
  43799. else
  43800. {
  43801. checkBounds (x, y, w, h,
  43802. component->getBounds(), limits,
  43803. isStretchingTop, isStretchingLeft,
  43804. isStretchingBottom, isStretchingRight);
  43805. }
  43806. applyBoundsToComponent (component, x, y, w, h);
  43807. }
  43808. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  43809. int x, int y, int w, int h)
  43810. {
  43811. component->setBounds (x, y, w, h);
  43812. }
  43813. void ComponentBoundsConstrainer::resizeStart()
  43814. {
  43815. }
  43816. void ComponentBoundsConstrainer::resizeEnd()
  43817. {
  43818. }
  43819. void ComponentBoundsConstrainer::checkBounds (int& x, int& y, int& w, int& h,
  43820. const Rectangle& old,
  43821. const Rectangle& limits,
  43822. const bool isStretchingTop,
  43823. const bool isStretchingLeft,
  43824. const bool isStretchingBottom,
  43825. const bool isStretchingRight)
  43826. {
  43827. // constrain the size if it's being stretched..
  43828. if (isStretchingLeft)
  43829. {
  43830. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  43831. w = old.getRight() - x;
  43832. }
  43833. if (isStretchingRight)
  43834. {
  43835. w = jlimit (minW, maxW, w);
  43836. }
  43837. if (isStretchingTop)
  43838. {
  43839. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  43840. h = old.getBottom() - y;
  43841. }
  43842. if (isStretchingBottom)
  43843. {
  43844. h = jlimit (minH, maxH, h);
  43845. }
  43846. // constrain the aspect ratio if one has been specified..
  43847. if (aspectRatio > 0.0 && w > 0 && h > 0)
  43848. {
  43849. bool adjustWidth;
  43850. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  43851. {
  43852. adjustWidth = true;
  43853. }
  43854. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  43855. {
  43856. adjustWidth = false;
  43857. }
  43858. else
  43859. {
  43860. const double oldRatio = (old.getHeight() > 0) ? fabs (old.getWidth() / (double) old.getHeight()) : 0.0;
  43861. const double newRatio = fabs (w / (double) h);
  43862. adjustWidth = (oldRatio > newRatio);
  43863. }
  43864. if (adjustWidth)
  43865. {
  43866. w = roundDoubleToInt (h * aspectRatio);
  43867. if (w > maxW || w < minW)
  43868. {
  43869. w = jlimit (minW, maxW, w);
  43870. h = roundDoubleToInt (w / aspectRatio);
  43871. }
  43872. }
  43873. else
  43874. {
  43875. h = roundDoubleToInt (w / aspectRatio);
  43876. if (h > maxH || h < minH)
  43877. {
  43878. h = jlimit (minH, maxH, h);
  43879. w = roundDoubleToInt (h * aspectRatio);
  43880. }
  43881. }
  43882. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  43883. {
  43884. x = old.getX() + (old.getWidth() - w) / 2;
  43885. }
  43886. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  43887. {
  43888. y = old.getY() + (old.getHeight() - h) / 2;
  43889. }
  43890. else
  43891. {
  43892. if (isStretchingLeft)
  43893. x = old.getRight() - w;
  43894. if (isStretchingTop)
  43895. y = old.getBottom() - h;
  43896. }
  43897. }
  43898. // ...and constrain the position if limits have been set for that.
  43899. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  43900. {
  43901. if (minOffTop > 0)
  43902. {
  43903. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  43904. if (y < limit)
  43905. {
  43906. if (isStretchingTop)
  43907. h -= (limit - y);
  43908. y = limit;
  43909. }
  43910. }
  43911. if (minOffLeft > 0)
  43912. {
  43913. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  43914. if (x < limit)
  43915. {
  43916. if (isStretchingLeft)
  43917. w -= (limit - x);
  43918. x = limit;
  43919. }
  43920. }
  43921. if (minOffBottom > 0)
  43922. {
  43923. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  43924. if (y > limit)
  43925. {
  43926. if (isStretchingBottom)
  43927. h += (limit - y);
  43928. else
  43929. y = limit;
  43930. }
  43931. }
  43932. if (minOffRight > 0)
  43933. {
  43934. const int limit = limits.getRight() - jmin (minOffRight, w);
  43935. if (x > limit)
  43936. {
  43937. if (isStretchingRight)
  43938. w += (limit - x);
  43939. else
  43940. x = limit;
  43941. }
  43942. }
  43943. }
  43944. jassert (w >= 0 && h >= 0);
  43945. }
  43946. END_JUCE_NAMESPACE
  43947. /********* End of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  43948. /********* Start of inlined file: juce_ComponentMovementWatcher.cpp *********/
  43949. BEGIN_JUCE_NAMESPACE
  43950. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  43951. : component (component_),
  43952. lastPeer (0),
  43953. registeredParentComps (4),
  43954. reentrant (false)
  43955. {
  43956. jassert (component != 0); // can't use this with a null pointer..
  43957. #ifdef JUCE_DEBUG
  43958. deletionWatcher = new ComponentDeletionWatcher (component_);
  43959. #endif
  43960. component->addComponentListener (this);
  43961. registerWithParentComps();
  43962. }
  43963. ComponentMovementWatcher::~ComponentMovementWatcher()
  43964. {
  43965. component->removeComponentListener (this);
  43966. unregister();
  43967. #ifdef JUCE_DEBUG
  43968. delete deletionWatcher;
  43969. #endif
  43970. }
  43971. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  43972. {
  43973. #ifdef JUCE_DEBUG
  43974. // agh! don't delete the target component without deleting this object first!
  43975. jassert (! deletionWatcher->hasBeenDeleted());
  43976. #endif
  43977. if (! reentrant)
  43978. {
  43979. reentrant = true;
  43980. ComponentPeer* const peer = component->getPeer();
  43981. if (peer != lastPeer)
  43982. {
  43983. ComponentDeletionWatcher watcher (component);
  43984. componentPeerChanged();
  43985. if (watcher.hasBeenDeleted())
  43986. return;
  43987. lastPeer = peer;
  43988. }
  43989. unregister();
  43990. registerWithParentComps();
  43991. reentrant = false;
  43992. componentMovedOrResized (*component, true, true);
  43993. }
  43994. }
  43995. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  43996. {
  43997. #ifdef JUCE_DEBUG
  43998. // agh! don't delete the target component without deleting this object first!
  43999. jassert (! deletionWatcher->hasBeenDeleted());
  44000. #endif
  44001. if (wasMoved)
  44002. {
  44003. int x = 0, y = 0;
  44004. component->relativePositionToOtherComponent (component->getTopLevelComponent(), x, y);
  44005. wasMoved = (lastX != x || lastY != y);
  44006. lastX = x;
  44007. lastY = y;
  44008. }
  44009. wasResized = (lastWidth != component->getWidth() || lastHeight != component->getHeight());
  44010. lastWidth = component->getWidth();
  44011. lastHeight = component->getHeight();
  44012. if (wasMoved || wasResized)
  44013. componentMovedOrResized (wasMoved, wasResized);
  44014. }
  44015. void ComponentMovementWatcher::registerWithParentComps() throw()
  44016. {
  44017. Component* p = component->getParentComponent();
  44018. while (p != 0)
  44019. {
  44020. p->addComponentListener (this);
  44021. registeredParentComps.add (p);
  44022. p = p->getParentComponent();
  44023. }
  44024. }
  44025. void ComponentMovementWatcher::unregister() throw()
  44026. {
  44027. for (int i = registeredParentComps.size(); --i >= 0;)
  44028. ((Component*) registeredParentComps.getUnchecked(i))->removeComponentListener (this);
  44029. registeredParentComps.clear();
  44030. }
  44031. END_JUCE_NAMESPACE
  44032. /********* End of inlined file: juce_ComponentMovementWatcher.cpp *********/
  44033. /********* Start of inlined file: juce_GroupComponent.cpp *********/
  44034. BEGIN_JUCE_NAMESPACE
  44035. GroupComponent::GroupComponent (const String& componentName,
  44036. const String& labelText)
  44037. : Component (componentName),
  44038. text (labelText),
  44039. justification (Justification::left)
  44040. {
  44041. setInterceptsMouseClicks (false, true);
  44042. }
  44043. GroupComponent::~GroupComponent()
  44044. {
  44045. }
  44046. void GroupComponent::setText (const String& newText) throw()
  44047. {
  44048. if (text != newText)
  44049. {
  44050. text = newText;
  44051. repaint();
  44052. }
  44053. }
  44054. const String GroupComponent::getText() const throw()
  44055. {
  44056. return text;
  44057. }
  44058. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  44059. {
  44060. if (justification.getFlags() != newJustification.getFlags())
  44061. {
  44062. justification = newJustification;
  44063. repaint();
  44064. }
  44065. }
  44066. void GroupComponent::paint (Graphics& g)
  44067. {
  44068. getLookAndFeel()
  44069. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  44070. text, justification,
  44071. *this);
  44072. }
  44073. void GroupComponent::enablementChanged()
  44074. {
  44075. repaint();
  44076. }
  44077. void GroupComponent::colourChanged()
  44078. {
  44079. repaint();
  44080. }
  44081. END_JUCE_NAMESPACE
  44082. /********* End of inlined file: juce_GroupComponent.cpp *********/
  44083. /********* Start of inlined file: juce_MultiDocumentPanel.cpp *********/
  44084. BEGIN_JUCE_NAMESPACE
  44085. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  44086. : DocumentWindow (String::empty, backgroundColour,
  44087. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  44088. {
  44089. }
  44090. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  44091. {
  44092. }
  44093. void MultiDocumentPanelWindow::maximiseButtonPressed()
  44094. {
  44095. MultiDocumentPanel* const owner = getOwner();
  44096. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  44097. if (owner != 0)
  44098. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  44099. }
  44100. void MultiDocumentPanelWindow::closeButtonPressed()
  44101. {
  44102. MultiDocumentPanel* const owner = getOwner();
  44103. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  44104. if (owner != 0)
  44105. owner->closeDocument (getContentComponent(), true);
  44106. }
  44107. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  44108. {
  44109. DocumentWindow::activeWindowStatusChanged();
  44110. updateOrder();
  44111. }
  44112. void MultiDocumentPanelWindow::broughtToFront()
  44113. {
  44114. DocumentWindow::broughtToFront();
  44115. updateOrder();
  44116. }
  44117. void MultiDocumentPanelWindow::updateOrder()
  44118. {
  44119. MultiDocumentPanel* const owner = getOwner();
  44120. if (owner != 0)
  44121. owner->updateOrder();
  44122. }
  44123. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  44124. {
  44125. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  44126. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  44127. }
  44128. class MDITabbedComponentInternal : public TabbedComponent
  44129. {
  44130. public:
  44131. MDITabbedComponentInternal()
  44132. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  44133. {
  44134. }
  44135. ~MDITabbedComponentInternal()
  44136. {
  44137. }
  44138. void currentTabChanged (const int, const String&)
  44139. {
  44140. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  44141. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  44142. if (owner != 0)
  44143. owner->updateOrder();
  44144. }
  44145. };
  44146. MultiDocumentPanel::MultiDocumentPanel()
  44147. : mode (MaximisedWindowsWithTabs),
  44148. tabComponent (0),
  44149. backgroundColour (Colours::lightblue),
  44150. maximumNumDocuments (0),
  44151. numDocsBeforeTabsUsed (0)
  44152. {
  44153. setOpaque (true);
  44154. }
  44155. MultiDocumentPanel::~MultiDocumentPanel()
  44156. {
  44157. closeAllDocuments (false);
  44158. }
  44159. static bool shouldDeleteComp (Component* const c)
  44160. {
  44161. return c->getComponentPropertyBool (T("mdiDocumentDelete_"), false);
  44162. }
  44163. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  44164. {
  44165. while (components.size() > 0)
  44166. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  44167. return false;
  44168. return true;
  44169. }
  44170. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  44171. {
  44172. return new MultiDocumentPanelWindow (backgroundColour);
  44173. }
  44174. void MultiDocumentPanel::addWindow (Component* component)
  44175. {
  44176. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  44177. dw->setResizable (true, false);
  44178. dw->setContentComponent (component, false, true);
  44179. dw->setName (component->getName());
  44180. dw->setBackgroundColour (component->getComponentPropertyColour (T("mdiDocumentBkg_"), false, backgroundColour));
  44181. int x = 4;
  44182. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  44183. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  44184. x += 16;
  44185. dw->setTopLeftPosition (x, x);
  44186. if (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty).isNotEmpty())
  44187. dw->restoreWindowStateFromString (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty));
  44188. addAndMakeVisible (dw);
  44189. dw->toFront (true);
  44190. }
  44191. bool MultiDocumentPanel::addDocument (Component* const component,
  44192. const Colour& backgroundColour,
  44193. const bool deleteWhenRemoved)
  44194. {
  44195. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  44196. // with a frame-within-a-frame! Just pass in the bare content component.
  44197. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  44198. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  44199. return false;
  44200. components.add (component);
  44201. component->setComponentProperty (T("mdiDocumentDelete_"), deleteWhenRemoved);
  44202. component->setComponentProperty (T("mdiDocumentBkg_"), backgroundColour);
  44203. component->addComponentListener (this);
  44204. if (mode == FloatingWindows)
  44205. {
  44206. if (isFullscreenWhenOneDocument())
  44207. {
  44208. if (components.size() == 1)
  44209. {
  44210. addAndMakeVisible (component);
  44211. }
  44212. else
  44213. {
  44214. if (components.size() == 2)
  44215. addWindow (components.getFirst());
  44216. addWindow (component);
  44217. }
  44218. }
  44219. else
  44220. {
  44221. addWindow (component);
  44222. }
  44223. }
  44224. else
  44225. {
  44226. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  44227. {
  44228. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  44229. Array <Component*> temp (components);
  44230. for (int i = 0; i < temp.size(); ++i)
  44231. tabComponent->addTab (temp[i]->getName(), backgroundColour, temp[i], false);
  44232. resized();
  44233. }
  44234. else
  44235. {
  44236. if (tabComponent != 0)
  44237. tabComponent->addTab (component->getName(), backgroundColour, component, false);
  44238. else
  44239. addAndMakeVisible (component);
  44240. }
  44241. setActiveDocument (component);
  44242. }
  44243. resized();
  44244. activeDocumentChanged();
  44245. return true;
  44246. }
  44247. bool MultiDocumentPanel::closeDocument (Component* component,
  44248. const bool checkItsOkToCloseFirst)
  44249. {
  44250. if (components.contains (component))
  44251. {
  44252. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  44253. return false;
  44254. component->removeComponentListener (this);
  44255. const bool shouldDelete = shouldDeleteComp (component);
  44256. component->removeComponentProperty (T("mdiDocumentDelete_"));
  44257. component->removeComponentProperty (T("mdiDocumentBkg_"));
  44258. if (mode == FloatingWindows)
  44259. {
  44260. for (int i = getNumChildComponents(); --i >= 0;)
  44261. {
  44262. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44263. if (dw != 0 && dw->getContentComponent() == component)
  44264. {
  44265. dw->setContentComponent (0, false);
  44266. delete dw;
  44267. break;
  44268. }
  44269. }
  44270. if (shouldDelete)
  44271. delete component;
  44272. components.removeValue (component);
  44273. if (isFullscreenWhenOneDocument() && components.size() == 1)
  44274. {
  44275. for (int i = getNumChildComponents(); --i >= 0;)
  44276. {
  44277. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44278. if (dw != 0)
  44279. {
  44280. dw->setContentComponent (0, false);
  44281. delete dw;
  44282. }
  44283. }
  44284. addAndMakeVisible (components.getFirst());
  44285. }
  44286. }
  44287. else
  44288. {
  44289. jassert (components.indexOf (component) >= 0);
  44290. if (tabComponent != 0)
  44291. {
  44292. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  44293. if (tabComponent->getTabContentComponent (i) == component)
  44294. tabComponent->removeTab (i);
  44295. }
  44296. else
  44297. {
  44298. removeChildComponent (component);
  44299. }
  44300. if (shouldDelete)
  44301. delete component;
  44302. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  44303. deleteAndZero (tabComponent);
  44304. components.removeValue (component);
  44305. if (components.size() > 0 && tabComponent == 0)
  44306. addAndMakeVisible (components.getFirst());
  44307. }
  44308. resized();
  44309. activeDocumentChanged();
  44310. }
  44311. else
  44312. {
  44313. jassertfalse
  44314. }
  44315. return true;
  44316. }
  44317. int MultiDocumentPanel::getNumDocuments() const throw()
  44318. {
  44319. return components.size();
  44320. }
  44321. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  44322. {
  44323. return components [index];
  44324. }
  44325. Component* MultiDocumentPanel::getActiveDocument() const throw()
  44326. {
  44327. if (mode == FloatingWindows)
  44328. {
  44329. for (int i = getNumChildComponents(); --i >= 0;)
  44330. {
  44331. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44332. if (dw != 0 && dw->isActiveWindow())
  44333. return dw->getContentComponent();
  44334. }
  44335. }
  44336. return components.getLast();
  44337. }
  44338. void MultiDocumentPanel::setActiveDocument (Component* component)
  44339. {
  44340. if (mode == FloatingWindows)
  44341. {
  44342. component = getContainerComp (component);
  44343. if (component != 0)
  44344. component->toFront (true);
  44345. }
  44346. else if (tabComponent != 0)
  44347. {
  44348. jassert (components.indexOf (component) >= 0);
  44349. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  44350. {
  44351. if (tabComponent->getTabContentComponent (i) == component)
  44352. {
  44353. tabComponent->setCurrentTabIndex (i);
  44354. break;
  44355. }
  44356. }
  44357. }
  44358. else
  44359. {
  44360. component->grabKeyboardFocus();
  44361. }
  44362. }
  44363. void MultiDocumentPanel::activeDocumentChanged()
  44364. {
  44365. }
  44366. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  44367. {
  44368. maximumNumDocuments = newNumber;
  44369. }
  44370. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  44371. {
  44372. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  44373. }
  44374. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  44375. {
  44376. return numDocsBeforeTabsUsed != 0;
  44377. }
  44378. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  44379. {
  44380. if (mode != newLayoutMode)
  44381. {
  44382. mode = newLayoutMode;
  44383. if (mode == FloatingWindows)
  44384. {
  44385. deleteAndZero (tabComponent);
  44386. }
  44387. else
  44388. {
  44389. for (int i = getNumChildComponents(); --i >= 0;)
  44390. {
  44391. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44392. if (dw != 0)
  44393. {
  44394. dw->getContentComponent()->setComponentProperty (T("mdiDocumentPos_"), dw->getWindowStateAsString());
  44395. dw->setContentComponent (0, false);
  44396. delete dw;
  44397. }
  44398. }
  44399. }
  44400. resized();
  44401. const Array <Component*> tempComps (components);
  44402. components.clear();
  44403. for (int i = 0; i < tempComps.size(); ++i)
  44404. {
  44405. Component* const c = tempComps.getUnchecked(i);
  44406. addDocument (c,
  44407. c->getComponentPropertyColour (T("mdiDocumentBkg_"), false, Colours::white),
  44408. shouldDeleteComp (c));
  44409. }
  44410. }
  44411. }
  44412. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  44413. {
  44414. if (backgroundColour != newBackgroundColour)
  44415. {
  44416. backgroundColour = newBackgroundColour;
  44417. setOpaque (newBackgroundColour.isOpaque());
  44418. repaint();
  44419. }
  44420. }
  44421. void MultiDocumentPanel::paint (Graphics& g)
  44422. {
  44423. g.fillAll (backgroundColour);
  44424. }
  44425. void MultiDocumentPanel::resized()
  44426. {
  44427. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  44428. {
  44429. for (int i = getNumChildComponents(); --i >= 0;)
  44430. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  44431. }
  44432. setWantsKeyboardFocus (components.size() == 0);
  44433. }
  44434. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  44435. {
  44436. if (mode == FloatingWindows)
  44437. {
  44438. for (int i = 0; i < getNumChildComponents(); ++i)
  44439. {
  44440. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44441. if (dw != 0 && dw->getContentComponent() == c)
  44442. {
  44443. c = dw;
  44444. break;
  44445. }
  44446. }
  44447. }
  44448. return c;
  44449. }
  44450. void MultiDocumentPanel::componentNameChanged (Component&)
  44451. {
  44452. if (mode == FloatingWindows)
  44453. {
  44454. for (int i = 0; i < getNumChildComponents(); ++i)
  44455. {
  44456. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44457. if (dw != 0)
  44458. dw->setName (dw->getContentComponent()->getName());
  44459. }
  44460. }
  44461. else if (tabComponent != 0)
  44462. {
  44463. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  44464. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  44465. }
  44466. }
  44467. void MultiDocumentPanel::updateOrder()
  44468. {
  44469. const Array <Component*> oldList (components);
  44470. if (mode == FloatingWindows)
  44471. {
  44472. components.clear();
  44473. for (int i = 0; i < getNumChildComponents(); ++i)
  44474. {
  44475. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44476. if (dw != 0)
  44477. components.add (dw->getContentComponent());
  44478. }
  44479. }
  44480. else
  44481. {
  44482. if (tabComponent != 0)
  44483. {
  44484. Component* const current = tabComponent->getCurrentContentComponent();
  44485. if (current != 0)
  44486. {
  44487. components.removeValue (current);
  44488. components.add (current);
  44489. }
  44490. }
  44491. }
  44492. if (components != oldList)
  44493. activeDocumentChanged();
  44494. }
  44495. END_JUCE_NAMESPACE
  44496. /********* End of inlined file: juce_MultiDocumentPanel.cpp *********/
  44497. /********* Start of inlined file: juce_ResizableBorderComponent.cpp *********/
  44498. BEGIN_JUCE_NAMESPACE
  44499. const int zoneL = 1;
  44500. const int zoneR = 2;
  44501. const int zoneT = 4;
  44502. const int zoneB = 8;
  44503. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  44504. ComponentBoundsConstrainer* const constrainer_)
  44505. : component (componentToResize),
  44506. constrainer (constrainer_),
  44507. borderSize (5),
  44508. mouseZone (0)
  44509. {
  44510. }
  44511. ResizableBorderComponent::~ResizableBorderComponent()
  44512. {
  44513. }
  44514. void ResizableBorderComponent::paint (Graphics& g)
  44515. {
  44516. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  44517. }
  44518. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  44519. {
  44520. updateMouseZone (e);
  44521. }
  44522. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  44523. {
  44524. updateMouseZone (e);
  44525. }
  44526. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  44527. {
  44528. if (component->isValidComponent())
  44529. {
  44530. updateMouseZone (e);
  44531. originalX = component->getX();
  44532. originalY = component->getY();
  44533. originalW = component->getWidth();
  44534. originalH = component->getHeight();
  44535. if (constrainer != 0)
  44536. constrainer->resizeStart();
  44537. }
  44538. else
  44539. {
  44540. jassertfalse
  44541. }
  44542. }
  44543. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  44544. {
  44545. if (! component->isValidComponent())
  44546. {
  44547. jassertfalse
  44548. return;
  44549. }
  44550. int x = originalX;
  44551. int y = originalY;
  44552. int w = originalW;
  44553. int h = originalH;
  44554. const int dx = e.getDistanceFromDragStartX();
  44555. const int dy = e.getDistanceFromDragStartY();
  44556. if ((mouseZone & zoneL) != 0)
  44557. {
  44558. x += dx;
  44559. w -= dx;
  44560. }
  44561. if ((mouseZone & zoneT) != 0)
  44562. {
  44563. y += dy;
  44564. h -= dy;
  44565. }
  44566. if ((mouseZone & zoneR) != 0)
  44567. w += dx;
  44568. if ((mouseZone & zoneB) != 0)
  44569. h += dy;
  44570. if (constrainer != 0)
  44571. constrainer->setBoundsForComponent (component,
  44572. x, y, w, h,
  44573. (mouseZone & zoneT) != 0,
  44574. (mouseZone & zoneL) != 0,
  44575. (mouseZone & zoneB) != 0,
  44576. (mouseZone & zoneR) != 0);
  44577. else
  44578. component->setBounds (x, y, w, h);
  44579. }
  44580. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  44581. {
  44582. if (constrainer != 0)
  44583. constrainer->resizeEnd();
  44584. }
  44585. bool ResizableBorderComponent::hitTest (int x, int y)
  44586. {
  44587. return x < borderSize.getLeft()
  44588. || x >= getWidth() - borderSize.getRight()
  44589. || y < borderSize.getTop()
  44590. || y >= getHeight() - borderSize.getBottom();
  44591. }
  44592. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize) throw()
  44593. {
  44594. if (borderSize != newBorderSize)
  44595. {
  44596. borderSize = newBorderSize;
  44597. repaint();
  44598. }
  44599. }
  44600. const BorderSize ResizableBorderComponent::getBorderThickness() const throw()
  44601. {
  44602. return borderSize;
  44603. }
  44604. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e) throw()
  44605. {
  44606. int newZone = 0;
  44607. if (ResizableBorderComponent::hitTest (e.x, e.y))
  44608. {
  44609. if (e.x < jmax (borderSize.getLeft(), proportionOfWidth (0.1f)))
  44610. newZone |= zoneL;
  44611. else if (e.x >= jmin (getWidth() - borderSize.getRight(), proportionOfWidth (0.9f)))
  44612. newZone |= zoneR;
  44613. if (e.y < jmax (borderSize.getTop(), proportionOfHeight (0.1f)))
  44614. newZone |= zoneT;
  44615. else if (e.y >= jmin (getHeight() - borderSize.getBottom(), proportionOfHeight (0.9f)))
  44616. newZone |= zoneB;
  44617. }
  44618. if (mouseZone != newZone)
  44619. {
  44620. mouseZone = newZone;
  44621. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  44622. switch (newZone)
  44623. {
  44624. case (zoneL | zoneT):
  44625. mc = MouseCursor::TopLeftCornerResizeCursor;
  44626. break;
  44627. case zoneT:
  44628. mc = MouseCursor::TopEdgeResizeCursor;
  44629. break;
  44630. case (zoneR | zoneT):
  44631. mc = MouseCursor::TopRightCornerResizeCursor;
  44632. break;
  44633. case zoneL:
  44634. mc = MouseCursor::LeftEdgeResizeCursor;
  44635. break;
  44636. case zoneR:
  44637. mc = MouseCursor::RightEdgeResizeCursor;
  44638. break;
  44639. case (zoneL | zoneB):
  44640. mc = MouseCursor::BottomLeftCornerResizeCursor;
  44641. break;
  44642. case zoneB:
  44643. mc = MouseCursor::BottomEdgeResizeCursor;
  44644. break;
  44645. case (zoneR | zoneB):
  44646. mc = MouseCursor::BottomRightCornerResizeCursor;
  44647. break;
  44648. default:
  44649. break;
  44650. }
  44651. setMouseCursor (mc);
  44652. }
  44653. }
  44654. END_JUCE_NAMESPACE
  44655. /********* End of inlined file: juce_ResizableBorderComponent.cpp *********/
  44656. /********* Start of inlined file: juce_ResizableCornerComponent.cpp *********/
  44657. BEGIN_JUCE_NAMESPACE
  44658. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  44659. ComponentBoundsConstrainer* const constrainer_)
  44660. : component (componentToResize),
  44661. constrainer (constrainer_)
  44662. {
  44663. setRepaintsOnMouseActivity (true);
  44664. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  44665. }
  44666. ResizableCornerComponent::~ResizableCornerComponent()
  44667. {
  44668. }
  44669. void ResizableCornerComponent::paint (Graphics& g)
  44670. {
  44671. getLookAndFeel()
  44672. .drawCornerResizer (g, getWidth(), getHeight(),
  44673. isMouseOverOrDragging(),
  44674. isMouseButtonDown());
  44675. }
  44676. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  44677. {
  44678. if (component->isValidComponent())
  44679. {
  44680. originalX = component->getX();
  44681. originalY = component->getY();
  44682. originalW = component->getWidth();
  44683. originalH = component->getHeight();
  44684. if (constrainer != 0)
  44685. constrainer->resizeStart();
  44686. }
  44687. else
  44688. {
  44689. jassertfalse
  44690. }
  44691. }
  44692. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  44693. {
  44694. if (! component->isValidComponent())
  44695. {
  44696. jassertfalse
  44697. return;
  44698. }
  44699. int x = originalX;
  44700. int y = originalY;
  44701. int w = originalW + e.getDistanceFromDragStartX();
  44702. int h = originalH + e.getDistanceFromDragStartY();
  44703. if (constrainer != 0)
  44704. constrainer->setBoundsForComponent (component, x, y, w, h,
  44705. false, false, true, true);
  44706. else
  44707. component->setBounds (x, y, w, h);
  44708. }
  44709. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  44710. {
  44711. if (constrainer != 0)
  44712. constrainer->resizeStart();
  44713. }
  44714. bool ResizableCornerComponent::hitTest (int x, int y)
  44715. {
  44716. if (getWidth() <= 0)
  44717. return false;
  44718. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  44719. return y >= yAtX - getHeight() / 4;
  44720. }
  44721. END_JUCE_NAMESPACE
  44722. /********* End of inlined file: juce_ResizableCornerComponent.cpp *********/
  44723. /********* Start of inlined file: juce_ScrollBar.cpp *********/
  44724. BEGIN_JUCE_NAMESPACE
  44725. class ScrollbarButton : public Button
  44726. {
  44727. public:
  44728. int direction;
  44729. ScrollbarButton (const int direction_,
  44730. ScrollBar& owner_) throw()
  44731. : Button (String::empty),
  44732. direction (direction_),
  44733. owner (owner_)
  44734. {
  44735. setWantsKeyboardFocus (false);
  44736. }
  44737. ~ScrollbarButton()
  44738. {
  44739. }
  44740. void paintButton (Graphics& g,
  44741. bool isMouseOver,
  44742. bool isMouseDown)
  44743. {
  44744. getLookAndFeel()
  44745. .drawScrollbarButton (g, owner,
  44746. getWidth(), getHeight(),
  44747. direction,
  44748. owner.isVertical(),
  44749. isMouseOver, isMouseDown);
  44750. }
  44751. void clicked()
  44752. {
  44753. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  44754. }
  44755. juce_UseDebuggingNewOperator
  44756. private:
  44757. ScrollBar& owner;
  44758. ScrollbarButton (const ScrollbarButton&);
  44759. const ScrollbarButton& operator= (const ScrollbarButton&);
  44760. };
  44761. ScrollBar::ScrollBar (const bool vertical_,
  44762. const bool buttonsAreVisible)
  44763. : minimum (0.0),
  44764. maximum (1.0),
  44765. rangeStart (0.0),
  44766. rangeSize (0.1),
  44767. singleStepSize (0.1),
  44768. thumbAreaStart (0),
  44769. thumbAreaSize (0),
  44770. thumbStart (0),
  44771. thumbSize (0),
  44772. initialDelayInMillisecs (100),
  44773. repeatDelayInMillisecs (50),
  44774. minimumDelayInMillisecs (10),
  44775. vertical (vertical_),
  44776. isDraggingThumb (false),
  44777. alwaysVisible (false),
  44778. upButton (0),
  44779. downButton (0),
  44780. listeners (2)
  44781. {
  44782. setButtonVisibility (buttonsAreVisible);
  44783. setRepaintsOnMouseActivity (true);
  44784. setFocusContainer (true);
  44785. }
  44786. ScrollBar::~ScrollBar()
  44787. {
  44788. deleteAllChildren();
  44789. }
  44790. void ScrollBar::setRangeLimits (const double newMinimum,
  44791. const double newMaximum) throw()
  44792. {
  44793. minimum = newMinimum;
  44794. maximum = newMaximum;
  44795. jassert (maximum >= minimum); // these can't be the wrong way round!
  44796. setCurrentRangeStart (rangeStart);
  44797. updateThumbPosition();
  44798. }
  44799. void ScrollBar::setCurrentRange (double newStart,
  44800. double newSize) throw()
  44801. {
  44802. newSize = jlimit (0.0, maximum - minimum, newSize);
  44803. newStart = jlimit (minimum, maximum - newSize, newStart);
  44804. if (rangeStart != newStart
  44805. || rangeSize != newSize)
  44806. {
  44807. rangeStart = newStart;
  44808. rangeSize = newSize;
  44809. updateThumbPosition();
  44810. triggerAsyncUpdate();
  44811. }
  44812. }
  44813. void ScrollBar::setCurrentRangeStart (double newStart) throw()
  44814. {
  44815. setCurrentRange (newStart, rangeSize);
  44816. }
  44817. void ScrollBar::setSingleStepSize (const double newSingleStepSize) throw()
  44818. {
  44819. singleStepSize = newSingleStepSize;
  44820. }
  44821. void ScrollBar::moveScrollbarInSteps (const int howManySteps) throw()
  44822. {
  44823. setCurrentRangeStart (rangeStart + howManySteps * singleStepSize);
  44824. }
  44825. void ScrollBar::moveScrollbarInPages (const int howManyPages) throw()
  44826. {
  44827. setCurrentRangeStart (rangeStart + howManyPages * rangeSize);
  44828. }
  44829. void ScrollBar::scrollToTop() throw()
  44830. {
  44831. setCurrentRangeStart (minimum);
  44832. }
  44833. void ScrollBar::scrollToBottom() throw()
  44834. {
  44835. setCurrentRangeStart (maximum - rangeSize);
  44836. }
  44837. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  44838. const int repeatDelayInMillisecs_,
  44839. const int minimumDelayInMillisecs_) throw()
  44840. {
  44841. initialDelayInMillisecs = initialDelayInMillisecs_;
  44842. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  44843. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  44844. if (upButton != 0)
  44845. {
  44846. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  44847. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  44848. }
  44849. }
  44850. void ScrollBar::addListener (ScrollBarListener* const listener) throw()
  44851. {
  44852. jassert (listener != 0);
  44853. if (listener != 0)
  44854. listeners.add (listener);
  44855. }
  44856. void ScrollBar::removeListener (ScrollBarListener* const listener) throw()
  44857. {
  44858. listeners.removeValue (listener);
  44859. }
  44860. void ScrollBar::handleAsyncUpdate()
  44861. {
  44862. const double value = getCurrentRangeStart();
  44863. for (int i = listeners.size(); --i >= 0;)
  44864. {
  44865. ((ScrollBarListener*) listeners.getUnchecked (i))->scrollBarMoved (this, value);
  44866. i = jmin (i, listeners.size());
  44867. }
  44868. }
  44869. void ScrollBar::updateThumbPosition() throw()
  44870. {
  44871. int newThumbSize = roundDoubleToInt ((maximum > minimum) ? (rangeSize * thumbAreaSize) / (maximum - minimum)
  44872. : thumbAreaSize);
  44873. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  44874. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  44875. if (newThumbSize > thumbAreaSize)
  44876. newThumbSize = thumbAreaSize;
  44877. int newThumbStart = thumbAreaStart;
  44878. if (maximum - minimum > rangeSize)
  44879. newThumbStart += roundDoubleToInt (((rangeStart - minimum) * (thumbAreaSize - newThumbSize))
  44880. / ((maximum - minimum) - rangeSize));
  44881. setVisible (alwaysVisible || (maximum - minimum > rangeSize && rangeSize > 0.0));
  44882. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  44883. {
  44884. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  44885. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  44886. if (vertical)
  44887. repaint (0, repaintStart, getWidth(), repaintSize);
  44888. else
  44889. repaint (repaintStart, 0, repaintSize, getHeight());
  44890. thumbStart = newThumbStart;
  44891. thumbSize = newThumbSize;
  44892. }
  44893. }
  44894. void ScrollBar::setOrientation (const bool shouldBeVertical) throw()
  44895. {
  44896. if (vertical != shouldBeVertical)
  44897. {
  44898. vertical = shouldBeVertical;
  44899. if (upButton != 0)
  44900. {
  44901. ((ScrollbarButton*) upButton)->direction = (vertical) ? 0 : 3;
  44902. ((ScrollbarButton*) downButton)->direction = (vertical) ? 2 : 1;
  44903. }
  44904. updateThumbPosition();
  44905. }
  44906. }
  44907. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  44908. {
  44909. deleteAndZero (upButton);
  44910. deleteAndZero (downButton);
  44911. if (buttonsAreVisible)
  44912. {
  44913. addAndMakeVisible (upButton = new ScrollbarButton ((vertical) ? 0 : 3, *this));
  44914. addAndMakeVisible (downButton = new ScrollbarButton ((vertical) ? 2 : 1, *this));
  44915. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  44916. }
  44917. updateThumbPosition();
  44918. }
  44919. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  44920. {
  44921. alwaysVisible = ! shouldHideWhenFullRange;
  44922. updateThumbPosition();
  44923. }
  44924. void ScrollBar::paint (Graphics& g)
  44925. {
  44926. if (thumbAreaSize > 0)
  44927. {
  44928. LookAndFeel& lf = getLookAndFeel();
  44929. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  44930. ? thumbSize : 0;
  44931. if (vertical)
  44932. {
  44933. lf.drawScrollbar (g, *this,
  44934. 0, thumbAreaStart,
  44935. getWidth(), thumbAreaSize,
  44936. vertical,
  44937. thumbStart, thumb,
  44938. isMouseOver(), isMouseButtonDown());
  44939. }
  44940. else
  44941. {
  44942. lf.drawScrollbar (g, *this,
  44943. thumbAreaStart, 0,
  44944. thumbAreaSize, getHeight(),
  44945. vertical,
  44946. thumbStart, thumb,
  44947. isMouseOver(), isMouseButtonDown());
  44948. }
  44949. }
  44950. }
  44951. void ScrollBar::lookAndFeelChanged()
  44952. {
  44953. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  44954. }
  44955. void ScrollBar::resized()
  44956. {
  44957. const int length = ((vertical) ? getHeight() : getWidth());
  44958. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  44959. : 0;
  44960. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  44961. {
  44962. thumbAreaStart = length >> 1;
  44963. thumbAreaSize = 0;
  44964. }
  44965. else
  44966. {
  44967. thumbAreaStart = buttonSize;
  44968. thumbAreaSize = length - (buttonSize << 1);
  44969. }
  44970. if (upButton != 0)
  44971. {
  44972. if (vertical)
  44973. {
  44974. upButton->setBounds (0, 0, getWidth(), buttonSize);
  44975. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  44976. }
  44977. else
  44978. {
  44979. upButton->setBounds (0, 0, buttonSize, getHeight());
  44980. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  44981. }
  44982. }
  44983. updateThumbPosition();
  44984. }
  44985. void ScrollBar::mouseDown (const MouseEvent& e)
  44986. {
  44987. isDraggingThumb = false;
  44988. lastMousePos = vertical ? e.y : e.x;
  44989. dragStartMousePos = lastMousePos;
  44990. dragStartRange = rangeStart;
  44991. if (dragStartMousePos < thumbStart)
  44992. {
  44993. moveScrollbarInPages (-1);
  44994. startTimer (400);
  44995. }
  44996. else if (dragStartMousePos >= thumbStart + thumbSize)
  44997. {
  44998. moveScrollbarInPages (1);
  44999. startTimer (400);
  45000. }
  45001. else
  45002. {
  45003. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  45004. && (thumbAreaSize > thumbSize);
  45005. }
  45006. }
  45007. void ScrollBar::mouseDrag (const MouseEvent& e)
  45008. {
  45009. if (isDraggingThumb)
  45010. {
  45011. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  45012. setCurrentRangeStart (dragStartRange
  45013. + deltaPixels * ((maximum - minimum) - rangeSize)
  45014. / (thumbAreaSize - thumbSize));
  45015. }
  45016. else
  45017. {
  45018. lastMousePos = (vertical) ? e.y : e.x;
  45019. }
  45020. }
  45021. void ScrollBar::mouseUp (const MouseEvent&)
  45022. {
  45023. isDraggingThumb = false;
  45024. stopTimer();
  45025. repaint();
  45026. }
  45027. void ScrollBar::mouseWheelMove (const MouseEvent&,
  45028. float wheelIncrementX,
  45029. float wheelIncrementY)
  45030. {
  45031. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  45032. if (increment < 0)
  45033. increment = jmin (increment * 10.0f, -1.0f);
  45034. else if (increment > 0)
  45035. increment = jmax (increment * 10.0f, 1.0f);
  45036. setCurrentRangeStart (rangeStart - singleStepSize * increment);
  45037. }
  45038. void ScrollBar::timerCallback()
  45039. {
  45040. if (isMouseButtonDown())
  45041. {
  45042. startTimer (40);
  45043. if (lastMousePos < thumbStart)
  45044. setCurrentRangeStart (rangeStart - rangeSize);
  45045. else if (lastMousePos > thumbStart + thumbSize)
  45046. setCurrentRangeStart (rangeStart + rangeSize);
  45047. }
  45048. else
  45049. {
  45050. stopTimer();
  45051. }
  45052. }
  45053. bool ScrollBar::keyPressed (const KeyPress& key)
  45054. {
  45055. if (! isVisible())
  45056. return false;
  45057. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  45058. moveScrollbarInSteps (-1);
  45059. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  45060. moveScrollbarInSteps (1);
  45061. else if (key.isKeyCode (KeyPress::pageUpKey))
  45062. moveScrollbarInPages (-1);
  45063. else if (key.isKeyCode (KeyPress::pageDownKey))
  45064. moveScrollbarInPages (1);
  45065. else if (key.isKeyCode (KeyPress::homeKey))
  45066. scrollToTop();
  45067. else if (key.isKeyCode (KeyPress::endKey))
  45068. scrollToBottom();
  45069. else
  45070. return false;
  45071. return true;
  45072. }
  45073. END_JUCE_NAMESPACE
  45074. /********* End of inlined file: juce_ScrollBar.cpp *********/
  45075. /********* Start of inlined file: juce_StretchableLayoutManager.cpp *********/
  45076. BEGIN_JUCE_NAMESPACE
  45077. StretchableLayoutManager::StretchableLayoutManager()
  45078. : totalSize (0)
  45079. {
  45080. }
  45081. StretchableLayoutManager::~StretchableLayoutManager()
  45082. {
  45083. }
  45084. void StretchableLayoutManager::clearAllItems()
  45085. {
  45086. items.clear();
  45087. totalSize = 0;
  45088. }
  45089. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  45090. const double minimumSize,
  45091. const double maximumSize,
  45092. const double preferredSize)
  45093. {
  45094. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  45095. if (layout == 0)
  45096. {
  45097. layout = new ItemLayoutProperties();
  45098. layout->itemIndex = itemIndex;
  45099. int i;
  45100. for (i = 0; i < items.size(); ++i)
  45101. if (items.getUnchecked (i)->itemIndex > itemIndex)
  45102. break;
  45103. items.insert (i, layout);
  45104. }
  45105. layout->minSize = minimumSize;
  45106. layout->maxSize = maximumSize;
  45107. layout->preferredSize = preferredSize;
  45108. layout->currentSize = 0;
  45109. }
  45110. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  45111. double& minimumSize,
  45112. double& maximumSize,
  45113. double& preferredSize) const
  45114. {
  45115. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  45116. if (layout != 0)
  45117. {
  45118. minimumSize = layout->minSize;
  45119. maximumSize = layout->maxSize;
  45120. preferredSize = layout->preferredSize;
  45121. return true;
  45122. }
  45123. return false;
  45124. }
  45125. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  45126. {
  45127. totalSize = newTotalSize;
  45128. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  45129. }
  45130. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  45131. {
  45132. int pos = 0;
  45133. for (int i = 0; i < itemIndex; ++i)
  45134. {
  45135. const ItemLayoutProperties* const layout = getInfoFor (i);
  45136. if (layout != 0)
  45137. pos += layout->currentSize;
  45138. }
  45139. return pos;
  45140. }
  45141. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  45142. {
  45143. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  45144. if (layout != 0)
  45145. return layout->currentSize;
  45146. return 0;
  45147. }
  45148. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  45149. {
  45150. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  45151. if (layout != 0)
  45152. return -layout->currentSize / (double) totalSize;
  45153. return 0;
  45154. }
  45155. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  45156. int newPosition)
  45157. {
  45158. for (int i = items.size(); --i >= 0;)
  45159. {
  45160. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  45161. if (layout->itemIndex == itemIndex)
  45162. {
  45163. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  45164. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  45165. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  45166. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  45167. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  45168. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  45169. endPos += layout->currentSize;
  45170. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  45171. updatePrefSizesToMatchCurrentPositions();
  45172. break;
  45173. }
  45174. }
  45175. }
  45176. void StretchableLayoutManager::layOutComponents (Component** const components,
  45177. int numComponents,
  45178. int x, int y, int w, int h,
  45179. const bool vertically,
  45180. const bool resizeOtherDimension)
  45181. {
  45182. setTotalSize (vertically ? h : w);
  45183. int pos = vertically ? y : x;
  45184. for (int i = 0; i < numComponents; ++i)
  45185. {
  45186. const ItemLayoutProperties* const layout = getInfoFor (i);
  45187. if (layout != 0)
  45188. {
  45189. Component* const c = components[i];
  45190. if (c != 0)
  45191. {
  45192. if (i == numComponents - 1)
  45193. {
  45194. // if it's the last item, crop it to exactly fit the available space..
  45195. if (resizeOtherDimension)
  45196. {
  45197. if (vertically)
  45198. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  45199. else
  45200. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  45201. }
  45202. else
  45203. {
  45204. if (vertically)
  45205. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  45206. else
  45207. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  45208. }
  45209. }
  45210. else
  45211. {
  45212. if (resizeOtherDimension)
  45213. {
  45214. if (vertically)
  45215. c->setBounds (x, pos, w, layout->currentSize);
  45216. else
  45217. c->setBounds (pos, y, layout->currentSize, h);
  45218. }
  45219. else
  45220. {
  45221. if (vertically)
  45222. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  45223. else
  45224. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  45225. }
  45226. }
  45227. }
  45228. pos += layout->currentSize;
  45229. }
  45230. }
  45231. }
  45232. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  45233. {
  45234. for (int i = items.size(); --i >= 0;)
  45235. if (items.getUnchecked(i)->itemIndex == itemIndex)
  45236. return items.getUnchecked(i);
  45237. return 0;
  45238. }
  45239. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  45240. const int endIndex,
  45241. const int availableSpace,
  45242. int startPos)
  45243. {
  45244. // calculate the total sizes
  45245. int i;
  45246. double totalIdealSize = 0.0;
  45247. int totalMinimums = 0;
  45248. for (i = startIndex; i < endIndex; ++i)
  45249. {
  45250. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45251. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  45252. totalMinimums += layout->currentSize;
  45253. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  45254. }
  45255. if (totalIdealSize <= 0)
  45256. totalIdealSize = 1.0;
  45257. // now calc the best sizes..
  45258. int extraSpace = availableSpace - totalMinimums;
  45259. while (extraSpace > 0)
  45260. {
  45261. int numWantingMoreSpace = 0;
  45262. int numHavingTakenExtraSpace = 0;
  45263. // first figure out how many comps want a slice of the extra space..
  45264. for (i = startIndex; i < endIndex; ++i)
  45265. {
  45266. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45267. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  45268. const int bestSize = jlimit (layout->currentSize,
  45269. jmax (layout->currentSize,
  45270. sizeToRealSize (layout->maxSize, totalSize)),
  45271. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  45272. if (bestSize > layout->currentSize)
  45273. ++numWantingMoreSpace;
  45274. }
  45275. // ..share out the extra space..
  45276. for (i = startIndex; i < endIndex; ++i)
  45277. {
  45278. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45279. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  45280. int bestSize = jlimit (layout->currentSize,
  45281. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  45282. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  45283. const int extraWanted = bestSize - layout->currentSize;
  45284. if (extraWanted > 0)
  45285. {
  45286. const int extraAllowed = jmin (extraWanted,
  45287. extraSpace / jmax (1, numWantingMoreSpace));
  45288. if (extraAllowed > 0)
  45289. {
  45290. ++numHavingTakenExtraSpace;
  45291. --numWantingMoreSpace;
  45292. layout->currentSize += extraAllowed;
  45293. extraSpace -= extraAllowed;
  45294. }
  45295. }
  45296. }
  45297. if (numHavingTakenExtraSpace <= 0)
  45298. break;
  45299. }
  45300. // ..and calculate the end position
  45301. for (i = startIndex; i < endIndex; ++i)
  45302. {
  45303. ItemLayoutProperties* const layout = items.getUnchecked(i);
  45304. startPos += layout->currentSize;
  45305. }
  45306. return startPos;
  45307. }
  45308. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  45309. const int endIndex) const
  45310. {
  45311. int totalMinimums = 0;
  45312. for (int i = startIndex; i < endIndex; ++i)
  45313. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  45314. return totalMinimums;
  45315. }
  45316. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  45317. {
  45318. int totalMaximums = 0;
  45319. for (int i = startIndex; i < endIndex; ++i)
  45320. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  45321. return totalMaximums;
  45322. }
  45323. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  45324. {
  45325. for (int i = 0; i < items.size(); ++i)
  45326. {
  45327. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45328. layout->preferredSize
  45329. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  45330. : getItemCurrentAbsoluteSize (i);
  45331. }
  45332. }
  45333. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  45334. {
  45335. if (size < 0)
  45336. size *= -totalSpace;
  45337. return roundDoubleToInt (size);
  45338. }
  45339. END_JUCE_NAMESPACE
  45340. /********* End of inlined file: juce_StretchableLayoutManager.cpp *********/
  45341. /********* Start of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  45342. BEGIN_JUCE_NAMESPACE
  45343. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  45344. const int itemIndex_,
  45345. const bool isVertical_)
  45346. : layout (layout_),
  45347. itemIndex (itemIndex_),
  45348. isVertical (isVertical_)
  45349. {
  45350. setRepaintsOnMouseActivity (true);
  45351. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  45352. : MouseCursor::UpDownResizeCursor));
  45353. }
  45354. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  45355. {
  45356. }
  45357. void StretchableLayoutResizerBar::paint (Graphics& g)
  45358. {
  45359. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  45360. getWidth(), getHeight(),
  45361. isVertical,
  45362. isMouseOver(),
  45363. isMouseButtonDown());
  45364. }
  45365. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  45366. {
  45367. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  45368. }
  45369. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  45370. {
  45371. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  45372. : e.getDistanceFromDragStartY());
  45373. layout->setItemPosition (itemIndex, desiredPos);
  45374. hasBeenMoved();
  45375. }
  45376. void StretchableLayoutResizerBar::hasBeenMoved()
  45377. {
  45378. if (getParentComponent() != 0)
  45379. getParentComponent()->resized();
  45380. }
  45381. END_JUCE_NAMESPACE
  45382. /********* End of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  45383. /********* Start of inlined file: juce_StretchableObjectResizer.cpp *********/
  45384. BEGIN_JUCE_NAMESPACE
  45385. StretchableObjectResizer::StretchableObjectResizer()
  45386. {
  45387. }
  45388. StretchableObjectResizer::~StretchableObjectResizer()
  45389. {
  45390. }
  45391. void StretchableObjectResizer::addItem (const double size,
  45392. const double minSize, const double maxSize,
  45393. const int order)
  45394. {
  45395. jassert (order >= 0 && order < INT_MAX); // the order must be >= 0 and less than INT_MAX
  45396. Item* const item = new Item();
  45397. item->size = size;
  45398. item->minSize = minSize;
  45399. item->maxSize = maxSize;
  45400. item->order = order;
  45401. items.add (item);
  45402. }
  45403. double StretchableObjectResizer::getItemSize (const int index) const throw()
  45404. {
  45405. const Item* const it = items [index];
  45406. return it != 0 ? it->size : 0;
  45407. }
  45408. void StretchableObjectResizer::resizeToFit (const double targetSize)
  45409. {
  45410. int order = 0;
  45411. for (;;)
  45412. {
  45413. double currentSize = 0;
  45414. double minSize = 0;
  45415. double maxSize = 0;
  45416. int nextHighestOrder = INT_MAX;
  45417. for (int i = 0; i < items.size(); ++i)
  45418. {
  45419. const Item* const it = items.getUnchecked(i);
  45420. currentSize += it->size;
  45421. if (it->order <= order)
  45422. {
  45423. minSize += it->minSize;
  45424. maxSize += it->maxSize;
  45425. }
  45426. else
  45427. {
  45428. minSize += it->size;
  45429. maxSize += it->size;
  45430. nextHighestOrder = jmin (nextHighestOrder, it->order);
  45431. }
  45432. }
  45433. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  45434. if (thisIterationTarget >= currentSize)
  45435. {
  45436. const double availableExtraSpace = maxSize - currentSize;
  45437. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  45438. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  45439. for (int i = 0; i < items.size(); ++i)
  45440. {
  45441. Item* const it = items.getUnchecked(i);
  45442. if (it->order <= order)
  45443. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  45444. }
  45445. }
  45446. else
  45447. {
  45448. const double amountOfSlack = currentSize - minSize;
  45449. const double targetAmountOfSlack = thisIterationTarget - minSize;
  45450. const double scale = targetAmountOfSlack / amountOfSlack;
  45451. for (int i = 0; i < items.size(); ++i)
  45452. {
  45453. Item* const it = items.getUnchecked(i);
  45454. if (it->order <= order)
  45455. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  45456. }
  45457. }
  45458. if (nextHighestOrder < INT_MAX)
  45459. order = nextHighestOrder;
  45460. else
  45461. break;
  45462. }
  45463. }
  45464. END_JUCE_NAMESPACE
  45465. /********* End of inlined file: juce_StretchableObjectResizer.cpp *********/
  45466. /********* Start of inlined file: juce_TabbedButtonBar.cpp *********/
  45467. BEGIN_JUCE_NAMESPACE
  45468. TabBarButton::TabBarButton (const String& name,
  45469. TabbedButtonBar* const owner_,
  45470. const int index)
  45471. : Button (name),
  45472. owner (owner_),
  45473. tabIndex (index),
  45474. overlapPixels (0)
  45475. {
  45476. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  45477. setComponentEffect (&shadow);
  45478. setWantsKeyboardFocus (false);
  45479. }
  45480. TabBarButton::~TabBarButton()
  45481. {
  45482. }
  45483. void TabBarButton::paintButton (Graphics& g,
  45484. bool isMouseOverButton,
  45485. bool isButtonDown)
  45486. {
  45487. int x, y, w, h;
  45488. getActiveArea (x, y, w, h);
  45489. g.setOrigin (x, y);
  45490. getLookAndFeel()
  45491. .drawTabButton (g, w, h,
  45492. owner->getTabBackgroundColour (tabIndex),
  45493. tabIndex, getButtonText(), *this,
  45494. owner->getOrientation(),
  45495. isMouseOverButton, isButtonDown,
  45496. getToggleState());
  45497. }
  45498. void TabBarButton::clicked (const ModifierKeys& mods)
  45499. {
  45500. if (mods.isPopupMenu())
  45501. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  45502. else
  45503. owner->setCurrentTabIndex (tabIndex);
  45504. }
  45505. bool TabBarButton::hitTest (int mx, int my)
  45506. {
  45507. int x, y, w, h;
  45508. getActiveArea (x, y, w, h);
  45509. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  45510. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  45511. {
  45512. if (((unsigned int) mx) < (unsigned int) getWidth()
  45513. && my >= y + overlapPixels
  45514. && my < y + h - overlapPixels)
  45515. return true;
  45516. }
  45517. else
  45518. {
  45519. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  45520. && ((unsigned int) my) < (unsigned int) getHeight())
  45521. return true;
  45522. }
  45523. Path p;
  45524. getLookAndFeel()
  45525. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  45526. owner->getOrientation(),
  45527. false, false, getToggleState());
  45528. return p.contains ((float) (mx - x),
  45529. (float) (my - y));
  45530. }
  45531. int TabBarButton::getBestTabLength (const int depth)
  45532. {
  45533. return jlimit (depth * 2,
  45534. depth * 7,
  45535. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  45536. }
  45537. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  45538. {
  45539. x = 0;
  45540. y = 0;
  45541. int r = getWidth();
  45542. int b = getHeight();
  45543. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  45544. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  45545. r -= spaceAroundImage;
  45546. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  45547. x += spaceAroundImage;
  45548. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  45549. y += spaceAroundImage;
  45550. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  45551. b -= spaceAroundImage;
  45552. w = r - x;
  45553. h = b - y;
  45554. }
  45555. class TabAreaBehindFrontButtonComponent : public Component
  45556. {
  45557. public:
  45558. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  45559. : owner (owner_)
  45560. {
  45561. setInterceptsMouseClicks (false, false);
  45562. }
  45563. ~TabAreaBehindFrontButtonComponent()
  45564. {
  45565. }
  45566. void paint (Graphics& g)
  45567. {
  45568. getLookAndFeel()
  45569. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  45570. *owner, owner->getOrientation());
  45571. }
  45572. void enablementChanged()
  45573. {
  45574. repaint();
  45575. }
  45576. private:
  45577. TabbedButtonBar* const owner;
  45578. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  45579. const TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  45580. };
  45581. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  45582. : orientation (orientation_),
  45583. currentTabIndex (-1),
  45584. extraTabsButton (0)
  45585. {
  45586. setInterceptsMouseClicks (false, true);
  45587. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  45588. setFocusContainer (true);
  45589. }
  45590. TabbedButtonBar::~TabbedButtonBar()
  45591. {
  45592. deleteAllChildren();
  45593. }
  45594. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  45595. {
  45596. orientation = newOrientation;
  45597. for (int i = getNumChildComponents(); --i >= 0;)
  45598. getChildComponent (i)->resized();
  45599. resized();
  45600. }
  45601. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  45602. {
  45603. return new TabBarButton (name, this, index);
  45604. }
  45605. void TabbedButtonBar::clearTabs()
  45606. {
  45607. tabs.clear();
  45608. tabColours.clear();
  45609. currentTabIndex = -1;
  45610. deleteAndZero (extraTabsButton);
  45611. removeChildComponent (behindFrontTab);
  45612. deleteAllChildren();
  45613. addChildComponent (behindFrontTab);
  45614. setCurrentTabIndex (-1);
  45615. }
  45616. void TabbedButtonBar::addTab (const String& tabName,
  45617. const Colour& tabBackgroundColour,
  45618. int insertIndex)
  45619. {
  45620. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  45621. if (tabName.isNotEmpty())
  45622. {
  45623. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  45624. insertIndex = tabs.size();
  45625. for (int i = tabs.size(); --i >= insertIndex;)
  45626. {
  45627. TabBarButton* const tb = getTabButton (i);
  45628. if (tb != 0)
  45629. tb->tabIndex++;
  45630. }
  45631. tabs.insert (insertIndex, tabName);
  45632. tabColours.insert (insertIndex, tabBackgroundColour);
  45633. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  45634. jassert (tb != 0); // your createTabButton() mustn't return zero!
  45635. addAndMakeVisible (tb, insertIndex);
  45636. resized();
  45637. if (currentTabIndex < 0)
  45638. setCurrentTabIndex (0);
  45639. }
  45640. }
  45641. void TabbedButtonBar::setTabName (const int tabIndex,
  45642. const String& newName)
  45643. {
  45644. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  45645. && tabs[tabIndex] != newName)
  45646. {
  45647. tabs.set (tabIndex, newName);
  45648. TabBarButton* const tb = getTabButton (tabIndex);
  45649. if (tb != 0)
  45650. tb->setButtonText (newName);
  45651. resized();
  45652. }
  45653. }
  45654. void TabbedButtonBar::removeTab (const int tabIndex)
  45655. {
  45656. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  45657. {
  45658. const int oldTabIndex = currentTabIndex;
  45659. if (currentTabIndex == tabIndex)
  45660. currentTabIndex = -1;
  45661. tabs.remove (tabIndex);
  45662. tabColours.remove (tabIndex);
  45663. TabBarButton* const tb = getTabButton (tabIndex);
  45664. if (tb != 0)
  45665. delete tb;
  45666. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  45667. {
  45668. TabBarButton* const tb = getTabButton (i);
  45669. if (tb != 0)
  45670. tb->tabIndex--;
  45671. }
  45672. resized();
  45673. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  45674. }
  45675. }
  45676. void TabbedButtonBar::moveTab (const int currentIndex,
  45677. const int newIndex)
  45678. {
  45679. tabs.move (currentIndex, newIndex);
  45680. tabColours.move (currentIndex, newIndex);
  45681. resized();
  45682. }
  45683. int TabbedButtonBar::getNumTabs() const
  45684. {
  45685. return tabs.size();
  45686. }
  45687. const StringArray TabbedButtonBar::getTabNames() const
  45688. {
  45689. return tabs;
  45690. }
  45691. void TabbedButtonBar::setCurrentTabIndex (int newIndex)
  45692. {
  45693. if (currentTabIndex != newIndex)
  45694. {
  45695. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  45696. newIndex = -1;
  45697. currentTabIndex = newIndex;
  45698. for (int i = 0; i < getNumChildComponents(); ++i)
  45699. {
  45700. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  45701. if (tb != 0)
  45702. tb->setToggleState (tb->tabIndex == newIndex, false);
  45703. }
  45704. resized();
  45705. sendChangeMessage (this);
  45706. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  45707. }
  45708. }
  45709. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  45710. {
  45711. for (int i = getNumChildComponents(); --i >= 0;)
  45712. {
  45713. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  45714. if (tb != 0 && tb->tabIndex == index)
  45715. return tb;
  45716. }
  45717. return 0;
  45718. }
  45719. void TabbedButtonBar::lookAndFeelChanged()
  45720. {
  45721. deleteAndZero (extraTabsButton);
  45722. resized();
  45723. }
  45724. void TabbedButtonBar::resized()
  45725. {
  45726. const double minimumScale = 0.7;
  45727. int depth = getWidth();
  45728. int length = getHeight();
  45729. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  45730. swapVariables (depth, length);
  45731. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  45732. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  45733. int i, totalLength = overlap;
  45734. int numVisibleButtons = tabs.size();
  45735. for (i = 0; i < getNumChildComponents(); ++i)
  45736. {
  45737. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  45738. if (tb != 0)
  45739. {
  45740. totalLength += tb->getBestTabLength (depth) - overlap;
  45741. tb->overlapPixels = overlap / 2;
  45742. }
  45743. }
  45744. double scale = 1.0;
  45745. if (totalLength > length)
  45746. scale = jmax (minimumScale, length / (double) totalLength);
  45747. const bool isTooBig = totalLength * scale > length;
  45748. int tabsButtonPos = 0;
  45749. if (isTooBig)
  45750. {
  45751. if (extraTabsButton == 0)
  45752. {
  45753. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  45754. extraTabsButton->addButtonListener (this);
  45755. extraTabsButton->setAlwaysOnTop (true);
  45756. extraTabsButton->setTriggeredOnMouseDown (true);
  45757. }
  45758. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  45759. extraTabsButton->setSize (buttonSize, buttonSize);
  45760. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  45761. {
  45762. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  45763. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  45764. }
  45765. else
  45766. {
  45767. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  45768. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  45769. }
  45770. totalLength = 0;
  45771. for (i = 0; i < tabs.size(); ++i)
  45772. {
  45773. TabBarButton* const tb = getTabButton (i);
  45774. if (tb != 0)
  45775. {
  45776. const int newLength = totalLength + tb->getBestTabLength (depth);
  45777. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  45778. {
  45779. totalLength += overlap;
  45780. break;
  45781. }
  45782. numVisibleButtons = i + 1;
  45783. totalLength = newLength - overlap;
  45784. }
  45785. }
  45786. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  45787. }
  45788. else
  45789. {
  45790. deleteAndZero (extraTabsButton);
  45791. }
  45792. int pos = 0;
  45793. TabBarButton* frontTab = 0;
  45794. for (i = 0; i < tabs.size(); ++i)
  45795. {
  45796. TabBarButton* const tb = getTabButton (i);
  45797. if (tb != 0)
  45798. {
  45799. const int bestLength = roundDoubleToInt (scale * tb->getBestTabLength (depth));
  45800. if (i < numVisibleButtons)
  45801. {
  45802. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  45803. tb->setBounds (pos, 0, bestLength, getHeight());
  45804. else
  45805. tb->setBounds (0, pos, getWidth(), bestLength);
  45806. tb->toBack();
  45807. if (tb->tabIndex == currentTabIndex)
  45808. frontTab = tb;
  45809. tb->setVisible (true);
  45810. }
  45811. else
  45812. {
  45813. tb->setVisible (false);
  45814. }
  45815. pos += bestLength - overlap;
  45816. }
  45817. }
  45818. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  45819. if (frontTab != 0)
  45820. {
  45821. frontTab->toFront (false);
  45822. behindFrontTab->toBehind (frontTab);
  45823. }
  45824. }
  45825. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  45826. {
  45827. return tabColours [tabIndex];
  45828. }
  45829. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  45830. {
  45831. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  45832. && tabColours [tabIndex] != newColour)
  45833. {
  45834. tabColours.set (tabIndex, newColour);
  45835. repaint();
  45836. }
  45837. }
  45838. void TabbedButtonBar::buttonClicked (Button* button)
  45839. {
  45840. if (extraTabsButton == button)
  45841. {
  45842. PopupMenu m;
  45843. for (int i = 0; i < tabs.size(); ++i)
  45844. {
  45845. TabBarButton* const tb = getTabButton (i);
  45846. if (tb != 0 && ! tb->isVisible())
  45847. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  45848. }
  45849. const int res = m.showAt (extraTabsButton);
  45850. if (res != 0)
  45851. setCurrentTabIndex (res - 1);
  45852. }
  45853. }
  45854. void TabbedButtonBar::currentTabChanged (const int, const String&)
  45855. {
  45856. }
  45857. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  45858. {
  45859. }
  45860. END_JUCE_NAMESPACE
  45861. /********* End of inlined file: juce_TabbedButtonBar.cpp *********/
  45862. /********* Start of inlined file: juce_TabbedComponent.cpp *********/
  45863. BEGIN_JUCE_NAMESPACE
  45864. class TabCompButtonBar : public TabbedButtonBar
  45865. {
  45866. public:
  45867. TabCompButtonBar (TabbedComponent* const owner_,
  45868. const TabbedButtonBar::Orientation orientation)
  45869. : TabbedButtonBar (orientation),
  45870. owner (owner_)
  45871. {
  45872. }
  45873. ~TabCompButtonBar()
  45874. {
  45875. }
  45876. void currentTabChanged (const int newCurrentTabIndex,
  45877. const String& newTabName)
  45878. {
  45879. owner->changeCallback (newCurrentTabIndex, newTabName);
  45880. }
  45881. void popupMenuClickOnTab (const int tabIndex,
  45882. const String& tabName)
  45883. {
  45884. owner->popupMenuClickOnTab (tabIndex, tabName);
  45885. }
  45886. const Colour getTabBackgroundColour (const int tabIndex)
  45887. {
  45888. return owner->tabs->getTabBackgroundColour (tabIndex);
  45889. }
  45890. TabBarButton* createTabButton (const String& tabName, const int tabIndex)
  45891. {
  45892. return owner->createTabButton (tabName, tabIndex);
  45893. }
  45894. juce_UseDebuggingNewOperator
  45895. private:
  45896. TabbedComponent* const owner;
  45897. TabCompButtonBar (const TabCompButtonBar&);
  45898. const TabCompButtonBar& operator= (const TabCompButtonBar&);
  45899. };
  45900. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  45901. : panelComponent (0),
  45902. tabDepth (30),
  45903. outlineColour (Colours::grey),
  45904. outlineThickness (1),
  45905. edgeIndent (0)
  45906. {
  45907. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  45908. }
  45909. TabbedComponent::~TabbedComponent()
  45910. {
  45911. clearTabs();
  45912. delete tabs;
  45913. }
  45914. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  45915. {
  45916. tabs->setOrientation (orientation);
  45917. resized();
  45918. }
  45919. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  45920. {
  45921. return tabs->getOrientation();
  45922. }
  45923. void TabbedComponent::setTabBarDepth (const int newDepth)
  45924. {
  45925. if (tabDepth != newDepth)
  45926. {
  45927. tabDepth = newDepth;
  45928. resized();
  45929. }
  45930. }
  45931. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  45932. {
  45933. return new TabBarButton (tabName, tabs, tabIndex);
  45934. }
  45935. void TabbedComponent::clearTabs()
  45936. {
  45937. if (panelComponent != 0)
  45938. {
  45939. panelComponent->setVisible (false);
  45940. removeChildComponent (panelComponent);
  45941. panelComponent = 0;
  45942. }
  45943. tabs->clearTabs();
  45944. for (int i = contentComponents.size(); --i >= 0;)
  45945. {
  45946. Component* const c = contentComponents.getUnchecked(i);
  45947. // be careful not to delete these components until they've been removed from the tab component
  45948. jassert (c == 0 || c->isValidComponent());
  45949. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  45950. delete c;
  45951. }
  45952. contentComponents.clear();
  45953. }
  45954. void TabbedComponent::addTab (const String& tabName,
  45955. const Colour& tabBackgroundColour,
  45956. Component* const contentComponent,
  45957. const bool deleteComponentWhenNotNeeded,
  45958. const int insertIndex)
  45959. {
  45960. contentComponents.insert (insertIndex, contentComponent);
  45961. if (contentComponent != 0)
  45962. contentComponent->setComponentProperty (T("deleteByTabComp_"), deleteComponentWhenNotNeeded);
  45963. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  45964. }
  45965. void TabbedComponent::setTabName (const int tabIndex,
  45966. const String& newName)
  45967. {
  45968. tabs->setTabName (tabIndex, newName);
  45969. }
  45970. void TabbedComponent::removeTab (const int tabIndex)
  45971. {
  45972. Component* const c = contentComponents [tabIndex];
  45973. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  45974. {
  45975. if (c == panelComponent)
  45976. panelComponent = 0;
  45977. delete c;
  45978. }
  45979. contentComponents.remove (tabIndex);
  45980. tabs->removeTab (tabIndex);
  45981. }
  45982. int TabbedComponent::getNumTabs() const
  45983. {
  45984. return tabs->getNumTabs();
  45985. }
  45986. const StringArray TabbedComponent::getTabNames() const
  45987. {
  45988. return tabs->getTabNames();
  45989. }
  45990. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  45991. {
  45992. return contentComponents [tabIndex];
  45993. }
  45994. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  45995. {
  45996. return tabs->getTabBackgroundColour (tabIndex);
  45997. }
  45998. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  45999. {
  46000. tabs->setTabBackgroundColour (tabIndex, newColour);
  46001. if (getCurrentTabIndex() == tabIndex)
  46002. repaint();
  46003. }
  46004. void TabbedComponent::setCurrentTabIndex (const int newTabIndex)
  46005. {
  46006. tabs->setCurrentTabIndex (newTabIndex);
  46007. }
  46008. int TabbedComponent::getCurrentTabIndex() const
  46009. {
  46010. return tabs->getCurrentTabIndex();
  46011. }
  46012. const String& TabbedComponent::getCurrentTabName() const
  46013. {
  46014. return tabs->getCurrentTabName();
  46015. }
  46016. void TabbedComponent::setOutline (const Colour& colour, int thickness)
  46017. {
  46018. outlineColour = colour;
  46019. outlineThickness = thickness;
  46020. repaint();
  46021. }
  46022. void TabbedComponent::setIndent (const int indentThickness)
  46023. {
  46024. edgeIndent = indentThickness;
  46025. }
  46026. void TabbedComponent::paint (Graphics& g)
  46027. {
  46028. const TabbedButtonBar::Orientation o = getOrientation();
  46029. int x = 0;
  46030. int y = 0;
  46031. int r = getWidth();
  46032. int b = getHeight();
  46033. if (o == TabbedButtonBar::TabsAtTop)
  46034. y += tabDepth;
  46035. else if (o == TabbedButtonBar::TabsAtBottom)
  46036. b -= tabDepth;
  46037. else if (o == TabbedButtonBar::TabsAtLeft)
  46038. x += tabDepth;
  46039. else if (o == TabbedButtonBar::TabsAtRight)
  46040. r -= tabDepth;
  46041. g.reduceClipRegion (x, y, r - x, b - y);
  46042. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  46043. if (outlineThickness > 0)
  46044. {
  46045. if (o == TabbedButtonBar::TabsAtTop)
  46046. --y;
  46047. else if (o == TabbedButtonBar::TabsAtBottom)
  46048. ++b;
  46049. else if (o == TabbedButtonBar::TabsAtLeft)
  46050. --x;
  46051. else if (o == TabbedButtonBar::TabsAtRight)
  46052. ++r;
  46053. g.setColour (outlineColour);
  46054. g.drawRect (x, y, r - x, b - y, outlineThickness);
  46055. }
  46056. }
  46057. void TabbedComponent::resized()
  46058. {
  46059. const TabbedButtonBar::Orientation o = getOrientation();
  46060. const int indent = edgeIndent + outlineThickness;
  46061. BorderSize indents (indent);
  46062. if (o == TabbedButtonBar::TabsAtTop)
  46063. {
  46064. tabs->setBounds (0, 0, getWidth(), tabDepth);
  46065. indents.setTop (tabDepth + edgeIndent);
  46066. }
  46067. else if (o == TabbedButtonBar::TabsAtBottom)
  46068. {
  46069. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  46070. indents.setBottom (tabDepth + edgeIndent);
  46071. }
  46072. else if (o == TabbedButtonBar::TabsAtLeft)
  46073. {
  46074. tabs->setBounds (0, 0, tabDepth, getHeight());
  46075. indents.setLeft (tabDepth + edgeIndent);
  46076. }
  46077. else if (o == TabbedButtonBar::TabsAtRight)
  46078. {
  46079. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  46080. indents.setRight (tabDepth + edgeIndent);
  46081. }
  46082. const Rectangle bounds (indents.subtractedFrom (Rectangle (0, 0, getWidth(), getHeight())));
  46083. for (int i = contentComponents.size(); --i >= 0;)
  46084. if (contentComponents.getUnchecked (i) != 0)
  46085. contentComponents.getUnchecked (i)->setBounds (bounds);
  46086. }
  46087. void TabbedComponent::lookAndFeelChanged()
  46088. {
  46089. for (int i = contentComponents.size(); --i >= 0;)
  46090. if (contentComponents.getUnchecked (i) != 0)
  46091. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  46092. }
  46093. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  46094. const String& newTabName)
  46095. {
  46096. if (panelComponent != 0)
  46097. {
  46098. panelComponent->setVisible (false);
  46099. removeChildComponent (panelComponent);
  46100. panelComponent = 0;
  46101. }
  46102. if (getCurrentTabIndex() >= 0)
  46103. {
  46104. panelComponent = contentComponents [getCurrentTabIndex()];
  46105. if (panelComponent != 0)
  46106. {
  46107. // do these ops as two stages instead of addAndMakeVisible() so that the
  46108. // component has always got a parent when it gets the visibilityChanged() callback
  46109. addChildComponent (panelComponent);
  46110. panelComponent->setVisible (true);
  46111. panelComponent->toFront (true);
  46112. }
  46113. repaint();
  46114. }
  46115. resized();
  46116. currentTabChanged (newCurrentTabIndex, newTabName);
  46117. }
  46118. void TabbedComponent::currentTabChanged (const int, const String&)
  46119. {
  46120. }
  46121. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  46122. {
  46123. }
  46124. END_JUCE_NAMESPACE
  46125. /********* End of inlined file: juce_TabbedComponent.cpp *********/
  46126. /********* Start of inlined file: juce_Viewport.cpp *********/
  46127. BEGIN_JUCE_NAMESPACE
  46128. Viewport::Viewport (const String& componentName)
  46129. : Component (componentName),
  46130. contentComp (0),
  46131. lastVX (0),
  46132. lastVY (0),
  46133. lastVW (0),
  46134. lastVH (0),
  46135. scrollBarThickness (0),
  46136. singleStepX (16),
  46137. singleStepY (16),
  46138. showHScrollbar (true),
  46139. showVScrollbar (true)
  46140. {
  46141. // content holder is used to clip the contents so they don't overlap the scrollbars
  46142. addAndMakeVisible (contentHolder = new Component());
  46143. contentHolder->setInterceptsMouseClicks (false, true);
  46144. verticalScrollBar = new ScrollBar (true);
  46145. horizontalScrollBar = new ScrollBar (false);
  46146. addChildComponent (verticalScrollBar);
  46147. addChildComponent (horizontalScrollBar);
  46148. verticalScrollBar->addListener (this);
  46149. horizontalScrollBar->addListener (this);
  46150. setInterceptsMouseClicks (false, true);
  46151. setWantsKeyboardFocus (true);
  46152. }
  46153. Viewport::~Viewport()
  46154. {
  46155. contentHolder->deleteAllChildren();
  46156. deleteAllChildren();
  46157. }
  46158. void Viewport::visibleAreaChanged (int, int, int, int)
  46159. {
  46160. }
  46161. void Viewport::setViewedComponent (Component* const newViewedComponent)
  46162. {
  46163. if (contentComp != newViewedComponent)
  46164. {
  46165. if (contentComp->isValidComponent())
  46166. {
  46167. Component* const oldComp = contentComp;
  46168. contentComp = 0;
  46169. delete oldComp;
  46170. }
  46171. contentComp = newViewedComponent;
  46172. if (contentComp != 0)
  46173. {
  46174. contentComp->setTopLeftPosition (0, 0);
  46175. contentHolder->addAndMakeVisible (contentComp);
  46176. contentComp->addComponentListener (this);
  46177. }
  46178. updateVisibleRegion();
  46179. }
  46180. }
  46181. int Viewport::getMaximumVisibleWidth() const throw()
  46182. {
  46183. return jmax (0, getWidth() - (verticalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  46184. }
  46185. int Viewport::getMaximumVisibleHeight() const throw()
  46186. {
  46187. return jmax (0, getHeight() - (horizontalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  46188. }
  46189. void Viewport::setViewPosition (const int xPixelsOffset,
  46190. const int yPixelsOffset)
  46191. {
  46192. if (contentComp != 0)
  46193. contentComp->setTopLeftPosition (-xPixelsOffset,
  46194. -yPixelsOffset);
  46195. }
  46196. void Viewport::setViewPositionProportionately (const double x,
  46197. const double y)
  46198. {
  46199. if (contentComp != 0)
  46200. setViewPosition (jmax (0, roundDoubleToInt (x * (contentComp->getWidth() - getWidth()))),
  46201. jmax (0, roundDoubleToInt (y * (contentComp->getHeight() - getHeight()))));
  46202. }
  46203. void Viewport::componentMovedOrResized (Component&, bool, bool)
  46204. {
  46205. updateVisibleRegion();
  46206. }
  46207. void Viewport::resized()
  46208. {
  46209. updateVisibleRegion();
  46210. }
  46211. void Viewport::updateVisibleRegion()
  46212. {
  46213. if (contentComp != 0)
  46214. {
  46215. const int newVX = -contentComp->getX();
  46216. const int newVY = -contentComp->getY();
  46217. if (newVX == 0 && newVY == 0
  46218. && contentComp->getWidth() <= getWidth()
  46219. && contentComp->getHeight() <= getHeight())
  46220. {
  46221. horizontalScrollBar->setVisible (false);
  46222. verticalScrollBar->setVisible (false);
  46223. }
  46224. if ((contentComp->getWidth() > 0) && showHScrollbar
  46225. && getHeight() > getScrollBarThickness())
  46226. {
  46227. horizontalScrollBar->setRangeLimits (0.0, contentComp->getWidth());
  46228. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  46229. horizontalScrollBar->setSingleStepSize (singleStepX);
  46230. }
  46231. else
  46232. {
  46233. horizontalScrollBar->setVisible (false);
  46234. }
  46235. if ((contentComp->getHeight() > 0) && showVScrollbar
  46236. && getWidth() > getScrollBarThickness())
  46237. {
  46238. verticalScrollBar->setRangeLimits (0.0, contentComp->getHeight());
  46239. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  46240. verticalScrollBar->setSingleStepSize (singleStepY);
  46241. }
  46242. else
  46243. {
  46244. verticalScrollBar->setVisible (false);
  46245. }
  46246. if (verticalScrollBar->isVisible())
  46247. {
  46248. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  46249. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  46250. verticalScrollBar
  46251. ->setBounds (getMaximumVisibleWidth(), 0,
  46252. getScrollBarThickness(), getMaximumVisibleHeight());
  46253. }
  46254. if (horizontalScrollBar->isVisible())
  46255. {
  46256. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  46257. horizontalScrollBar
  46258. ->setBounds (0, getMaximumVisibleHeight(),
  46259. getMaximumVisibleWidth(), getScrollBarThickness());
  46260. }
  46261. contentHolder->setSize (getMaximumVisibleWidth(),
  46262. getMaximumVisibleHeight());
  46263. const int newVW = jmin (contentComp->getRight(), getMaximumVisibleWidth());
  46264. const int newVH = jmin (contentComp->getBottom(), getMaximumVisibleHeight());
  46265. if (newVX != lastVX
  46266. || newVY != lastVY
  46267. || newVW != lastVW
  46268. || newVH != lastVH)
  46269. {
  46270. lastVX = newVX;
  46271. lastVY = newVY;
  46272. lastVW = newVW;
  46273. lastVH = newVH;
  46274. visibleAreaChanged (newVX, newVY, newVW, newVH);
  46275. }
  46276. horizontalScrollBar->handleUpdateNowIfNeeded();
  46277. verticalScrollBar->handleUpdateNowIfNeeded();
  46278. }
  46279. else
  46280. {
  46281. horizontalScrollBar->setVisible (false);
  46282. verticalScrollBar->setVisible (false);
  46283. }
  46284. }
  46285. void Viewport::setSingleStepSizes (const int stepX,
  46286. const int stepY)
  46287. {
  46288. singleStepX = stepX;
  46289. singleStepY = stepY;
  46290. updateVisibleRegion();
  46291. }
  46292. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  46293. const bool showHorizontalScrollbarIfNeeded)
  46294. {
  46295. showVScrollbar = showVerticalScrollbarIfNeeded;
  46296. showHScrollbar = showHorizontalScrollbarIfNeeded;
  46297. updateVisibleRegion();
  46298. }
  46299. void Viewport::setScrollBarThickness (const int thickness)
  46300. {
  46301. scrollBarThickness = thickness;
  46302. updateVisibleRegion();
  46303. }
  46304. int Viewport::getScrollBarThickness() const throw()
  46305. {
  46306. return (scrollBarThickness > 0) ? scrollBarThickness
  46307. : getLookAndFeel().getDefaultScrollbarWidth();
  46308. }
  46309. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  46310. {
  46311. verticalScrollBar->setButtonVisibility (buttonsVisible);
  46312. horizontalScrollBar->setButtonVisibility (buttonsVisible);
  46313. }
  46314. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart)
  46315. {
  46316. if (scrollBarThatHasMoved == horizontalScrollBar)
  46317. {
  46318. setViewPosition (roundDoubleToInt (newRangeStart), getViewPositionY());
  46319. }
  46320. else if (scrollBarThatHasMoved == verticalScrollBar)
  46321. {
  46322. setViewPosition (getViewPositionX(), roundDoubleToInt (newRangeStart));
  46323. }
  46324. }
  46325. void Viewport::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  46326. {
  46327. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  46328. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  46329. }
  46330. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  46331. {
  46332. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  46333. {
  46334. const bool hasVertBar = verticalScrollBar->isVisible();
  46335. const bool hasHorzBar = horizontalScrollBar->isVisible();
  46336. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  46337. {
  46338. horizontalScrollBar->mouseWheelMove (e.getEventRelativeTo (horizontalScrollBar),
  46339. wheelIncrementX, wheelIncrementY);
  46340. return true;
  46341. }
  46342. else if (hasVertBar && wheelIncrementY != 0)
  46343. {
  46344. verticalScrollBar->mouseWheelMove (e.getEventRelativeTo (verticalScrollBar),
  46345. wheelIncrementX, wheelIncrementY);
  46346. return true;
  46347. }
  46348. }
  46349. return false;
  46350. }
  46351. bool Viewport::keyPressed (const KeyPress& key)
  46352. {
  46353. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  46354. || key.isKeyCode (KeyPress::downKey)
  46355. || key.isKeyCode (KeyPress::pageUpKey)
  46356. || key.isKeyCode (KeyPress::pageDownKey)
  46357. || key.isKeyCode (KeyPress::homeKey)
  46358. || key.isKeyCode (KeyPress::endKey);
  46359. if (verticalScrollBar->isVisible() && isUpDownKey)
  46360. return verticalScrollBar->keyPressed (key);
  46361. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  46362. || key.isKeyCode (KeyPress::rightKey);
  46363. if (horizontalScrollBar->isVisible() && (isUpDownKey || isLeftRightKey))
  46364. return horizontalScrollBar->keyPressed (key);
  46365. return false;
  46366. }
  46367. END_JUCE_NAMESPACE
  46368. /********* End of inlined file: juce_Viewport.cpp *********/
  46369. /********* Start of inlined file: juce_LookAndFeel.cpp *********/
  46370. BEGIN_JUCE_NAMESPACE
  46371. static const Colour createBaseColour (const Colour& buttonColour,
  46372. const bool hasKeyboardFocus,
  46373. const bool isMouseOverButton,
  46374. const bool isButtonDown) throw()
  46375. {
  46376. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  46377. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  46378. if (isButtonDown)
  46379. return baseColour.contrasting (0.2f);
  46380. else if (isMouseOverButton)
  46381. return baseColour.contrasting (0.1f);
  46382. return baseColour;
  46383. }
  46384. LookAndFeel::LookAndFeel()
  46385. {
  46386. /* if this fails it means you're trying to create a LookAndFeel object before
  46387. the static Colours have been initialised. That ain't gonna work. It probably
  46388. means that you're using a static LookAndFeel object and that your compiler has
  46389. decided to intialise it before the Colours class.
  46390. */
  46391. jassert (Colours::white == Colour (0xffffffff));
  46392. // set up the standard set of colours..
  46393. #define textButtonColour 0xffbbbbff
  46394. #define textHighlightColour 0x401111ee
  46395. #define standardOutlineColour 0xb2808080
  46396. static const int standardColours[] =
  46397. {
  46398. TextButton::buttonColourId, textButtonColour,
  46399. TextButton::buttonOnColourId, 0xff4444ff,
  46400. TextButton::textColourId, 0xff000000,
  46401. ComboBox::buttonColourId, 0xffbbbbff,
  46402. ComboBox::outlineColourId, standardOutlineColour,
  46403. ToggleButton::textColourId, 0xff000000,
  46404. TextEditor::backgroundColourId, 0xffffffff,
  46405. TextEditor::textColourId, 0xff000000,
  46406. TextEditor::highlightColourId, textHighlightColour,
  46407. TextEditor::highlightedTextColourId, 0xff000000,
  46408. TextEditor::caretColourId, 0xff000000,
  46409. TextEditor::outlineColourId, 0x00000000,
  46410. TextEditor::focusedOutlineColourId, textButtonColour,
  46411. TextEditor::shadowColourId, 0x38000000,
  46412. Label::backgroundColourId, 0x00000000,
  46413. Label::textColourId, 0xff000000,
  46414. Label::outlineColourId, 0x00000000,
  46415. ScrollBar::backgroundColourId, 0x00000000,
  46416. ScrollBar::thumbColourId, 0xffffffff,
  46417. ScrollBar::trackColourId, 0xffffffff,
  46418. TreeView::linesColourId, 0x4c000000,
  46419. TreeView::backgroundColourId, 0x00000000,
  46420. PopupMenu::backgroundColourId, 0xffffffff,
  46421. PopupMenu::textColourId, 0xff000000,
  46422. PopupMenu::headerTextColourId, 0xff000000,
  46423. PopupMenu::highlightedTextColourId, 0xffffffff,
  46424. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  46425. ComboBox::textColourId, 0xff000000,
  46426. ComboBox::backgroundColourId, 0xffffffff,
  46427. ComboBox::arrowColourId, 0x99000000,
  46428. ListBox::backgroundColourId, 0xffffffff,
  46429. ListBox::outlineColourId, standardOutlineColour,
  46430. ListBox::textColourId, 0xff000000,
  46431. Slider::backgroundColourId, 0x00000000,
  46432. Slider::thumbColourId, textButtonColour,
  46433. Slider::trackColourId, 0x7fffffff,
  46434. Slider::rotarySliderFillColourId, 0x7f0000ff,
  46435. Slider::rotarySliderOutlineColourId, 0x66000000,
  46436. Slider::textBoxTextColourId, 0xff000000,
  46437. Slider::textBoxBackgroundColourId, 0xffffffff,
  46438. Slider::textBoxHighlightColourId, textHighlightColour,
  46439. Slider::textBoxOutlineColourId, standardOutlineColour,
  46440. AlertWindow::backgroundColourId, 0xffededed,
  46441. AlertWindow::textColourId, 0xff000000,
  46442. AlertWindow::outlineColourId, 0xff666666,
  46443. ProgressBar::backgroundColourId, 0xffeeeeee,
  46444. ProgressBar::foregroundColourId, 0xffaaaaee,
  46445. TooltipWindow::backgroundColourId, 0xffeeeebb,
  46446. TooltipWindow::textColourId, 0xff000000,
  46447. TooltipWindow::outlineColourId, 0x4c000000,
  46448. Toolbar::backgroundColourId, 0xfff6f8f9,
  46449. Toolbar::separatorColourId, 0x4c000000,
  46450. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  46451. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  46452. Toolbar::labelTextColourId, 0xff000000,
  46453. Toolbar::editingModeOutlineColourId, 0xffff0000,
  46454. HyperlinkButton::textColourId, 0xcc1111ee,
  46455. GroupComponent::outlineColourId, 0x66000000,
  46456. GroupComponent::textColourId, 0xff000000,
  46457. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  46458. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  46459. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  46460. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  46461. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  46462. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  46463. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  46464. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  46465. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  46466. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  46467. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  46468. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  46469. ColourSelector::backgroundColourId, 0xffe5e5e5,
  46470. ColourSelector::labelTextColourId, 0xff000000,
  46471. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  46472. };
  46473. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  46474. setColour (standardColours [i], Colour (standardColours [i + 1]));
  46475. }
  46476. LookAndFeel::~LookAndFeel()
  46477. {
  46478. }
  46479. const Colour LookAndFeel::findColour (const int colourId) const throw()
  46480. {
  46481. const int index = colourIds.indexOf (colourId);
  46482. if (index >= 0)
  46483. return colours [index];
  46484. jassertfalse
  46485. return Colours::black;
  46486. }
  46487. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  46488. {
  46489. const int index = colourIds.indexOf (colourId);
  46490. if (index >= 0)
  46491. colours.set (index, colour);
  46492. colourIds.add (colourId);
  46493. colours.add (colour);
  46494. }
  46495. static LookAndFeel* defaultLF = 0;
  46496. static LookAndFeel* currentDefaultLF = 0;
  46497. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  46498. {
  46499. // if this happens, your app hasn't initialised itself properly.. if you're
  46500. // trying to hack your own main() function, have a look at
  46501. // JUCEApplication::initialiseForGUI()
  46502. jassert (currentDefaultLF != 0);
  46503. return *currentDefaultLF;
  46504. }
  46505. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  46506. {
  46507. if (newDefaultLookAndFeel == 0)
  46508. {
  46509. if (defaultLF == 0)
  46510. defaultLF = new LookAndFeel();
  46511. newDefaultLookAndFeel = defaultLF;
  46512. }
  46513. currentDefaultLF = newDefaultLookAndFeel;
  46514. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  46515. {
  46516. Component* const c = Desktop::getInstance().getComponent (i);
  46517. if (c != 0)
  46518. c->sendLookAndFeelChange();
  46519. }
  46520. }
  46521. void LookAndFeel::clearDefaultLookAndFeel() throw()
  46522. {
  46523. if (currentDefaultLF == defaultLF)
  46524. currentDefaultLF = 0;
  46525. deleteAndZero (defaultLF);
  46526. }
  46527. void LookAndFeel::drawButtonBackground (Graphics& g,
  46528. Button& button,
  46529. const Colour& backgroundColour,
  46530. bool isMouseOverButton,
  46531. bool isButtonDown)
  46532. {
  46533. const int width = button.getWidth();
  46534. const int height = button.getHeight();
  46535. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  46536. const float halfThickness = outlineThickness * 0.5f;
  46537. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  46538. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  46539. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  46540. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  46541. const Colour baseColour (createBaseColour (backgroundColour,
  46542. button.hasKeyboardFocus (true),
  46543. isMouseOverButton, isButtonDown)
  46544. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  46545. drawGlassLozenge (g,
  46546. indentL,
  46547. indentT,
  46548. width - indentL - indentR,
  46549. height - indentT - indentB,
  46550. baseColour, outlineThickness, -1.0f,
  46551. button.isConnectedOnLeft(),
  46552. button.isConnectedOnRight(),
  46553. button.isConnectedOnTop(),
  46554. button.isConnectedOnBottom());
  46555. }
  46556. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  46557. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  46558. {
  46559. g.setFont (button.getFont());
  46560. g.setColour (button.findColour (TextButton::textColourId)
  46561. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  46562. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  46563. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  46564. const int fontHeight = roundFloatToInt (g.getCurrentFont().getHeight() * 0.6f);
  46565. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  46566. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  46567. g.drawFittedText (button.getButtonText(),
  46568. leftIndent,
  46569. yIndent,
  46570. button.getWidth() - leftIndent - rightIndent,
  46571. button.getHeight() - yIndent * 2,
  46572. Justification::centred, 2);
  46573. }
  46574. void LookAndFeel::drawTickBox (Graphics& g,
  46575. Component& component,
  46576. int x, int y, int w, int h,
  46577. const bool ticked,
  46578. const bool isEnabled,
  46579. const bool isMouseOverButton,
  46580. const bool isButtonDown)
  46581. {
  46582. const float boxSize = w * 0.7f;
  46583. drawGlassSphere (g, (float) x, y + (h - boxSize) * 0.5f, boxSize,
  46584. createBaseColour (component.findColour (TextButton::buttonColourId)
  46585. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  46586. true,
  46587. isMouseOverButton,
  46588. isButtonDown),
  46589. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  46590. if (ticked)
  46591. {
  46592. Path tick;
  46593. tick.startNewSubPath (1.5f, 3.0f);
  46594. tick.lineTo (3.0f, 6.0f);
  46595. tick.lineTo (6.0f, 0.0f);
  46596. g.setColour (isEnabled ? Colours::black : Colours::grey);
  46597. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  46598. .translated ((float) x, (float) y));
  46599. g.strokePath (tick, PathStrokeType (2.5f), trans);
  46600. }
  46601. }
  46602. void LookAndFeel::drawToggleButton (Graphics& g,
  46603. ToggleButton& button,
  46604. bool isMouseOverButton,
  46605. bool isButtonDown)
  46606. {
  46607. if (button.hasKeyboardFocus (true))
  46608. {
  46609. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  46610. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  46611. }
  46612. const int tickWidth = jmin (20, button.getHeight() - 4);
  46613. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  46614. tickWidth, tickWidth,
  46615. button.getToggleState(),
  46616. button.isEnabled(),
  46617. isMouseOverButton,
  46618. isButtonDown);
  46619. g.setColour (button.findColour (ToggleButton::textColourId));
  46620. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  46621. if (! button.isEnabled())
  46622. g.setOpacity (0.5f);
  46623. const int textX = tickWidth + 5;
  46624. g.drawFittedText (button.getButtonText(),
  46625. textX, 4,
  46626. button.getWidth() - textX - 2, button.getHeight() - 8,
  46627. Justification::centredLeft, 10);
  46628. }
  46629. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  46630. {
  46631. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  46632. const int tickWidth = jmin (24, button.getHeight());
  46633. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  46634. button.getHeight());
  46635. }
  46636. void LookAndFeel::drawAlertBox (Graphics& g,
  46637. AlertWindow& alert,
  46638. const Rectangle& textArea,
  46639. TextLayout& textLayout)
  46640. {
  46641. const int iconWidth = 80;
  46642. const Colour background (alert.findColour (AlertWindow::backgroundColourId));
  46643. g.fillAll (background);
  46644. int iconSpaceUsed = 0;
  46645. Justification alignment (Justification::horizontallyCentred);
  46646. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  46647. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  46648. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  46649. const Rectangle iconRect (iconSize / -10,
  46650. iconSize / -10,
  46651. iconSize,
  46652. iconSize);
  46653. if (alert.getAlertType() == AlertWindow::QuestionIcon
  46654. || alert.getAlertType() == AlertWindow::InfoIcon)
  46655. {
  46656. if (alert.getAlertType() == AlertWindow::InfoIcon)
  46657. g.setColour (background.overlaidWith (Colour (0x280000ff)));
  46658. else
  46659. g.setColour (background.overlaidWith (Colours::gold.darker().withAlpha (0.25f)));
  46660. g.fillEllipse ((float) iconRect.getX(),
  46661. (float) iconRect.getY(),
  46662. (float) iconRect.getWidth(),
  46663. (float) iconRect.getHeight());
  46664. g.setColour (background);
  46665. g.setFont (iconRect.getHeight() * 0.9f, Font::bold);
  46666. g.drawText ((alert.getAlertType() == AlertWindow::InfoIcon) ? "i"
  46667. : "?",
  46668. iconRect.getX(),
  46669. iconRect.getY(),
  46670. iconRect.getWidth(),
  46671. iconRect.getHeight(),
  46672. Justification::centred, false);
  46673. iconSpaceUsed = iconWidth;
  46674. alignment = Justification::left;
  46675. }
  46676. else if (alert.getAlertType() == AlertWindow::WarningIcon)
  46677. {
  46678. Path p;
  46679. p.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f,
  46680. (float) iconRect.getY(),
  46681. (float) iconRect.getRight(),
  46682. (float) iconRect.getBottom(),
  46683. (float) iconRect.getX(),
  46684. (float) iconRect.getBottom());
  46685. g.setColour (background.overlaidWith (Colour (0x33ff0000)));
  46686. g.fillPath (p.createPathWithRoundedCorners (5.0f));
  46687. g.setColour (background);
  46688. g.setFont (iconRect.getHeight() * 0.9f, Font::bold);
  46689. g.drawText (T("!"),
  46690. iconRect.getX(),
  46691. iconRect.getY(),
  46692. iconRect.getWidth(),
  46693. iconRect.getHeight() + iconRect.getHeight() / 8,
  46694. Justification::centred, false);
  46695. iconSpaceUsed = iconWidth;
  46696. alignment = Justification::left;
  46697. }
  46698. g.setColour (alert.findColour (AlertWindow::textColourId));
  46699. textLayout.drawWithin (g,
  46700. textArea.getX() + iconSpaceUsed,
  46701. textArea.getY(),
  46702. textArea.getWidth() - iconSpaceUsed,
  46703. textArea.getHeight(),
  46704. alignment.getFlags() | Justification::top);
  46705. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  46706. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  46707. }
  46708. int LookAndFeel::getAlertBoxWindowFlags()
  46709. {
  46710. return ComponentPeer::windowAppearsOnTaskbar
  46711. | ComponentPeer::windowHasDropShadow;
  46712. }
  46713. int LookAndFeel::getAlertWindowButtonHeight()
  46714. {
  46715. return 28;
  46716. }
  46717. const Font LookAndFeel::getAlertWindowFont()
  46718. {
  46719. return Font (12.0f);
  46720. }
  46721. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  46722. int width, int height,
  46723. double progress, const String& textToShow)
  46724. {
  46725. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  46726. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  46727. g.fillAll (background);
  46728. if (progress >= 0.0f && progress < 1.0f)
  46729. {
  46730. drawGlassLozenge (g, 1.0f, 1.0f,
  46731. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  46732. (float) (height - 2),
  46733. foreground,
  46734. 0.5f, 0.0f,
  46735. true, true, true, true);
  46736. }
  46737. else
  46738. {
  46739. // spinning bar..
  46740. g.setColour (foreground);
  46741. const int stripeWidth = height * 2;
  46742. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  46743. Path p;
  46744. for (float x = (float) (-stripeWidth - position); x < width + stripeWidth; x += stripeWidth)
  46745. p.addQuadrilateral (x, 0.0f,
  46746. x + stripeWidth * 0.5f, 0.0f,
  46747. x, (float) height,
  46748. x - stripeWidth * 0.5f, (float) height);
  46749. Image im (Image::ARGB, width, height, true);
  46750. {
  46751. Graphics g (im);
  46752. drawGlassLozenge (g, 1.0f, 1.0f,
  46753. (float) (width - 2),
  46754. (float) (height - 2),
  46755. foreground,
  46756. 0.5f, 0.0f,
  46757. true, true, true, true);
  46758. }
  46759. ImageBrush ib (&im, 0, 0, 0.85f);
  46760. g.setBrush (&ib);
  46761. g.fillPath (p);
  46762. }
  46763. if (textToShow.isNotEmpty())
  46764. {
  46765. g.setColour (Colour::contrasting (background, foreground));
  46766. g.setFont (height * 0.6f);
  46767. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  46768. }
  46769. }
  46770. void LookAndFeel::drawScrollbarButton (Graphics& g,
  46771. ScrollBar& scrollbar,
  46772. int width, int height,
  46773. int buttonDirection,
  46774. bool /*isScrollbarVertical*/,
  46775. bool /*isMouseOverButton*/,
  46776. bool isButtonDown)
  46777. {
  46778. Path p;
  46779. if (buttonDirection == 0)
  46780. p.addTriangle (width * 0.5f, height * 0.2f,
  46781. width * 0.1f, height * 0.7f,
  46782. width * 0.9f, height * 0.7f);
  46783. else if (buttonDirection == 1)
  46784. p.addTriangle (width * 0.8f, height * 0.5f,
  46785. width * 0.3f, height * 0.1f,
  46786. width * 0.3f, height * 0.9f);
  46787. else if (buttonDirection == 2)
  46788. p.addTriangle (width * 0.5f, height * 0.8f,
  46789. width * 0.1f, height * 0.3f,
  46790. width * 0.9f, height * 0.3f);
  46791. else if (buttonDirection == 3)
  46792. p.addTriangle (width * 0.2f, height * 0.5f,
  46793. width * 0.7f, height * 0.1f,
  46794. width * 0.7f, height * 0.9f);
  46795. if (isButtonDown)
  46796. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  46797. else
  46798. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  46799. g.fillPath (p);
  46800. g.setColour (Colour (0x80000000));
  46801. g.strokePath (p, PathStrokeType (0.5f));
  46802. }
  46803. void LookAndFeel::drawScrollbar (Graphics& g,
  46804. ScrollBar& scrollbar,
  46805. int x, int y,
  46806. int width, int height,
  46807. bool isScrollbarVertical,
  46808. int thumbStartPosition,
  46809. int thumbSize,
  46810. bool /*isMouseOver*/,
  46811. bool /*isMouseDown*/)
  46812. {
  46813. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  46814. Path slotPath, thumbPath;
  46815. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  46816. const float slotIndentx2 = slotIndent * 2.0f;
  46817. const float thumbIndent = slotIndent + 1.0f;
  46818. const float thumbIndentx2 = thumbIndent * 2.0f;
  46819. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  46820. if (isScrollbarVertical)
  46821. {
  46822. slotPath.addRoundedRectangle (x + slotIndent,
  46823. y + slotIndent,
  46824. width - slotIndentx2,
  46825. height - slotIndentx2,
  46826. (width - slotIndentx2) * 0.5f);
  46827. if (thumbSize > 0)
  46828. thumbPath.addRoundedRectangle (x + thumbIndent,
  46829. thumbStartPosition + thumbIndent,
  46830. width - thumbIndentx2,
  46831. thumbSize - thumbIndentx2,
  46832. (width - thumbIndentx2) * 0.5f);
  46833. gx1 = (float) x;
  46834. gx2 = x + width * 0.7f;
  46835. }
  46836. else
  46837. {
  46838. slotPath.addRoundedRectangle (x + slotIndent,
  46839. y + slotIndent,
  46840. width - slotIndentx2,
  46841. height - slotIndentx2,
  46842. (height - slotIndentx2) * 0.5f);
  46843. if (thumbSize > 0)
  46844. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  46845. y + thumbIndent,
  46846. thumbSize - thumbIndentx2,
  46847. height - thumbIndentx2,
  46848. (height - thumbIndentx2) * 0.5f);
  46849. gy1 = (float) y;
  46850. gy2 = y + height * 0.7f;
  46851. }
  46852. const Colour thumbColour (scrollbar.findColour (ScrollBar::trackColourId));
  46853. GradientBrush gb (thumbColour.overlaidWith (Colour (0x44000000)),
  46854. gx1, gy1,
  46855. thumbColour.overlaidWith (Colour (0x19000000)),
  46856. gx2, gy2, false);
  46857. g.setBrush (&gb);
  46858. g.fillPath (slotPath);
  46859. if (isScrollbarVertical)
  46860. {
  46861. gx1 = x + width * 0.6f;
  46862. gx2 = (float) x + width;
  46863. }
  46864. else
  46865. {
  46866. gy1 = y + height * 0.6f;
  46867. gy2 = (float) y + height;
  46868. }
  46869. GradientBrush gb2 (Colours::transparentBlack,
  46870. gx1, gy1,
  46871. Colour (0x19000000),
  46872. gx2, gy2, false);
  46873. g.setBrush (&gb2);
  46874. g.fillPath (slotPath);
  46875. g.setColour (thumbColour);
  46876. g.fillPath (thumbPath);
  46877. GradientBrush gb3 (Colour (0x10000000),
  46878. gx1, gy1,
  46879. Colours::transparentBlack,
  46880. gx2, gy2, false);
  46881. g.saveState();
  46882. g.setBrush (&gb3);
  46883. if (isScrollbarVertical)
  46884. g.reduceClipRegion (x + width / 2, y, width, height);
  46885. else
  46886. g.reduceClipRegion (x, y + height / 2, width, height);
  46887. g.fillPath (thumbPath);
  46888. g.restoreState();
  46889. g.setColour (Colour (0x4c000000));
  46890. g.strokePath (thumbPath, PathStrokeType (0.4f));
  46891. }
  46892. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  46893. {
  46894. return 0;
  46895. }
  46896. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  46897. {
  46898. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  46899. }
  46900. int LookAndFeel::getDefaultScrollbarWidth()
  46901. {
  46902. return 18;
  46903. }
  46904. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  46905. {
  46906. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  46907. : scrollbar.getHeight());
  46908. }
  46909. const Path LookAndFeel::getTickShape (const float height)
  46910. {
  46911. static const unsigned char tickShapeData[] =
  46912. {
  46913. 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,
  46914. 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,
  46915. 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,
  46916. 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,
  46917. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  46918. };
  46919. Path p;
  46920. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  46921. p.scaleToFit (0, 0, height * 2.0f, height, true);
  46922. return p;
  46923. }
  46924. const Path LookAndFeel::getCrossShape (const float height)
  46925. {
  46926. static const unsigned char crossShapeData[] =
  46927. {
  46928. 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,
  46929. 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,
  46930. 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,
  46931. 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,
  46932. 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,
  46933. 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,
  46934. 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
  46935. };
  46936. Path p;
  46937. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  46938. p.scaleToFit (0, 0, height * 2.0f, height, true);
  46939. return p;
  46940. }
  46941. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus)
  46942. {
  46943. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  46944. x += (w - boxSize) >> 1;
  46945. y += (h - boxSize) >> 1;
  46946. w = boxSize;
  46947. h = boxSize;
  46948. g.setColour (Colour (0xe5ffffff));
  46949. g.fillRect (x, y, w, h);
  46950. g.setColour (Colour (0x80000000));
  46951. g.drawRect (x, y, w, h);
  46952. const float size = boxSize / 2 + 1.0f;
  46953. const float centre = (float) (boxSize / 2);
  46954. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  46955. if (isPlus)
  46956. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  46957. }
  46958. void LookAndFeel::drawBubble (Graphics& g,
  46959. float tipX, float tipY,
  46960. float boxX, float boxY,
  46961. float boxW, float boxH)
  46962. {
  46963. int side = 0;
  46964. if (tipX < boxX)
  46965. side = 1;
  46966. else if (tipX > boxX + boxW)
  46967. side = 3;
  46968. else if (tipY > boxY + boxH)
  46969. side = 2;
  46970. const float indent = 2.0f;
  46971. Path p;
  46972. p.addBubble (boxX + indent,
  46973. boxY + indent,
  46974. boxW - indent * 2.0f,
  46975. boxH - indent * 2.0f,
  46976. 5.0f,
  46977. tipX, tipY,
  46978. side,
  46979. 0.5f,
  46980. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  46981. //xxx need to take comp as param for colour
  46982. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  46983. g.fillPath (p);
  46984. //xxx as above
  46985. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  46986. g.strokePath (p, PathStrokeType (1.33f));
  46987. }
  46988. const Font LookAndFeel::getPopupMenuFont()
  46989. {
  46990. return Font (17.0f);
  46991. }
  46992. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  46993. const bool isSeparator,
  46994. int standardMenuItemHeight,
  46995. int& idealWidth,
  46996. int& idealHeight)
  46997. {
  46998. if (isSeparator)
  46999. {
  47000. idealWidth = 50;
  47001. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  47002. }
  47003. else
  47004. {
  47005. Font font (getPopupMenuFont());
  47006. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  47007. font.setHeight (standardMenuItemHeight / 1.3f);
  47008. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundFloatToInt (font.getHeight() * 1.3f);
  47009. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  47010. }
  47011. }
  47012. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  47013. {
  47014. const Colour background (findColour (PopupMenu::backgroundColourId));
  47015. g.fillAll (background);
  47016. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  47017. for (int i = 0; i < height; i += 3)
  47018. g.fillRect (0, i, width, 1);
  47019. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  47020. g.drawRect (0, 0, width, height);
  47021. }
  47022. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  47023. int width, int height,
  47024. bool isScrollUpArrow)
  47025. {
  47026. const Colour background (findColour (PopupMenu::backgroundColourId));
  47027. GradientBrush gb (background,
  47028. 0.0f, height * 0.5f,
  47029. background.withAlpha (0.0f),
  47030. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  47031. false);
  47032. g.setBrush (&gb);
  47033. g.fillRect (1, 1, width - 2, height - 2);
  47034. const float hw = width * 0.5f;
  47035. const float arrowW = height * 0.3f;
  47036. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  47037. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  47038. Path p;
  47039. p.addTriangle (hw - arrowW, y1,
  47040. hw + arrowW, y1,
  47041. hw, y2);
  47042. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  47043. g.fillPath (p);
  47044. }
  47045. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  47046. int width, int height,
  47047. const bool isSeparator,
  47048. const bool isActive,
  47049. const bool isHighlighted,
  47050. const bool isTicked,
  47051. const bool hasSubMenu,
  47052. const String& text,
  47053. const String& shortcutKeyText,
  47054. Image* image,
  47055. const Colour* const textColourToUse)
  47056. {
  47057. const float halfH = height * 0.5f;
  47058. if (isSeparator)
  47059. {
  47060. const float separatorIndent = 5.5f;
  47061. g.setColour (Colour (0x33000000));
  47062. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  47063. g.setColour (Colour (0x66ffffff));
  47064. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  47065. }
  47066. else
  47067. {
  47068. Colour textColour (findColour (PopupMenu::textColourId));
  47069. if (textColourToUse != 0)
  47070. textColour = *textColourToUse;
  47071. if (isHighlighted)
  47072. {
  47073. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  47074. g.fillRect (1, 1, width - 2, height - 2);
  47075. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  47076. }
  47077. else
  47078. {
  47079. g.setColour (textColour);
  47080. }
  47081. if (! isActive)
  47082. g.setOpacity (0.3f);
  47083. Font font (getPopupMenuFont());
  47084. if (font.getHeight() > height / 1.3f)
  47085. font.setHeight (height / 1.3f);
  47086. g.setFont (font);
  47087. const int leftBorder = (height * 5) / 4;
  47088. const int rightBorder = 4;
  47089. if (image != 0)
  47090. {
  47091. g.drawImageWithin (image,
  47092. 2, 1, leftBorder - 4, height - 2,
  47093. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  47094. }
  47095. else if (isTicked)
  47096. {
  47097. const Path tick (getTickShape (1.0f));
  47098. const float th = font.getAscent();
  47099. const float ty = halfH - th * 0.5f;
  47100. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  47101. th, true));
  47102. }
  47103. g.drawFittedText (text,
  47104. leftBorder, 0,
  47105. width - (leftBorder + rightBorder), height,
  47106. Justification::centredLeft, 1);
  47107. if (shortcutKeyText.isNotEmpty())
  47108. {
  47109. Font f2 (g.getCurrentFont());
  47110. f2.setHeight (f2.getHeight() * 0.75f);
  47111. f2.setHorizontalScale (0.95f);
  47112. g.setFont (f2);
  47113. g.drawText (shortcutKeyText,
  47114. leftBorder,
  47115. 0,
  47116. width - (leftBorder + rightBorder + 4),
  47117. height,
  47118. Justification::centredRight,
  47119. true);
  47120. }
  47121. if (hasSubMenu)
  47122. {
  47123. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  47124. const float x = width - height * 0.6f;
  47125. Path p;
  47126. p.addTriangle (x, halfH - arrowH * 0.5f,
  47127. x, halfH + arrowH * 0.5f,
  47128. x + arrowH * 0.6f, halfH);
  47129. g.fillPath (p);
  47130. }
  47131. }
  47132. }
  47133. int LookAndFeel::getMenuWindowFlags()
  47134. {
  47135. return ComponentPeer::windowHasDropShadow;
  47136. }
  47137. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  47138. bool, MenuBarComponent& menuBar)
  47139. {
  47140. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  47141. if (menuBar.isEnabled())
  47142. {
  47143. drawShinyButtonShape (g,
  47144. -4.0f, 0.0f,
  47145. width + 8.0f, (float) height,
  47146. 0.0f,
  47147. baseColour,
  47148. 0.4f,
  47149. true, true, true, true);
  47150. }
  47151. else
  47152. {
  47153. g.fillAll (baseColour);
  47154. }
  47155. }
  47156. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  47157. {
  47158. return Font (menuBar.getHeight() * 0.7f);
  47159. }
  47160. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  47161. {
  47162. return getMenuBarFont (menuBar, itemIndex, itemText)
  47163. .getStringWidth (itemText) + menuBar.getHeight();
  47164. }
  47165. void LookAndFeel::drawMenuBarItem (Graphics& g,
  47166. int width, int height,
  47167. int itemIndex,
  47168. const String& itemText,
  47169. bool isMouseOverItem,
  47170. bool isMenuOpen,
  47171. bool /*isMouseOverBar*/,
  47172. MenuBarComponent& menuBar)
  47173. {
  47174. if (! menuBar.isEnabled())
  47175. {
  47176. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  47177. .withMultipliedAlpha (0.5f));
  47178. }
  47179. else if (isMenuOpen || isMouseOverItem)
  47180. {
  47181. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  47182. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  47183. }
  47184. else
  47185. {
  47186. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  47187. }
  47188. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  47189. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  47190. }
  47191. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  47192. TextEditor& textEditor)
  47193. {
  47194. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  47195. }
  47196. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  47197. {
  47198. if (textEditor.isEnabled())
  47199. {
  47200. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  47201. {
  47202. const int border = 2;
  47203. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  47204. g.drawRect (0, 0, width, height, border);
  47205. g.setOpacity (1.0f);
  47206. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  47207. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  47208. }
  47209. else
  47210. {
  47211. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  47212. g.drawRect (0, 0, width, height);
  47213. g.setOpacity (1.0f);
  47214. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  47215. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  47216. }
  47217. }
  47218. }
  47219. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  47220. const bool isButtonDown,
  47221. int buttonX, int buttonY,
  47222. int buttonW, int buttonH,
  47223. ComboBox& box)
  47224. {
  47225. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  47226. if (box.isEnabled() && box.hasKeyboardFocus (false))
  47227. {
  47228. g.setColour (box.findColour (TextButton::buttonColourId));
  47229. g.drawRect (0, 0, width, height, 2);
  47230. }
  47231. else
  47232. {
  47233. g.setColour (box.findColour (ComboBox::outlineColourId));
  47234. g.drawRect (0, 0, width, height);
  47235. }
  47236. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  47237. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  47238. box.hasKeyboardFocus (true),
  47239. false, isButtonDown)
  47240. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  47241. drawGlassLozenge (g,
  47242. buttonX + outlineThickness, buttonY + outlineThickness,
  47243. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  47244. baseColour, outlineThickness, -1.0f,
  47245. true, true, true, true);
  47246. if (box.isEnabled())
  47247. {
  47248. const float arrowX = 0.3f;
  47249. const float arrowH = 0.2f;
  47250. Path p;
  47251. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  47252. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  47253. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  47254. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  47255. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  47256. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  47257. g.setColour (box.findColour (ComboBox::arrowColourId));
  47258. g.fillPath (p);
  47259. }
  47260. }
  47261. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  47262. {
  47263. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  47264. }
  47265. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  47266. {
  47267. return new Label (String::empty, String::empty);
  47268. }
  47269. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  47270. {
  47271. label.setBounds (1, 1,
  47272. box.getWidth() + 3 - box.getHeight(),
  47273. box.getHeight() - 2);
  47274. label.setFont (getComboBoxFont (box));
  47275. }
  47276. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  47277. int x, int y,
  47278. int width, int height,
  47279. float /*sliderPos*/,
  47280. float /*minSliderPos*/,
  47281. float /*maxSliderPos*/,
  47282. const Slider::SliderStyle /*style*/,
  47283. Slider& slider)
  47284. {
  47285. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  47286. const Colour trackColour (slider.findColour (Slider::trackColourId));
  47287. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  47288. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  47289. Path indent;
  47290. if (slider.isHorizontal())
  47291. {
  47292. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  47293. const float ih = sliderRadius;
  47294. GradientBrush gb (gradCol1, 0.0f, iy,
  47295. gradCol2, 0.0f, iy + ih, false);
  47296. g.setBrush (&gb);
  47297. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  47298. width + sliderRadius, ih,
  47299. 5.0f);
  47300. g.fillPath (indent);
  47301. }
  47302. else
  47303. {
  47304. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  47305. const float iw = sliderRadius;
  47306. GradientBrush gb (gradCol1, ix, 0.0f,
  47307. gradCol2, ix + iw, 0.0f, false);
  47308. g.setBrush (&gb);
  47309. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  47310. iw, height + sliderRadius,
  47311. 5.0f);
  47312. g.fillPath (indent);
  47313. }
  47314. g.setColour (Colour (0x4c000000));
  47315. g.strokePath (indent, PathStrokeType (0.5f));
  47316. }
  47317. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  47318. int x, int y,
  47319. int width, int height,
  47320. float sliderPos,
  47321. float minSliderPos,
  47322. float maxSliderPos,
  47323. const Slider::SliderStyle style,
  47324. Slider& slider)
  47325. {
  47326. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  47327. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  47328. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  47329. slider.isMouseOverOrDragging() && slider.isEnabled(),
  47330. slider.isMouseButtonDown() && slider.isEnabled()));
  47331. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  47332. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  47333. {
  47334. float kx, ky;
  47335. if (style == Slider::LinearVertical)
  47336. {
  47337. kx = x + width * 0.5f;
  47338. ky = sliderPos;
  47339. }
  47340. else
  47341. {
  47342. kx = sliderPos;
  47343. ky = y + height * 0.5f;
  47344. }
  47345. drawGlassSphere (g,
  47346. kx - sliderRadius,
  47347. ky - sliderRadius,
  47348. sliderRadius * 2.0f,
  47349. knobColour, outlineThickness);
  47350. }
  47351. else
  47352. {
  47353. if (style == Slider::ThreeValueVertical)
  47354. {
  47355. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  47356. sliderPos - sliderRadius,
  47357. sliderRadius * 2.0f,
  47358. knobColour, outlineThickness);
  47359. }
  47360. else if (style == Slider::ThreeValueHorizontal)
  47361. {
  47362. drawGlassSphere (g,sliderPos - sliderRadius,
  47363. y + height * 0.5f - sliderRadius,
  47364. sliderRadius * 2.0f,
  47365. knobColour, outlineThickness);
  47366. }
  47367. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  47368. {
  47369. const float sr = jmin (sliderRadius, width * 0.4f);
  47370. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  47371. minSliderPos - sliderRadius,
  47372. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  47373. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  47374. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  47375. }
  47376. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  47377. {
  47378. const float sr = jmin (sliderRadius, height * 0.4f);
  47379. drawGlassPointer (g, minSliderPos - sr,
  47380. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  47381. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  47382. drawGlassPointer (g, maxSliderPos - sliderRadius,
  47383. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  47384. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  47385. }
  47386. }
  47387. }
  47388. void LookAndFeel::drawLinearSlider (Graphics& g,
  47389. int x, int y,
  47390. int width, int height,
  47391. float sliderPos,
  47392. float minSliderPos,
  47393. float maxSliderPos,
  47394. const Slider::SliderStyle style,
  47395. Slider& slider)
  47396. {
  47397. g.fillAll (slider.findColour (Slider::backgroundColourId));
  47398. if (style == Slider::LinearBar)
  47399. {
  47400. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  47401. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  47402. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  47403. false,
  47404. isMouseOver,
  47405. isMouseOver || slider.isMouseButtonDown()));
  47406. drawShinyButtonShape (g,
  47407. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  47408. baseColour,
  47409. slider.isEnabled() ? 0.9f : 0.3f,
  47410. true, true, true, true);
  47411. }
  47412. else
  47413. {
  47414. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  47415. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  47416. }
  47417. }
  47418. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  47419. {
  47420. return jmin (7,
  47421. slider.getHeight() / 2,
  47422. slider.getWidth() / 2) + 2;
  47423. }
  47424. void LookAndFeel::drawRotarySlider (Graphics& g,
  47425. int x, int y,
  47426. int width, int height,
  47427. float sliderPos,
  47428. const float rotaryStartAngle,
  47429. const float rotaryEndAngle,
  47430. Slider& slider)
  47431. {
  47432. const float radius = jmin (width / 2, height / 2) - 2.0f;
  47433. const float centreX = x + width * 0.5f;
  47434. const float centreY = y + height * 0.5f;
  47435. const float rx = centreX - radius;
  47436. const float ry = centreY - radius;
  47437. const float rw = radius * 2.0f;
  47438. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  47439. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  47440. if (radius > 12.0f)
  47441. {
  47442. if (slider.isEnabled())
  47443. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  47444. else
  47445. g.setColour (Colour (0x80808080));
  47446. const float thickness = 0.7f;
  47447. {
  47448. Path filledArc;
  47449. filledArc.addPieSegment (rx, ry, rw, rw,
  47450. rotaryStartAngle,
  47451. angle,
  47452. thickness);
  47453. g.fillPath (filledArc);
  47454. }
  47455. if (thickness > 0)
  47456. {
  47457. const float innerRadius = radius * 0.2f;
  47458. Path p;
  47459. p.addTriangle (-innerRadius, 0.0f,
  47460. 0.0f, -radius * thickness * 1.1f,
  47461. innerRadius, 0.0f);
  47462. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  47463. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  47464. }
  47465. if (slider.isEnabled())
  47466. {
  47467. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  47468. Path outlineArc;
  47469. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  47470. outlineArc.closeSubPath();
  47471. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  47472. }
  47473. }
  47474. else
  47475. {
  47476. if (slider.isEnabled())
  47477. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  47478. else
  47479. g.setColour (Colour (0x80808080));
  47480. Path p;
  47481. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  47482. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  47483. p.addLineSegment (0.0f, 0.0f, 0.0f, -radius, rw * 0.2f);
  47484. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  47485. }
  47486. }
  47487. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  47488. {
  47489. return new TextButton (isIncrement ? "+" : "-", String::empty);
  47490. }
  47491. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  47492. {
  47493. Label* const l = new Label (T("n"), String::empty);
  47494. l->setJustificationType (Justification::centred);
  47495. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  47496. l->setColour (Label::backgroundColourId,
  47497. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  47498. : slider.findColour (Slider::textBoxBackgroundColourId));
  47499. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  47500. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  47501. l->setColour (TextEditor::backgroundColourId,
  47502. slider.findColour (Slider::textBoxBackgroundColourId)
  47503. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  47504. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  47505. return l;
  47506. }
  47507. ImageEffectFilter* LookAndFeel::getSliderEffect()
  47508. {
  47509. return 0;
  47510. }
  47511. static const TextLayout layoutTooltipText (const String& text) throw()
  47512. {
  47513. const float tooltipFontSize = 15.0f;
  47514. const int maxToolTipWidth = 400;
  47515. const Font f (tooltipFontSize, Font::bold);
  47516. TextLayout tl (text, f);
  47517. tl.layout (maxToolTipWidth, Justification::left, true);
  47518. return tl;
  47519. }
  47520. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  47521. {
  47522. const TextLayout tl (layoutTooltipText (tipText));
  47523. width = tl.getWidth() + 14;
  47524. height = tl.getHeight() + 10;
  47525. }
  47526. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  47527. {
  47528. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  47529. const Colour textCol (findColour (TooltipWindow::textColourId));
  47530. g.setColour (findColour (TooltipWindow::outlineColourId));
  47531. g.drawRect (0, 0, width, height);
  47532. const TextLayout tl (layoutTooltipText (text));
  47533. g.setColour (findColour (TooltipWindow::textColourId));
  47534. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  47535. }
  47536. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  47537. {
  47538. return new TextButton (text, TRANS("click to browse for a different file"));
  47539. }
  47540. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  47541. ComboBox* filenameBox,
  47542. Button* browseButton)
  47543. {
  47544. browseButton->setSize (80, filenameComp.getHeight());
  47545. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  47546. if (tb != 0)
  47547. tb->changeWidthToFitText();
  47548. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  47549. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  47550. }
  47551. void LookAndFeel::drawCornerResizer (Graphics& g,
  47552. int w, int h,
  47553. bool /*isMouseOver*/,
  47554. bool /*isMouseDragging*/)
  47555. {
  47556. const float lineThickness = jmin (w, h) * 0.075f;
  47557. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  47558. {
  47559. g.setColour (Colours::lightgrey);
  47560. g.drawLine (w * i,
  47561. h + 1.0f,
  47562. w + 1.0f,
  47563. h * i,
  47564. lineThickness);
  47565. g.setColour (Colours::darkgrey);
  47566. g.drawLine (w * i + lineThickness,
  47567. h + 1.0f,
  47568. w + 1.0f,
  47569. h * i + lineThickness,
  47570. lineThickness);
  47571. }
  47572. }
  47573. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  47574. const BorderSize& /*borders*/)
  47575. {
  47576. }
  47577. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  47578. const BorderSize& border, ResizableWindow&)
  47579. {
  47580. g.setColour (Colour (0x80000000));
  47581. g.drawRect (0, 0, w, h);
  47582. g.setColour (Colour (0x19000000));
  47583. g.drawRect (border.getLeft() - 1,
  47584. border.getTop() - 1,
  47585. w + 2 - border.getLeftAndRight(),
  47586. h + 2 - border.getTopAndBottom());
  47587. }
  47588. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  47589. Graphics& g, int w, int h,
  47590. int titleSpaceX, int titleSpaceW,
  47591. const Image* icon,
  47592. bool drawTitleTextOnLeft)
  47593. {
  47594. const bool isActive = window.isActiveWindow();
  47595. GradientBrush gb (window.getBackgroundColour(),
  47596. 0.0f, 0.0f,
  47597. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  47598. 0.0f, (float) h, false);
  47599. g.setBrush (&gb);
  47600. g.fillAll();
  47601. g.setFont (h * 0.65f, Font::bold);
  47602. int textW = g.getCurrentFont().getStringWidth (window.getName());
  47603. int iconW = 0;
  47604. int iconH = 0;
  47605. if (icon != 0)
  47606. {
  47607. iconH = (int) g.getCurrentFont().getHeight();
  47608. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  47609. }
  47610. textW = jmin (titleSpaceW, textW + iconW);
  47611. int textX = drawTitleTextOnLeft ? titleSpaceX
  47612. : jmax (titleSpaceX, (w - textW) / 2);
  47613. if (textX + textW > titleSpaceX + titleSpaceW)
  47614. textX = titleSpaceX + titleSpaceW - textW;
  47615. if (icon != 0)
  47616. {
  47617. g.setOpacity (isActive ? 1.0f : 0.6f);
  47618. g.drawImageWithin (icon, textX, (h - iconH) / 2, iconW, iconH,
  47619. RectanglePlacement::centred, false);
  47620. textX += iconW;
  47621. textW -= iconW;
  47622. }
  47623. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  47624. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  47625. }
  47626. class GlassWindowButton : public Button
  47627. {
  47628. public:
  47629. GlassWindowButton (const String& name, const Colour& col,
  47630. const Path& normalShape_,
  47631. const Path& toggledShape_) throw()
  47632. : Button (name),
  47633. colour (col),
  47634. normalShape (normalShape_),
  47635. toggledShape (toggledShape_)
  47636. {
  47637. }
  47638. ~GlassWindowButton()
  47639. {
  47640. }
  47641. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  47642. {
  47643. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  47644. if (! isEnabled())
  47645. alpha *= 0.5f;
  47646. float x = 0, y = 0, diam;
  47647. if (getWidth() < getHeight())
  47648. {
  47649. diam = (float) getWidth();
  47650. y = (getHeight() - getWidth()) * 0.5f;
  47651. }
  47652. else
  47653. {
  47654. diam = (float) getHeight();
  47655. y = (getWidth() - getHeight()) * 0.5f;
  47656. }
  47657. x += diam * 0.05f;
  47658. y += diam * 0.05f;
  47659. diam *= 0.9f;
  47660. GradientBrush gb1 (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  47661. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false);
  47662. g.setBrush (&gb1);
  47663. g.fillEllipse (x, y, diam, diam);
  47664. x += 2.0f;
  47665. y += 2.0f;
  47666. diam -= 4.0f;
  47667. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  47668. Path& p = getToggleState() ? toggledShape : normalShape;
  47669. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  47670. diam * 0.4f, diam * 0.4f, true));
  47671. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  47672. g.fillPath (p, t);
  47673. }
  47674. juce_UseDebuggingNewOperator
  47675. private:
  47676. Colour colour;
  47677. Path normalShape, toggledShape;
  47678. GlassWindowButton (const GlassWindowButton&);
  47679. const GlassWindowButton& operator= (const GlassWindowButton&);
  47680. };
  47681. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  47682. {
  47683. Path shape;
  47684. const float crossThickness = 0.25f;
  47685. if (buttonType == DocumentWindow::closeButton)
  47686. {
  47687. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, crossThickness * 1.4f);
  47688. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, crossThickness * 1.4f);
  47689. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  47690. }
  47691. else if (buttonType == DocumentWindow::minimiseButton)
  47692. {
  47693. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  47694. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  47695. }
  47696. else if (buttonType == DocumentWindow::maximiseButton)
  47697. {
  47698. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, crossThickness);
  47699. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  47700. Path fullscreenShape;
  47701. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  47702. fullscreenShape.lineTo (0.0f, 100.0f);
  47703. fullscreenShape.lineTo (0.0f, 0.0f);
  47704. fullscreenShape.lineTo (100.0f, 0.0f);
  47705. fullscreenShape.lineTo (100.0f, 45.0f);
  47706. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  47707. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  47708. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  47709. }
  47710. jassertfalse
  47711. return 0;
  47712. }
  47713. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  47714. int titleBarX,
  47715. int titleBarY,
  47716. int titleBarW,
  47717. int titleBarH,
  47718. Button* minimiseButton,
  47719. Button* maximiseButton,
  47720. Button* closeButton,
  47721. bool positionTitleBarButtonsOnLeft)
  47722. {
  47723. const int buttonW = titleBarH - titleBarH / 8;
  47724. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  47725. : titleBarX + titleBarW - buttonW - buttonW / 4;
  47726. if (closeButton != 0)
  47727. {
  47728. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  47729. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  47730. }
  47731. if (positionTitleBarButtonsOnLeft)
  47732. swapVariables (minimiseButton, maximiseButton);
  47733. if (maximiseButton != 0)
  47734. {
  47735. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  47736. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  47737. }
  47738. if (minimiseButton != 0)
  47739. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  47740. }
  47741. int LookAndFeel::getDefaultMenuBarHeight()
  47742. {
  47743. return 24;
  47744. }
  47745. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  47746. {
  47747. return new DropShadower (0.4f, 1, 5, 10);
  47748. }
  47749. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  47750. int w, int h,
  47751. bool /*isVerticalBar*/,
  47752. bool isMouseOver,
  47753. bool isMouseDragging)
  47754. {
  47755. float alpha = 0.5f;
  47756. if (isMouseOver || isMouseDragging)
  47757. {
  47758. g.fillAll (Colour (0x190000ff));
  47759. alpha = 1.0f;
  47760. }
  47761. const float cx = w * 0.5f;
  47762. const float cy = h * 0.5f;
  47763. const float cr = jmin (w, h) * 0.4f;
  47764. GradientBrush gb (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  47765. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  47766. true);
  47767. g.setBrush (&gb);
  47768. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  47769. }
  47770. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  47771. const String& text,
  47772. const Justification& position,
  47773. GroupComponent& group)
  47774. {
  47775. const float textH = 15.0f;
  47776. const float indent = 3.0f;
  47777. const float textEdgeGap = 4.0f;
  47778. float cs = 5.0f;
  47779. Font f (textH);
  47780. Path p;
  47781. float x = indent;
  47782. float y = f.getAscent() - 3.0f;
  47783. float w = jmax (0.0f, width - x * 2.0f);
  47784. float h = jmax (0.0f, height - y - indent);
  47785. cs = jmin (cs, w * 0.5f, h * 0.5f);
  47786. const float cs2 = 2.0f * cs;
  47787. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  47788. float textX = cs + textEdgeGap;
  47789. if (position.testFlags (Justification::horizontallyCentred))
  47790. textX = cs + (w - cs2 - textW) * 0.5f;
  47791. else if (position.testFlags (Justification::right))
  47792. textX = w - cs - textW - textEdgeGap;
  47793. p.startNewSubPath (x + textX + textW, y);
  47794. p.lineTo (x + w - cs, y);
  47795. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  47796. p.lineTo (x + w, y + h - cs);
  47797. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  47798. p.lineTo (x + cs, y + h);
  47799. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  47800. p.lineTo (x, y + cs);
  47801. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  47802. p.lineTo (x + textX, y);
  47803. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  47804. g.setColour (group.findColour (GroupComponent::outlineColourId)
  47805. .withMultipliedAlpha (alpha));
  47806. g.strokePath (p, PathStrokeType (2.0f));
  47807. g.setColour (group.findColour (GroupComponent::textColourId)
  47808. .withMultipliedAlpha (alpha));
  47809. g.setFont (f);
  47810. g.drawText (text,
  47811. roundFloatToInt (x + textX), 0,
  47812. roundFloatToInt (textW),
  47813. roundFloatToInt (textH),
  47814. Justification::centred, true);
  47815. }
  47816. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  47817. {
  47818. return 1 + tabDepth / 3;
  47819. }
  47820. int LookAndFeel::getTabButtonSpaceAroundImage()
  47821. {
  47822. return 4;
  47823. }
  47824. void LookAndFeel::createTabButtonShape (Path& p,
  47825. int width, int height,
  47826. int /*tabIndex*/,
  47827. const String& /*text*/,
  47828. Button& /*button*/,
  47829. TabbedButtonBar::Orientation orientation,
  47830. const bool /*isMouseOver*/,
  47831. const bool /*isMouseDown*/,
  47832. const bool /*isFrontTab*/)
  47833. {
  47834. const float w = (float) width;
  47835. const float h = (float) height;
  47836. float length = w;
  47837. float depth = h;
  47838. if (orientation == TabbedButtonBar::TabsAtLeft
  47839. || orientation == TabbedButtonBar::TabsAtRight)
  47840. {
  47841. swapVariables (length, depth);
  47842. }
  47843. const float indent = (float) getTabButtonOverlap ((int) depth);
  47844. const float overhang = 4.0f;
  47845. if (orientation == TabbedButtonBar::TabsAtLeft)
  47846. {
  47847. p.startNewSubPath (w, 0.0f);
  47848. p.lineTo (0.0f, indent);
  47849. p.lineTo (0.0f, h - indent);
  47850. p.lineTo (w, h);
  47851. p.lineTo (w + overhang, h + overhang);
  47852. p.lineTo (w + overhang, -overhang);
  47853. }
  47854. else if (orientation == TabbedButtonBar::TabsAtRight)
  47855. {
  47856. p.startNewSubPath (0.0f, 0.0f);
  47857. p.lineTo (w, indent);
  47858. p.lineTo (w, h - indent);
  47859. p.lineTo (0.0f, h);
  47860. p.lineTo (-overhang, h + overhang);
  47861. p.lineTo (-overhang, -overhang);
  47862. }
  47863. else if (orientation == TabbedButtonBar::TabsAtBottom)
  47864. {
  47865. p.startNewSubPath (0.0f, 0.0f);
  47866. p.lineTo (indent, h);
  47867. p.lineTo (w - indent, h);
  47868. p.lineTo (w, 0.0f);
  47869. p.lineTo (w + overhang, -overhang);
  47870. p.lineTo (-overhang, -overhang);
  47871. }
  47872. else
  47873. {
  47874. p.startNewSubPath (0.0f, h);
  47875. p.lineTo (indent, 0.0f);
  47876. p.lineTo (w - indent, 0.0f);
  47877. p.lineTo (w, h);
  47878. p.lineTo (w + overhang, h + overhang);
  47879. p.lineTo (-overhang, h + overhang);
  47880. }
  47881. p.closeSubPath();
  47882. p = p.createPathWithRoundedCorners (3.0f);
  47883. }
  47884. void LookAndFeel::fillTabButtonShape (Graphics& g,
  47885. const Path& path,
  47886. const Colour& preferredColour,
  47887. int /*tabIndex*/,
  47888. const String& /*text*/,
  47889. Button& button,
  47890. TabbedButtonBar::Orientation /*orientation*/,
  47891. const bool /*isMouseOver*/,
  47892. const bool /*isMouseDown*/,
  47893. const bool isFrontTab)
  47894. {
  47895. g.setColour (isFrontTab ? preferredColour
  47896. : preferredColour.withMultipliedAlpha (0.9f));
  47897. g.fillPath (path);
  47898. g.setColour (Colours::black.withAlpha (button.isEnabled() ? 0.5f : 0.25f));
  47899. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  47900. }
  47901. void LookAndFeel::drawTabButtonText (Graphics& g,
  47902. int x, int y, int w, int h,
  47903. const Colour& preferredBackgroundColour,
  47904. int /*tabIndex*/,
  47905. const String& text,
  47906. Button& button,
  47907. TabbedButtonBar::Orientation orientation,
  47908. const bool isMouseOver,
  47909. const bool isMouseDown,
  47910. const bool /*isFrontTab*/)
  47911. {
  47912. int length = w;
  47913. int depth = h;
  47914. if (orientation == TabbedButtonBar::TabsAtLeft
  47915. || orientation == TabbedButtonBar::TabsAtRight)
  47916. {
  47917. swapVariables (length, depth);
  47918. }
  47919. Font font (depth * 0.6f);
  47920. font.setUnderline (button.hasKeyboardFocus (false));
  47921. GlyphArrangement textLayout;
  47922. textLayout.addFittedText (font, text.trim(),
  47923. 0.0f, 0.0f, (float) length, (float) depth,
  47924. Justification::centred,
  47925. jmax (1, depth / 12));
  47926. AffineTransform transform;
  47927. if (orientation == TabbedButtonBar::TabsAtLeft)
  47928. {
  47929. transform = transform.rotated (float_Pi * -0.5f)
  47930. .translated ((float) x, (float) (y + h));
  47931. }
  47932. else if (orientation == TabbedButtonBar::TabsAtRight)
  47933. {
  47934. transform = transform.rotated (float_Pi * 0.5f)
  47935. .translated ((float) (x + w), (float) y);
  47936. }
  47937. else
  47938. {
  47939. transform = transform.translated ((float) x, (float) y);
  47940. }
  47941. g.setColour (preferredBackgroundColour.contrasting());
  47942. if (! (isMouseOver || isMouseDown))
  47943. g.setOpacity (0.8f);
  47944. if (! button.isEnabled())
  47945. g.setOpacity (0.3f);
  47946. textLayout.draw (g, transform);
  47947. }
  47948. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  47949. const String& text,
  47950. int tabDepth,
  47951. Button&)
  47952. {
  47953. Font f (tabDepth * 0.6f);
  47954. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  47955. }
  47956. void LookAndFeel::drawTabButton (Graphics& g,
  47957. int w, int h,
  47958. const Colour& preferredColour,
  47959. int tabIndex,
  47960. const String& text,
  47961. Button& button,
  47962. TabbedButtonBar::Orientation orientation,
  47963. const bool isMouseOver,
  47964. const bool isMouseDown,
  47965. const bool isFrontTab)
  47966. {
  47967. int length = w;
  47968. int depth = h;
  47969. if (orientation == TabbedButtonBar::TabsAtLeft
  47970. || orientation == TabbedButtonBar::TabsAtRight)
  47971. {
  47972. swapVariables (length, depth);
  47973. }
  47974. Path tabShape;
  47975. createTabButtonShape (tabShape, w, h,
  47976. tabIndex, text, button, orientation,
  47977. isMouseOver, isMouseDown, isFrontTab);
  47978. fillTabButtonShape (g, tabShape, preferredColour,
  47979. tabIndex, text, button, orientation,
  47980. isMouseOver, isMouseDown, isFrontTab);
  47981. const int indent = getTabButtonOverlap (depth);
  47982. int x = 0, y = 0;
  47983. if (orientation == TabbedButtonBar::TabsAtLeft
  47984. || orientation == TabbedButtonBar::TabsAtRight)
  47985. {
  47986. y += indent;
  47987. h -= indent * 2;
  47988. }
  47989. else
  47990. {
  47991. x += indent;
  47992. w -= indent * 2;
  47993. }
  47994. drawTabButtonText (g, x, y, w, h, preferredColour,
  47995. tabIndex, text, button, orientation,
  47996. isMouseOver, isMouseDown, isFrontTab);
  47997. }
  47998. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  47999. int w, int h,
  48000. TabbedButtonBar& tabBar,
  48001. TabbedButtonBar::Orientation orientation)
  48002. {
  48003. const float shadowSize = 0.2f;
  48004. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  48005. Rectangle shadowRect;
  48006. if (orientation == TabbedButtonBar::TabsAtLeft)
  48007. {
  48008. x1 = (float) w;
  48009. x2 = w * (1.0f - shadowSize);
  48010. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  48011. }
  48012. else if (orientation == TabbedButtonBar::TabsAtRight)
  48013. {
  48014. x2 = w * shadowSize;
  48015. shadowRect.setBounds (0, 0, (int) x2, h);
  48016. }
  48017. else if (orientation == TabbedButtonBar::TabsAtBottom)
  48018. {
  48019. y2 = h * shadowSize;
  48020. shadowRect.setBounds (0, 0, w, (int) y2);
  48021. }
  48022. else
  48023. {
  48024. y1 = (float) h;
  48025. y2 = h * (1.0f - shadowSize);
  48026. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  48027. }
  48028. GradientBrush gb (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  48029. Colours::transparentBlack, x2, y2,
  48030. false);
  48031. g.setBrush (&gb);
  48032. shadowRect.expand (2, 2);
  48033. g.fillRect (shadowRect);
  48034. g.setColour (Colour (0x80000000));
  48035. if (orientation == TabbedButtonBar::TabsAtLeft)
  48036. {
  48037. g.fillRect (w - 1, 0, 1, h);
  48038. }
  48039. else if (orientation == TabbedButtonBar::TabsAtRight)
  48040. {
  48041. g.fillRect (0, 0, 1, h);
  48042. }
  48043. else if (orientation == TabbedButtonBar::TabsAtBottom)
  48044. {
  48045. g.fillRect (0, 0, w, 1);
  48046. }
  48047. else
  48048. {
  48049. g.fillRect (0, h - 1, w, 1);
  48050. }
  48051. }
  48052. Button* LookAndFeel::createTabBarExtrasButton()
  48053. {
  48054. const float thickness = 7.0f;
  48055. const float indent = 22.0f;
  48056. Path p;
  48057. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  48058. DrawablePath ellipse;
  48059. ellipse.setPath (p);
  48060. ellipse.setSolidFill (Colour (0x99ffffff));
  48061. p.clear();
  48062. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  48063. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  48064. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  48065. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  48066. p.setUsingNonZeroWinding (false);
  48067. DrawablePath dp;
  48068. dp.setPath (p);
  48069. dp.setSolidFill (Colour (0x59000000));
  48070. DrawableComposite normalImage;
  48071. normalImage.insertDrawable (ellipse);
  48072. normalImage.insertDrawable (dp);
  48073. dp.setSolidFill (Colour (0xcc000000));
  48074. DrawableComposite overImage;
  48075. overImage.insertDrawable (ellipse);
  48076. overImage.insertDrawable (dp);
  48077. DrawableButton* db = new DrawableButton (T("tabs"), DrawableButton::ImageFitted);
  48078. db->setImages (&normalImage, &overImage, 0);
  48079. return db;
  48080. }
  48081. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  48082. {
  48083. g.fillAll (Colours::white);
  48084. const int w = header.getWidth();
  48085. const int h = header.getHeight();
  48086. GradientBrush gb (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  48087. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  48088. false);
  48089. g.setBrush (&gb);
  48090. g.fillRect (0, h / 2, w, h);
  48091. g.setColour (Colour (0x33000000));
  48092. g.fillRect (0, h - 1, w, 1);
  48093. for (int i = header.getNumColumns (true); --i >= 0;)
  48094. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  48095. }
  48096. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  48097. int width, int height,
  48098. bool isMouseOver, bool isMouseDown,
  48099. int columnFlags)
  48100. {
  48101. if (isMouseDown)
  48102. g.fillAll (Colour (0x8899aadd));
  48103. else if (isMouseOver)
  48104. g.fillAll (Colour (0x5599aadd));
  48105. int rightOfText = width - 4;
  48106. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  48107. {
  48108. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  48109. const float bottom = height - top;
  48110. const float w = height * 0.5f;
  48111. const float x = rightOfText - (w * 1.25f);
  48112. rightOfText = (int) x;
  48113. Path sortArrow;
  48114. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  48115. g.setColour (Colour (0x99000000));
  48116. g.fillPath (sortArrow);
  48117. }
  48118. g.setColour (Colours::black);
  48119. g.setFont (height * 0.5f, Font::bold);
  48120. const int textX = 4;
  48121. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  48122. }
  48123. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  48124. {
  48125. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  48126. GradientBrush gb (background, 0.0f, 0.0f,
  48127. background.darker (0.1f),
  48128. toolbar.isVertical() ? w - 1.0f : 0.0f,
  48129. toolbar.isVertical() ? 0.0f : h - 1.0f,
  48130. false);
  48131. g.setBrush (&gb);
  48132. g.fillAll();
  48133. }
  48134. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  48135. {
  48136. return createTabBarExtrasButton();
  48137. }
  48138. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  48139. bool isMouseOver, bool isMouseDown,
  48140. ToolbarItemComponent& component)
  48141. {
  48142. if (isMouseDown)
  48143. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  48144. else if (isMouseOver)
  48145. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  48146. }
  48147. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  48148. const String& text, ToolbarItemComponent& component)
  48149. {
  48150. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  48151. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  48152. const float fontHeight = jmin (14.0f, height * 0.85f);
  48153. g.setFont (fontHeight);
  48154. g.drawFittedText (text,
  48155. x, y, width, height,
  48156. Justification::centred,
  48157. jmax (1, height / (int) fontHeight));
  48158. }
  48159. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  48160. bool isOpen, int width, int height)
  48161. {
  48162. const int buttonSize = (height * 3) / 4;
  48163. const int buttonIndent = (height - buttonSize) / 2;
  48164. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen);
  48165. const int textX = buttonIndent * 2 + buttonSize + 2;
  48166. g.setColour (Colours::black);
  48167. g.setFont (height * 0.7f, Font::bold);
  48168. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  48169. }
  48170. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  48171. PropertyComponent&)
  48172. {
  48173. g.setColour (Colour (0x66ffffff));
  48174. g.fillRect (0, 0, width, height - 1);
  48175. }
  48176. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  48177. PropertyComponent& component)
  48178. {
  48179. g.setColour (Colours::black);
  48180. if (! component.isEnabled())
  48181. g.setOpacity (g.getCurrentColour().getAlpha() * 0.6f);
  48182. g.setFont (jmin (height, 24) * 0.65f);
  48183. const Rectangle r (getPropertyComponentContentPosition (component));
  48184. g.drawFittedText (component.getName(),
  48185. 3, r.getY(), r.getX() - 5, r.getHeight(),
  48186. Justification::centredLeft, 2);
  48187. }
  48188. const Rectangle LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  48189. {
  48190. return Rectangle (component.getWidth() / 3, 1,
  48191. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  48192. }
  48193. void LookAndFeel::createFileChooserHeaderText (const String& title,
  48194. const String& instructions,
  48195. GlyphArrangement& text,
  48196. int width)
  48197. {
  48198. text.clear();
  48199. text.addJustifiedText (Font (17.0f, Font::bold), title,
  48200. 8.0f, 22.0f, width - 16.0f,
  48201. Justification::centred);
  48202. text.addJustifiedText (Font (14.0f), instructions,
  48203. 8.0f, 24.0f + 16.0f, width - 16.0f,
  48204. Justification::centred);
  48205. }
  48206. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  48207. const String& filename, Image* icon,
  48208. const String& fileSizeDescription,
  48209. const String& fileTimeDescription,
  48210. const bool isDirectory,
  48211. const bool isItemSelected,
  48212. const int /*itemIndex*/)
  48213. {
  48214. if (isItemSelected)
  48215. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  48216. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  48217. g.setFont (height * 0.7f);
  48218. Image* im = icon;
  48219. Image* toRelease = 0;
  48220. if (im == 0)
  48221. {
  48222. toRelease = im = (isDirectory ? getDefaultFolderImage()
  48223. : getDefaultDocumentFileImage());
  48224. }
  48225. const int x = 32;
  48226. if (im != 0)
  48227. {
  48228. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  48229. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48230. false);
  48231. ImageCache::release (toRelease);
  48232. }
  48233. if (width > 450 && ! isDirectory)
  48234. {
  48235. const int sizeX = roundFloatToInt (width * 0.7f);
  48236. const int dateX = roundFloatToInt (width * 0.8f);
  48237. g.drawFittedText (filename,
  48238. x, 0, sizeX - x, height,
  48239. Justification::centredLeft, 1);
  48240. g.setFont (height * 0.5f);
  48241. g.setColour (Colours::darkgrey);
  48242. if (! isDirectory)
  48243. {
  48244. g.drawFittedText (fileSizeDescription,
  48245. sizeX, 0, dateX - sizeX - 8, height,
  48246. Justification::centredRight, 1);
  48247. g.drawFittedText (fileTimeDescription,
  48248. dateX, 0, width - 8 - dateX, height,
  48249. Justification::centredRight, 1);
  48250. }
  48251. }
  48252. else
  48253. {
  48254. g.drawFittedText (filename,
  48255. x, 0, width - x, height,
  48256. Justification::centredLeft, 1);
  48257. }
  48258. }
  48259. Button* LookAndFeel::createFileBrowserGoUpButton()
  48260. {
  48261. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  48262. Path arrowPath;
  48263. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  48264. DrawablePath arrowImage;
  48265. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  48266. arrowImage.setPath (arrowPath);
  48267. goUpButton->setImages (&arrowImage);
  48268. return goUpButton;
  48269. }
  48270. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  48271. DirectoryContentsDisplayComponent* fileListComponent,
  48272. FilePreviewComponent* previewComp,
  48273. ComboBox* currentPathBox,
  48274. TextEditor* filenameBox,
  48275. Button* goUpButton)
  48276. {
  48277. const int x = 8;
  48278. int w = browserComp.getWidth() - x - x;
  48279. if (previewComp != 0)
  48280. {
  48281. const int previewWidth = w / 3;
  48282. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  48283. w -= previewWidth + 4;
  48284. }
  48285. int y = 4;
  48286. const int controlsHeight = 22;
  48287. const int bottomSectionHeight = controlsHeight + 8;
  48288. const int upButtonWidth = 50;
  48289. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  48290. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  48291. y += controlsHeight + 4;
  48292. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  48293. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  48294. y = listAsComp->getBottom() + 4;
  48295. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  48296. }
  48297. Image* LookAndFeel::getDefaultFolderImage()
  48298. {
  48299. 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,
  48300. 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,
  48301. 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,
  48302. 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,
  48303. 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,
  48304. 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,
  48305. 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,
  48306. 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,
  48307. 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,
  48308. 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,
  48309. 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,
  48310. 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,
  48311. 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,
  48312. 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,
  48313. 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,
  48314. 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,
  48315. 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,
  48316. 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,
  48317. 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,
  48318. 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,
  48319. 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,
  48320. 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,
  48321. 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,
  48322. 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,
  48323. 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,
  48324. 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,
  48325. 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,
  48326. 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,
  48327. 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,
  48328. 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,
  48329. 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,
  48330. 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,
  48331. 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,
  48332. 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,
  48333. 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,
  48334. 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,
  48335. 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,
  48336. 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,
  48337. 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,
  48338. 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,
  48339. 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,
  48340. 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,
  48341. 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,
  48342. 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};
  48343. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  48344. }
  48345. Image* LookAndFeel::getDefaultDocumentFileImage()
  48346. {
  48347. 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,
  48348. 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,
  48349. 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,
  48350. 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,
  48351. 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,
  48352. 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,
  48353. 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,
  48354. 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,
  48355. 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,
  48356. 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,
  48357. 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,
  48358. 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,
  48359. 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,
  48360. 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,
  48361. 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,
  48362. 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,
  48363. 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,
  48364. 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,
  48365. 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,
  48366. 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,
  48367. 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,
  48368. 174,66,96,130,0,0};
  48369. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  48370. }
  48371. void LookAndFeel::playAlertSound()
  48372. {
  48373. PlatformUtilities::beep();
  48374. }
  48375. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  48376. {
  48377. g.setColour (Colours::white.withAlpha (0.7f));
  48378. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  48379. g.setColour (Colours::black.withAlpha (0.2f));
  48380. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  48381. const int totalBlocks = 7;
  48382. const int numBlocks = roundDoubleToInt (totalBlocks * level);
  48383. const float w = (width - 6.0f) / (float) totalBlocks;
  48384. for (int i = 0; i < totalBlocks; ++i)
  48385. {
  48386. if (i >= numBlocks)
  48387. g.setColour (Colours::lightblue.withAlpha (0.6f));
  48388. else
  48389. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  48390. : Colours::red);
  48391. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  48392. }
  48393. }
  48394. static void createRoundedPath (Path& p,
  48395. const float x, const float y,
  48396. const float w, const float h,
  48397. const float cs,
  48398. const bool curveTopLeft, const bool curveTopRight,
  48399. const bool curveBottomLeft, const bool curveBottomRight) throw()
  48400. {
  48401. const float cs2 = 2.0f * cs;
  48402. if (curveTopLeft)
  48403. {
  48404. p.startNewSubPath (x, y + cs);
  48405. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  48406. }
  48407. else
  48408. {
  48409. p.startNewSubPath (x, y);
  48410. }
  48411. if (curveTopRight)
  48412. {
  48413. p.lineTo (x + w - cs, y);
  48414. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  48415. }
  48416. else
  48417. {
  48418. p.lineTo (x + w, y);
  48419. }
  48420. if (curveBottomRight)
  48421. {
  48422. p.lineTo (x + w, y + h - cs);
  48423. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  48424. }
  48425. else
  48426. {
  48427. p.lineTo (x + w, y + h);
  48428. }
  48429. if (curveBottomLeft)
  48430. {
  48431. p.lineTo (x + cs, y + h);
  48432. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  48433. }
  48434. else
  48435. {
  48436. p.lineTo (x, y + h);
  48437. }
  48438. p.closeSubPath();
  48439. }
  48440. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  48441. float x, float y, float w, float h,
  48442. float maxCornerSize,
  48443. const Colour& baseColour,
  48444. const float strokeWidth,
  48445. const bool flatOnLeft,
  48446. const bool flatOnRight,
  48447. const bool flatOnTop,
  48448. const bool flatOnBottom) throw()
  48449. {
  48450. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  48451. return;
  48452. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  48453. Path outline;
  48454. createRoundedPath (outline, x, y, w, h, cs,
  48455. ! (flatOnLeft || flatOnTop),
  48456. ! (flatOnRight || flatOnTop),
  48457. ! (flatOnLeft || flatOnBottom),
  48458. ! (flatOnRight || flatOnBottom));
  48459. ColourGradient cg (baseColour, 0.0f, y,
  48460. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  48461. false);
  48462. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  48463. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  48464. GradientBrush gb (cg);
  48465. g.setBrush (&gb);
  48466. g.fillPath (outline);
  48467. g.setColour (Colour (0x80000000));
  48468. g.strokePath (outline, PathStrokeType (strokeWidth));
  48469. }
  48470. void LookAndFeel::drawGlassSphere (Graphics& g,
  48471. const float x, const float y,
  48472. const float diameter,
  48473. const Colour& colour,
  48474. const float outlineThickness) throw()
  48475. {
  48476. if (diameter <= outlineThickness)
  48477. return;
  48478. Path p;
  48479. p.addEllipse (x, y, diameter, diameter);
  48480. {
  48481. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  48482. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  48483. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  48484. GradientBrush gb (cg);
  48485. g.setBrush (&gb);
  48486. g.fillPath (p);
  48487. }
  48488. {
  48489. GradientBrush gb (Colours::white, 0, y + diameter * 0.06f,
  48490. Colours::transparentWhite, 0, y + diameter * 0.3f, false);
  48491. g.setBrush (&gb);
  48492. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  48493. }
  48494. {
  48495. ColourGradient cg (Colours::transparentBlack,
  48496. x + diameter * 0.5f, y + diameter * 0.5f,
  48497. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  48498. x, y + diameter * 0.5f, true);
  48499. cg.addColour (0.7, Colours::transparentBlack);
  48500. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  48501. GradientBrush gb (cg);
  48502. g.setBrush (&gb);
  48503. g.fillPath (p);
  48504. }
  48505. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  48506. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  48507. }
  48508. void LookAndFeel::drawGlassPointer (Graphics& g,
  48509. const float x, const float y,
  48510. const float diameter,
  48511. const Colour& colour, const float outlineThickness,
  48512. const int direction) throw()
  48513. {
  48514. if (diameter <= outlineThickness)
  48515. return;
  48516. Path p;
  48517. p.startNewSubPath (x + diameter * 0.5f, y);
  48518. p.lineTo (x + diameter, y + diameter * 0.6f);
  48519. p.lineTo (x + diameter, y + diameter);
  48520. p.lineTo (x, y + diameter);
  48521. p.lineTo (x, y + diameter * 0.6f);
  48522. p.closeSubPath();
  48523. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  48524. {
  48525. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  48526. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  48527. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  48528. GradientBrush gb (cg);
  48529. g.setBrush (&gb);
  48530. g.fillPath (p);
  48531. }
  48532. {
  48533. ColourGradient cg (Colours::transparentBlack,
  48534. x + diameter * 0.5f, y + diameter * 0.5f,
  48535. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  48536. x - diameter * 0.2f, y + diameter * 0.5f, true);
  48537. cg.addColour (0.5, Colours::transparentBlack);
  48538. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  48539. GradientBrush gb (cg);
  48540. g.setBrush (&gb);
  48541. g.fillPath (p);
  48542. }
  48543. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  48544. g.strokePath (p, PathStrokeType (outlineThickness));
  48545. }
  48546. void LookAndFeel::drawGlassLozenge (Graphics& g,
  48547. const float x, const float y,
  48548. const float width, const float height,
  48549. const Colour& colour,
  48550. const float outlineThickness,
  48551. const float cornerSize,
  48552. const bool flatOnLeft,
  48553. const bool flatOnRight,
  48554. const bool flatOnTop,
  48555. const bool flatOnBottom) throw()
  48556. {
  48557. if (width <= outlineThickness || height <= outlineThickness)
  48558. return;
  48559. const int intX = (int) x;
  48560. const int intY = (int) y;
  48561. const int intW = (int) width;
  48562. const int intH = (int) height;
  48563. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  48564. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  48565. const int intEdge = (int) edgeBlurRadius;
  48566. Path outline;
  48567. createRoundedPath (outline, x, y, width, height, cs,
  48568. ! (flatOnLeft || flatOnTop),
  48569. ! (flatOnRight || flatOnTop),
  48570. ! (flatOnLeft || flatOnBottom),
  48571. ! (flatOnRight || flatOnBottom));
  48572. {
  48573. ColourGradient cg (colour.darker (0.2f), 0, y,
  48574. colour.darker (0.2f), 0, y + height, false);
  48575. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  48576. cg.addColour (0.4, colour);
  48577. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  48578. GradientBrush gb (cg);
  48579. g.setBrush (&gb);
  48580. g.fillPath (outline);
  48581. }
  48582. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  48583. colour.darker (0.2f), x, y + height * 0.5f, true);
  48584. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  48585. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  48586. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  48587. {
  48588. GradientBrush gb (cg);
  48589. g.saveState();
  48590. g.setBrush (&gb);
  48591. g.reduceClipRegion (intX, intY, intEdge, intH);
  48592. g.fillPath (outline);
  48593. g.restoreState();
  48594. }
  48595. if (! (flatOnRight || flatOnTop || flatOnBottom))
  48596. {
  48597. cg.x1 = x + width - edgeBlurRadius;
  48598. cg.x2 = x + width;
  48599. GradientBrush gb (cg);
  48600. g.saveState();
  48601. g.setBrush (&gb);
  48602. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  48603. g.fillPath (outline);
  48604. g.restoreState();
  48605. }
  48606. {
  48607. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  48608. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  48609. Path highlight;
  48610. createRoundedPath (highlight,
  48611. x + leftIndent,
  48612. y + cs * 0.1f,
  48613. width - (leftIndent + rightIndent),
  48614. height * 0.4f, cs * 0.4f,
  48615. ! (flatOnLeft || flatOnTop),
  48616. ! (flatOnRight || flatOnTop),
  48617. ! (flatOnLeft || flatOnBottom),
  48618. ! (flatOnRight || flatOnBottom));
  48619. GradientBrush gb (colour.brighter (10.0f), 0, y + height * 0.06f,
  48620. Colours::transparentWhite, 0, y + height * 0.4f, false);
  48621. g.setBrush (&gb);
  48622. g.fillPath (highlight);
  48623. }
  48624. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  48625. g.strokePath (outline, PathStrokeType (outlineThickness));
  48626. }
  48627. END_JUCE_NAMESPACE
  48628. /********* End of inlined file: juce_LookAndFeel.cpp *********/
  48629. /********* Start of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  48630. BEGIN_JUCE_NAMESPACE
  48631. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  48632. {
  48633. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  48634. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  48635. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  48636. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  48637. setColour (Slider::thumbColourId, Colours::white);
  48638. setColour (Slider::trackColourId, Colour (0x7f000000));
  48639. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  48640. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  48641. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  48642. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  48643. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  48644. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  48645. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  48646. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  48647. }
  48648. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  48649. {
  48650. }
  48651. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  48652. Button& button,
  48653. const Colour& backgroundColour,
  48654. bool isMouseOverButton,
  48655. bool isButtonDown)
  48656. {
  48657. const int width = button.getWidth();
  48658. const int height = button.getHeight();
  48659. const float indent = 2.0f;
  48660. const int cornerSize = jmin (roundFloatToInt (width * 0.4f),
  48661. roundFloatToInt (height * 0.4f));
  48662. Path p;
  48663. p.addRoundedRectangle (indent, indent,
  48664. width - indent * 2.0f,
  48665. height - indent * 2.0f,
  48666. (float) cornerSize);
  48667. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  48668. if (isMouseOverButton)
  48669. {
  48670. if (isButtonDown)
  48671. bc = bc.brighter();
  48672. else if (bc.getBrightness() > 0.5f)
  48673. bc = bc.darker (0.1f);
  48674. else
  48675. bc = bc.brighter (0.1f);
  48676. }
  48677. g.setColour (bc);
  48678. g.fillPath (p);
  48679. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  48680. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  48681. }
  48682. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  48683. Component& /*component*/,
  48684. int x, int y, int w, int h,
  48685. const bool ticked,
  48686. const bool isEnabled,
  48687. const bool /*isMouseOverButton*/,
  48688. const bool isButtonDown)
  48689. {
  48690. Path box;
  48691. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  48692. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  48693. : Colours::lightgrey.withAlpha (0.1f));
  48694. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  48695. .translated ((float) x, (float) y));
  48696. g.fillPath (box, trans);
  48697. g.setColour (Colours::black.withAlpha (0.6f));
  48698. g.strokePath (box, PathStrokeType (0.9f), trans);
  48699. if (ticked)
  48700. {
  48701. Path tick;
  48702. tick.startNewSubPath (1.5f, 3.0f);
  48703. tick.lineTo (3.0f, 6.0f);
  48704. tick.lineTo (6.0f, 0.0f);
  48705. g.setColour (isEnabled ? Colours::black : Colours::grey);
  48706. g.strokePath (tick, PathStrokeType (2.5f), trans);
  48707. }
  48708. }
  48709. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  48710. ToggleButton& button,
  48711. bool isMouseOverButton,
  48712. bool isButtonDown)
  48713. {
  48714. if (button.hasKeyboardFocus (true))
  48715. {
  48716. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  48717. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  48718. }
  48719. const int tickWidth = jmin (20, button.getHeight() - 4);
  48720. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  48721. tickWidth, tickWidth,
  48722. button.getToggleState(),
  48723. button.isEnabled(),
  48724. isMouseOverButton,
  48725. isButtonDown);
  48726. g.setColour (button.findColour (ToggleButton::textColourId));
  48727. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  48728. if (! button.isEnabled())
  48729. g.setOpacity (0.5f);
  48730. const int textX = tickWidth + 5;
  48731. g.drawFittedText (button.getButtonText(),
  48732. textX, 4,
  48733. button.getWidth() - textX - 2, button.getHeight() - 8,
  48734. Justification::centredLeft, 10);
  48735. }
  48736. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  48737. int width, int height,
  48738. double progress, const String& textToShow)
  48739. {
  48740. if (progress < 0 || progress >= 1.0)
  48741. {
  48742. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  48743. }
  48744. else
  48745. {
  48746. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  48747. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  48748. g.fillAll (background);
  48749. g.setColour (foreground);
  48750. g.fillRect (1, 1,
  48751. jlimit (0, width - 2, roundDoubleToInt (progress * (width - 2))),
  48752. height - 2);
  48753. if (textToShow.isNotEmpty())
  48754. {
  48755. g.setColour (Colour::contrasting (background, foreground));
  48756. g.setFont (height * 0.6f);
  48757. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  48758. }
  48759. }
  48760. }
  48761. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  48762. ScrollBar& bar,
  48763. int width, int height,
  48764. int buttonDirection,
  48765. bool isScrollbarVertical,
  48766. bool isMouseOverButton,
  48767. bool isButtonDown)
  48768. {
  48769. if (isScrollbarVertical)
  48770. width -= 2;
  48771. else
  48772. height -= 2;
  48773. Path p;
  48774. if (buttonDirection == 0)
  48775. p.addTriangle (width * 0.5f, height * 0.2f,
  48776. width * 0.1f, height * 0.7f,
  48777. width * 0.9f, height * 0.7f);
  48778. else if (buttonDirection == 1)
  48779. p.addTriangle (width * 0.8f, height * 0.5f,
  48780. width * 0.3f, height * 0.1f,
  48781. width * 0.3f, height * 0.9f);
  48782. else if (buttonDirection == 2)
  48783. p.addTriangle (width * 0.5f, height * 0.8f,
  48784. width * 0.1f, height * 0.3f,
  48785. width * 0.9f, height * 0.3f);
  48786. else if (buttonDirection == 3)
  48787. p.addTriangle (width * 0.2f, height * 0.5f,
  48788. width * 0.7f, height * 0.1f,
  48789. width * 0.7f, height * 0.9f);
  48790. if (isButtonDown)
  48791. g.setColour (Colours::white);
  48792. else if (isMouseOverButton)
  48793. g.setColour (Colours::white.withAlpha (0.7f));
  48794. else
  48795. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  48796. g.fillPath (p);
  48797. g.setColour (Colours::black.withAlpha (0.5f));
  48798. g.strokePath (p, PathStrokeType (0.5f));
  48799. }
  48800. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  48801. ScrollBar& bar,
  48802. int x, int y,
  48803. int width, int height,
  48804. bool isScrollbarVertical,
  48805. int thumbStartPosition,
  48806. int thumbSize,
  48807. bool isMouseOver,
  48808. bool isMouseDown)
  48809. {
  48810. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  48811. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  48812. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  48813. if (thumbSize > 0.0f)
  48814. {
  48815. Rectangle thumb;
  48816. if (isScrollbarVertical)
  48817. {
  48818. width -= 2;
  48819. g.fillRect (x + roundFloatToInt (width * 0.35f), y,
  48820. roundFloatToInt (width * 0.3f), height);
  48821. thumb.setBounds (x + 1, thumbStartPosition,
  48822. width - 2, thumbSize);
  48823. }
  48824. else
  48825. {
  48826. height -= 2;
  48827. g.fillRect (x, y + roundFloatToInt (height * 0.35f),
  48828. width, roundFloatToInt (height * 0.3f));
  48829. thumb.setBounds (thumbStartPosition, y + 1,
  48830. thumbSize, height - 2);
  48831. }
  48832. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  48833. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  48834. g.fillRect (thumb);
  48835. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  48836. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  48837. if (thumbSize > 16)
  48838. {
  48839. for (int i = 3; --i >= 0;)
  48840. {
  48841. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  48842. g.setColour (Colours::black.withAlpha (0.15f));
  48843. if (isScrollbarVertical)
  48844. {
  48845. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  48846. g.setColour (Colours::white.withAlpha (0.15f));
  48847. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  48848. }
  48849. else
  48850. {
  48851. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  48852. g.setColour (Colours::white.withAlpha (0.15f));
  48853. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  48854. }
  48855. }
  48856. }
  48857. }
  48858. }
  48859. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  48860. {
  48861. return &scrollbarShadow;
  48862. }
  48863. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  48864. {
  48865. g.fillAll (findColour (PopupMenu::backgroundColourId));
  48866. g.setColour (Colours::black.withAlpha (0.6f));
  48867. g.drawRect (0, 0, width, height);
  48868. }
  48869. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  48870. bool, MenuBarComponent& menuBar)
  48871. {
  48872. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  48873. }
  48874. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  48875. {
  48876. if (textEditor.isEnabled())
  48877. {
  48878. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  48879. g.drawRect (0, 0, width, height);
  48880. }
  48881. }
  48882. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  48883. const bool isButtonDown,
  48884. int buttonX, int buttonY,
  48885. int buttonW, int buttonH,
  48886. ComboBox& box)
  48887. {
  48888. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  48889. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  48890. : ComboBox::backgroundColourId));
  48891. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  48892. g.setColour (box.findColour (ComboBox::outlineColourId));
  48893. g.drawRect (0, 0, width, height);
  48894. const float arrowX = 0.2f;
  48895. const float arrowH = 0.3f;
  48896. if (box.isEnabled())
  48897. {
  48898. Path p;
  48899. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  48900. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  48901. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  48902. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  48903. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  48904. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  48905. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  48906. : ComboBox::buttonColourId));
  48907. g.fillPath (p);
  48908. }
  48909. }
  48910. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  48911. {
  48912. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  48913. f.setHorizontalScale (0.9f);
  48914. return f;
  48915. }
  48916. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  48917. {
  48918. Path p;
  48919. p.addTriangle (x1, y1, x2, y2, x3, y3);
  48920. g.setColour (fill);
  48921. g.fillPath (p);
  48922. g.setColour (outline);
  48923. g.strokePath (p, PathStrokeType (0.3f));
  48924. }
  48925. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  48926. int x, int y,
  48927. int w, int h,
  48928. float sliderPos,
  48929. float minSliderPos,
  48930. float maxSliderPos,
  48931. const Slider::SliderStyle style,
  48932. Slider& slider)
  48933. {
  48934. g.fillAll (slider.findColour (Slider::backgroundColourId));
  48935. if (style == Slider::LinearBar)
  48936. {
  48937. g.setColour (slider.findColour (Slider::thumbColourId));
  48938. g.fillRect (x, y, (int) sliderPos - x, h);
  48939. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  48940. g.drawRect (x, y, (int) sliderPos - x, h);
  48941. }
  48942. else
  48943. {
  48944. g.setColour (slider.findColour (Slider::trackColourId)
  48945. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  48946. if (slider.isHorizontal())
  48947. {
  48948. g.fillRect (x, y + roundFloatToInt (h * 0.6f),
  48949. w, roundFloatToInt (h * 0.2f));
  48950. }
  48951. else
  48952. {
  48953. g.fillRect (x + roundFloatToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  48954. jmin (4, roundFloatToInt (w * 0.2f)), h);
  48955. }
  48956. float alpha = 0.35f;
  48957. if (slider.isEnabled())
  48958. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  48959. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  48960. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  48961. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  48962. {
  48963. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  48964. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  48965. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  48966. fill, outline);
  48967. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  48968. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  48969. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  48970. fill, outline);
  48971. }
  48972. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  48973. {
  48974. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  48975. minSliderPos - 7.0f, y + h * 0.9f ,
  48976. minSliderPos, y + h * 0.9f,
  48977. fill, outline);
  48978. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  48979. maxSliderPos, y + h * 0.9f,
  48980. maxSliderPos + 7.0f, y + h * 0.9f,
  48981. fill, outline);
  48982. }
  48983. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  48984. {
  48985. drawTriangle (g, sliderPos, y + h * 0.9f,
  48986. sliderPos - 7.0f, y + h * 0.2f,
  48987. sliderPos + 7.0f, y + h * 0.2f,
  48988. fill, outline);
  48989. }
  48990. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  48991. {
  48992. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  48993. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  48994. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  48995. fill, outline);
  48996. }
  48997. }
  48998. }
  48999. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  49000. {
  49001. if (isIncrement)
  49002. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  49003. else
  49004. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  49005. }
  49006. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  49007. {
  49008. return &scrollbarShadow;
  49009. }
  49010. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  49011. {
  49012. return 8;
  49013. }
  49014. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  49015. int w, int h,
  49016. bool isMouseOver,
  49017. bool isMouseDragging)
  49018. {
  49019. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  49020. : Colours::darkgrey);
  49021. const float lineThickness = jmin (w, h) * 0.1f;
  49022. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  49023. {
  49024. g.drawLine (w * i,
  49025. h + 1.0f,
  49026. w + 1.0f,
  49027. h * i,
  49028. lineThickness);
  49029. }
  49030. }
  49031. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  49032. {
  49033. Path shape;
  49034. if (buttonType == DocumentWindow::closeButton)
  49035. {
  49036. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, 0.35f);
  49037. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, 0.35f);
  49038. ShapeButton* const b = new ShapeButton ("close",
  49039. Colour (0x7fff3333),
  49040. Colour (0xd7ff3333),
  49041. Colour (0xf7ff3333));
  49042. b->setShape (shape, true, true, true);
  49043. return b;
  49044. }
  49045. else if (buttonType == DocumentWindow::minimiseButton)
  49046. {
  49047. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  49048. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  49049. DrawablePath dp;
  49050. dp.setPath (shape);
  49051. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  49052. b->setImages (&dp);
  49053. return b;
  49054. }
  49055. else if (buttonType == DocumentWindow::maximiseButton)
  49056. {
  49057. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, 0.25f);
  49058. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  49059. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  49060. DrawablePath dp;
  49061. dp.setPath (shape);
  49062. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  49063. b->setImages (&dp);
  49064. return b;
  49065. }
  49066. jassertfalse
  49067. return 0;
  49068. }
  49069. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  49070. int titleBarX,
  49071. int titleBarY,
  49072. int titleBarW,
  49073. int titleBarH,
  49074. Button* minimiseButton,
  49075. Button* maximiseButton,
  49076. Button* closeButton,
  49077. bool positionTitleBarButtonsOnLeft)
  49078. {
  49079. titleBarY += titleBarH / 8;
  49080. titleBarH -= titleBarH / 4;
  49081. const int buttonW = titleBarH;
  49082. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  49083. : titleBarX + titleBarW - buttonW - 4;
  49084. if (closeButton != 0)
  49085. {
  49086. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  49087. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  49088. : -(buttonW + buttonW / 5);
  49089. }
  49090. if (positionTitleBarButtonsOnLeft)
  49091. swapVariables (minimiseButton, maximiseButton);
  49092. if (maximiseButton != 0)
  49093. {
  49094. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  49095. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  49096. }
  49097. if (minimiseButton != 0)
  49098. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  49099. }
  49100. END_JUCE_NAMESPACE
  49101. /********* End of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  49102. /********* Start of inlined file: juce_MenuBarComponent.cpp *********/
  49103. BEGIN_JUCE_NAMESPACE
  49104. class DummyMenuComponent : public Component
  49105. {
  49106. DummyMenuComponent (const DummyMenuComponent&);
  49107. const DummyMenuComponent& operator= (const DummyMenuComponent&);
  49108. public:
  49109. DummyMenuComponent() {}
  49110. ~DummyMenuComponent() {}
  49111. void inputAttemptWhenModal()
  49112. {
  49113. exitModalState (0);
  49114. }
  49115. };
  49116. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  49117. : model (0),
  49118. itemUnderMouse (-1),
  49119. currentPopupIndex (-1),
  49120. indexToShowAgain (-1),
  49121. lastMouseX (0),
  49122. lastMouseY (0),
  49123. inModalState (false),
  49124. currentPopup (0)
  49125. {
  49126. setRepaintsOnMouseActivity (true);
  49127. setWantsKeyboardFocus (false);
  49128. setMouseClickGrabsKeyboardFocus (false);
  49129. setModel (model_);
  49130. }
  49131. MenuBarComponent::~MenuBarComponent()
  49132. {
  49133. setModel (0);
  49134. Desktop::getInstance().removeGlobalMouseListener (this);
  49135. deleteAndZero (currentPopup);
  49136. }
  49137. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  49138. {
  49139. if (model != newModel)
  49140. {
  49141. if (model != 0)
  49142. model->removeListener (this);
  49143. model = newModel;
  49144. if (model != 0)
  49145. model->addListener (this);
  49146. repaint();
  49147. menuBarItemsChanged (0);
  49148. }
  49149. }
  49150. void MenuBarComponent::paint (Graphics& g)
  49151. {
  49152. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  49153. getLookAndFeel().drawMenuBarBackground (g,
  49154. getWidth(),
  49155. getHeight(),
  49156. isMouseOverBar,
  49157. *this);
  49158. if (model != 0)
  49159. {
  49160. for (int i = 0; i < menuNames.size(); ++i)
  49161. {
  49162. g.saveState();
  49163. g.setOrigin (xPositions [i], 0);
  49164. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  49165. getLookAndFeel().drawMenuBarItem (g,
  49166. xPositions[i + 1] - xPositions[i],
  49167. getHeight(),
  49168. i,
  49169. menuNames[i],
  49170. i == itemUnderMouse,
  49171. i == currentPopupIndex,
  49172. isMouseOverBar,
  49173. *this);
  49174. g.restoreState();
  49175. }
  49176. }
  49177. }
  49178. void MenuBarComponent::resized()
  49179. {
  49180. xPositions.clear();
  49181. int x = 2;
  49182. xPositions.add (x);
  49183. for (int i = 0; i < menuNames.size(); ++i)
  49184. {
  49185. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  49186. xPositions.add (x);
  49187. }
  49188. }
  49189. int MenuBarComponent::getItemAt (const int x, const int y)
  49190. {
  49191. for (int i = 0; i < xPositions.size(); ++i)
  49192. if (x >= xPositions[i] && x < xPositions[i + 1])
  49193. return reallyContains (x, y, true) ? i : -1;
  49194. return -1;
  49195. }
  49196. void MenuBarComponent::repaintMenuItem (int index)
  49197. {
  49198. if (((unsigned int) index) < (unsigned int) xPositions.size())
  49199. {
  49200. const int x1 = xPositions [index];
  49201. const int x2 = xPositions [index + 1];
  49202. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  49203. }
  49204. }
  49205. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  49206. {
  49207. const int newItem = getItemAt (x, y);
  49208. if (itemUnderMouse != newItem)
  49209. {
  49210. repaintMenuItem (itemUnderMouse);
  49211. itemUnderMouse = newItem;
  49212. repaintMenuItem (itemUnderMouse);
  49213. }
  49214. }
  49215. void MenuBarComponent::hideCurrentMenu()
  49216. {
  49217. deleteAndZero (currentPopup);
  49218. repaint();
  49219. }
  49220. void MenuBarComponent::showMenu (int index)
  49221. {
  49222. if (index != currentPopupIndex)
  49223. {
  49224. if (inModalState)
  49225. {
  49226. hideCurrentMenu();
  49227. indexToShowAgain = index;
  49228. return;
  49229. }
  49230. indexToShowAgain = -1;
  49231. currentPopupIndex = -1;
  49232. itemUnderMouse = index;
  49233. deleteAndZero (currentPopup);
  49234. menuBarItemsChanged (0);
  49235. Component* const prevFocused = getCurrentlyFocusedComponent();
  49236. ComponentDeletionWatcher* prevCompDeletionChecker = 0;
  49237. if (prevFocused != 0)
  49238. prevCompDeletionChecker = new ComponentDeletionWatcher (prevFocused);
  49239. ComponentDeletionWatcher deletionChecker (this);
  49240. enterModalState (false);
  49241. inModalState = true;
  49242. int result = 0;
  49243. ApplicationCommandManager* managerOfChosenCommand = 0;
  49244. Desktop::getInstance().addGlobalMouseListener (this);
  49245. for (;;)
  49246. {
  49247. const int x = getScreenX() + xPositions [itemUnderMouse];
  49248. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  49249. currentPopupIndex = itemUnderMouse;
  49250. indexToShowAgain = -1;
  49251. repaint();
  49252. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  49253. {
  49254. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  49255. menuNames [itemUnderMouse]));
  49256. currentPopup = m.createMenuComponent (x, getScreenY(),
  49257. w, getHeight(),
  49258. 0, w, 0, 0,
  49259. true, this,
  49260. &managerOfChosenCommand,
  49261. this);
  49262. }
  49263. if (currentPopup == 0)
  49264. {
  49265. currentPopup = new DummyMenuComponent();
  49266. addAndMakeVisible (currentPopup);
  49267. }
  49268. currentPopup->enterModalState (false);
  49269. currentPopup->toFront (false); // need to do this after making it modal, or it could
  49270. // be stuck behind other comps that are already modal..
  49271. result = currentPopup->runModalLoop();
  49272. if (deletionChecker.hasBeenDeleted())
  49273. {
  49274. delete prevCompDeletionChecker;
  49275. return;
  49276. }
  49277. const int lastPopupIndex = currentPopupIndex;
  49278. deleteAndZero (currentPopup);
  49279. currentPopupIndex = -1;
  49280. if (result != 0)
  49281. {
  49282. topLevelIndexClicked = lastPopupIndex;
  49283. break;
  49284. }
  49285. else if (indexToShowAgain >= 0)
  49286. {
  49287. menuBarItemsChanged (0);
  49288. repaint();
  49289. itemUnderMouse = indexToShowAgain;
  49290. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  49291. break;
  49292. }
  49293. else
  49294. {
  49295. break;
  49296. }
  49297. }
  49298. Desktop::getInstance().removeGlobalMouseListener (this);
  49299. inModalState = false;
  49300. exitModalState (0);
  49301. if (prevCompDeletionChecker != 0)
  49302. {
  49303. if (! prevCompDeletionChecker->hasBeenDeleted())
  49304. prevFocused->grabKeyboardFocus();
  49305. delete prevCompDeletionChecker;
  49306. }
  49307. int mx, my;
  49308. getMouseXYRelative (mx, my);
  49309. updateItemUnderMouse (mx, my);
  49310. repaint();
  49311. if (result != 0)
  49312. {
  49313. if (managerOfChosenCommand != 0)
  49314. {
  49315. ApplicationCommandTarget::InvocationInfo info (result);
  49316. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  49317. managerOfChosenCommand->invoke (info, true);
  49318. }
  49319. postCommandMessage (result);
  49320. }
  49321. }
  49322. }
  49323. void MenuBarComponent::handleCommandMessage (int commandId)
  49324. {
  49325. if (model != 0)
  49326. model->menuItemSelected (commandId, topLevelIndexClicked);
  49327. }
  49328. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  49329. {
  49330. if (e.eventComponent == this)
  49331. updateItemUnderMouse (e.x, e.y);
  49332. }
  49333. void MenuBarComponent::mouseExit (const MouseEvent& e)
  49334. {
  49335. if (e.eventComponent == this)
  49336. updateItemUnderMouse (e.x, e.y);
  49337. }
  49338. void MenuBarComponent::mouseDown (const MouseEvent& e)
  49339. {
  49340. const MouseEvent e2 (e.getEventRelativeTo (this));
  49341. if (currentPopupIndex < 0)
  49342. {
  49343. updateItemUnderMouse (e2.x, e2.y);
  49344. currentPopupIndex = -2;
  49345. showMenu (itemUnderMouse);
  49346. }
  49347. }
  49348. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  49349. {
  49350. const MouseEvent e2 (e.getEventRelativeTo (this));
  49351. const int item = getItemAt (e2.x, e2.y);
  49352. if (item >= 0)
  49353. showMenu (item);
  49354. }
  49355. void MenuBarComponent::mouseUp (const MouseEvent& e)
  49356. {
  49357. const MouseEvent e2 (e.getEventRelativeTo (this));
  49358. updateItemUnderMouse (e2.x, e2.y);
  49359. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (currentPopup) != 0)
  49360. hideCurrentMenu();
  49361. }
  49362. void MenuBarComponent::mouseMove (const MouseEvent& e)
  49363. {
  49364. const MouseEvent e2 (e.getEventRelativeTo (this));
  49365. if (lastMouseX != e2.x || lastMouseY != e2.y)
  49366. {
  49367. if (currentPopupIndex >= 0)
  49368. {
  49369. const int item = getItemAt (e2.x, e2.y);
  49370. if (item >= 0)
  49371. showMenu (item);
  49372. }
  49373. else
  49374. {
  49375. updateItemUnderMouse (e2.x, e2.y);
  49376. }
  49377. lastMouseX = e2.x;
  49378. lastMouseY = e2.y;
  49379. }
  49380. }
  49381. bool MenuBarComponent::keyPressed (const KeyPress& key)
  49382. {
  49383. bool used = false;
  49384. const int numMenus = menuNames.size();
  49385. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  49386. if (key.isKeyCode (KeyPress::leftKey))
  49387. {
  49388. showMenu ((currentIndex + numMenus - 1) % numMenus);
  49389. used = true;
  49390. }
  49391. else if (key.isKeyCode (KeyPress::rightKey))
  49392. {
  49393. showMenu ((currentIndex + 1) % numMenus);
  49394. used = true;
  49395. }
  49396. return used;
  49397. }
  49398. void MenuBarComponent::inputAttemptWhenModal()
  49399. {
  49400. hideCurrentMenu();
  49401. }
  49402. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  49403. {
  49404. StringArray newNames;
  49405. if (model != 0)
  49406. newNames = model->getMenuBarNames();
  49407. if (newNames != menuNames)
  49408. {
  49409. menuNames = newNames;
  49410. repaint();
  49411. resized();
  49412. }
  49413. }
  49414. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  49415. const ApplicationCommandTarget::InvocationInfo& info)
  49416. {
  49417. if (model == 0
  49418. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  49419. return;
  49420. for (int i = 0; i < menuNames.size(); ++i)
  49421. {
  49422. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  49423. if (menu.containsCommandItem (info.commandID))
  49424. {
  49425. itemUnderMouse = i;
  49426. repaintMenuItem (i);
  49427. startTimer (200);
  49428. break;
  49429. }
  49430. }
  49431. }
  49432. void MenuBarComponent::timerCallback()
  49433. {
  49434. stopTimer();
  49435. int mx, my;
  49436. getMouseXYRelative (mx, my);
  49437. updateItemUnderMouse (mx, my);
  49438. }
  49439. END_JUCE_NAMESPACE
  49440. /********* End of inlined file: juce_MenuBarComponent.cpp *********/
  49441. /********* Start of inlined file: juce_MenuBarModel.cpp *********/
  49442. BEGIN_JUCE_NAMESPACE
  49443. MenuBarModel::MenuBarModel() throw()
  49444. : manager (0)
  49445. {
  49446. }
  49447. MenuBarModel::~MenuBarModel()
  49448. {
  49449. setApplicationCommandManagerToWatch (0);
  49450. }
  49451. void MenuBarModel::menuItemsChanged()
  49452. {
  49453. triggerAsyncUpdate();
  49454. }
  49455. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  49456. {
  49457. if (manager != newManager)
  49458. {
  49459. if (manager != 0)
  49460. manager->removeListener (this);
  49461. manager = newManager;
  49462. if (manager != 0)
  49463. manager->addListener (this);
  49464. }
  49465. }
  49466. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  49467. {
  49468. jassert (newListener != 0);
  49469. jassert (! listeners.contains (newListener)); // trying to add a listener to the list twice!
  49470. if (newListener != 0)
  49471. listeners.add (newListener);
  49472. }
  49473. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  49474. {
  49475. // Trying to remove a listener that isn't on the list!
  49476. // If this assertion happens because this object is a dangling pointer, make sure you've not
  49477. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  49478. jassert (listeners.contains (listenerToRemove));
  49479. listeners.removeValue (listenerToRemove);
  49480. }
  49481. void MenuBarModel::handleAsyncUpdate()
  49482. {
  49483. for (int i = listeners.size(); --i >= 0;)
  49484. {
  49485. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuBarItemsChanged (this);
  49486. i = jmin (i, listeners.size());
  49487. }
  49488. }
  49489. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  49490. {
  49491. for (int i = listeners.size(); --i >= 0;)
  49492. {
  49493. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuCommandInvoked (this, info);
  49494. i = jmin (i, listeners.size());
  49495. }
  49496. }
  49497. void MenuBarModel::applicationCommandListChanged()
  49498. {
  49499. menuItemsChanged();
  49500. }
  49501. END_JUCE_NAMESPACE
  49502. /********* End of inlined file: juce_MenuBarModel.cpp *********/
  49503. /********* Start of inlined file: juce_PopupMenu.cpp *********/
  49504. BEGIN_JUCE_NAMESPACE
  49505. static VoidArray activeMenuWindows;
  49506. class MenuItemInfo
  49507. {
  49508. public:
  49509. const int itemId;
  49510. String text;
  49511. const Colour textColour;
  49512. const bool active, isSeparator, isTicked, usesColour;
  49513. Image* image;
  49514. PopupMenuCustomComponent* const customComp;
  49515. PopupMenu* subMenu;
  49516. ApplicationCommandManager* const commandManager;
  49517. MenuItemInfo() throw()
  49518. : itemId (0),
  49519. active (true),
  49520. isSeparator (true),
  49521. isTicked (false),
  49522. usesColour (false),
  49523. image (0),
  49524. customComp (0),
  49525. subMenu (0),
  49526. commandManager (0)
  49527. {
  49528. }
  49529. MenuItemInfo (const int itemId_,
  49530. const String& text_,
  49531. const bool active_,
  49532. const bool isTicked_,
  49533. const Image* im,
  49534. const Colour& textColour_,
  49535. const bool usesColour_,
  49536. PopupMenuCustomComponent* const customComp_,
  49537. const PopupMenu* const subMenu_,
  49538. ApplicationCommandManager* const commandManager_) throw()
  49539. : itemId (itemId_),
  49540. text (text_),
  49541. textColour (textColour_),
  49542. active (active_),
  49543. isSeparator (false),
  49544. isTicked (isTicked_),
  49545. usesColour (usesColour_),
  49546. image (0),
  49547. customComp (customComp_),
  49548. commandManager (commandManager_)
  49549. {
  49550. subMenu = (subMenu_ != 0) ? new PopupMenu (*subMenu_) : 0;
  49551. if (customComp != 0)
  49552. customComp->refCount_++;
  49553. if (im != 0)
  49554. image = im->createCopy();
  49555. if (commandManager_ != 0 && itemId_ != 0)
  49556. {
  49557. String shortcutKey;
  49558. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  49559. ->getKeyPressesAssignedToCommand (itemId_));
  49560. for (int i = 0; i < keyPresses.size(); ++i)
  49561. {
  49562. const String key (keyPresses.getReference(i).getTextDescription());
  49563. if (shortcutKey.isNotEmpty())
  49564. shortcutKey << ", ";
  49565. if (key.length() == 1)
  49566. shortcutKey << "shortcut: '" << key << '\'';
  49567. else
  49568. shortcutKey << key;
  49569. }
  49570. shortcutKey = shortcutKey.trim();
  49571. if (shortcutKey.isNotEmpty())
  49572. text << "<end>" << shortcutKey;
  49573. }
  49574. }
  49575. MenuItemInfo (const MenuItemInfo& other) throw()
  49576. : itemId (other.itemId),
  49577. text (other.text),
  49578. textColour (other.textColour),
  49579. active (other.active),
  49580. isSeparator (other.isSeparator),
  49581. isTicked (other.isTicked),
  49582. usesColour (other.usesColour),
  49583. customComp (other.customComp),
  49584. commandManager (other.commandManager)
  49585. {
  49586. if (other.subMenu != 0)
  49587. subMenu = new PopupMenu (*(other.subMenu));
  49588. else
  49589. subMenu = 0;
  49590. if (other.image != 0)
  49591. image = other.image->createCopy();
  49592. else
  49593. image = 0;
  49594. if (customComp != 0)
  49595. customComp->refCount_++;
  49596. }
  49597. ~MenuItemInfo() throw()
  49598. {
  49599. delete subMenu;
  49600. delete image;
  49601. if (customComp != 0 && --(customComp->refCount_) == 0)
  49602. delete customComp;
  49603. }
  49604. bool canBeTriggered() const throw()
  49605. {
  49606. return active && ! (isSeparator || (subMenu != 0));
  49607. }
  49608. bool hasActiveSubMenu() const throw()
  49609. {
  49610. return active && (subMenu != 0);
  49611. }
  49612. juce_UseDebuggingNewOperator
  49613. private:
  49614. const MenuItemInfo& operator= (const MenuItemInfo&);
  49615. };
  49616. class MenuItemComponent : public Component
  49617. {
  49618. bool isHighlighted;
  49619. public:
  49620. MenuItemInfo itemInfo;
  49621. MenuItemComponent (const MenuItemInfo& itemInfo_)
  49622. : isHighlighted (false),
  49623. itemInfo (itemInfo_)
  49624. {
  49625. if (itemInfo.customComp != 0)
  49626. addAndMakeVisible (itemInfo.customComp);
  49627. }
  49628. ~MenuItemComponent()
  49629. {
  49630. if (itemInfo.customComp != 0)
  49631. removeChildComponent (itemInfo.customComp);
  49632. }
  49633. void getIdealSize (int& idealWidth,
  49634. int& idealHeight,
  49635. const int standardItemHeight)
  49636. {
  49637. if (itemInfo.customComp != 0)
  49638. {
  49639. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  49640. }
  49641. else
  49642. {
  49643. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  49644. itemInfo.isSeparator,
  49645. standardItemHeight,
  49646. idealWidth,
  49647. idealHeight);
  49648. }
  49649. }
  49650. void paint (Graphics& g)
  49651. {
  49652. if (itemInfo.customComp == 0)
  49653. {
  49654. String mainText (itemInfo.text);
  49655. String endText;
  49656. const int endIndex = mainText.indexOf (T("<end>"));
  49657. if (endIndex >= 0)
  49658. {
  49659. endText = mainText.substring (endIndex + 5).trim();
  49660. mainText = mainText.substring (0, endIndex);
  49661. }
  49662. getLookAndFeel()
  49663. .drawPopupMenuItem (g, getWidth(), getHeight(),
  49664. itemInfo.isSeparator,
  49665. itemInfo.active,
  49666. isHighlighted,
  49667. itemInfo.isTicked,
  49668. itemInfo.subMenu != 0,
  49669. mainText, endText,
  49670. itemInfo.image,
  49671. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  49672. }
  49673. }
  49674. void resized()
  49675. {
  49676. if (getNumChildComponents() > 0)
  49677. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  49678. }
  49679. void setHighlighted (bool shouldBeHighlighted)
  49680. {
  49681. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  49682. if (isHighlighted != shouldBeHighlighted)
  49683. {
  49684. isHighlighted = shouldBeHighlighted;
  49685. if (itemInfo.customComp != 0)
  49686. {
  49687. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  49688. itemInfo.customComp->repaint();
  49689. }
  49690. repaint();
  49691. }
  49692. }
  49693. private:
  49694. MenuItemComponent (const MenuItemComponent&);
  49695. const MenuItemComponent& operator= (const MenuItemComponent&);
  49696. };
  49697. static const int scrollZone = 24;
  49698. static const int borderSize = 2;
  49699. static const int timerInterval = 50;
  49700. static const int dismissCommandId = 0x6287345f;
  49701. static bool wasHiddenBecauseOfAppChange = false;
  49702. class PopupMenuWindow : public Component,
  49703. private Timer
  49704. {
  49705. public:
  49706. PopupMenuWindow() throw()
  49707. : Component (T("menu")),
  49708. owner (0),
  49709. currentChild (0),
  49710. activeSubMenu (0),
  49711. menuBarComponent (0),
  49712. managerOfChosenCommand (0),
  49713. componentAttachedTo (0),
  49714. attachedCompWatcher (0),
  49715. lastMouseX (0),
  49716. lastMouseY (0),
  49717. minimumWidth (0),
  49718. maximumNumColumns (7),
  49719. standardItemHeight (0),
  49720. isOver (false),
  49721. hasBeenOver (false),
  49722. isDown (false),
  49723. needsToScroll (false),
  49724. hideOnExit (false),
  49725. disableMouseMoves (false),
  49726. hasAnyJuceCompHadFocus (false),
  49727. numColumns (0),
  49728. contentHeight (0),
  49729. childYOffset (0),
  49730. timeEnteredCurrentChildComp (0),
  49731. scrollAcceleration (1.0)
  49732. {
  49733. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  49734. setWantsKeyboardFocus (true);
  49735. setOpaque (true);
  49736. setAlwaysOnTop (true);
  49737. Desktop::getInstance().addGlobalMouseListener (this);
  49738. activeMenuWindows.add (this);
  49739. }
  49740. ~PopupMenuWindow()
  49741. {
  49742. activeMenuWindows.removeValue (this);
  49743. Desktop::getInstance().removeGlobalMouseListener (this);
  49744. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49745. delete activeSubMenu;
  49746. deleteAllChildren();
  49747. delete attachedCompWatcher;
  49748. }
  49749. static PopupMenuWindow* create (const PopupMenu& menu,
  49750. const bool dismissOnMouseUp,
  49751. PopupMenuWindow* const owner_,
  49752. const int minX, const int maxX,
  49753. const int minY, const int maxY,
  49754. const int minimumWidth,
  49755. const int maximumNumColumns,
  49756. const int standardItemHeight,
  49757. const bool alignToRectangle,
  49758. const int itemIdThatMustBeVisible,
  49759. Component* const menuBarComponent,
  49760. ApplicationCommandManager** managerOfChosenCommand,
  49761. Component* const componentAttachedTo) throw()
  49762. {
  49763. if (menu.items.size() > 0)
  49764. {
  49765. int totalItems = 0;
  49766. PopupMenuWindow* const mw = new PopupMenuWindow();
  49767. mw->setLookAndFeel (menu.lookAndFeel);
  49768. mw->setWantsKeyboardFocus (false);
  49769. mw->minimumWidth = minimumWidth;
  49770. mw->maximumNumColumns = maximumNumColumns;
  49771. mw->standardItemHeight = standardItemHeight;
  49772. mw->dismissOnMouseUp = dismissOnMouseUp;
  49773. for (int i = 0; i < menu.items.size(); ++i)
  49774. {
  49775. MenuItemInfo* const item = (MenuItemInfo*) menu.items.getUnchecked(i);
  49776. mw->addItem (*item);
  49777. ++totalItems;
  49778. }
  49779. if (totalItems == 0)
  49780. {
  49781. delete mw;
  49782. }
  49783. else
  49784. {
  49785. mw->owner = owner_;
  49786. mw->menuBarComponent = menuBarComponent;
  49787. mw->managerOfChosenCommand = managerOfChosenCommand;
  49788. mw->componentAttachedTo = componentAttachedTo;
  49789. delete mw->attachedCompWatcher;
  49790. mw->attachedCompWatcher = componentAttachedTo != 0 ? new ComponentDeletionWatcher (componentAttachedTo) : 0;
  49791. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  49792. mw->setTopLeftPosition (mw->windowPos.getX(),
  49793. mw->windowPos.getY());
  49794. mw->updateYPositions();
  49795. if (itemIdThatMustBeVisible != 0)
  49796. {
  49797. const int y = minY - mw->windowPos.getY();
  49798. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  49799. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  49800. }
  49801. mw->resizeToBestWindowPos();
  49802. mw->addToDesktop (ComponentPeer::windowIsTemporary
  49803. | mw->getLookAndFeel().getMenuWindowFlags());
  49804. return mw;
  49805. }
  49806. }
  49807. return 0;
  49808. }
  49809. void paint (Graphics& g)
  49810. {
  49811. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  49812. }
  49813. void paintOverChildren (Graphics& g)
  49814. {
  49815. if (isScrolling())
  49816. {
  49817. LookAndFeel& lf = getLookAndFeel();
  49818. if (isScrollZoneActive (false))
  49819. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, true);
  49820. if (isScrollZoneActive (true))
  49821. {
  49822. g.setOrigin (0, getHeight() - scrollZone);
  49823. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, false);
  49824. }
  49825. }
  49826. }
  49827. bool isScrollZoneActive (bool bottomOne) const
  49828. {
  49829. return isScrolling()
  49830. && (bottomOne
  49831. ? childYOffset < contentHeight - windowPos.getHeight()
  49832. : childYOffset > 0);
  49833. }
  49834. void addItem (const MenuItemInfo& item) throw()
  49835. {
  49836. MenuItemComponent* const mic = new MenuItemComponent (item);
  49837. addAndMakeVisible (mic);
  49838. int itemW = 80;
  49839. int itemH = 16;
  49840. mic->getIdealSize (itemW, itemH, standardItemHeight);
  49841. mic->setSize (itemW, jlimit (10, 600, itemH));
  49842. mic->addMouseListener (this, false);
  49843. }
  49844. // hide this and all sub-comps
  49845. void hide (const MenuItemInfo* const item) throw()
  49846. {
  49847. if (isVisible())
  49848. {
  49849. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49850. deleteAndZero (activeSubMenu);
  49851. currentChild = 0;
  49852. exitModalState (item != 0 ? item->itemId : 0);
  49853. setVisible (false);
  49854. if (item != 0
  49855. && item->commandManager != 0
  49856. && item->itemId != 0)
  49857. {
  49858. *managerOfChosenCommand = item->commandManager;
  49859. }
  49860. }
  49861. }
  49862. void dismissMenu (const MenuItemInfo* const item) throw()
  49863. {
  49864. if (owner != 0)
  49865. {
  49866. owner->dismissMenu (item);
  49867. }
  49868. else
  49869. {
  49870. if (item != 0)
  49871. {
  49872. // need a copy of this on the stack as the one passed in will get deleted during this call
  49873. const MenuItemInfo mi (*item);
  49874. hide (&mi);
  49875. }
  49876. else
  49877. {
  49878. hide (0);
  49879. }
  49880. }
  49881. }
  49882. void mouseMove (const MouseEvent&)
  49883. {
  49884. timerCallback();
  49885. }
  49886. void mouseDown (const MouseEvent&)
  49887. {
  49888. timerCallback();
  49889. }
  49890. void mouseDrag (const MouseEvent&)
  49891. {
  49892. timerCallback();
  49893. }
  49894. void mouseUp (const MouseEvent&)
  49895. {
  49896. timerCallback();
  49897. }
  49898. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  49899. {
  49900. alterChildYPos (roundFloatToInt (-10.0f * amountY * scrollZone));
  49901. lastMouseX = -1;
  49902. }
  49903. bool keyPressed (const KeyPress& key)
  49904. {
  49905. if (key.isKeyCode (KeyPress::downKey))
  49906. {
  49907. selectNextItem (1);
  49908. }
  49909. else if (key.isKeyCode (KeyPress::upKey))
  49910. {
  49911. selectNextItem (-1);
  49912. }
  49913. else if (key.isKeyCode (KeyPress::leftKey))
  49914. {
  49915. PopupMenuWindow* parentWindow = owner;
  49916. if (parentWindow != 0)
  49917. {
  49918. MenuItemComponent* currentChildOfParent
  49919. = (parentWindow != 0) ? parentWindow->currentChild : 0;
  49920. hide (0);
  49921. if (parentWindow->isValidComponent())
  49922. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  49923. disableTimerUntilMouseMoves();
  49924. }
  49925. else if (menuBarComponent != 0)
  49926. {
  49927. menuBarComponent->keyPressed (key);
  49928. }
  49929. }
  49930. else if (key.isKeyCode (KeyPress::rightKey))
  49931. {
  49932. disableTimerUntilMouseMoves();
  49933. if (showSubMenuFor (currentChild))
  49934. {
  49935. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49936. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  49937. activeSubMenu->selectNextItem (1);
  49938. }
  49939. else if (menuBarComponent != 0)
  49940. {
  49941. menuBarComponent->keyPressed (key);
  49942. }
  49943. }
  49944. else if (key.isKeyCode (KeyPress::returnKey))
  49945. {
  49946. triggerCurrentlyHighlightedItem();
  49947. }
  49948. else if (key.isKeyCode (KeyPress::escapeKey))
  49949. {
  49950. dismissMenu (0);
  49951. }
  49952. else
  49953. {
  49954. return false;
  49955. }
  49956. return true;
  49957. }
  49958. void inputAttemptWhenModal()
  49959. {
  49960. timerCallback();
  49961. if (! isOverAnyMenu())
  49962. {
  49963. if (componentAttachedTo != 0 && ! attachedCompWatcher->hasBeenDeleted())
  49964. {
  49965. // we want to dismiss the menu, but if we do it synchronously, then
  49966. // the mouse-click will be allowed to pass through. That's good, except
  49967. // when the user clicks on the button that orginally popped the menu up,
  49968. // as they'll expect the menu to go away, and in fact it'll just
  49969. // come back. So only dismiss synchronously if they're not on the original
  49970. // comp that we're attached to.
  49971. int mx, my;
  49972. componentAttachedTo->getMouseXYRelative (mx, my);
  49973. if (componentAttachedTo->reallyContains (mx, my, true))
  49974. {
  49975. postCommandMessage (dismissCommandId); // dismiss asynchrounously
  49976. return;
  49977. }
  49978. }
  49979. dismissMenu (0);
  49980. }
  49981. }
  49982. void handleCommandMessage (int commandId)
  49983. {
  49984. Component::handleCommandMessage (commandId);
  49985. if (commandId == dismissCommandId)
  49986. dismissMenu (0);
  49987. }
  49988. void timerCallback()
  49989. {
  49990. if (! isVisible())
  49991. return;
  49992. if (attachedCompWatcher != 0 && attachedCompWatcher->hasBeenDeleted())
  49993. {
  49994. dismissMenu (0);
  49995. return;
  49996. }
  49997. PopupMenuWindow* currentlyModalWindow = dynamic_cast <PopupMenuWindow*> (Component::getCurrentlyModalComponent());
  49998. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  49999. return;
  50000. startTimer (timerInterval); // do this in case it was called from a mouse
  50001. // move rather than a real timer callback
  50002. int mx, my;
  50003. Desktop::getMousePosition (mx, my);
  50004. int x = mx, y = my;
  50005. globalPositionToRelative (x, y);
  50006. const uint32 now = Time::getMillisecondCounter();
  50007. if (now > timeEnteredCurrentChildComp + 100
  50008. && reallyContains (x, y, true)
  50009. && currentChild->isValidComponent()
  50010. && (! disableMouseMoves)
  50011. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  50012. {
  50013. showSubMenuFor (currentChild);
  50014. }
  50015. if (mx != lastMouseX || my != lastMouseY || now > lastMouseMoveTime + 350)
  50016. {
  50017. highlightItemUnderMouse (mx, my, x, y);
  50018. }
  50019. bool overScrollArea = false;
  50020. if (isScrolling()
  50021. && (isOver || (isDown && ((unsigned int) x) < (unsigned int) getWidth()))
  50022. && ((isScrollZoneActive (false) && y < scrollZone)
  50023. || (isScrollZoneActive (true) && y > getHeight() - scrollZone)))
  50024. {
  50025. if (now > lastScroll + 20)
  50026. {
  50027. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  50028. int amount = 0;
  50029. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  50030. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  50031. alterChildYPos (y < scrollZone ? -amount : amount);
  50032. lastScroll = now;
  50033. }
  50034. overScrollArea = true;
  50035. lastMouseX = -1; // trigger a mouse-move
  50036. }
  50037. else
  50038. {
  50039. scrollAcceleration = 1.0;
  50040. }
  50041. const bool wasDown = isDown;
  50042. bool isOverAny = isOverAnyMenu();
  50043. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  50044. {
  50045. activeSubMenu->updateMouseOverStatus (mx, my);
  50046. isOverAny = isOverAnyMenu();
  50047. }
  50048. if (hideOnExit && hasBeenOver && ! isOverAny)
  50049. {
  50050. hide (0);
  50051. }
  50052. else
  50053. {
  50054. isDown = hasBeenOver
  50055. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  50056. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  50057. bool anyFocused = Process::isForegroundProcess();
  50058. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  50059. {
  50060. // because no component at all may have focus, our test here will
  50061. // only be triggered when something has focus and then loses it.
  50062. anyFocused = ! hasAnyJuceCompHadFocus;
  50063. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  50064. {
  50065. if (ComponentPeer::getPeer (i)->isFocused())
  50066. {
  50067. anyFocused = true;
  50068. hasAnyJuceCompHadFocus = true;
  50069. break;
  50070. }
  50071. }
  50072. }
  50073. if (! anyFocused)
  50074. {
  50075. if (now > lastFocused + 10)
  50076. {
  50077. wasHiddenBecauseOfAppChange = true;
  50078. dismissMenu (0);
  50079. return; // may have been deleted by the previous call..
  50080. }
  50081. }
  50082. else if (wasDown && now > menuCreationTime + 250
  50083. && ! (isDown || overScrollArea))
  50084. {
  50085. isOver = reallyContains (x, y, true);
  50086. if (isOver)
  50087. {
  50088. triggerCurrentlyHighlightedItem();
  50089. }
  50090. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  50091. {
  50092. dismissMenu (0);
  50093. }
  50094. return; // may have been deleted by the previous calls..
  50095. }
  50096. else
  50097. {
  50098. lastFocused = now;
  50099. }
  50100. }
  50101. }
  50102. juce_UseDebuggingNewOperator
  50103. private:
  50104. PopupMenuWindow* owner;
  50105. MenuItemComponent* currentChild;
  50106. PopupMenuWindow* activeSubMenu;
  50107. Component* menuBarComponent;
  50108. ApplicationCommandManager** managerOfChosenCommand;
  50109. Component* componentAttachedTo;
  50110. ComponentDeletionWatcher* attachedCompWatcher;
  50111. Rectangle windowPos;
  50112. int lastMouseX, lastMouseY;
  50113. int minimumWidth, maximumNumColumns, standardItemHeight;
  50114. bool isOver, hasBeenOver, isDown, needsToScroll;
  50115. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  50116. int numColumns, contentHeight, childYOffset;
  50117. Array <int> columnWidths;
  50118. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  50119. double scrollAcceleration;
  50120. bool overlaps (const Rectangle& r) const throw()
  50121. {
  50122. return r.intersects (getBounds())
  50123. || (owner != 0 && owner->overlaps (r));
  50124. }
  50125. bool isOverAnyMenu() const throw()
  50126. {
  50127. return (owner != 0) ? owner->isOverAnyMenu()
  50128. : isOverChildren();
  50129. }
  50130. bool isOverChildren() const throw()
  50131. {
  50132. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  50133. return isVisible()
  50134. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  50135. }
  50136. void updateMouseOverStatus (const int mx, const int my) throw()
  50137. {
  50138. int rx = mx, ry = my;
  50139. globalPositionToRelative (rx, ry);
  50140. isOver = reallyContains (rx, ry, true);
  50141. if (activeSubMenu != 0)
  50142. activeSubMenu->updateMouseOverStatus (mx, my);
  50143. }
  50144. bool treeContains (const PopupMenuWindow* const window) const throw()
  50145. {
  50146. const PopupMenuWindow* mw = this;
  50147. while (mw->owner != 0)
  50148. mw = mw->owner;
  50149. while (mw != 0)
  50150. {
  50151. if (mw == window)
  50152. return true;
  50153. mw = mw->activeSubMenu;
  50154. }
  50155. return false;
  50156. }
  50157. void calculateWindowPos (const int minX, const int maxX,
  50158. const int minY, const int maxY,
  50159. const bool alignToRectangle)
  50160. {
  50161. const Rectangle mon (Desktop::getInstance()
  50162. .getMonitorAreaContaining ((minX + maxX) / 2,
  50163. (minY + maxY) / 2,
  50164. true));
  50165. int x, y, widthToUse, heightToUse;
  50166. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  50167. if (alignToRectangle)
  50168. {
  50169. x = minX;
  50170. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  50171. const int spaceOver = minY - mon.getY();
  50172. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  50173. y = maxY;
  50174. else
  50175. y = minY - heightToUse;
  50176. }
  50177. else
  50178. {
  50179. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  50180. if (owner != 0)
  50181. {
  50182. if (owner->owner != 0)
  50183. {
  50184. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  50185. > owner->owner->getX() + owner->owner->getWidth() / 2);
  50186. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  50187. tendTowardsRight = true;
  50188. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  50189. tendTowardsRight = false;
  50190. }
  50191. else if (maxX + widthToUse < mon.getRight() - 32)
  50192. {
  50193. tendTowardsRight = true;
  50194. }
  50195. }
  50196. const int biggestSpace = jmax (mon.getRight() - maxX,
  50197. minX - mon.getX()) - 32;
  50198. if (biggestSpace < widthToUse)
  50199. {
  50200. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  50201. if (numColumns > 1)
  50202. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  50203. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  50204. }
  50205. if (tendTowardsRight)
  50206. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  50207. else
  50208. x = jmax (mon.getX() + 4, minX - widthToUse);
  50209. y = minY;
  50210. if ((minY + maxY) / 2 > mon.getCentreY())
  50211. y = jmax (mon.getY(), maxY - heightToUse);
  50212. }
  50213. x = jlimit (mon.getX() + 1, mon.getRight() - (widthToUse + 6), x);
  50214. y = jlimit (mon.getY() + 1, mon.getBottom() - (heightToUse + 6), y);
  50215. windowPos.setBounds (x, y, widthToUse, heightToUse);
  50216. // sets this flag if it's big enough to obscure any of its parent menus
  50217. hideOnExit = (owner != 0)
  50218. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  50219. }
  50220. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  50221. {
  50222. numColumns = 0;
  50223. contentHeight = 0;
  50224. const int maxMenuH = getParentHeight() - 24;
  50225. int totalW;
  50226. do
  50227. {
  50228. ++numColumns;
  50229. totalW = workOutBestSize (numColumns, maxMenuW);
  50230. if (totalW > maxMenuW)
  50231. {
  50232. numColumns = jmax (1, numColumns - 1);
  50233. totalW = workOutBestSize (numColumns, maxMenuW); // to update col widths
  50234. break;
  50235. }
  50236. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  50237. {
  50238. break;
  50239. }
  50240. } while (numColumns < maximumNumColumns);
  50241. const int actualH = jmin (contentHeight, maxMenuH);
  50242. needsToScroll = contentHeight > actualH;
  50243. width = updateYPositions();
  50244. height = actualH + borderSize * 2;
  50245. }
  50246. int workOutBestSize (const int numColumns, const int maxMenuW)
  50247. {
  50248. int totalW = 0;
  50249. contentHeight = 0;
  50250. int childNum = 0;
  50251. for (int col = 0; col < numColumns; ++col)
  50252. {
  50253. int i, colW = 50, colH = 0;
  50254. const int numChildren = jmin (getNumChildComponents() - childNum,
  50255. (getNumChildComponents() + numColumns - 1) / numColumns);
  50256. for (i = numChildren; --i >= 0;)
  50257. {
  50258. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  50259. colH += getChildComponent (childNum + i)->getHeight();
  50260. }
  50261. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + borderSize * 2);
  50262. columnWidths.set (col, colW);
  50263. totalW += colW;
  50264. contentHeight = jmax (contentHeight, colH);
  50265. childNum += numChildren;
  50266. }
  50267. if (totalW < minimumWidth)
  50268. {
  50269. totalW = minimumWidth;
  50270. for (int col = 0; col < numColumns; ++col)
  50271. columnWidths.set (0, totalW / numColumns);
  50272. }
  50273. return totalW;
  50274. }
  50275. void ensureItemIsVisible (const int itemId, int wantedY)
  50276. {
  50277. jassert (itemId != 0)
  50278. for (int i = getNumChildComponents(); --i >= 0;)
  50279. {
  50280. MenuItemComponent* const m = (MenuItemComponent*) getChildComponent (i);
  50281. if (m != 0
  50282. && m->itemInfo.itemId == itemId
  50283. && windowPos.getHeight() > scrollZone * 4)
  50284. {
  50285. const int currentY = m->getY();
  50286. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  50287. {
  50288. if (wantedY < 0)
  50289. wantedY = jlimit (scrollZone,
  50290. jmax (scrollZone, windowPos.getHeight() - (scrollZone + m->getHeight())),
  50291. currentY);
  50292. const Rectangle mon (Desktop::getInstance()
  50293. .getMonitorAreaContaining (windowPos.getX(),
  50294. windowPos.getY(),
  50295. true));
  50296. int deltaY = wantedY - currentY;
  50297. const int newY = jlimit (mon.getY(),
  50298. mon.getBottom() - windowPos.getHeight(),
  50299. windowPos.getY() + deltaY);
  50300. deltaY -= newY - windowPos.getY();
  50301. childYOffset -= deltaY;
  50302. windowPos.setPosition (windowPos.getX(), newY);
  50303. updateYPositions();
  50304. }
  50305. break;
  50306. }
  50307. }
  50308. }
  50309. void resizeToBestWindowPos()
  50310. {
  50311. Rectangle r (windowPos);
  50312. if (childYOffset < 0)
  50313. {
  50314. r.setBounds (r.getX(), r.getY() - childYOffset,
  50315. r.getWidth(), r.getHeight() + childYOffset);
  50316. }
  50317. else if (childYOffset > 0)
  50318. {
  50319. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  50320. if (spaceAtBottom > 0)
  50321. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  50322. }
  50323. setBounds (r);
  50324. updateYPositions();
  50325. }
  50326. void alterChildYPos (const int delta)
  50327. {
  50328. if (isScrolling())
  50329. {
  50330. childYOffset += delta;
  50331. if (delta < 0)
  50332. {
  50333. childYOffset = jmax (childYOffset, 0);
  50334. }
  50335. else if (delta > 0)
  50336. {
  50337. childYOffset = jmin (childYOffset,
  50338. contentHeight - windowPos.getHeight() + borderSize);
  50339. }
  50340. updateYPositions();
  50341. }
  50342. else
  50343. {
  50344. childYOffset = 0;
  50345. }
  50346. resizeToBestWindowPos();
  50347. repaint();
  50348. }
  50349. int updateYPositions()
  50350. {
  50351. int x = 0;
  50352. int childNum = 0;
  50353. for (int col = 0; col < numColumns; ++col)
  50354. {
  50355. const int numChildren = jmin (getNumChildComponents() - childNum,
  50356. (getNumChildComponents() + numColumns - 1) / numColumns);
  50357. const int colW = columnWidths [col];
  50358. int y = borderSize - (childYOffset + (getY() - windowPos.getY()));
  50359. for (int i = 0; i < numChildren; ++i)
  50360. {
  50361. Component* const c = getChildComponent (childNum + i);
  50362. c->setBounds (x, y, colW, c->getHeight());
  50363. y += c->getHeight();
  50364. }
  50365. x += colW;
  50366. childNum += numChildren;
  50367. }
  50368. return x;
  50369. }
  50370. bool isScrolling() const throw()
  50371. {
  50372. return childYOffset != 0 || needsToScroll;
  50373. }
  50374. void setCurrentlyHighlightedChild (MenuItemComponent* const child) throw()
  50375. {
  50376. if (currentChild->isValidComponent())
  50377. currentChild->setHighlighted (false);
  50378. currentChild = child;
  50379. if (currentChild != 0)
  50380. {
  50381. currentChild->setHighlighted (true);
  50382. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  50383. }
  50384. }
  50385. bool showSubMenuFor (MenuItemComponent* const childComp)
  50386. {
  50387. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  50388. deleteAndZero (activeSubMenu);
  50389. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  50390. {
  50391. int left = 0, top = 0;
  50392. childComp->relativePositionToGlobal (left, top);
  50393. int right = childComp->getWidth(), bottom = childComp->getHeight();
  50394. childComp->relativePositionToGlobal (right, bottom);
  50395. activeSubMenu = PopupMenuWindow::create (*(childComp->itemInfo.subMenu),
  50396. dismissOnMouseUp,
  50397. this,
  50398. left, right, top, bottom,
  50399. 0, maximumNumColumns,
  50400. standardItemHeight,
  50401. false, 0, menuBarComponent,
  50402. managerOfChosenCommand,
  50403. componentAttachedTo);
  50404. if (activeSubMenu != 0)
  50405. {
  50406. activeSubMenu->setVisible (true);
  50407. activeSubMenu->enterModalState (false);
  50408. activeSubMenu->toFront (false);
  50409. return true;
  50410. }
  50411. }
  50412. return false;
  50413. }
  50414. void highlightItemUnderMouse (const int mx, const int my, const int x, const int y)
  50415. {
  50416. isOver = reallyContains (x, y, true);
  50417. if (isOver)
  50418. hasBeenOver = true;
  50419. if (abs (lastMouseX - mx) > 2 || abs (lastMouseY - my) > 2)
  50420. {
  50421. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  50422. if (disableMouseMoves && isOver)
  50423. disableMouseMoves = false;
  50424. }
  50425. if (disableMouseMoves)
  50426. return;
  50427. bool isMovingTowardsMenu = false;
  50428. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  50429. if (isOver && (activeSubMenu != 0) && (mx != lastMouseX || my != lastMouseY))
  50430. {
  50431. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  50432. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  50433. // extends from the last mouse pos to the submenu's rectangle..
  50434. float subX = (float) activeSubMenu->getScreenX();
  50435. if (activeSubMenu->getX() > getX())
  50436. {
  50437. lastMouseX -= 2; // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  50438. }
  50439. else
  50440. {
  50441. lastMouseX += 2;
  50442. subX += activeSubMenu->getWidth();
  50443. }
  50444. Path areaTowardsSubMenu;
  50445. areaTowardsSubMenu.addTriangle ((float) lastMouseX,
  50446. (float) lastMouseY,
  50447. subX,
  50448. (float) activeSubMenu->getScreenY(),
  50449. subX,
  50450. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  50451. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) mx, (float) my);
  50452. }
  50453. lastMouseX = mx;
  50454. lastMouseY = my;
  50455. if (! isMovingTowardsMenu)
  50456. {
  50457. Component* c = getComponentAt (x, y);
  50458. if (c == this)
  50459. c = 0;
  50460. MenuItemComponent* mic = dynamic_cast <MenuItemComponent*> (c);
  50461. if (mic == 0 && c != 0)
  50462. mic = c->findParentComponentOfClass ((MenuItemComponent*) 0);
  50463. if (mic != currentChild
  50464. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  50465. {
  50466. if (isOver && (c != 0) && (activeSubMenu != 0))
  50467. {
  50468. activeSubMenu->hide (0);
  50469. }
  50470. if (! isOver)
  50471. mic = 0;
  50472. setCurrentlyHighlightedChild (mic);
  50473. }
  50474. }
  50475. }
  50476. void triggerCurrentlyHighlightedItem()
  50477. {
  50478. if (currentChild->isValidComponent()
  50479. && currentChild->itemInfo.canBeTriggered()
  50480. && (currentChild->itemInfo.customComp == 0
  50481. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  50482. {
  50483. dismissMenu (&currentChild->itemInfo);
  50484. }
  50485. }
  50486. void selectNextItem (const int delta)
  50487. {
  50488. disableTimerUntilMouseMoves();
  50489. MenuItemComponent* mic = 0;
  50490. bool wasLastOne = (currentChild == 0);
  50491. const int numItems = getNumChildComponents();
  50492. for (int i = 0; i < numItems + 1; ++i)
  50493. {
  50494. int index = (delta > 0) ? i : (numItems - 1 - i);
  50495. index = (index + numItems) % numItems;
  50496. mic = dynamic_cast <MenuItemComponent*> (getChildComponent (index));
  50497. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  50498. && wasLastOne)
  50499. break;
  50500. if (mic == currentChild)
  50501. wasLastOne = true;
  50502. }
  50503. setCurrentlyHighlightedChild (mic);
  50504. }
  50505. void disableTimerUntilMouseMoves() throw()
  50506. {
  50507. disableMouseMoves = true;
  50508. if (owner != 0)
  50509. owner->disableTimerUntilMouseMoves();
  50510. }
  50511. PopupMenuWindow (const PopupMenuWindow&);
  50512. const PopupMenuWindow& operator= (const PopupMenuWindow&);
  50513. };
  50514. PopupMenu::PopupMenu() throw()
  50515. : items (8),
  50516. lookAndFeel (0),
  50517. separatorPending (false)
  50518. {
  50519. }
  50520. PopupMenu::PopupMenu (const PopupMenu& other) throw()
  50521. : items (8),
  50522. lookAndFeel (other.lookAndFeel),
  50523. separatorPending (false)
  50524. {
  50525. items.ensureStorageAllocated (other.items.size());
  50526. for (int i = 0; i < other.items.size(); ++i)
  50527. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  50528. }
  50529. const PopupMenu& PopupMenu::operator= (const PopupMenu& other) throw()
  50530. {
  50531. if (this != &other)
  50532. {
  50533. lookAndFeel = other.lookAndFeel;
  50534. clear();
  50535. items.ensureStorageAllocated (other.items.size());
  50536. for (int i = 0; i < other.items.size(); ++i)
  50537. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  50538. }
  50539. return *this;
  50540. }
  50541. PopupMenu::~PopupMenu() throw()
  50542. {
  50543. clear();
  50544. }
  50545. void PopupMenu::clear() throw()
  50546. {
  50547. for (int i = items.size(); --i >= 0;)
  50548. {
  50549. MenuItemInfo* const mi = (MenuItemInfo*) items.getUnchecked(i);
  50550. delete mi;
  50551. }
  50552. items.clear();
  50553. separatorPending = false;
  50554. }
  50555. void PopupMenu::addSeparatorIfPending()
  50556. {
  50557. if (separatorPending)
  50558. {
  50559. separatorPending = false;
  50560. if (items.size() > 0)
  50561. items.add (new MenuItemInfo());
  50562. }
  50563. }
  50564. void PopupMenu::addItem (const int itemResultId,
  50565. const String& itemText,
  50566. const bool isActive,
  50567. const bool isTicked,
  50568. const Image* const iconToUse) throw()
  50569. {
  50570. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  50571. // didn't pick anything, so you shouldn't use it as the id
  50572. // for an item..
  50573. addSeparatorIfPending();
  50574. items.add (new MenuItemInfo (itemResultId,
  50575. itemText,
  50576. isActive,
  50577. isTicked,
  50578. iconToUse,
  50579. Colours::black,
  50580. false,
  50581. 0, 0, 0));
  50582. }
  50583. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  50584. const int commandID,
  50585. const String& displayName) throw()
  50586. {
  50587. jassert (commandManager != 0 && commandID != 0);
  50588. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  50589. if (registeredInfo != 0)
  50590. {
  50591. ApplicationCommandInfo info (*registeredInfo);
  50592. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  50593. addSeparatorIfPending();
  50594. items.add (new MenuItemInfo (commandID,
  50595. displayName.isNotEmpty() ? displayName
  50596. : info.shortName,
  50597. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  50598. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  50599. 0,
  50600. Colours::black,
  50601. false,
  50602. 0, 0,
  50603. commandManager));
  50604. }
  50605. }
  50606. void PopupMenu::addColouredItem (const int itemResultId,
  50607. const String& itemText,
  50608. const Colour& itemTextColour,
  50609. const bool isActive,
  50610. const bool isTicked,
  50611. const Image* const iconToUse) throw()
  50612. {
  50613. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  50614. // didn't pick anything, so you shouldn't use it as the id
  50615. // for an item..
  50616. addSeparatorIfPending();
  50617. items.add (new MenuItemInfo (itemResultId,
  50618. itemText,
  50619. isActive,
  50620. isTicked,
  50621. iconToUse,
  50622. itemTextColour,
  50623. true,
  50624. 0, 0, 0));
  50625. }
  50626. void PopupMenu::addCustomItem (const int itemResultId,
  50627. PopupMenuCustomComponent* const customComponent) throw()
  50628. {
  50629. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  50630. // didn't pick anything, so you shouldn't use it as the id
  50631. // for an item..
  50632. addSeparatorIfPending();
  50633. items.add (new MenuItemInfo (itemResultId,
  50634. String::empty,
  50635. true,
  50636. false,
  50637. 0,
  50638. Colours::black,
  50639. false,
  50640. customComponent,
  50641. 0, 0));
  50642. }
  50643. class NormalComponentWrapper : public PopupMenuCustomComponent
  50644. {
  50645. public:
  50646. NormalComponentWrapper (Component* const comp,
  50647. const int w, const int h,
  50648. const bool triggerMenuItemAutomaticallyWhenClicked)
  50649. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  50650. width (w),
  50651. height (h)
  50652. {
  50653. addAndMakeVisible (comp);
  50654. }
  50655. ~NormalComponentWrapper() {}
  50656. void getIdealSize (int& idealWidth, int& idealHeight)
  50657. {
  50658. idealWidth = width;
  50659. idealHeight = height;
  50660. }
  50661. void resized()
  50662. {
  50663. if (getChildComponent(0) != 0)
  50664. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  50665. }
  50666. juce_UseDebuggingNewOperator
  50667. private:
  50668. const int width, height;
  50669. NormalComponentWrapper (const NormalComponentWrapper&);
  50670. const NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  50671. };
  50672. void PopupMenu::addCustomItem (const int itemResultId,
  50673. Component* customComponent,
  50674. int idealWidth, int idealHeight,
  50675. const bool triggerMenuItemAutomaticallyWhenClicked) throw()
  50676. {
  50677. addCustomItem (itemResultId,
  50678. new NormalComponentWrapper (customComponent,
  50679. idealWidth, idealHeight,
  50680. triggerMenuItemAutomaticallyWhenClicked));
  50681. }
  50682. void PopupMenu::addSubMenu (const String& subMenuName,
  50683. const PopupMenu& subMenu,
  50684. const bool isActive,
  50685. Image* const iconToUse) throw()
  50686. {
  50687. addSeparatorIfPending();
  50688. items.add (new MenuItemInfo (0,
  50689. subMenuName,
  50690. isActive && (subMenu.getNumItems() > 0),
  50691. false,
  50692. iconToUse,
  50693. Colours::black,
  50694. false,
  50695. 0,
  50696. &subMenu,
  50697. 0));
  50698. }
  50699. void PopupMenu::addSeparator() throw()
  50700. {
  50701. separatorPending = true;
  50702. }
  50703. class HeaderItemComponent : public PopupMenuCustomComponent
  50704. {
  50705. public:
  50706. HeaderItemComponent (const String& name)
  50707. : PopupMenuCustomComponent (false)
  50708. {
  50709. setName (name);
  50710. }
  50711. ~HeaderItemComponent()
  50712. {
  50713. }
  50714. void paint (Graphics& g)
  50715. {
  50716. Font f (getLookAndFeel().getPopupMenuFont());
  50717. f.setBold (true);
  50718. g.setFont (f);
  50719. g.setColour (findColour (PopupMenu::headerTextColourId));
  50720. g.drawFittedText (getName(),
  50721. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  50722. Justification::bottomLeft, 1);
  50723. }
  50724. void getIdealSize (int& idealWidth,
  50725. int& idealHeight)
  50726. {
  50727. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  50728. idealHeight += idealHeight / 2;
  50729. idealWidth += idealWidth / 4;
  50730. }
  50731. juce_UseDebuggingNewOperator
  50732. };
  50733. void PopupMenu::addSectionHeader (const String& title) throw()
  50734. {
  50735. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  50736. }
  50737. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  50738. const int itemIdThatMustBeVisible,
  50739. const int minimumWidth,
  50740. const int maximumNumColumns,
  50741. const int standardItemHeight,
  50742. const bool alignToRectangle,
  50743. Component* menuBarComponent,
  50744. ApplicationCommandManager** managerOfChosenCommand,
  50745. Component* const componentAttachedTo) throw()
  50746. {
  50747. PopupMenuWindow* const pw
  50748. = PopupMenuWindow::create (*this,
  50749. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  50750. 0,
  50751. x, x + w,
  50752. y, y + h,
  50753. minimumWidth,
  50754. maximumNumColumns,
  50755. standardItemHeight,
  50756. alignToRectangle,
  50757. itemIdThatMustBeVisible,
  50758. menuBarComponent,
  50759. managerOfChosenCommand,
  50760. componentAttachedTo);
  50761. if (pw != 0)
  50762. pw->setVisible (true);
  50763. return pw;
  50764. }
  50765. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  50766. const int itemIdThatMustBeVisible,
  50767. const int minimumWidth,
  50768. const int maximumNumColumns,
  50769. const int standardItemHeight,
  50770. const bool alignToRectangle,
  50771. Component* const componentAttachedTo) throw()
  50772. {
  50773. Component* const prevFocused = Component::getCurrentlyFocusedComponent();
  50774. ComponentDeletionWatcher* deletionChecker1 = 0;
  50775. if (prevFocused != 0)
  50776. deletionChecker1 = new ComponentDeletionWatcher (prevFocused);
  50777. Component* const prevTopLevel = (prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0;
  50778. ComponentDeletionWatcher* deletionChecker2 = 0;
  50779. if (prevTopLevel != 0)
  50780. deletionChecker2 = new ComponentDeletionWatcher (prevTopLevel);
  50781. wasHiddenBecauseOfAppChange = false;
  50782. int result = 0;
  50783. ApplicationCommandManager* managerOfChosenCommand = 0;
  50784. Component* const popupComp = createMenuComponent (x, y, w, h,
  50785. itemIdThatMustBeVisible,
  50786. minimumWidth,
  50787. maximumNumColumns > 0 ? maximumNumColumns : 7,
  50788. standardItemHeight,
  50789. alignToRectangle, 0,
  50790. &managerOfChosenCommand,
  50791. componentAttachedTo);
  50792. if (popupComp != 0)
  50793. {
  50794. popupComp->enterModalState (false);
  50795. popupComp->toFront (false); // need to do this after making it modal, or it could
  50796. // be stuck behind other comps that are already modal..
  50797. result = popupComp->runModalLoop();
  50798. delete popupComp;
  50799. if (! wasHiddenBecauseOfAppChange)
  50800. {
  50801. if (deletionChecker2 != 0 && ! deletionChecker2->hasBeenDeleted())
  50802. prevTopLevel->toFront (true);
  50803. if (deletionChecker1 != 0 && ! deletionChecker1->hasBeenDeleted())
  50804. prevFocused->grabKeyboardFocus();
  50805. }
  50806. }
  50807. delete deletionChecker1;
  50808. delete deletionChecker2;
  50809. if (managerOfChosenCommand != 0 && result != 0)
  50810. {
  50811. ApplicationCommandTarget::InvocationInfo info (result);
  50812. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  50813. managerOfChosenCommand->invoke (info, true);
  50814. }
  50815. return result;
  50816. }
  50817. int PopupMenu::show (const int itemIdThatMustBeVisible,
  50818. const int minimumWidth,
  50819. const int maximumNumColumns,
  50820. const int standardItemHeight)
  50821. {
  50822. int x, y;
  50823. Desktop::getMousePosition (x, y);
  50824. return showAt (x, y,
  50825. itemIdThatMustBeVisible,
  50826. minimumWidth,
  50827. maximumNumColumns,
  50828. standardItemHeight);
  50829. }
  50830. int PopupMenu::showAt (const int screenX,
  50831. const int screenY,
  50832. const int itemIdThatMustBeVisible,
  50833. const int minimumWidth,
  50834. const int maximumNumColumns,
  50835. const int standardItemHeight)
  50836. {
  50837. return showMenu (screenX, screenY, 1, 1,
  50838. itemIdThatMustBeVisible,
  50839. minimumWidth, maximumNumColumns,
  50840. standardItemHeight,
  50841. false, 0);
  50842. }
  50843. int PopupMenu::showAt (Component* componentToAttachTo,
  50844. const int itemIdThatMustBeVisible,
  50845. const int minimumWidth,
  50846. const int maximumNumColumns,
  50847. const int standardItemHeight)
  50848. {
  50849. if (componentToAttachTo != 0)
  50850. {
  50851. return showMenu (componentToAttachTo->getScreenX(),
  50852. componentToAttachTo->getScreenY(),
  50853. componentToAttachTo->getWidth(),
  50854. componentToAttachTo->getHeight(),
  50855. itemIdThatMustBeVisible,
  50856. minimumWidth,
  50857. maximumNumColumns,
  50858. standardItemHeight,
  50859. true, componentToAttachTo);
  50860. }
  50861. else
  50862. {
  50863. return show (itemIdThatMustBeVisible,
  50864. minimumWidth,
  50865. maximumNumColumns,
  50866. standardItemHeight);
  50867. }
  50868. }
  50869. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus() throw()
  50870. {
  50871. for (int i = activeMenuWindows.size(); --i >= 0;)
  50872. {
  50873. PopupMenuWindow* const pmw = (PopupMenuWindow*) activeMenuWindows[i];
  50874. if (pmw != 0)
  50875. pmw->dismissMenu (0);
  50876. }
  50877. }
  50878. int PopupMenu::getNumItems() const throw()
  50879. {
  50880. int num = 0;
  50881. for (int i = items.size(); --i >= 0;)
  50882. if (! ((MenuItemInfo*) items.getUnchecked(i))->isSeparator)
  50883. ++num;
  50884. return num;
  50885. }
  50886. bool PopupMenu::containsCommandItem (const int commandID) const throw()
  50887. {
  50888. for (int i = items.size(); --i >= 0;)
  50889. {
  50890. const MenuItemInfo* mi = (const MenuItemInfo*) items.getUnchecked (i);
  50891. if ((mi->itemId == commandID && mi->commandManager != 0)
  50892. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  50893. {
  50894. return true;
  50895. }
  50896. }
  50897. return false;
  50898. }
  50899. bool PopupMenu::containsAnyActiveItems() const throw()
  50900. {
  50901. for (int i = items.size(); --i >= 0;)
  50902. {
  50903. const MenuItemInfo* const mi = (const MenuItemInfo*) items.getUnchecked (i);
  50904. if (mi->subMenu != 0)
  50905. {
  50906. if (mi->subMenu->containsAnyActiveItems())
  50907. return true;
  50908. }
  50909. else if (mi->active)
  50910. {
  50911. return true;
  50912. }
  50913. }
  50914. return false;
  50915. }
  50916. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel) throw()
  50917. {
  50918. lookAndFeel = newLookAndFeel;
  50919. }
  50920. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  50921. : refCount_ (0),
  50922. isHighlighted (false),
  50923. isTriggeredAutomatically (isTriggeredAutomatically_)
  50924. {
  50925. }
  50926. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  50927. {
  50928. jassert (refCount_ == 0); // should be deleted only by the menu component, as they keep a ref-count.
  50929. }
  50930. void PopupMenuCustomComponent::triggerMenuItem()
  50931. {
  50932. MenuItemComponent* const mic = dynamic_cast<MenuItemComponent*> (getParentComponent());
  50933. if (mic != 0)
  50934. {
  50935. PopupMenuWindow* const pmw = dynamic_cast<PopupMenuWindow*> (mic->getParentComponent());
  50936. if (pmw != 0)
  50937. {
  50938. pmw->dismissMenu (&mic->itemInfo);
  50939. }
  50940. else
  50941. {
  50942. // something must have gone wrong with the component hierarchy if this happens..
  50943. jassertfalse
  50944. }
  50945. }
  50946. else
  50947. {
  50948. // why isn't this component inside a menu? Not much point triggering the item if
  50949. // there's no menu.
  50950. jassertfalse
  50951. }
  50952. }
  50953. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_) throw()
  50954. : subMenu (0),
  50955. itemId (0),
  50956. isSeparator (false),
  50957. isTicked (false),
  50958. isEnabled (false),
  50959. isCustomComponent (false),
  50960. isSectionHeader (false),
  50961. customColour (0),
  50962. customImage (0),
  50963. menu (menu_),
  50964. index (0)
  50965. {
  50966. }
  50967. PopupMenu::MenuItemIterator::~MenuItemIterator() throw()
  50968. {
  50969. }
  50970. bool PopupMenu::MenuItemIterator::next() throw()
  50971. {
  50972. if (index >= menu.items.size())
  50973. return false;
  50974. const MenuItemInfo* const item = (const MenuItemInfo*) menu.items.getUnchecked (index);
  50975. ++index;
  50976. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  50977. subMenu = item->subMenu;
  50978. itemId = item->itemId;
  50979. isSeparator = item->isSeparator;
  50980. isTicked = item->isTicked;
  50981. isEnabled = item->active;
  50982. isSectionHeader = dynamic_cast <HeaderItemComponent*> (item->customComp) != 0;
  50983. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  50984. customColour = item->usesColour ? &(item->textColour) : 0;
  50985. customImage = item->image;
  50986. commandManager = item->commandManager;
  50987. return true;
  50988. }
  50989. END_JUCE_NAMESPACE
  50990. /********* End of inlined file: juce_PopupMenu.cpp *********/
  50991. /********* Start of inlined file: juce_ComponentDragger.cpp *********/
  50992. BEGIN_JUCE_NAMESPACE
  50993. ComponentDragger::ComponentDragger()
  50994. : constrainer (0),
  50995. originalX (0),
  50996. originalY (0)
  50997. {
  50998. }
  50999. ComponentDragger::~ComponentDragger()
  51000. {
  51001. }
  51002. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  51003. ComponentBoundsConstrainer* const constrainer_)
  51004. {
  51005. jassert (componentToDrag->isValidComponent());
  51006. if (componentToDrag->isValidComponent())
  51007. {
  51008. constrainer = constrainer_;
  51009. originalX = 0;
  51010. originalY = 0;
  51011. componentToDrag->relativePositionToGlobal (originalX, originalY);
  51012. }
  51013. }
  51014. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  51015. {
  51016. jassert (componentToDrag->isValidComponent());
  51017. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  51018. if (componentToDrag->isValidComponent())
  51019. {
  51020. int x = originalX + e.getDistanceFromDragStartX();
  51021. int y = originalY + e.getDistanceFromDragStartY();
  51022. int w = componentToDrag->getWidth();
  51023. int h = componentToDrag->getHeight();
  51024. const Component* const parentComp = componentToDrag->getParentComponent();
  51025. if (parentComp != 0)
  51026. parentComp->globalPositionToRelative (x, y);
  51027. if (constrainer != 0)
  51028. constrainer->setBoundsForComponent (componentToDrag, x, y, w, h,
  51029. false, false, false, false);
  51030. else
  51031. componentToDrag->setBounds (x, y, w, h);
  51032. }
  51033. }
  51034. END_JUCE_NAMESPACE
  51035. /********* End of inlined file: juce_ComponentDragger.cpp *********/
  51036. /********* Start of inlined file: juce_DragAndDropContainer.cpp *********/
  51037. BEGIN_JUCE_NAMESPACE
  51038. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  51039. bool juce_performDragDropText (const String& text, bool& shouldStop);
  51040. class DragImageComponent : public Component,
  51041. public Timer
  51042. {
  51043. private:
  51044. Image* image;
  51045. Component* const source;
  51046. DragAndDropContainer* const owner;
  51047. ComponentDeletionWatcher* sourceWatcher;
  51048. Component* mouseDragSource;
  51049. ComponentDeletionWatcher* mouseDragSourceWatcher;
  51050. DragAndDropTarget* currentlyOver;
  51051. String dragDesc;
  51052. int xOff, yOff;
  51053. bool hasCheckedForExternalDrag, drawImage;
  51054. DragImageComponent (const DragImageComponent&);
  51055. const DragImageComponent& operator= (const DragImageComponent&);
  51056. public:
  51057. DragImageComponent (Image* const im,
  51058. const String& desc,
  51059. Component* const s,
  51060. DragAndDropContainer* const o)
  51061. : image (im),
  51062. source (s),
  51063. owner (o),
  51064. currentlyOver (0),
  51065. dragDesc (desc),
  51066. hasCheckedForExternalDrag (false),
  51067. drawImage (true)
  51068. {
  51069. setSize (im->getWidth(), im->getHeight());
  51070. sourceWatcher = new ComponentDeletionWatcher (source);
  51071. mouseDragSource = Component::getComponentUnderMouse();
  51072. if (mouseDragSource == 0)
  51073. mouseDragSource = source;
  51074. mouseDragSourceWatcher = new ComponentDeletionWatcher (mouseDragSource);
  51075. mouseDragSource->addMouseListener (this, false);
  51076. int mx, my;
  51077. Desktop::getLastMouseDownPosition (mx, my);
  51078. source->globalPositionToRelative (mx, my);
  51079. xOff = jlimit (0, im->getWidth(), mx);
  51080. yOff = jlimit (0, im->getHeight(), my);
  51081. startTimer (200);
  51082. setInterceptsMouseClicks (false, false);
  51083. setAlwaysOnTop (true);
  51084. }
  51085. ~DragImageComponent()
  51086. {
  51087. if (owner->dragImageComponent == this)
  51088. owner->dragImageComponent = 0;
  51089. if (((Component*) currentlyOver)->isValidComponent())
  51090. {
  51091. Component* const over = dynamic_cast <Component*> (currentlyOver);
  51092. if (over != 0
  51093. && over->isValidComponent()
  51094. && source->isValidComponent()
  51095. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  51096. {
  51097. currentlyOver->itemDragExit (dragDesc, source);
  51098. }
  51099. }
  51100. if (! mouseDragSourceWatcher->hasBeenDeleted())
  51101. mouseDragSource->removeMouseListener (this);
  51102. delete mouseDragSourceWatcher;
  51103. delete sourceWatcher;
  51104. delete image;
  51105. }
  51106. void paint (Graphics& g)
  51107. {
  51108. if (isOpaque())
  51109. g.fillAll (Colours::white);
  51110. if (drawImage)
  51111. {
  51112. g.setOpacity (1.0f);
  51113. g.drawImageAt (image, 0, 0);
  51114. }
  51115. }
  51116. DragAndDropTarget* findTarget (const int screenX, const int screenY,
  51117. int& relX, int& relY) const throw()
  51118. {
  51119. Component* hit = getParentComponent();
  51120. if (hit == 0)
  51121. {
  51122. hit = Desktop::getInstance().findComponentAt (screenX, screenY);
  51123. }
  51124. else
  51125. {
  51126. int rx = screenX, ry = screenY;
  51127. hit->globalPositionToRelative (rx, ry);
  51128. hit = hit->getComponentAt (rx, ry);
  51129. }
  51130. while (hit != 0)
  51131. {
  51132. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  51133. if (ddt != 0 && ddt->isInterestedInDragSource (dragDesc, source))
  51134. {
  51135. relX = screenX;
  51136. relY = screenY;
  51137. hit->globalPositionToRelative (relX, relY);
  51138. return ddt;
  51139. }
  51140. hit = hit->getParentComponent();
  51141. }
  51142. return 0;
  51143. }
  51144. void mouseUp (const MouseEvent& e)
  51145. {
  51146. if (e.originalComponent != this)
  51147. {
  51148. if (! mouseDragSourceWatcher->hasBeenDeleted())
  51149. mouseDragSource->removeMouseListener (this);
  51150. bool dropAccepted = false;
  51151. DragAndDropTarget* ddt = 0;
  51152. int relX = 0, relY = 0;
  51153. if (isVisible())
  51154. {
  51155. setVisible (false);
  51156. ddt = findTarget (e.getScreenX(),
  51157. e.getScreenY(),
  51158. relX, relY);
  51159. // fade this component and remove it - it'll be deleted later by the timer callback
  51160. dropAccepted = ddt != 0;
  51161. setVisible (true);
  51162. if (dropAccepted || sourceWatcher->hasBeenDeleted())
  51163. {
  51164. fadeOutComponent (120);
  51165. }
  51166. else
  51167. {
  51168. int targetX = source->getWidth() / 2;
  51169. int targetY = source->getHeight() / 2;
  51170. source->relativePositionToGlobal (targetX, targetY);
  51171. int ourCentreX = getWidth() / 2;
  51172. int ourCentreY = getHeight() / 2;
  51173. relativePositionToGlobal (ourCentreX, ourCentreY);
  51174. fadeOutComponent (120,
  51175. targetX - ourCentreX,
  51176. targetY - ourCentreY);
  51177. }
  51178. }
  51179. if (getParentComponent() != 0)
  51180. getParentComponent()->removeChildComponent (this);
  51181. if (dropAccepted && ddt != 0)
  51182. ddt->itemDropped (dragDesc, source, relX, relY);
  51183. // careful - this object could now be deleted..
  51184. }
  51185. }
  51186. void updateLocation (const bool canDoExternalDrag, int x, int y)
  51187. {
  51188. int newX = x - xOff;
  51189. int newY = y - yOff;
  51190. if (getParentComponent() != 0)
  51191. getParentComponent()->globalPositionToRelative (newX, newY);
  51192. if (newX != getX() || newY != getY())
  51193. {
  51194. setTopLeftPosition (newX, newY);
  51195. int relX = 0, relY = 0;
  51196. DragAndDropTarget* const ddt = findTarget (x, y, relX, relY);
  51197. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  51198. if (ddt != currentlyOver)
  51199. {
  51200. Component* const over = dynamic_cast <Component*> (currentlyOver);
  51201. if (over != 0
  51202. && over->isValidComponent()
  51203. && ! (sourceWatcher->hasBeenDeleted())
  51204. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  51205. {
  51206. currentlyOver->itemDragExit (dragDesc, source);
  51207. }
  51208. currentlyOver = ddt;
  51209. if (currentlyOver != 0
  51210. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  51211. currentlyOver->itemDragEnter (dragDesc, source, relX, relY);
  51212. }
  51213. if (currentlyOver != 0
  51214. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  51215. currentlyOver->itemDragMove (dragDesc, source, relX, relY);
  51216. if (currentlyOver == 0
  51217. && canDoExternalDrag
  51218. && ! hasCheckedForExternalDrag)
  51219. {
  51220. if (Desktop::getInstance().findComponentAt (x, y) == 0)
  51221. {
  51222. hasCheckedForExternalDrag = true;
  51223. StringArray files;
  51224. bool canMoveFiles = false;
  51225. if (owner->shouldDropFilesWhenDraggedExternally (dragDesc, source, files, canMoveFiles)
  51226. && files.size() > 0)
  51227. {
  51228. ComponentDeletionWatcher cdw (this);
  51229. setVisible (false);
  51230. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  51231. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  51232. if (! cdw.hasBeenDeleted())
  51233. delete this;
  51234. return;
  51235. }
  51236. }
  51237. }
  51238. }
  51239. }
  51240. void mouseDrag (const MouseEvent& e)
  51241. {
  51242. if (e.originalComponent != this)
  51243. updateLocation (true, e.getScreenX(), e.getScreenY());
  51244. }
  51245. void timerCallback()
  51246. {
  51247. if (sourceWatcher->hasBeenDeleted())
  51248. {
  51249. delete this;
  51250. }
  51251. else if (! isMouseButtonDownAnywhere())
  51252. {
  51253. if (! mouseDragSourceWatcher->hasBeenDeleted())
  51254. mouseDragSource->removeMouseListener (this);
  51255. delete this;
  51256. }
  51257. }
  51258. };
  51259. DragAndDropContainer::DragAndDropContainer()
  51260. : dragImageComponent (0)
  51261. {
  51262. }
  51263. DragAndDropContainer::~DragAndDropContainer()
  51264. {
  51265. if (dragImageComponent != 0)
  51266. delete dragImageComponent;
  51267. }
  51268. void DragAndDropContainer::startDragging (const String& sourceDescription,
  51269. Component* sourceComponent,
  51270. Image* im,
  51271. const bool allowDraggingToExternalWindows)
  51272. {
  51273. if (dragImageComponent != 0)
  51274. {
  51275. if (im != 0)
  51276. delete im;
  51277. }
  51278. else
  51279. {
  51280. Component* const thisComp = dynamic_cast <Component*> (this);
  51281. if (thisComp != 0)
  51282. {
  51283. int mx, my;
  51284. Desktop::getLastMouseDownPosition (mx, my);
  51285. if (im == 0)
  51286. {
  51287. im = sourceComponent->createComponentSnapshot (Rectangle (0, 0, sourceComponent->getWidth(), sourceComponent->getHeight()));
  51288. if (im->getFormat() != Image::ARGB)
  51289. {
  51290. Image* newIm = new Image (Image::ARGB, im->getWidth(), im->getHeight(), true);
  51291. Graphics g2 (*newIm);
  51292. g2.drawImageAt (im, 0, 0);
  51293. delete im;
  51294. im = newIm;
  51295. }
  51296. im->multiplyAllAlphas (0.6f);
  51297. const int lo = 150;
  51298. const int hi = 400;
  51299. int rx = mx, ry = my;
  51300. sourceComponent->globalPositionToRelative (rx, ry);
  51301. const int cx = jlimit (0, im->getWidth(), rx);
  51302. const int cy = jlimit (0, im->getHeight(), ry);
  51303. for (int y = im->getHeight(); --y >= 0;)
  51304. {
  51305. const double dy = (y - cy) * (y - cy);
  51306. for (int x = im->getWidth(); --x >= 0;)
  51307. {
  51308. const int dx = x - cx;
  51309. const int distance = roundDoubleToInt (sqrt (dx * dx + dy));
  51310. if (distance > lo)
  51311. {
  51312. const float alpha = (distance > hi) ? 0
  51313. : (hi - distance) / (float) (hi - lo)
  51314. + Random::getSystemRandom().nextFloat() * 0.008f;
  51315. im->multiplyAlphaAt (x, y, alpha);
  51316. }
  51317. }
  51318. }
  51319. }
  51320. DragImageComponent* const dic
  51321. = new DragImageComponent (im,
  51322. sourceDescription,
  51323. sourceComponent,
  51324. this);
  51325. dragImageComponent = dic;
  51326. currentDragDesc = sourceDescription;
  51327. if (allowDraggingToExternalWindows)
  51328. {
  51329. if (! Desktop::canUseSemiTransparentWindows())
  51330. dic->setOpaque (true);
  51331. dic->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  51332. | ComponentPeer::windowIsTemporary);
  51333. }
  51334. else
  51335. thisComp->addChildComponent (dic);
  51336. dic->updateLocation (false, mx, my);
  51337. dic->setVisible (true);
  51338. }
  51339. else
  51340. {
  51341. // this class must only be implemented by an object that
  51342. // is also a Component.
  51343. jassertfalse
  51344. if (im != 0)
  51345. delete im;
  51346. }
  51347. }
  51348. }
  51349. bool DragAndDropContainer::isDragAndDropActive() const
  51350. {
  51351. return dragImageComponent != 0;
  51352. }
  51353. const String DragAndDropContainer::getCurrentDragDescription() const
  51354. {
  51355. return (dragImageComponent != 0) ? currentDragDesc
  51356. : String::empty;
  51357. }
  51358. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  51359. {
  51360. if (c == 0)
  51361. return 0;
  51362. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  51363. return c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  51364. }
  51365. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  51366. {
  51367. return false;
  51368. }
  51369. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  51370. {
  51371. }
  51372. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  51373. {
  51374. }
  51375. void DragAndDropTarget::itemDragExit (const String&, Component*)
  51376. {
  51377. }
  51378. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  51379. {
  51380. return true;
  51381. }
  51382. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  51383. {
  51384. }
  51385. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  51386. {
  51387. }
  51388. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  51389. {
  51390. }
  51391. END_JUCE_NAMESPACE
  51392. /********* End of inlined file: juce_DragAndDropContainer.cpp *********/
  51393. /********* Start of inlined file: juce_MouseCursor.cpp *********/
  51394. BEGIN_JUCE_NAMESPACE
  51395. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw();
  51396. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw();
  51397. // isStandard set depending on which interface was used to create the cursor
  51398. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw();
  51399. static CriticalSection mouseCursorLock;
  51400. static VoidArray standardCursors (2);
  51401. class RefCountedMouseCursor
  51402. {
  51403. public:
  51404. RefCountedMouseCursor (const MouseCursor::StandardCursorType t) throw()
  51405. : refCount (1),
  51406. standardType (t),
  51407. isStandard (true)
  51408. {
  51409. handle = juce_createStandardMouseCursor (standardType);
  51410. standardCursors.add (this);
  51411. }
  51412. RefCountedMouseCursor (Image& image,
  51413. const int hotSpotX,
  51414. const int hotSpotY) throw()
  51415. : refCount (1),
  51416. standardType (MouseCursor::NormalCursor),
  51417. isStandard (false)
  51418. {
  51419. handle = juce_createMouseCursorFromImage (image, hotSpotX, hotSpotY);
  51420. }
  51421. ~RefCountedMouseCursor() throw()
  51422. {
  51423. juce_deleteMouseCursor (handle, isStandard);
  51424. standardCursors.removeValue (this);
  51425. }
  51426. void decRef() throw()
  51427. {
  51428. if (--refCount == 0)
  51429. delete this;
  51430. }
  51431. void incRef() throw()
  51432. {
  51433. ++refCount;
  51434. }
  51435. void* getHandle() const throw()
  51436. {
  51437. return handle;
  51438. }
  51439. static RefCountedMouseCursor* findInstance (MouseCursor::StandardCursorType type) throw()
  51440. {
  51441. const ScopedLock sl (mouseCursorLock);
  51442. for (int i = 0; i < standardCursors.size(); i++)
  51443. {
  51444. RefCountedMouseCursor* const r = (RefCountedMouseCursor*) standardCursors.getUnchecked(i);
  51445. if (r->standardType == type)
  51446. {
  51447. r->incRef();
  51448. return r;
  51449. }
  51450. }
  51451. return new RefCountedMouseCursor (type);
  51452. }
  51453. juce_UseDebuggingNewOperator
  51454. private:
  51455. void* handle;
  51456. int refCount;
  51457. const MouseCursor::StandardCursorType standardType;
  51458. const bool isStandard;
  51459. const RefCountedMouseCursor& operator= (const RefCountedMouseCursor&);
  51460. };
  51461. MouseCursor::MouseCursor() throw()
  51462. {
  51463. cursorHandle = RefCountedMouseCursor::findInstance (NormalCursor);
  51464. }
  51465. MouseCursor::MouseCursor (const StandardCursorType type) throw()
  51466. {
  51467. cursorHandle = RefCountedMouseCursor::findInstance (type);
  51468. }
  51469. MouseCursor::MouseCursor (Image& image,
  51470. const int hotSpotX,
  51471. const int hotSpotY) throw()
  51472. {
  51473. cursorHandle = new RefCountedMouseCursor (image, hotSpotX, hotSpotY);
  51474. }
  51475. MouseCursor::MouseCursor (const MouseCursor& other) throw()
  51476. : cursorHandle (other.cursorHandle)
  51477. {
  51478. const ScopedLock sl (mouseCursorLock);
  51479. cursorHandle->incRef();
  51480. }
  51481. MouseCursor::~MouseCursor() throw()
  51482. {
  51483. const ScopedLock sl (mouseCursorLock);
  51484. cursorHandle->decRef();
  51485. }
  51486. const MouseCursor& MouseCursor::operator= (const MouseCursor& other) throw()
  51487. {
  51488. if (this != &other)
  51489. {
  51490. const ScopedLock sl (mouseCursorLock);
  51491. cursorHandle->decRef();
  51492. cursorHandle = other.cursorHandle;
  51493. cursorHandle->incRef();
  51494. }
  51495. return *this;
  51496. }
  51497. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  51498. {
  51499. return cursorHandle == other.cursorHandle;
  51500. }
  51501. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  51502. {
  51503. return cursorHandle != other.cursorHandle;
  51504. }
  51505. void* MouseCursor::getHandle() const throw()
  51506. {
  51507. return cursorHandle->getHandle();
  51508. }
  51509. void MouseCursor::showWaitCursor() throw()
  51510. {
  51511. const MouseCursor mc (MouseCursor::WaitCursor);
  51512. mc.showInAllWindows();
  51513. }
  51514. void MouseCursor::hideWaitCursor() throw()
  51515. {
  51516. if (Component::getComponentUnderMouse()->isValidComponent())
  51517. {
  51518. Component::getComponentUnderMouse()->getMouseCursor().showInAllWindows();
  51519. }
  51520. else
  51521. {
  51522. const MouseCursor mc (MouseCursor::NormalCursor);
  51523. mc.showInAllWindows();
  51524. }
  51525. }
  51526. END_JUCE_NAMESPACE
  51527. /********* End of inlined file: juce_MouseCursor.cpp *********/
  51528. /********* Start of inlined file: juce_MouseEvent.cpp *********/
  51529. BEGIN_JUCE_NAMESPACE
  51530. MouseEvent::MouseEvent (const int x_,
  51531. const int y_,
  51532. const ModifierKeys& mods_,
  51533. Component* const originator,
  51534. const Time& eventTime_,
  51535. const int mouseDownX_,
  51536. const int mouseDownY_,
  51537. const Time& mouseDownTime_,
  51538. const int numberOfClicks_,
  51539. const bool mouseWasDragged) throw()
  51540. : x (x_),
  51541. y (y_),
  51542. mods (mods_),
  51543. eventComponent (originator),
  51544. originalComponent (originator),
  51545. eventTime (eventTime_),
  51546. mouseDownX (mouseDownX_),
  51547. mouseDownY (mouseDownY_),
  51548. mouseDownTime (mouseDownTime_),
  51549. numberOfClicks (numberOfClicks_),
  51550. wasMovedSinceMouseDown (mouseWasDragged)
  51551. {
  51552. }
  51553. MouseEvent::~MouseEvent() throw()
  51554. {
  51555. }
  51556. bool MouseEvent::mouseWasClicked() const throw()
  51557. {
  51558. return ! wasMovedSinceMouseDown;
  51559. }
  51560. int MouseEvent::getMouseDownX() const throw()
  51561. {
  51562. return mouseDownX;
  51563. }
  51564. int MouseEvent::getMouseDownY() const throw()
  51565. {
  51566. return mouseDownY;
  51567. }
  51568. int MouseEvent::getDistanceFromDragStartX() const throw()
  51569. {
  51570. return x - mouseDownX;
  51571. }
  51572. int MouseEvent::getDistanceFromDragStartY() const throw()
  51573. {
  51574. return y - mouseDownY;
  51575. }
  51576. int MouseEvent::getDistanceFromDragStart() const throw()
  51577. {
  51578. return roundDoubleToInt (juce_hypot (getDistanceFromDragStartX(),
  51579. getDistanceFromDragStartY()));
  51580. }
  51581. int MouseEvent::getLengthOfMousePress() const throw()
  51582. {
  51583. if (mouseDownTime.toMilliseconds() > 0)
  51584. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  51585. return 0;
  51586. }
  51587. int MouseEvent::getScreenX() const throw()
  51588. {
  51589. int sx = x, sy = y;
  51590. eventComponent->relativePositionToGlobal (sx, sy);
  51591. return sx;
  51592. }
  51593. int MouseEvent::getScreenY() const throw()
  51594. {
  51595. int sx = x, sy = y;
  51596. eventComponent->relativePositionToGlobal (sx, sy);
  51597. return sy;
  51598. }
  51599. int MouseEvent::getMouseDownScreenX() const throw()
  51600. {
  51601. int sx = mouseDownX, sy = mouseDownY;
  51602. eventComponent->relativePositionToGlobal (sx, sy);
  51603. return sx;
  51604. }
  51605. int MouseEvent::getMouseDownScreenY() const throw()
  51606. {
  51607. int sx = mouseDownX, sy = mouseDownY;
  51608. eventComponent->relativePositionToGlobal (sx, sy);
  51609. return sy;
  51610. }
  51611. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  51612. {
  51613. if (otherComponent == 0)
  51614. {
  51615. jassertfalse
  51616. return *this;
  51617. }
  51618. MouseEvent me (*this);
  51619. eventComponent->relativePositionToOtherComponent (otherComponent, me.x, me.y);
  51620. eventComponent->relativePositionToOtherComponent (otherComponent, me.mouseDownX, me.mouseDownY);
  51621. me.eventComponent = otherComponent;
  51622. return me;
  51623. }
  51624. static int doubleClickTimeOutMs = 400;
  51625. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  51626. {
  51627. doubleClickTimeOutMs = newTime;
  51628. }
  51629. int MouseEvent::getDoubleClickTimeout() throw()
  51630. {
  51631. return doubleClickTimeOutMs;
  51632. }
  51633. END_JUCE_NAMESPACE
  51634. /********* End of inlined file: juce_MouseEvent.cpp *********/
  51635. /********* Start of inlined file: juce_MouseHoverDetector.cpp *********/
  51636. BEGIN_JUCE_NAMESPACE
  51637. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  51638. : source (0),
  51639. hoverTimeMillisecs (hoverTimeMillisecs_),
  51640. hasJustHovered (false)
  51641. {
  51642. internalTimer.owner = this;
  51643. }
  51644. MouseHoverDetector::~MouseHoverDetector()
  51645. {
  51646. setHoverComponent (0);
  51647. }
  51648. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  51649. {
  51650. hoverTimeMillisecs = newTimeInMillisecs;
  51651. }
  51652. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  51653. {
  51654. if (source != newSourceComponent)
  51655. {
  51656. internalTimer.stopTimer();
  51657. hasJustHovered = false;
  51658. if (source != 0)
  51659. {
  51660. // ! you need to delete the hover detector before deleting its component
  51661. jassert (source->isValidComponent());
  51662. source->removeMouseListener (&internalTimer);
  51663. }
  51664. source = newSourceComponent;
  51665. if (newSourceComponent != 0)
  51666. newSourceComponent->addMouseListener (&internalTimer, false);
  51667. }
  51668. }
  51669. void MouseHoverDetector::hoverTimerCallback()
  51670. {
  51671. internalTimer.stopTimer();
  51672. if (source != 0)
  51673. {
  51674. int mx, my;
  51675. source->getMouseXYRelative (mx, my);
  51676. if (source->reallyContains (mx, my, false))
  51677. {
  51678. hasJustHovered = true;
  51679. mouseHovered (mx, my);
  51680. }
  51681. }
  51682. }
  51683. void MouseHoverDetector::checkJustHoveredCallback()
  51684. {
  51685. if (hasJustHovered)
  51686. {
  51687. hasJustHovered = false;
  51688. mouseMovedAfterHover();
  51689. }
  51690. }
  51691. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  51692. {
  51693. owner->hoverTimerCallback();
  51694. }
  51695. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  51696. {
  51697. stopTimer();
  51698. owner->checkJustHoveredCallback();
  51699. }
  51700. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  51701. {
  51702. stopTimer();
  51703. owner->checkJustHoveredCallback();
  51704. }
  51705. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  51706. {
  51707. stopTimer();
  51708. owner->checkJustHoveredCallback();
  51709. }
  51710. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  51711. {
  51712. stopTimer();
  51713. owner->checkJustHoveredCallback();
  51714. }
  51715. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  51716. {
  51717. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  51718. {
  51719. lastX = e.x;
  51720. lastY = e.y;
  51721. if (owner->source != 0)
  51722. startTimer (owner->hoverTimeMillisecs);
  51723. owner->checkJustHoveredCallback();
  51724. }
  51725. }
  51726. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  51727. {
  51728. stopTimer();
  51729. owner->checkJustHoveredCallback();
  51730. }
  51731. END_JUCE_NAMESPACE
  51732. /********* End of inlined file: juce_MouseHoverDetector.cpp *********/
  51733. /********* Start of inlined file: juce_MouseListener.cpp *********/
  51734. BEGIN_JUCE_NAMESPACE
  51735. void MouseListener::mouseEnter (const MouseEvent&)
  51736. {
  51737. }
  51738. void MouseListener::mouseExit (const MouseEvent&)
  51739. {
  51740. }
  51741. void MouseListener::mouseDown (const MouseEvent&)
  51742. {
  51743. }
  51744. void MouseListener::mouseUp (const MouseEvent&)
  51745. {
  51746. }
  51747. void MouseListener::mouseDrag (const MouseEvent&)
  51748. {
  51749. }
  51750. void MouseListener::mouseMove (const MouseEvent&)
  51751. {
  51752. }
  51753. void MouseListener::mouseDoubleClick (const MouseEvent&)
  51754. {
  51755. }
  51756. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  51757. {
  51758. }
  51759. END_JUCE_NAMESPACE
  51760. /********* End of inlined file: juce_MouseListener.cpp *********/
  51761. /********* Start of inlined file: juce_BooleanPropertyComponent.cpp *********/
  51762. BEGIN_JUCE_NAMESPACE
  51763. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  51764. const String& buttonTextWhenTrue,
  51765. const String& buttonTextWhenFalse)
  51766. : PropertyComponent (name),
  51767. onText (buttonTextWhenTrue),
  51768. offText (buttonTextWhenFalse)
  51769. {
  51770. addAndMakeVisible (button = new ToggleButton (String::empty));
  51771. button->setClickingTogglesState (false);
  51772. button->addButtonListener (this);
  51773. }
  51774. BooleanPropertyComponent::~BooleanPropertyComponent()
  51775. {
  51776. deleteAllChildren();
  51777. }
  51778. void BooleanPropertyComponent::paint (Graphics& g)
  51779. {
  51780. PropertyComponent::paint (g);
  51781. const Rectangle r (button->getBounds());
  51782. g.setColour (Colours::white);
  51783. g.fillRect (r);
  51784. g.setColour (findColour (ComboBox::outlineColourId));
  51785. g.drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  51786. }
  51787. void BooleanPropertyComponent::refresh()
  51788. {
  51789. button->setToggleState (getState(), false);
  51790. button->setButtonText (button->getToggleState() ? onText : offText);
  51791. }
  51792. void BooleanPropertyComponent::buttonClicked (Button*)
  51793. {
  51794. setState (! getState());
  51795. }
  51796. END_JUCE_NAMESPACE
  51797. /********* End of inlined file: juce_BooleanPropertyComponent.cpp *********/
  51798. /********* Start of inlined file: juce_ButtonPropertyComponent.cpp *********/
  51799. BEGIN_JUCE_NAMESPACE
  51800. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  51801. const bool triggerOnMouseDown)
  51802. : PropertyComponent (name)
  51803. {
  51804. addAndMakeVisible (button = new TextButton (String::empty));
  51805. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  51806. button->addButtonListener (this);
  51807. }
  51808. ButtonPropertyComponent::~ButtonPropertyComponent()
  51809. {
  51810. deleteAllChildren();
  51811. }
  51812. void ButtonPropertyComponent::refresh()
  51813. {
  51814. button->setButtonText (getButtonText());
  51815. }
  51816. void ButtonPropertyComponent::buttonClicked (Button*)
  51817. {
  51818. buttonClicked();
  51819. }
  51820. END_JUCE_NAMESPACE
  51821. /********* End of inlined file: juce_ButtonPropertyComponent.cpp *********/
  51822. /********* Start of inlined file: juce_ChoicePropertyComponent.cpp *********/
  51823. BEGIN_JUCE_NAMESPACE
  51824. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  51825. : PropertyComponent (name),
  51826. comboBox (0)
  51827. {
  51828. }
  51829. ChoicePropertyComponent::~ChoicePropertyComponent()
  51830. {
  51831. deleteAllChildren();
  51832. }
  51833. const StringArray& ChoicePropertyComponent::getChoices() const throw()
  51834. {
  51835. return choices;
  51836. }
  51837. void ChoicePropertyComponent::refresh()
  51838. {
  51839. if (comboBox == 0)
  51840. {
  51841. addAndMakeVisible (comboBox = new ComboBox (String::empty));
  51842. for (int i = 0; i < choices.size(); ++i)
  51843. {
  51844. if (choices[i].isNotEmpty())
  51845. comboBox->addItem (choices[i], i + 1);
  51846. else
  51847. comboBox->addSeparator();
  51848. }
  51849. comboBox->setEditableText (false);
  51850. comboBox->addListener (this);
  51851. }
  51852. comboBox->setSelectedId (getIndex() + 1, true);
  51853. }
  51854. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  51855. {
  51856. const int newIndex = comboBox->getSelectedId() - 1;
  51857. if (newIndex != getIndex())
  51858. setIndex (newIndex);
  51859. }
  51860. END_JUCE_NAMESPACE
  51861. /********* End of inlined file: juce_ChoicePropertyComponent.cpp *********/
  51862. /********* Start of inlined file: juce_PropertyComponent.cpp *********/
  51863. BEGIN_JUCE_NAMESPACE
  51864. PropertyComponent::PropertyComponent (const String& name,
  51865. const int preferredHeight_)
  51866. : Component (name),
  51867. preferredHeight (preferredHeight_)
  51868. {
  51869. jassert (name.isNotEmpty());
  51870. }
  51871. PropertyComponent::~PropertyComponent()
  51872. {
  51873. }
  51874. void PropertyComponent::paint (Graphics& g)
  51875. {
  51876. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  51877. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  51878. }
  51879. void PropertyComponent::resized()
  51880. {
  51881. if (getNumChildComponents() > 0)
  51882. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  51883. }
  51884. void PropertyComponent::enablementChanged()
  51885. {
  51886. repaint();
  51887. }
  51888. END_JUCE_NAMESPACE
  51889. /********* End of inlined file: juce_PropertyComponent.cpp *********/
  51890. /********* Start of inlined file: juce_PropertyPanel.cpp *********/
  51891. BEGIN_JUCE_NAMESPACE
  51892. class PropertyHolderComponent : public Component
  51893. {
  51894. public:
  51895. PropertyHolderComponent()
  51896. {
  51897. }
  51898. ~PropertyHolderComponent()
  51899. {
  51900. deleteAllChildren();
  51901. }
  51902. void paint (Graphics&)
  51903. {
  51904. }
  51905. void updateLayout (const int width);
  51906. void refreshAll() const;
  51907. };
  51908. class PropertySectionComponent : public Component
  51909. {
  51910. public:
  51911. PropertySectionComponent (const String& sectionTitle,
  51912. const Array <PropertyComponent*>& newProperties,
  51913. const bool open)
  51914. : Component (sectionTitle),
  51915. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  51916. isOpen_ (open)
  51917. {
  51918. for (int i = newProperties.size(); --i >= 0;)
  51919. {
  51920. addAndMakeVisible (newProperties.getUnchecked(i));
  51921. newProperties.getUnchecked(i)->refresh();
  51922. }
  51923. }
  51924. ~PropertySectionComponent()
  51925. {
  51926. deleteAllChildren();
  51927. }
  51928. void paint (Graphics& g)
  51929. {
  51930. if (titleHeight > 0)
  51931. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  51932. }
  51933. void resized()
  51934. {
  51935. int y = titleHeight;
  51936. for (int i = getNumChildComponents(); --i >= 0;)
  51937. {
  51938. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51939. if (pec != 0)
  51940. {
  51941. const int prefH = pec->getPreferredHeight();
  51942. pec->setBounds (1, y, getWidth() - 2, prefH);
  51943. y += prefH;
  51944. }
  51945. }
  51946. }
  51947. int getPreferredHeight() const
  51948. {
  51949. int y = titleHeight;
  51950. if (isOpen())
  51951. {
  51952. for (int i = 0; i < getNumChildComponents(); ++i)
  51953. {
  51954. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51955. if (pec != 0)
  51956. y += pec->getPreferredHeight();
  51957. }
  51958. }
  51959. return y;
  51960. }
  51961. void setOpen (const bool open)
  51962. {
  51963. if (isOpen_ != open)
  51964. {
  51965. isOpen_ = open;
  51966. for (int i = 0; i < getNumChildComponents(); ++i)
  51967. {
  51968. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51969. if (pec != 0)
  51970. pec->setVisible (open);
  51971. }
  51972. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  51973. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  51974. if (pp != 0)
  51975. pp->resized();
  51976. }
  51977. }
  51978. bool isOpen() const throw()
  51979. {
  51980. return isOpen_;
  51981. }
  51982. void refreshAll() const
  51983. {
  51984. for (int i = 0; i < getNumChildComponents(); ++i)
  51985. {
  51986. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51987. if (pec != 0)
  51988. pec->refresh();
  51989. }
  51990. }
  51991. void mouseDown (const MouseEvent&)
  51992. {
  51993. }
  51994. void mouseUp (const MouseEvent& e)
  51995. {
  51996. if (e.getMouseDownX() < titleHeight
  51997. && e.x < titleHeight
  51998. && e.y < titleHeight
  51999. && e.getNumberOfClicks() != 2)
  52000. {
  52001. setOpen (! isOpen());
  52002. }
  52003. }
  52004. void mouseDoubleClick (const MouseEvent& e)
  52005. {
  52006. if (e.y < titleHeight)
  52007. setOpen (! isOpen());
  52008. }
  52009. private:
  52010. int titleHeight;
  52011. bool isOpen_;
  52012. };
  52013. void PropertyHolderComponent::updateLayout (const int width)
  52014. {
  52015. int y = 0;
  52016. for (int i = getNumChildComponents(); --i >= 0;)
  52017. {
  52018. PropertySectionComponent* const section
  52019. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  52020. if (section != 0)
  52021. {
  52022. const int prefH = section->getPreferredHeight();
  52023. section->setBounds (0, y, width, prefH);
  52024. y += prefH;
  52025. }
  52026. }
  52027. setSize (width, y);
  52028. repaint();
  52029. }
  52030. void PropertyHolderComponent::refreshAll() const
  52031. {
  52032. for (int i = getNumChildComponents(); --i >= 0;)
  52033. {
  52034. PropertySectionComponent* const section
  52035. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  52036. if (section != 0)
  52037. section->refreshAll();
  52038. }
  52039. }
  52040. PropertyPanel::PropertyPanel()
  52041. {
  52042. messageWhenEmpty = TRANS("(nothing selected)");
  52043. addAndMakeVisible (viewport = new Viewport());
  52044. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  52045. viewport->setFocusContainer (true);
  52046. }
  52047. PropertyPanel::~PropertyPanel()
  52048. {
  52049. clear();
  52050. deleteAllChildren();
  52051. }
  52052. void PropertyPanel::paint (Graphics& g)
  52053. {
  52054. if (propertyHolderComponent->getNumChildComponents() == 0)
  52055. {
  52056. g.setColour (Colours::black.withAlpha (0.5f));
  52057. g.setFont (14.0f);
  52058. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  52059. Justification::centred, true);
  52060. }
  52061. }
  52062. void PropertyPanel::resized()
  52063. {
  52064. viewport->setBounds (0, 0, getWidth(), getHeight());
  52065. updatePropHolderLayout();
  52066. }
  52067. void PropertyPanel::clear()
  52068. {
  52069. if (propertyHolderComponent->getNumChildComponents() > 0)
  52070. {
  52071. propertyHolderComponent->deleteAllChildren();
  52072. repaint();
  52073. }
  52074. }
  52075. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  52076. {
  52077. if (propertyHolderComponent->getNumChildComponents() == 0)
  52078. repaint();
  52079. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  52080. newProperties,
  52081. true), 0);
  52082. updatePropHolderLayout();
  52083. }
  52084. void PropertyPanel::addSection (const String& sectionTitle,
  52085. const Array <PropertyComponent*>& newProperties,
  52086. const bool shouldBeOpen)
  52087. {
  52088. jassert (sectionTitle.isNotEmpty());
  52089. if (propertyHolderComponent->getNumChildComponents() == 0)
  52090. repaint();
  52091. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  52092. newProperties,
  52093. shouldBeOpen), 0);
  52094. updatePropHolderLayout();
  52095. }
  52096. void PropertyPanel::updatePropHolderLayout() const
  52097. {
  52098. const int maxWidth = viewport->getMaximumVisibleWidth();
  52099. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (maxWidth);
  52100. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  52101. if (maxWidth != newMaxWidth)
  52102. {
  52103. // need to do this twice because of scrollbars changing the size, etc.
  52104. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (newMaxWidth);
  52105. }
  52106. }
  52107. void PropertyPanel::refreshAll() const
  52108. {
  52109. ((PropertyHolderComponent*) propertyHolderComponent)->refreshAll();
  52110. }
  52111. const StringArray PropertyPanel::getSectionNames() const
  52112. {
  52113. StringArray s;
  52114. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  52115. {
  52116. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  52117. if (section != 0 && section->getName().isNotEmpty())
  52118. s.add (section->getName());
  52119. }
  52120. return s;
  52121. }
  52122. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  52123. {
  52124. int index = 0;
  52125. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  52126. {
  52127. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  52128. if (section != 0 && section->getName().isNotEmpty())
  52129. {
  52130. if (index == sectionIndex)
  52131. return section->isOpen();
  52132. ++index;
  52133. }
  52134. }
  52135. return false;
  52136. }
  52137. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  52138. {
  52139. int index = 0;
  52140. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  52141. {
  52142. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  52143. if (section != 0 && section->getName().isNotEmpty())
  52144. {
  52145. if (index == sectionIndex)
  52146. {
  52147. section->setOpen (shouldBeOpen);
  52148. break;
  52149. }
  52150. ++index;
  52151. }
  52152. }
  52153. }
  52154. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  52155. {
  52156. int index = 0;
  52157. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  52158. {
  52159. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  52160. if (section != 0 && section->getName().isNotEmpty())
  52161. {
  52162. if (index == sectionIndex)
  52163. {
  52164. section->setEnabled (shouldBeEnabled);
  52165. break;
  52166. }
  52167. ++index;
  52168. }
  52169. }
  52170. }
  52171. XmlElement* PropertyPanel::getOpennessState() const
  52172. {
  52173. XmlElement* const xml = new XmlElement (T("PROPERTYPANELSTATE"));
  52174. const StringArray sections (getSectionNames());
  52175. for (int i = 0; i < sections.size(); ++i)
  52176. {
  52177. if (sections[i].isNotEmpty())
  52178. {
  52179. XmlElement* const e = new XmlElement (T("SECTION"));
  52180. e->setAttribute (T("name"), sections[i]);
  52181. e->setAttribute (T("open"), isSectionOpen (i) ? 1 : 0);
  52182. xml->addChildElement (e);
  52183. }
  52184. }
  52185. return xml;
  52186. }
  52187. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  52188. {
  52189. if (xml.hasTagName (T("PROPERTYPANELSTATE")))
  52190. {
  52191. const StringArray sections (getSectionNames());
  52192. forEachXmlChildElementWithTagName (xml, e, T("SECTION"))
  52193. {
  52194. setSectionOpen (sections.indexOf (e->getStringAttribute (T("name"))),
  52195. e->getBoolAttribute (T("open")));
  52196. }
  52197. }
  52198. }
  52199. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  52200. {
  52201. if (messageWhenEmpty != newMessage)
  52202. {
  52203. messageWhenEmpty = newMessage;
  52204. repaint();
  52205. }
  52206. }
  52207. const String& PropertyPanel::getMessageWhenEmpty() const throw()
  52208. {
  52209. return messageWhenEmpty;
  52210. }
  52211. END_JUCE_NAMESPACE
  52212. /********* End of inlined file: juce_PropertyPanel.cpp *********/
  52213. /********* Start of inlined file: juce_SliderPropertyComponent.cpp *********/
  52214. BEGIN_JUCE_NAMESPACE
  52215. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  52216. const double rangeMin,
  52217. const double rangeMax,
  52218. const double interval,
  52219. const double skewFactor)
  52220. : PropertyComponent (name)
  52221. {
  52222. addAndMakeVisible (slider = new Slider (name));
  52223. slider->setRange (rangeMin, rangeMax, interval);
  52224. slider->setSkewFactor (skewFactor);
  52225. slider->setSliderStyle (Slider::LinearBar);
  52226. slider->addListener (this);
  52227. }
  52228. SliderPropertyComponent::~SliderPropertyComponent()
  52229. {
  52230. deleteAllChildren();
  52231. }
  52232. void SliderPropertyComponent::refresh()
  52233. {
  52234. slider->setValue (getValue(), false);
  52235. }
  52236. void SliderPropertyComponent::sliderValueChanged (Slider*)
  52237. {
  52238. if (getValue() != slider->getValue())
  52239. setValue (slider->getValue());
  52240. }
  52241. END_JUCE_NAMESPACE
  52242. /********* End of inlined file: juce_SliderPropertyComponent.cpp *********/
  52243. /********* Start of inlined file: juce_TextPropertyComponent.cpp *********/
  52244. BEGIN_JUCE_NAMESPACE
  52245. class TextPropLabel : public Label
  52246. {
  52247. TextPropertyComponent& owner;
  52248. int maxChars;
  52249. bool isMultiline;
  52250. public:
  52251. TextPropLabel (TextPropertyComponent& owner_,
  52252. const int maxChars_, const bool isMultiline_)
  52253. : Label (String::empty, String::empty),
  52254. owner (owner_),
  52255. maxChars (maxChars_),
  52256. isMultiline (isMultiline_)
  52257. {
  52258. setEditable (true, true, false);
  52259. setColour (backgroundColourId, Colours::white);
  52260. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  52261. }
  52262. ~TextPropLabel()
  52263. {
  52264. }
  52265. TextEditor* createEditorComponent()
  52266. {
  52267. TextEditor* const textEditor = Label::createEditorComponent();
  52268. textEditor->setInputRestrictions (maxChars);
  52269. if (isMultiline)
  52270. {
  52271. textEditor->setMultiLine (true, true);
  52272. textEditor->setReturnKeyStartsNewLine (true);
  52273. }
  52274. return textEditor;
  52275. }
  52276. void textWasEdited()
  52277. {
  52278. owner.textWasEdited();
  52279. }
  52280. };
  52281. TextPropertyComponent::TextPropertyComponent (const String& name,
  52282. const int maxNumChars,
  52283. const bool isMultiLine)
  52284. : PropertyComponent (name)
  52285. {
  52286. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  52287. if (isMultiLine)
  52288. {
  52289. textEditor->setJustificationType (Justification::topLeft);
  52290. preferredHeight = 120;
  52291. }
  52292. }
  52293. TextPropertyComponent::~TextPropertyComponent()
  52294. {
  52295. deleteAllChildren();
  52296. }
  52297. void TextPropertyComponent::refresh()
  52298. {
  52299. textEditor->setText (getText(), false);
  52300. }
  52301. void TextPropertyComponent::textWasEdited()
  52302. {
  52303. const String newText (textEditor->getText());
  52304. if (getText() != newText)
  52305. setText (newText);
  52306. }
  52307. END_JUCE_NAMESPACE
  52308. /********* End of inlined file: juce_TextPropertyComponent.cpp *********/
  52309. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  52310. BEGIN_JUCE_NAMESPACE
  52311. class SimpleDeviceManagerInputLevelMeter : public Component,
  52312. public Timer
  52313. {
  52314. public:
  52315. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  52316. : manager (manager_),
  52317. level (0)
  52318. {
  52319. startTimer (50);
  52320. manager->enableInputLevelMeasurement (true);
  52321. }
  52322. ~SimpleDeviceManagerInputLevelMeter()
  52323. {
  52324. manager->enableInputLevelMeasurement (false);
  52325. }
  52326. void timerCallback()
  52327. {
  52328. const float newLevel = (float) manager->getCurrentInputLevel();
  52329. if (fabsf (level - newLevel) > 0.005f)
  52330. {
  52331. level = newLevel;
  52332. repaint();
  52333. }
  52334. }
  52335. void paint (Graphics& g)
  52336. {
  52337. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(), level);
  52338. }
  52339. private:
  52340. AudioDeviceManager* const manager;
  52341. float level;
  52342. };
  52343. class MidiInputSelectorComponentListBox : public ListBox,
  52344. public ListBoxModel
  52345. {
  52346. public:
  52347. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  52348. const String& noItemsMessage_,
  52349. const int minNumber_,
  52350. const int maxNumber_)
  52351. : ListBox (String::empty, 0),
  52352. deviceManager (deviceManager_),
  52353. noItemsMessage (noItemsMessage_),
  52354. minNumber (minNumber_),
  52355. maxNumber (maxNumber_)
  52356. {
  52357. items = MidiInput::getDevices();
  52358. setModel (this);
  52359. setOutlineThickness (1);
  52360. }
  52361. ~MidiInputSelectorComponentListBox()
  52362. {
  52363. }
  52364. int getNumRows()
  52365. {
  52366. return items.size();
  52367. }
  52368. void paintListBoxItem (int row,
  52369. Graphics& g,
  52370. int width, int height,
  52371. bool rowIsSelected)
  52372. {
  52373. if (((unsigned int) row) < (unsigned int) items.size())
  52374. {
  52375. if (rowIsSelected)
  52376. g.fillAll (findColour (TextEditor::highlightColourId)
  52377. .withMultipliedAlpha (0.3f));
  52378. const String item (items [row]);
  52379. bool enabled = deviceManager.isMidiInputEnabled (item);
  52380. const int x = getTickX();
  52381. const int tickW = height - height / 4;
  52382. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  52383. enabled, true, true, false);
  52384. g.setFont (height * 0.6f);
  52385. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  52386. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  52387. }
  52388. }
  52389. void listBoxItemClicked (int row, const MouseEvent& e)
  52390. {
  52391. selectRow (row);
  52392. if (e.x < getTickX())
  52393. flipEnablement (row);
  52394. }
  52395. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  52396. {
  52397. flipEnablement (row);
  52398. }
  52399. void returnKeyPressed (int row)
  52400. {
  52401. flipEnablement (row);
  52402. }
  52403. void paint (Graphics& g)
  52404. {
  52405. ListBox::paint (g);
  52406. if (items.size() == 0)
  52407. {
  52408. g.setColour (Colours::grey);
  52409. g.setFont (13.0f);
  52410. g.drawText (noItemsMessage,
  52411. 0, 0, getWidth(), getHeight() / 2,
  52412. Justification::centred, true);
  52413. }
  52414. }
  52415. int getBestHeight (const int preferredHeight)
  52416. {
  52417. const int extra = getOutlineThickness() * 2;
  52418. return jmax (getRowHeight() * 2 + extra,
  52419. jmin (getRowHeight() * getNumRows() + extra,
  52420. preferredHeight));
  52421. }
  52422. juce_UseDebuggingNewOperator
  52423. private:
  52424. AudioDeviceManager& deviceManager;
  52425. const String noItemsMessage;
  52426. StringArray items;
  52427. int minNumber, maxNumber;
  52428. void flipEnablement (const int row)
  52429. {
  52430. if (((unsigned int) row) < (unsigned int) items.size())
  52431. {
  52432. const String item (items [row]);
  52433. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  52434. }
  52435. }
  52436. int getTickX() const throw()
  52437. {
  52438. return getRowHeight() + 5;
  52439. }
  52440. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  52441. const MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  52442. };
  52443. class AudioDeviceSettingsPanel : public Component,
  52444. public ComboBoxListener,
  52445. public ChangeListener,
  52446. public ButtonListener
  52447. {
  52448. public:
  52449. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  52450. AudioIODeviceType::DeviceSetupDetails& setup_,
  52451. const bool hideAdvancedOptionsWithButton)
  52452. : type (type_),
  52453. setup (setup_)
  52454. {
  52455. sampleRateDropDown = 0;
  52456. sampleRateLabel = 0;
  52457. bufferSizeDropDown = 0;
  52458. bufferSizeLabel = 0;
  52459. outputDeviceDropDown = 0;
  52460. outputDeviceLabel = 0;
  52461. inputDeviceDropDown = 0;
  52462. inputDeviceLabel = 0;
  52463. testButton = 0;
  52464. inputLevelMeter = 0;
  52465. showUIButton = 0;
  52466. inputChanList = 0;
  52467. outputChanList = 0;
  52468. inputChanLabel = 0;
  52469. outputChanLabel = 0;
  52470. showAdvancedSettingsButton = 0;
  52471. if (hideAdvancedOptionsWithButton)
  52472. {
  52473. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  52474. showAdvancedSettingsButton->addButtonListener (this);
  52475. }
  52476. type->scanForDevices();
  52477. setup.manager->addChangeListener (this);
  52478. changeListenerCallback (0);
  52479. }
  52480. ~AudioDeviceSettingsPanel()
  52481. {
  52482. setup.manager->removeChangeListener (this);
  52483. deleteAndZero (outputDeviceLabel);
  52484. deleteAndZero (inputDeviceLabel);
  52485. deleteAndZero (sampleRateLabel);
  52486. deleteAndZero (bufferSizeLabel);
  52487. deleteAndZero (showUIButton);
  52488. deleteAndZero (inputChanLabel);
  52489. deleteAndZero (outputChanLabel);
  52490. deleteAndZero (showAdvancedSettingsButton);
  52491. deleteAllChildren();
  52492. }
  52493. void resized()
  52494. {
  52495. const int lx = proportionOfWidth (0.35f);
  52496. const int w = proportionOfWidth (0.4f);
  52497. const int h = 24;
  52498. const int space = 6;
  52499. const int dh = h + space;
  52500. int y = 0;
  52501. if (outputDeviceDropDown != 0)
  52502. {
  52503. outputDeviceDropDown->setBounds (lx, y, w, h);
  52504. if (testButton != 0)
  52505. testButton->setBounds (proportionOfWidth (0.77f),
  52506. outputDeviceDropDown->getY(),
  52507. proportionOfWidth (0.18f),
  52508. h);
  52509. y += dh;
  52510. }
  52511. if (inputDeviceDropDown != 0)
  52512. {
  52513. inputDeviceDropDown->setBounds (lx, y, w, h);
  52514. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  52515. inputDeviceDropDown->getY(),
  52516. proportionOfWidth (0.18f),
  52517. h);
  52518. y += dh;
  52519. }
  52520. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  52521. if (outputChanList != 0)
  52522. {
  52523. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  52524. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  52525. y += bh + space;
  52526. }
  52527. if (inputChanList != 0)
  52528. {
  52529. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  52530. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  52531. y += bh + space;
  52532. }
  52533. y += space * 2;
  52534. if (showAdvancedSettingsButton != 0)
  52535. {
  52536. showAdvancedSettingsButton->changeWidthToFitText (h);
  52537. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  52538. }
  52539. if (sampleRateDropDown != 0)
  52540. {
  52541. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  52542. || ! showAdvancedSettingsButton->isVisible());
  52543. sampleRateDropDown->setBounds (lx, y, w, h);
  52544. y += dh;
  52545. }
  52546. if (bufferSizeDropDown != 0)
  52547. {
  52548. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  52549. || ! showAdvancedSettingsButton->isVisible());
  52550. bufferSizeDropDown->setBounds (lx, y, w, h);
  52551. y += dh;
  52552. }
  52553. if (showUIButton != 0)
  52554. {
  52555. showUIButton->setVisible (showAdvancedSettingsButton == 0
  52556. || ! showAdvancedSettingsButton->isVisible());
  52557. showUIButton->changeWidthToFitText (h);
  52558. showUIButton->setTopLeftPosition (lx, y);
  52559. }
  52560. }
  52561. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  52562. {
  52563. if (comboBoxThatHasChanged == 0)
  52564. return;
  52565. AudioDeviceManager::AudioDeviceSetup config;
  52566. setup.manager->getAudioDeviceSetup (config);
  52567. String error;
  52568. if (comboBoxThatHasChanged == outputDeviceDropDown
  52569. || comboBoxThatHasChanged == inputDeviceDropDown)
  52570. {
  52571. if (outputDeviceDropDown != 0)
  52572. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  52573. : outputDeviceDropDown->getText();
  52574. if (inputDeviceDropDown != 0)
  52575. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  52576. : inputDeviceDropDown->getText();
  52577. if (! type->hasSeparateInputsAndOutputs())
  52578. config.inputDeviceName = config.outputDeviceName;
  52579. if (comboBoxThatHasChanged == inputDeviceDropDown)
  52580. config.useDefaultInputChannels = true;
  52581. else
  52582. config.useDefaultOutputChannels = true;
  52583. error = setup.manager->setAudioDeviceSetup (config, true);
  52584. showCorrectDeviceName (inputDeviceDropDown, true);
  52585. showCorrectDeviceName (outputDeviceDropDown, false);
  52586. updateControlPanelButton();
  52587. resized();
  52588. }
  52589. else if (comboBoxThatHasChanged == sampleRateDropDown)
  52590. {
  52591. if (sampleRateDropDown->getSelectedId() > 0)
  52592. {
  52593. config.sampleRate = sampleRateDropDown->getSelectedId();
  52594. error = setup.manager->setAudioDeviceSetup (config, true);
  52595. }
  52596. }
  52597. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  52598. {
  52599. if (bufferSizeDropDown->getSelectedId() > 0)
  52600. {
  52601. config.bufferSize = bufferSizeDropDown->getSelectedId();
  52602. error = setup.manager->setAudioDeviceSetup (config, true);
  52603. }
  52604. }
  52605. if (error.isNotEmpty())
  52606. {
  52607. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  52608. T("Error when trying to open audio device!"),
  52609. error);
  52610. }
  52611. }
  52612. void buttonClicked (Button* button)
  52613. {
  52614. if (button == showAdvancedSettingsButton)
  52615. {
  52616. showAdvancedSettingsButton->setVisible (false);
  52617. resized();
  52618. }
  52619. else if (button == showUIButton)
  52620. {
  52621. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  52622. if (device != 0 && device->showControlPanel())
  52623. {
  52624. setup.manager->closeAudioDevice();
  52625. setup.manager->restartLastAudioDevice();
  52626. getTopLevelComponent()->toFront (true);
  52627. }
  52628. }
  52629. else if (button == testButton && testButton != 0)
  52630. {
  52631. setup.manager->playTestSound();
  52632. }
  52633. }
  52634. void updateControlPanelButton()
  52635. {
  52636. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  52637. deleteAndZero (showUIButton);
  52638. if (currentDevice != 0 && currentDevice->hasControlPanel())
  52639. {
  52640. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  52641. TRANS ("opens the device's own control panel")));
  52642. showUIButton->addButtonListener (this);
  52643. }
  52644. resized();
  52645. }
  52646. void changeListenerCallback (void*)
  52647. {
  52648. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  52649. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  52650. {
  52651. if (outputDeviceDropDown == 0)
  52652. {
  52653. outputDeviceDropDown = new ComboBox (String::empty);
  52654. outputDeviceDropDown->addListener (this);
  52655. addAndMakeVisible (outputDeviceDropDown);
  52656. outputDeviceLabel = new Label (String::empty,
  52657. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  52658. : TRANS ("device:"));
  52659. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  52660. if (setup.maxNumOutputChannels > 0)
  52661. {
  52662. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  52663. testButton->addButtonListener (this);
  52664. }
  52665. }
  52666. addNamesToDeviceBox (*outputDeviceDropDown, false);
  52667. }
  52668. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  52669. {
  52670. if (inputDeviceDropDown == 0)
  52671. {
  52672. inputDeviceDropDown = new ComboBox (String::empty);
  52673. inputDeviceDropDown->addListener (this);
  52674. addAndMakeVisible (inputDeviceDropDown);
  52675. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  52676. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  52677. addAndMakeVisible (inputLevelMeter
  52678. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  52679. }
  52680. addNamesToDeviceBox (*inputDeviceDropDown, true);
  52681. }
  52682. updateControlPanelButton();
  52683. showCorrectDeviceName (inputDeviceDropDown, true);
  52684. showCorrectDeviceName (outputDeviceDropDown, false);
  52685. if (currentDevice != 0)
  52686. {
  52687. if (setup.maxNumOutputChannels > 0
  52688. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  52689. {
  52690. if (outputChanList == 0)
  52691. {
  52692. addAndMakeVisible (outputChanList
  52693. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  52694. TRANS ("(no audio output channels found)")));
  52695. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  52696. outputChanLabel->attachToComponent (outputChanList, true);
  52697. }
  52698. outputChanList->refresh();
  52699. }
  52700. else
  52701. {
  52702. deleteAndZero (outputChanLabel);
  52703. deleteAndZero (outputChanList);
  52704. }
  52705. if (setup.maxNumInputChannels > 0
  52706. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  52707. {
  52708. if (inputChanList == 0)
  52709. {
  52710. addAndMakeVisible (inputChanList
  52711. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  52712. TRANS ("(no audio input channels found)")));
  52713. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  52714. inputChanLabel->attachToComponent (inputChanList, true);
  52715. }
  52716. inputChanList->refresh();
  52717. }
  52718. else
  52719. {
  52720. deleteAndZero (inputChanLabel);
  52721. deleteAndZero (inputChanList);
  52722. }
  52723. // sample rate..
  52724. {
  52725. if (sampleRateDropDown == 0)
  52726. {
  52727. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  52728. sampleRateDropDown->addListener (this);
  52729. delete sampleRateLabel;
  52730. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  52731. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  52732. }
  52733. else
  52734. {
  52735. sampleRateDropDown->clear();
  52736. sampleRateDropDown->removeListener (this);
  52737. }
  52738. const int numRates = currentDevice->getNumSampleRates();
  52739. for (int i = 0; i < numRates; ++i)
  52740. {
  52741. const int rate = roundDoubleToInt (currentDevice->getSampleRate (i));
  52742. sampleRateDropDown->addItem (String (rate) + T(" Hz"), rate);
  52743. }
  52744. sampleRateDropDown->setSelectedId (roundDoubleToInt (currentDevice->getCurrentSampleRate()), true);
  52745. sampleRateDropDown->addListener (this);
  52746. }
  52747. // buffer size
  52748. {
  52749. if (bufferSizeDropDown == 0)
  52750. {
  52751. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  52752. bufferSizeDropDown->addListener (this);
  52753. delete bufferSizeLabel;
  52754. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  52755. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  52756. }
  52757. else
  52758. {
  52759. bufferSizeDropDown->clear();
  52760. }
  52761. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  52762. double currentRate = currentDevice->getCurrentSampleRate();
  52763. if (currentRate == 0)
  52764. currentRate = 48000.0;
  52765. for (int i = 0; i < numBufferSizes; ++i)
  52766. {
  52767. const int bs = currentDevice->getBufferSizeSamples (i);
  52768. bufferSizeDropDown->addItem (String (bs)
  52769. + T(" samples (")
  52770. + String (bs * 1000.0 / currentRate, 1)
  52771. + T(" ms)"),
  52772. bs);
  52773. }
  52774. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  52775. }
  52776. }
  52777. else
  52778. {
  52779. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  52780. deleteAndZero (sampleRateLabel);
  52781. deleteAndZero (bufferSizeLabel);
  52782. deleteAndZero (sampleRateDropDown);
  52783. deleteAndZero (bufferSizeDropDown);
  52784. if (outputDeviceDropDown != 0)
  52785. outputDeviceDropDown->setSelectedId (-1, true);
  52786. if (inputDeviceDropDown != 0)
  52787. inputDeviceDropDown->setSelectedId (-1, true);
  52788. }
  52789. resized();
  52790. setSize (getWidth(), getLowestY() + 4);
  52791. }
  52792. private:
  52793. AudioIODeviceType* const type;
  52794. const AudioIODeviceType::DeviceSetupDetails setup;
  52795. ComboBox* outputDeviceDropDown;
  52796. ComboBox* inputDeviceDropDown;
  52797. ComboBox* sampleRateDropDown;
  52798. ComboBox* bufferSizeDropDown;
  52799. Label* outputDeviceLabel;
  52800. Label* inputDeviceLabel;
  52801. Label* sampleRateLabel;
  52802. Label* bufferSizeLabel;
  52803. Label* inputChanLabel;
  52804. Label* outputChanLabel;
  52805. TextButton* testButton;
  52806. Component* inputLevelMeter;
  52807. TextButton* showUIButton;
  52808. TextButton* showAdvancedSettingsButton;
  52809. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  52810. {
  52811. if (box != 0)
  52812. {
  52813. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  52814. const int index = type->getIndexOfDevice (currentDevice, isInput);
  52815. box->setSelectedId (index + 1, true);
  52816. if (testButton != 0 && ! isInput)
  52817. testButton->setEnabled (index >= 0);
  52818. }
  52819. }
  52820. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  52821. {
  52822. const StringArray devs (type->getDeviceNames (isInputs));
  52823. combo.clear (true);
  52824. for (int i = 0; i < devs.size(); ++i)
  52825. combo.addItem (devs[i], i + 1);
  52826. combo.addItem (TRANS("<< none >>"), -1);
  52827. combo.setSelectedId (-1, true);
  52828. }
  52829. int getLowestY() const
  52830. {
  52831. int y = 0;
  52832. for (int i = getNumChildComponents(); --i >= 0;)
  52833. y = jmax (y, getChildComponent (i)->getBottom());
  52834. return y;
  52835. }
  52836. class ChannelSelectorListBox : public ListBox,
  52837. public ListBoxModel
  52838. {
  52839. public:
  52840. enum BoxType
  52841. {
  52842. audioInputType,
  52843. audioOutputType
  52844. };
  52845. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  52846. const BoxType type_,
  52847. const String& noItemsMessage_)
  52848. : ListBox (String::empty, 0),
  52849. setup (setup_),
  52850. type (type_),
  52851. noItemsMessage (noItemsMessage_)
  52852. {
  52853. refresh();
  52854. setModel (this);
  52855. setOutlineThickness (1);
  52856. }
  52857. ~ChannelSelectorListBox()
  52858. {
  52859. }
  52860. void refresh()
  52861. {
  52862. items.clear();
  52863. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  52864. if (currentDevice != 0)
  52865. {
  52866. if (type == audioInputType)
  52867. items = currentDevice->getInputChannelNames();
  52868. else if (type == audioOutputType)
  52869. items = currentDevice->getOutputChannelNames();
  52870. if (setup.useStereoPairs)
  52871. {
  52872. StringArray pairs;
  52873. for (int i = 0; i < items.size(); i += 2)
  52874. {
  52875. String name (items[i]);
  52876. String name2 (items[i + 1]);
  52877. String commonBit;
  52878. for (int j = 0; j < name.length(); ++j)
  52879. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  52880. commonBit = name.substring (0, j);
  52881. pairs.add (name.trim()
  52882. + " + "
  52883. + name2.substring (commonBit.length()).trim());
  52884. }
  52885. items = pairs;
  52886. }
  52887. }
  52888. updateContent();
  52889. repaint();
  52890. }
  52891. int getNumRows()
  52892. {
  52893. return items.size();
  52894. }
  52895. void paintListBoxItem (int row,
  52896. Graphics& g,
  52897. int width, int height,
  52898. bool rowIsSelected)
  52899. {
  52900. if (((unsigned int) row) < (unsigned int) items.size())
  52901. {
  52902. if (rowIsSelected)
  52903. g.fillAll (findColour (TextEditor::highlightColourId)
  52904. .withMultipliedAlpha (0.3f));
  52905. const String item (items [row]);
  52906. bool enabled = false;
  52907. AudioDeviceManager::AudioDeviceSetup config;
  52908. setup.manager->getAudioDeviceSetup (config);
  52909. if (setup.useStereoPairs)
  52910. {
  52911. if (type == audioInputType)
  52912. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  52913. else if (type == audioOutputType)
  52914. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  52915. }
  52916. else
  52917. {
  52918. if (type == audioInputType)
  52919. enabled = config.inputChannels [row];
  52920. else if (type == audioOutputType)
  52921. enabled = config.outputChannels [row];
  52922. }
  52923. const int x = getTickX();
  52924. const int tickW = height - height / 4;
  52925. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  52926. enabled, true, true, false);
  52927. g.setFont (height * 0.6f);
  52928. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  52929. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  52930. }
  52931. }
  52932. void listBoxItemClicked (int row, const MouseEvent& e)
  52933. {
  52934. selectRow (row);
  52935. if (e.x < getTickX())
  52936. flipEnablement (row);
  52937. }
  52938. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  52939. {
  52940. flipEnablement (row);
  52941. }
  52942. void returnKeyPressed (int row)
  52943. {
  52944. flipEnablement (row);
  52945. }
  52946. void paint (Graphics& g)
  52947. {
  52948. ListBox::paint (g);
  52949. if (items.size() == 0)
  52950. {
  52951. g.setColour (Colours::grey);
  52952. g.setFont (13.0f);
  52953. g.drawText (noItemsMessage,
  52954. 0, 0, getWidth(), getHeight() / 2,
  52955. Justification::centred, true);
  52956. }
  52957. }
  52958. int getBestHeight (int maxHeight)
  52959. {
  52960. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  52961. getNumRows())
  52962. + getOutlineThickness() * 2;
  52963. }
  52964. juce_UseDebuggingNewOperator
  52965. private:
  52966. const AudioIODeviceType::DeviceSetupDetails setup;
  52967. const BoxType type;
  52968. const String noItemsMessage;
  52969. StringArray items;
  52970. void flipEnablement (const int row)
  52971. {
  52972. jassert (type == audioInputType || type == audioOutputType);
  52973. if (((unsigned int) row) < (unsigned int) items.size())
  52974. {
  52975. AudioDeviceManager::AudioDeviceSetup config;
  52976. setup.manager->getAudioDeviceSetup (config);
  52977. if (setup.useStereoPairs)
  52978. {
  52979. BitArray bits;
  52980. BitArray& original = (type == audioInputType ? config.inputChannels
  52981. : config.outputChannels);
  52982. int i;
  52983. for (i = 0; i < 256; i += 2)
  52984. bits.setBit (i / 2, original [i] || original [i + 1]);
  52985. if (type == audioInputType)
  52986. {
  52987. config.useDefaultInputChannels = false;
  52988. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  52989. }
  52990. else
  52991. {
  52992. config.useDefaultOutputChannels = false;
  52993. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  52994. }
  52995. for (i = 0; i < 256; ++i)
  52996. original.setBit (i, bits [i / 2]);
  52997. }
  52998. else
  52999. {
  53000. if (type == audioInputType)
  53001. {
  53002. config.useDefaultInputChannels = false;
  53003. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  53004. }
  53005. else
  53006. {
  53007. config.useDefaultOutputChannels = false;
  53008. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  53009. }
  53010. }
  53011. String error (setup.manager->setAudioDeviceSetup (config, true));
  53012. if (! error.isEmpty())
  53013. {
  53014. //xxx
  53015. }
  53016. }
  53017. }
  53018. static void flipBit (BitArray& chans, int index, int minNumber, int maxNumber)
  53019. {
  53020. const int numActive = chans.countNumberOfSetBits();
  53021. if (chans [index])
  53022. {
  53023. if (numActive > minNumber)
  53024. chans.setBit (index, false);
  53025. }
  53026. else
  53027. {
  53028. if (numActive >= maxNumber)
  53029. {
  53030. const int firstActiveChan = chans.findNextSetBit();
  53031. chans.setBit (index > firstActiveChan
  53032. ? firstActiveChan : chans.getHighestBit(),
  53033. false);
  53034. }
  53035. chans.setBit (index, true);
  53036. }
  53037. }
  53038. int getTickX() const throw()
  53039. {
  53040. return getRowHeight() + 5;
  53041. }
  53042. ChannelSelectorListBox (const ChannelSelectorListBox&);
  53043. const ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  53044. };
  53045. ChannelSelectorListBox* inputChanList;
  53046. ChannelSelectorListBox* outputChanList;
  53047. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  53048. const AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  53049. };
  53050. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  53051. const int minInputChannels_,
  53052. const int maxInputChannels_,
  53053. const int minOutputChannels_,
  53054. const int maxOutputChannels_,
  53055. const bool showMidiInputOptions,
  53056. const bool showMidiOutputSelector,
  53057. const bool showChannelsAsStereoPairs_,
  53058. const bool hideAdvancedOptionsWithButton_)
  53059. : deviceManager (deviceManager_),
  53060. minOutputChannels (minOutputChannels_),
  53061. maxOutputChannels (maxOutputChannels_),
  53062. minInputChannels (minInputChannels_),
  53063. maxInputChannels (maxInputChannels_),
  53064. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  53065. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_),
  53066. deviceTypeDropDown (0),
  53067. deviceTypeDropDownLabel (0),
  53068. audioDeviceSettingsComp (0)
  53069. {
  53070. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  53071. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  53072. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  53073. {
  53074. deviceTypeDropDown = new ComboBox (String::empty);
  53075. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  53076. {
  53077. deviceTypeDropDown
  53078. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  53079. i + 1);
  53080. }
  53081. addAndMakeVisible (deviceTypeDropDown);
  53082. deviceTypeDropDown->addListener (this);
  53083. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  53084. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  53085. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  53086. }
  53087. if (showMidiInputOptions)
  53088. {
  53089. addAndMakeVisible (midiInputsList
  53090. = new MidiInputSelectorComponentListBox (deviceManager,
  53091. TRANS("(no midi inputs available)"),
  53092. 0, 0));
  53093. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  53094. midiInputsLabel->setJustificationType (Justification::topRight);
  53095. midiInputsLabel->attachToComponent (midiInputsList, true);
  53096. }
  53097. else
  53098. {
  53099. midiInputsList = 0;
  53100. midiInputsLabel = 0;
  53101. }
  53102. if (showMidiOutputSelector)
  53103. {
  53104. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  53105. midiOutputSelector->addListener (this);
  53106. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  53107. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  53108. }
  53109. else
  53110. {
  53111. midiOutputSelector = 0;
  53112. midiOutputLabel = 0;
  53113. }
  53114. deviceManager_.addChangeListener (this);
  53115. changeListenerCallback (0);
  53116. }
  53117. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  53118. {
  53119. deviceManager.removeChangeListener (this);
  53120. deleteAllChildren();
  53121. }
  53122. void AudioDeviceSelectorComponent::resized()
  53123. {
  53124. const int lx = proportionOfWidth (0.35f);
  53125. const int w = proportionOfWidth (0.4f);
  53126. const int h = 24;
  53127. const int space = 6;
  53128. const int dh = h + space;
  53129. int y = 15;
  53130. if (deviceTypeDropDown != 0)
  53131. {
  53132. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  53133. y += dh + space * 2;
  53134. }
  53135. if (audioDeviceSettingsComp != 0)
  53136. {
  53137. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  53138. y += audioDeviceSettingsComp->getHeight() + space;
  53139. }
  53140. if (midiInputsList != 0)
  53141. {
  53142. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space));
  53143. midiInputsList->setBounds (lx, y, w, bh);
  53144. y += bh + space;
  53145. }
  53146. if (midiOutputSelector != 0)
  53147. midiOutputSelector->setBounds (lx, y, w, h);
  53148. }
  53149. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  53150. {
  53151. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  53152. if (device != 0 && device->hasControlPanel())
  53153. {
  53154. if (device->showControlPanel())
  53155. deviceManager.restartLastAudioDevice();
  53156. getTopLevelComponent()->toFront (true);
  53157. }
  53158. }
  53159. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  53160. {
  53161. if (comboBoxThatHasChanged == deviceTypeDropDown)
  53162. {
  53163. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  53164. if (type != 0)
  53165. {
  53166. deleteAndZero (audioDeviceSettingsComp);
  53167. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  53168. changeListenerCallback (0); // needed in case the type hasn't actally changed
  53169. }
  53170. }
  53171. else if (comboBoxThatHasChanged == midiOutputSelector)
  53172. {
  53173. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  53174. }
  53175. }
  53176. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  53177. {
  53178. if (deviceTypeDropDown != 0)
  53179. {
  53180. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  53181. }
  53182. if (audioDeviceSettingsComp == 0
  53183. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  53184. {
  53185. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  53186. deleteAndZero (audioDeviceSettingsComp);
  53187. AudioIODeviceType* const type
  53188. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  53189. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  53190. if (type != 0)
  53191. {
  53192. AudioIODeviceType::DeviceSetupDetails details;
  53193. details.manager = &deviceManager;
  53194. details.minNumInputChannels = minInputChannels;
  53195. details.maxNumInputChannels = maxInputChannels;
  53196. details.minNumOutputChannels = minOutputChannels;
  53197. details.maxNumOutputChannels = maxOutputChannels;
  53198. details.useStereoPairs = showChannelsAsStereoPairs;
  53199. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  53200. if (audioDeviceSettingsComp != 0)
  53201. {
  53202. addAndMakeVisible (audioDeviceSettingsComp);
  53203. audioDeviceSettingsComp->resized();
  53204. }
  53205. }
  53206. }
  53207. if (midiInputsList != 0)
  53208. {
  53209. midiInputsList->updateContent();
  53210. midiInputsList->repaint();
  53211. }
  53212. if (midiOutputSelector != 0)
  53213. {
  53214. midiOutputSelector->clear();
  53215. const StringArray midiOuts (MidiOutput::getDevices());
  53216. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  53217. midiOutputSelector->addSeparator();
  53218. for (int i = 0; i < midiOuts.size(); ++i)
  53219. midiOutputSelector->addItem (midiOuts[i], i + 1);
  53220. int current = -1;
  53221. if (deviceManager.getDefaultMidiOutput() != 0)
  53222. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  53223. midiOutputSelector->setSelectedId (current, true);
  53224. }
  53225. resized();
  53226. }
  53227. END_JUCE_NAMESPACE
  53228. /********* End of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  53229. /********* Start of inlined file: juce_BubbleComponent.cpp *********/
  53230. BEGIN_JUCE_NAMESPACE
  53231. BubbleComponent::BubbleComponent()
  53232. : side (0),
  53233. allowablePlacements (above | below | left | right),
  53234. arrowTipX (0.0f),
  53235. arrowTipY (0.0f)
  53236. {
  53237. setInterceptsMouseClicks (false, false);
  53238. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  53239. setComponentEffect (&shadow);
  53240. }
  53241. BubbleComponent::~BubbleComponent()
  53242. {
  53243. }
  53244. void BubbleComponent::paint (Graphics& g)
  53245. {
  53246. int x = content.getX();
  53247. int y = content.getY();
  53248. int w = content.getWidth();
  53249. int h = content.getHeight();
  53250. int cw, ch;
  53251. getContentSize (cw, ch);
  53252. if (side == 3)
  53253. x += w - cw;
  53254. else if (side != 1)
  53255. x += (w - cw) / 2;
  53256. w = cw;
  53257. if (side == 2)
  53258. y += h - ch;
  53259. else if (side != 0)
  53260. y += (h - ch) / 2;
  53261. h = ch;
  53262. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  53263. (float) x, (float) y,
  53264. (float) w, (float) h);
  53265. const int cx = x + (w - cw) / 2;
  53266. const int cy = y + (h - ch) / 2;
  53267. const int indent = 3;
  53268. g.setOrigin (cx + indent, cy + indent);
  53269. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  53270. paintContent (g, cw - indent * 2, ch - indent * 2);
  53271. }
  53272. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  53273. {
  53274. allowablePlacements = newPlacement;
  53275. }
  53276. void BubbleComponent::setPosition (Component* componentToPointTo)
  53277. {
  53278. jassert (componentToPointTo->isValidComponent());
  53279. int tx = 0;
  53280. int ty = 0;
  53281. if (getParentComponent() != 0)
  53282. componentToPointTo->relativePositionToOtherComponent (getParentComponent(), tx, ty);
  53283. else
  53284. componentToPointTo->relativePositionToGlobal (tx, ty);
  53285. setPosition (Rectangle (tx, ty, componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  53286. }
  53287. void BubbleComponent::setPosition (const int arrowTipX,
  53288. const int arrowTipY)
  53289. {
  53290. setPosition (Rectangle (arrowTipX, arrowTipY, 1, 1));
  53291. }
  53292. void BubbleComponent::setPosition (const Rectangle& rectangleToPointTo)
  53293. {
  53294. Rectangle availableSpace;
  53295. if (getParentComponent() != 0)
  53296. {
  53297. availableSpace.setSize (getParentComponent()->getWidth(),
  53298. getParentComponent()->getHeight());
  53299. }
  53300. else
  53301. {
  53302. availableSpace = getParentMonitorArea();
  53303. }
  53304. int x = 0;
  53305. int y = 0;
  53306. int w = 150;
  53307. int h = 30;
  53308. getContentSize (w, h);
  53309. w += 30;
  53310. h += 30;
  53311. const float edgeIndent = 2.0f;
  53312. const int arrowLength = jmin (10, h / 3, w / 3);
  53313. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  53314. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  53315. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  53316. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  53317. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  53318. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  53319. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  53320. {
  53321. spaceLeft = spaceRight = 0;
  53322. }
  53323. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  53324. && (spaceLeft > w + 20 || spaceRight > w + 20))
  53325. {
  53326. spaceAbove = spaceBelow = 0;
  53327. }
  53328. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  53329. {
  53330. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  53331. arrowTipX = w * 0.5f;
  53332. content.setSize (w, h - arrowLength);
  53333. if (spaceAbove >= spaceBelow)
  53334. {
  53335. // above
  53336. y = rectangleToPointTo.getY() - h;
  53337. content.setPosition (0, 0);
  53338. arrowTipY = h - edgeIndent;
  53339. side = 2;
  53340. }
  53341. else
  53342. {
  53343. // below
  53344. y = rectangleToPointTo.getBottom();
  53345. content.setPosition (0, arrowLength);
  53346. arrowTipY = edgeIndent;
  53347. side = 0;
  53348. }
  53349. }
  53350. else
  53351. {
  53352. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  53353. arrowTipY = h * 0.5f;
  53354. content.setSize (w - arrowLength, h);
  53355. if (spaceLeft > spaceRight)
  53356. {
  53357. // on the left
  53358. x = rectangleToPointTo.getX() - w;
  53359. content.setPosition (0, 0);
  53360. arrowTipX = w - edgeIndent;
  53361. side = 3;
  53362. }
  53363. else
  53364. {
  53365. // on the right
  53366. x = rectangleToPointTo.getRight();
  53367. content.setPosition (arrowLength, 0);
  53368. arrowTipX = edgeIndent;
  53369. side = 1;
  53370. }
  53371. }
  53372. setBounds (x, y, w, h);
  53373. }
  53374. END_JUCE_NAMESPACE
  53375. /********* End of inlined file: juce_BubbleComponent.cpp *********/
  53376. /********* Start of inlined file: juce_BubbleMessageComponent.cpp *********/
  53377. BEGIN_JUCE_NAMESPACE
  53378. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  53379. : fadeOutLength (fadeOutLengthMs),
  53380. deleteAfterUse (false)
  53381. {
  53382. }
  53383. BubbleMessageComponent::~BubbleMessageComponent()
  53384. {
  53385. fadeOutComponent (fadeOutLength);
  53386. }
  53387. void BubbleMessageComponent::showAt (int x, int y,
  53388. const String& text,
  53389. const int numMillisecondsBeforeRemoving,
  53390. const bool removeWhenMouseClicked,
  53391. const bool deleteSelfAfterUse)
  53392. {
  53393. textLayout.clear();
  53394. textLayout.setText (text, Font (14.0f));
  53395. textLayout.layout (256, Justification::centredLeft, true);
  53396. setPosition (x, y);
  53397. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  53398. }
  53399. void BubbleMessageComponent::showAt (Component* const component,
  53400. const String& text,
  53401. const int numMillisecondsBeforeRemoving,
  53402. const bool removeWhenMouseClicked,
  53403. const bool deleteSelfAfterUse)
  53404. {
  53405. textLayout.clear();
  53406. textLayout.setText (text, Font (14.0f));
  53407. textLayout.layout (256, Justification::centredLeft, true);
  53408. setPosition (component);
  53409. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  53410. }
  53411. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  53412. const bool removeWhenMouseClicked,
  53413. const bool deleteSelfAfterUse)
  53414. {
  53415. setVisible (true);
  53416. deleteAfterUse = deleteSelfAfterUse;
  53417. if (numMillisecondsBeforeRemoving > 0)
  53418. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  53419. else
  53420. expiryTime = 0;
  53421. startTimer (77);
  53422. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  53423. if (! (removeWhenMouseClicked && isShowing()))
  53424. mouseClickCounter += 0xfffff;
  53425. repaint();
  53426. }
  53427. void BubbleMessageComponent::getContentSize (int& w, int& h)
  53428. {
  53429. w = textLayout.getWidth() + 16;
  53430. h = textLayout.getHeight() + 16;
  53431. }
  53432. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  53433. {
  53434. g.setColour (findColour (TooltipWindow::textColourId));
  53435. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  53436. }
  53437. void BubbleMessageComponent::timerCallback()
  53438. {
  53439. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  53440. {
  53441. stopTimer();
  53442. setVisible (false);
  53443. if (deleteAfterUse)
  53444. delete this;
  53445. }
  53446. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  53447. {
  53448. stopTimer();
  53449. fadeOutComponent (fadeOutLength);
  53450. if (deleteAfterUse)
  53451. delete this;
  53452. }
  53453. }
  53454. END_JUCE_NAMESPACE
  53455. /********* End of inlined file: juce_BubbleMessageComponent.cpp *********/
  53456. /********* Start of inlined file: juce_ColourSelector.cpp *********/
  53457. BEGIN_JUCE_NAMESPACE
  53458. static const int swatchesPerRow = 8;
  53459. static const int swatchHeight = 22;
  53460. class ColourComponentSlider : public Slider
  53461. {
  53462. public:
  53463. ColourComponentSlider (const String& name)
  53464. : Slider (name)
  53465. {
  53466. setRange (0.0, 255.0, 1.0);
  53467. }
  53468. ~ColourComponentSlider()
  53469. {
  53470. }
  53471. const String getTextFromValue (double currentValue)
  53472. {
  53473. return String::formatted (T("%02X"), (int)currentValue);
  53474. }
  53475. double getValueFromText (const String& text)
  53476. {
  53477. return (double) text.getHexValue32();
  53478. }
  53479. private:
  53480. ColourComponentSlider (const ColourComponentSlider&);
  53481. const ColourComponentSlider& operator= (const ColourComponentSlider&);
  53482. };
  53483. class ColourSpaceMarker : public Component
  53484. {
  53485. public:
  53486. ColourSpaceMarker()
  53487. {
  53488. setInterceptsMouseClicks (false, false);
  53489. }
  53490. ~ColourSpaceMarker()
  53491. {
  53492. }
  53493. void paint (Graphics& g)
  53494. {
  53495. g.setColour (Colour::greyLevel (0.1f));
  53496. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  53497. g.setColour (Colour::greyLevel (0.9f));
  53498. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  53499. }
  53500. private:
  53501. ColourSpaceMarker (const ColourSpaceMarker&);
  53502. const ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  53503. };
  53504. class ColourSpaceView : public Component
  53505. {
  53506. ColourSelector* const owner;
  53507. float& h;
  53508. float& s;
  53509. float& v;
  53510. float lastHue;
  53511. ColourSpaceMarker* marker;
  53512. const int edge;
  53513. public:
  53514. ColourSpaceView (ColourSelector* owner_,
  53515. float& h_, float& s_, float& v_,
  53516. const int edgeSize)
  53517. : owner (owner_),
  53518. h (h_), s (s_), v (v_),
  53519. lastHue (0.0f),
  53520. edge (edgeSize)
  53521. {
  53522. addAndMakeVisible (marker = new ColourSpaceMarker());
  53523. setMouseCursor (MouseCursor::CrosshairCursor);
  53524. }
  53525. ~ColourSpaceView()
  53526. {
  53527. deleteAllChildren();
  53528. }
  53529. void paint (Graphics& g)
  53530. {
  53531. const float hue = h;
  53532. const float xScale = 1.0f / (getWidth() - edge * 2);
  53533. const float yScale = 1.0f / (getHeight() - edge * 2);
  53534. const Rectangle clip (g.getClipBounds());
  53535. const int x1 = jmax (clip.getX(), edge) & ~1;
  53536. const int x2 = jmin (clip.getRight(), getWidth() - edge) | 1;
  53537. const int y1 = jmax (clip.getY(), edge) & ~1;
  53538. const int y2 = jmin (clip.getBottom(), getHeight() - edge) | 1;
  53539. for (int y = y1; y < y2; y += 2)
  53540. {
  53541. const float v = jlimit (0.0f, 1.0f, 1.0f - (y - edge) * yScale);
  53542. for (int x = x1; x < x2; x += 2)
  53543. {
  53544. const float s = jlimit (0.0f, 1.0f, (x - edge) * xScale);
  53545. g.setColour (Colour (hue, s, v, 1.0f));
  53546. g.fillRect (x, y, 2, 2);
  53547. }
  53548. }
  53549. }
  53550. void mouseDown (const MouseEvent& e)
  53551. {
  53552. mouseDrag (e);
  53553. }
  53554. void mouseDrag (const MouseEvent& e)
  53555. {
  53556. const float s = (e.x - edge) / (float) (getWidth() - edge * 2);
  53557. const float v = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  53558. owner->setSV (s, v);
  53559. }
  53560. void updateIfNeeded()
  53561. {
  53562. if (lastHue != h)
  53563. {
  53564. lastHue = h;
  53565. repaint();
  53566. }
  53567. resized();
  53568. }
  53569. void resized()
  53570. {
  53571. marker->setBounds (roundFloatToInt ((getWidth() - edge * 2) * s),
  53572. roundFloatToInt ((getHeight() - edge * 2) * (1.0f - v)),
  53573. edge * 2, edge * 2);
  53574. }
  53575. private:
  53576. ColourSpaceView (const ColourSpaceView&);
  53577. const ColourSpaceView& operator= (const ColourSpaceView&);
  53578. };
  53579. class HueSelectorMarker : public Component
  53580. {
  53581. public:
  53582. HueSelectorMarker()
  53583. {
  53584. setInterceptsMouseClicks (false, false);
  53585. }
  53586. ~HueSelectorMarker()
  53587. {
  53588. }
  53589. void paint (Graphics& g)
  53590. {
  53591. Path p;
  53592. p.addTriangle (1.0f, 1.0f,
  53593. getWidth() * 0.3f, getHeight() * 0.5f,
  53594. 1.0f, getHeight() - 1.0f);
  53595. p.addTriangle (getWidth() - 1.0f, 1.0f,
  53596. getWidth() * 0.7f, getHeight() * 0.5f,
  53597. getWidth() - 1.0f, getHeight() - 1.0f);
  53598. g.setColour (Colours::white.withAlpha (0.75f));
  53599. g.fillPath (p);
  53600. g.setColour (Colours::black.withAlpha (0.75f));
  53601. g.strokePath (p, PathStrokeType (1.2f));
  53602. }
  53603. private:
  53604. HueSelectorMarker (const HueSelectorMarker&);
  53605. const HueSelectorMarker& operator= (const HueSelectorMarker&);
  53606. };
  53607. class HueSelectorComp : public Component
  53608. {
  53609. public:
  53610. HueSelectorComp (ColourSelector* owner_,
  53611. float& h_, float& s_, float& v_,
  53612. const int edgeSize)
  53613. : owner (owner_),
  53614. h (h_), s (s_), v (v_),
  53615. lastHue (0.0f),
  53616. edge (edgeSize)
  53617. {
  53618. addAndMakeVisible (marker = new HueSelectorMarker());
  53619. }
  53620. ~HueSelectorComp()
  53621. {
  53622. deleteAllChildren();
  53623. }
  53624. void paint (Graphics& g)
  53625. {
  53626. const float yScale = 1.0f / (getHeight() - edge * 2);
  53627. const Rectangle clip (g.getClipBounds());
  53628. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  53629. {
  53630. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  53631. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  53632. }
  53633. }
  53634. void resized()
  53635. {
  53636. marker->setBounds (0, roundFloatToInt ((getHeight() - edge * 2) * h),
  53637. getWidth(), edge * 2);
  53638. }
  53639. void mouseDown (const MouseEvent& e)
  53640. {
  53641. mouseDrag (e);
  53642. }
  53643. void mouseDrag (const MouseEvent& e)
  53644. {
  53645. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  53646. owner->setHue (hue);
  53647. }
  53648. void updateIfNeeded()
  53649. {
  53650. resized();
  53651. }
  53652. private:
  53653. ColourSelector* const owner;
  53654. float& h;
  53655. float& s;
  53656. float& v;
  53657. float lastHue;
  53658. HueSelectorMarker* marker;
  53659. const int edge;
  53660. HueSelectorComp (const HueSelectorComp&);
  53661. const HueSelectorComp& operator= (const HueSelectorComp&);
  53662. };
  53663. class SwatchComponent : public Component
  53664. {
  53665. public:
  53666. SwatchComponent (ColourSelector* owner_, int index_)
  53667. : owner (owner_),
  53668. index (index_)
  53669. {
  53670. }
  53671. ~SwatchComponent()
  53672. {
  53673. }
  53674. void paint (Graphics& g)
  53675. {
  53676. const Colour colour (owner->getSwatchColour (index));
  53677. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  53678. 6, 6,
  53679. Colour (0xffdddddd).overlaidWith (colour),
  53680. Colour (0xffffffff).overlaidWith (colour));
  53681. }
  53682. void mouseDown (const MouseEvent&)
  53683. {
  53684. PopupMenu m;
  53685. m.addItem (1, TRANS("Use this swatch as the current colour"));
  53686. m.addSeparator();
  53687. m.addItem (2, TRANS("Set this swatch to the current colour"));
  53688. const int r = m.showAt (this);
  53689. if (r == 1)
  53690. {
  53691. owner->setCurrentColour (owner->getSwatchColour (index));
  53692. }
  53693. else if (r == 2)
  53694. {
  53695. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  53696. {
  53697. owner->setSwatchColour (index, owner->getCurrentColour());
  53698. repaint();
  53699. }
  53700. }
  53701. }
  53702. private:
  53703. ColourSelector* const owner;
  53704. const int index;
  53705. SwatchComponent (const SwatchComponent&);
  53706. const SwatchComponent& operator= (const SwatchComponent&);
  53707. };
  53708. ColourSelector::ColourSelector (const int flags_,
  53709. const int edgeGap_,
  53710. const int gapAroundColourSpaceComponent)
  53711. : colour (Colours::white),
  53712. flags (flags_),
  53713. topSpace (0),
  53714. edgeGap (edgeGap_)
  53715. {
  53716. // not much point having a selector with no components in it!
  53717. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  53718. updateHSV();
  53719. if ((flags & showSliders) != 0)
  53720. {
  53721. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  53722. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  53723. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  53724. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  53725. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  53726. for (int i = 4; --i >= 0;)
  53727. sliders[i]->addListener (this);
  53728. }
  53729. else
  53730. {
  53731. zeromem (sliders, sizeof (sliders));
  53732. }
  53733. if ((flags & showColourspace) != 0)
  53734. {
  53735. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  53736. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  53737. }
  53738. else
  53739. {
  53740. colourSpace = 0;
  53741. hueSelector = 0;
  53742. }
  53743. update();
  53744. }
  53745. ColourSelector::~ColourSelector()
  53746. {
  53747. dispatchPendingMessages();
  53748. deleteAllChildren();
  53749. }
  53750. const Colour ColourSelector::getCurrentColour() const
  53751. {
  53752. return ((flags & showAlphaChannel) != 0) ? colour
  53753. : colour.withAlpha ((uint8) 0xff);
  53754. }
  53755. void ColourSelector::setCurrentColour (const Colour& c)
  53756. {
  53757. if (c != colour)
  53758. {
  53759. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  53760. updateHSV();
  53761. update();
  53762. }
  53763. }
  53764. void ColourSelector::setHue (float newH)
  53765. {
  53766. newH = jlimit (0.0f, 1.0f, newH);
  53767. if (h != newH)
  53768. {
  53769. h = newH;
  53770. colour = Colour (h, s, v, colour.getFloatAlpha());
  53771. update();
  53772. }
  53773. }
  53774. void ColourSelector::setSV (float newS, float newV)
  53775. {
  53776. newS = jlimit (0.0f, 1.0f, newS);
  53777. newV = jlimit (0.0f, 1.0f, newV);
  53778. if (s != newS || v != newV)
  53779. {
  53780. s = newS;
  53781. v = newV;
  53782. colour = Colour (h, s, v, colour.getFloatAlpha());
  53783. update();
  53784. }
  53785. }
  53786. void ColourSelector::updateHSV()
  53787. {
  53788. colour.getHSB (h, s, v);
  53789. }
  53790. void ColourSelector::update()
  53791. {
  53792. if (sliders[0] != 0)
  53793. {
  53794. sliders[0]->setValue ((int) colour.getRed());
  53795. sliders[1]->setValue ((int) colour.getGreen());
  53796. sliders[2]->setValue ((int) colour.getBlue());
  53797. sliders[3]->setValue ((int) colour.getAlpha());
  53798. }
  53799. if (colourSpace != 0)
  53800. {
  53801. ((ColourSpaceView*) colourSpace)->updateIfNeeded();
  53802. ((HueSelectorComp*) hueSelector)->updateIfNeeded();
  53803. }
  53804. if ((flags & showColourAtTop) != 0)
  53805. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  53806. sendChangeMessage (this);
  53807. }
  53808. void ColourSelector::paint (Graphics& g)
  53809. {
  53810. g.fillAll (findColour (backgroundColourId));
  53811. if ((flags & showColourAtTop) != 0)
  53812. {
  53813. const Colour colour (getCurrentColour());
  53814. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  53815. 10, 10,
  53816. Colour (0xffdddddd).overlaidWith (colour),
  53817. Colour (0xffffffff).overlaidWith (colour));
  53818. g.setColour (Colours::white.overlaidWith (colour).contrasting());
  53819. g.setFont (14.0f, true);
  53820. g.drawText (((flags & showAlphaChannel) != 0)
  53821. ? String::formatted (T("#%02X%02X%02X%02X"),
  53822. (int) colour.getAlpha(),
  53823. (int) colour.getRed(),
  53824. (int) colour.getGreen(),
  53825. (int) colour.getBlue())
  53826. : String::formatted (T("#%02X%02X%02X"),
  53827. (int) colour.getRed(),
  53828. (int) colour.getGreen(),
  53829. (int) colour.getBlue()),
  53830. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  53831. Justification::centred, false);
  53832. }
  53833. if ((flags & showSliders) != 0)
  53834. {
  53835. g.setColour (findColour (labelTextColourId));
  53836. g.setFont (11.0f);
  53837. for (int i = 4; --i >= 0;)
  53838. {
  53839. if (sliders[i]->isVisible())
  53840. g.drawText (sliders[i]->getName() + T(":"),
  53841. 0, sliders[i]->getY(),
  53842. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  53843. Justification::centredRight, false);
  53844. }
  53845. }
  53846. }
  53847. void ColourSelector::resized()
  53848. {
  53849. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  53850. const int numSwatches = getNumSwatches();
  53851. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  53852. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  53853. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  53854. int y = topSpace;
  53855. if ((flags & showColourspace) != 0)
  53856. {
  53857. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  53858. colourSpace->setBounds (edgeGap, y,
  53859. getWidth() - hueWidth - edgeGap - 4,
  53860. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  53861. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  53862. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  53863. colourSpace->getHeight());
  53864. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  53865. }
  53866. if ((flags & showSliders) != 0)
  53867. {
  53868. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  53869. for (int i = 0; i < numSliders; ++i)
  53870. {
  53871. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  53872. proportionOfWidth (0.72f), sliderHeight - 2);
  53873. y += sliderHeight;
  53874. }
  53875. }
  53876. if (numSwatches > 0)
  53877. {
  53878. const int startX = 8;
  53879. const int xGap = 4;
  53880. const int yGap = 4;
  53881. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  53882. y += edgeGap;
  53883. if (swatchComponents.size() != numSwatches)
  53884. {
  53885. int i;
  53886. for (i = swatchComponents.size(); --i >= 0;)
  53887. {
  53888. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  53889. delete sc;
  53890. }
  53891. for (i = 0; i < numSwatches; ++i)
  53892. {
  53893. SwatchComponent* const sc = new SwatchComponent (this, i);
  53894. swatchComponents.add (sc);
  53895. addAndMakeVisible (sc);
  53896. }
  53897. }
  53898. int x = startX;
  53899. for (int i = 0; i < swatchComponents.size(); ++i)
  53900. {
  53901. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  53902. sc->setBounds (x + xGap / 2,
  53903. y + yGap / 2,
  53904. swatchWidth - xGap,
  53905. swatchHeight - yGap);
  53906. if (((i + 1) % swatchesPerRow) == 0)
  53907. {
  53908. x = startX;
  53909. y += swatchHeight;
  53910. }
  53911. else
  53912. {
  53913. x += swatchWidth;
  53914. }
  53915. }
  53916. }
  53917. }
  53918. void ColourSelector::sliderValueChanged (Slider*)
  53919. {
  53920. if (sliders[0] != 0)
  53921. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  53922. (uint8) sliders[1]->getValue(),
  53923. (uint8) sliders[2]->getValue(),
  53924. (uint8) sliders[3]->getValue()));
  53925. }
  53926. int ColourSelector::getNumSwatches() const
  53927. {
  53928. return 0;
  53929. }
  53930. const Colour ColourSelector::getSwatchColour (const int) const
  53931. {
  53932. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  53933. return Colours::black;
  53934. }
  53935. void ColourSelector::setSwatchColour (const int, const Colour&) const
  53936. {
  53937. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  53938. }
  53939. END_JUCE_NAMESPACE
  53940. /********* End of inlined file: juce_ColourSelector.cpp *********/
  53941. /********* Start of inlined file: juce_DropShadower.cpp *********/
  53942. BEGIN_JUCE_NAMESPACE
  53943. class ShadowWindow : public Component
  53944. {
  53945. Component* owner;
  53946. Image** shadowImageSections;
  53947. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  53948. public:
  53949. ShadowWindow (Component* const owner_,
  53950. const int type_,
  53951. Image** const shadowImageSections_)
  53952. : owner (owner_),
  53953. shadowImageSections (shadowImageSections_),
  53954. type (type_)
  53955. {
  53956. setInterceptsMouseClicks (false, false);
  53957. if (owner_->isOnDesktop())
  53958. {
  53959. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  53960. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  53961. | ComponentPeer::windowIsTemporary);
  53962. }
  53963. else if (owner_->getParentComponent() != 0)
  53964. {
  53965. owner_->getParentComponent()->addChildComponent (this);
  53966. }
  53967. }
  53968. ~ShadowWindow()
  53969. {
  53970. }
  53971. void paint (Graphics& g)
  53972. {
  53973. Image* const topLeft = shadowImageSections [type * 3];
  53974. Image* const bottomRight = shadowImageSections [type * 3 + 1];
  53975. Image* const filler = shadowImageSections [type * 3 + 2];
  53976. ImageBrush fillBrush (filler, 0, 0, 1.0f);
  53977. g.setOpacity (1.0f);
  53978. if (type < 2)
  53979. {
  53980. int imH = jmin (topLeft->getHeight(), getHeight() / 2);
  53981. g.drawImage (topLeft,
  53982. 0, 0, topLeft->getWidth(), imH,
  53983. 0, 0, topLeft->getWidth(), imH);
  53984. imH = jmin (bottomRight->getHeight(), getHeight() - getHeight() / 2);
  53985. g.drawImage (bottomRight,
  53986. 0, getHeight() - imH, bottomRight->getWidth(), imH,
  53987. 0, bottomRight->getHeight() - imH, bottomRight->getWidth(), imH);
  53988. g.setBrush (&fillBrush);
  53989. g.fillRect (0, topLeft->getHeight(), getWidth(), getHeight() - (topLeft->getHeight() + bottomRight->getHeight()));
  53990. }
  53991. else
  53992. {
  53993. int imW = jmin (topLeft->getWidth(), getWidth() / 2);
  53994. g.drawImage (topLeft,
  53995. 0, 0, imW, topLeft->getHeight(),
  53996. 0, 0, imW, topLeft->getHeight());
  53997. imW = jmin (bottomRight->getWidth(), getWidth() - getWidth() / 2);
  53998. g.drawImage (bottomRight,
  53999. getWidth() - imW, 0, imW, bottomRight->getHeight(),
  54000. bottomRight->getWidth() - imW, 0, imW, bottomRight->getHeight());
  54001. g.setBrush (&fillBrush);
  54002. g.fillRect (topLeft->getWidth(), 0, getWidth() - (topLeft->getWidth() + bottomRight->getWidth()), getHeight());
  54003. }
  54004. }
  54005. void resized()
  54006. {
  54007. repaint(); // (needed for correct repainting)
  54008. }
  54009. private:
  54010. ShadowWindow (const ShadowWindow&);
  54011. const ShadowWindow& operator= (const ShadowWindow&);
  54012. };
  54013. DropShadower::DropShadower (const float alpha_,
  54014. const int xOffset_,
  54015. const int yOffset_,
  54016. const float blurRadius_)
  54017. : owner (0),
  54018. numShadows (0),
  54019. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  54020. xOffset (xOffset_),
  54021. yOffset (yOffset_),
  54022. alpha (alpha_),
  54023. blurRadius (blurRadius_),
  54024. inDestructor (false),
  54025. reentrant (false)
  54026. {
  54027. }
  54028. DropShadower::~DropShadower()
  54029. {
  54030. if (owner != 0)
  54031. owner->removeComponentListener (this);
  54032. inDestructor = true;
  54033. deleteShadowWindows();
  54034. }
  54035. void DropShadower::deleteShadowWindows()
  54036. {
  54037. if (numShadows > 0)
  54038. {
  54039. int i;
  54040. for (i = numShadows; --i >= 0;)
  54041. delete shadowWindows[i];
  54042. for (i = 12; --i >= 0;)
  54043. delete shadowImageSections[i];
  54044. numShadows = 0;
  54045. }
  54046. }
  54047. void DropShadower::setOwner (Component* componentToFollow)
  54048. {
  54049. if (componentToFollow != owner)
  54050. {
  54051. if (owner != 0)
  54052. owner->removeComponentListener (this);
  54053. // (the component can't be null)
  54054. jassert (componentToFollow != 0);
  54055. owner = componentToFollow;
  54056. jassert (owner != 0);
  54057. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  54058. owner->addComponentListener (this);
  54059. updateShadows();
  54060. }
  54061. }
  54062. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  54063. {
  54064. updateShadows();
  54065. }
  54066. void DropShadower::componentBroughtToFront (Component&)
  54067. {
  54068. bringShadowWindowsToFront();
  54069. }
  54070. void DropShadower::componentChildrenChanged (Component&)
  54071. {
  54072. }
  54073. void DropShadower::componentParentHierarchyChanged (Component&)
  54074. {
  54075. deleteShadowWindows();
  54076. updateShadows();
  54077. }
  54078. void DropShadower::componentVisibilityChanged (Component&)
  54079. {
  54080. updateShadows();
  54081. }
  54082. void DropShadower::updateShadows()
  54083. {
  54084. if (reentrant || inDestructor || (owner == 0))
  54085. return;
  54086. reentrant = true;
  54087. ComponentPeer* const nw = owner->getPeer();
  54088. const bool isOwnerVisible = owner->isVisible()
  54089. && (nw == 0 || ! nw->isMinimised());
  54090. const bool createShadowWindows = numShadows == 0
  54091. && owner->getWidth() > 0
  54092. && owner->getHeight() > 0
  54093. && isOwnerVisible
  54094. && (Desktop::canUseSemiTransparentWindows()
  54095. || owner->getParentComponent() != 0);
  54096. if (createShadowWindows)
  54097. {
  54098. // keep a cached version of the image to save doing the gaussian too often
  54099. String imageId;
  54100. imageId << shadowEdge << T(',')
  54101. << xOffset << T(',')
  54102. << yOffset << T(',')
  54103. << alpha;
  54104. const int hash = imageId.hashCode();
  54105. Image* bigIm = ImageCache::getFromHashCode (hash);
  54106. if (bigIm == 0)
  54107. {
  54108. bigIm = new Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true);
  54109. Graphics bigG (*bigIm);
  54110. bigG.setColour (Colours::black.withAlpha (alpha));
  54111. bigG.fillRect (shadowEdge + xOffset,
  54112. shadowEdge + yOffset,
  54113. bigIm->getWidth() - (shadowEdge * 2),
  54114. bigIm->getHeight() - (shadowEdge * 2));
  54115. ImageConvolutionKernel blurKernel (roundFloatToInt (blurRadius * 2.0f));
  54116. blurKernel.createGaussianBlur (blurRadius);
  54117. blurKernel.applyToImage (*bigIm, 0,
  54118. xOffset,
  54119. yOffset,
  54120. bigIm->getWidth(),
  54121. bigIm->getHeight());
  54122. ImageCache::addImageToCache (bigIm, hash);
  54123. }
  54124. const int iw = bigIm->getWidth();
  54125. const int ih = bigIm->getHeight();
  54126. const int shadowEdge2 = shadowEdge * 2;
  54127. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  54128. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  54129. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  54130. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  54131. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  54132. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  54133. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  54134. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  54135. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  54136. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  54137. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  54138. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  54139. ImageCache::release (bigIm);
  54140. for (int i = 0; i < 4; ++i)
  54141. {
  54142. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  54143. ++numShadows;
  54144. }
  54145. }
  54146. if (numShadows > 0)
  54147. {
  54148. for (int i = numShadows; --i >= 0;)
  54149. {
  54150. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  54151. shadowWindows[i]->setVisible (isOwnerVisible);
  54152. }
  54153. const int x = owner->getX();
  54154. const int y = owner->getY() - shadowEdge;
  54155. const int w = owner->getWidth();
  54156. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  54157. shadowWindows[0]->setBounds (x - shadowEdge,
  54158. y,
  54159. shadowEdge,
  54160. h);
  54161. shadowWindows[1]->setBounds (x + w,
  54162. y,
  54163. shadowEdge,
  54164. h);
  54165. shadowWindows[2]->setBounds (x,
  54166. y,
  54167. w,
  54168. shadowEdge);
  54169. shadowWindows[3]->setBounds (x,
  54170. owner->getBottom(),
  54171. w,
  54172. shadowEdge);
  54173. }
  54174. reentrant = false;
  54175. if (createShadowWindows)
  54176. bringShadowWindowsToFront();
  54177. }
  54178. void DropShadower::setShadowImage (Image* const src,
  54179. const int num,
  54180. const int w,
  54181. const int h,
  54182. const int sx,
  54183. const int sy) throw()
  54184. {
  54185. shadowImageSections[num] = new Image (Image::ARGB, w, h, true);
  54186. Graphics g (*shadowImageSections[num]);
  54187. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  54188. }
  54189. void DropShadower::bringShadowWindowsToFront()
  54190. {
  54191. if (! (inDestructor || reentrant))
  54192. {
  54193. updateShadows();
  54194. reentrant = true;
  54195. for (int i = numShadows; --i >= 0;)
  54196. shadowWindows[i]->toBehind (owner);
  54197. reentrant = false;
  54198. }
  54199. }
  54200. END_JUCE_NAMESPACE
  54201. /********* End of inlined file: juce_DropShadower.cpp *********/
  54202. /********* Start of inlined file: juce_MagnifierComponent.cpp *********/
  54203. BEGIN_JUCE_NAMESPACE
  54204. class MagnifyingPeer : public ComponentPeer
  54205. {
  54206. public:
  54207. MagnifyingPeer (Component* const component,
  54208. MagnifierComponent* const magnifierComp_)
  54209. : ComponentPeer (component, 0),
  54210. magnifierComp (magnifierComp_)
  54211. {
  54212. }
  54213. ~MagnifyingPeer()
  54214. {
  54215. }
  54216. void* getNativeHandle() const { return 0; }
  54217. void setVisible (bool) {}
  54218. void setTitle (const String&) {}
  54219. void setPosition (int, int) {}
  54220. void setSize (int, int) {}
  54221. void setBounds (int, int, int, int, const bool) {}
  54222. void setMinimised (bool) {}
  54223. bool isMinimised() const { return false; }
  54224. void setFullScreen (bool) {}
  54225. bool isFullScreen() const { return false; }
  54226. const BorderSize getFrameSize() const { return BorderSize (0); }
  54227. bool setAlwaysOnTop (bool) { return true; }
  54228. void toFront (bool) {}
  54229. void toBehind (ComponentPeer*) {}
  54230. void setIcon (const Image&) {}
  54231. bool isFocused() const
  54232. {
  54233. return magnifierComp->hasKeyboardFocus (true);
  54234. }
  54235. void grabFocus()
  54236. {
  54237. ComponentPeer* peer = magnifierComp->getPeer();
  54238. if (peer != 0)
  54239. peer->grabFocus();
  54240. }
  54241. void textInputRequired (int x, int y)
  54242. {
  54243. ComponentPeer* peer = magnifierComp->getPeer();
  54244. if (peer != 0)
  54245. peer->textInputRequired (x, y);
  54246. }
  54247. void getBounds (int& x, int& y, int& w, int& h) const
  54248. {
  54249. x = magnifierComp->getScreenX();
  54250. y = magnifierComp->getScreenY();
  54251. w = component->getWidth();
  54252. h = component->getHeight();
  54253. }
  54254. int getScreenX() const { return magnifierComp->getScreenX(); }
  54255. int getScreenY() const { return magnifierComp->getScreenY(); }
  54256. void relativePositionToGlobal (int& x, int& y)
  54257. {
  54258. const double zoom = magnifierComp->getScaleFactor();
  54259. x = roundDoubleToInt (x * zoom);
  54260. y = roundDoubleToInt (y * zoom);
  54261. magnifierComp->relativePositionToGlobal (x, y);
  54262. }
  54263. void globalPositionToRelative (int& x, int& y)
  54264. {
  54265. magnifierComp->globalPositionToRelative (x, y);
  54266. const double zoom = magnifierComp->getScaleFactor();
  54267. x = roundDoubleToInt (x / zoom);
  54268. y = roundDoubleToInt (y / zoom);
  54269. }
  54270. bool contains (int x, int y, bool) const
  54271. {
  54272. return ((unsigned int) x) < (unsigned int) magnifierComp->getWidth()
  54273. && ((unsigned int) y) < (unsigned int) magnifierComp->getHeight();
  54274. }
  54275. void repaint (int x, int y, int w, int h)
  54276. {
  54277. const double zoom = magnifierComp->getScaleFactor();
  54278. magnifierComp->repaint ((int) (x * zoom),
  54279. (int) (y * zoom),
  54280. roundDoubleToInt (w * zoom) + 1,
  54281. roundDoubleToInt (h * zoom) + 1);
  54282. }
  54283. void performAnyPendingRepaintsNow()
  54284. {
  54285. }
  54286. juce_UseDebuggingNewOperator
  54287. private:
  54288. MagnifierComponent* const magnifierComp;
  54289. MagnifyingPeer (const MagnifyingPeer&);
  54290. const MagnifyingPeer& operator= (const MagnifyingPeer&);
  54291. };
  54292. class PeerHolderComp : public Component
  54293. {
  54294. public:
  54295. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  54296. : magnifierComp (magnifierComp_)
  54297. {
  54298. setVisible (true);
  54299. }
  54300. ~PeerHolderComp()
  54301. {
  54302. }
  54303. ComponentPeer* createNewPeer (int, void*)
  54304. {
  54305. return new MagnifyingPeer (this, magnifierComp);
  54306. }
  54307. void childBoundsChanged (Component* c)
  54308. {
  54309. if (c != 0)
  54310. {
  54311. setSize (c->getWidth(), c->getHeight());
  54312. magnifierComp->childBoundsChanged (this);
  54313. }
  54314. }
  54315. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  54316. {
  54317. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  54318. Component* const p = magnifierComp->getParentComponent();
  54319. if (p != 0)
  54320. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  54321. }
  54322. private:
  54323. MagnifierComponent* const magnifierComp;
  54324. PeerHolderComp (const PeerHolderComp&);
  54325. const PeerHolderComp& operator= (const PeerHolderComp&);
  54326. };
  54327. MagnifierComponent::MagnifierComponent (Component* const content_,
  54328. const bool deleteContentCompWhenNoLongerNeeded)
  54329. : content (content_),
  54330. scaleFactor (0.0),
  54331. peer (0),
  54332. deleteContent (deleteContentCompWhenNoLongerNeeded)
  54333. {
  54334. holderComp = new PeerHolderComp (this);
  54335. setScaleFactor (1.0);
  54336. }
  54337. MagnifierComponent::~MagnifierComponent()
  54338. {
  54339. delete holderComp;
  54340. if (deleteContent)
  54341. delete content;
  54342. }
  54343. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  54344. {
  54345. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  54346. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  54347. if (scaleFactor != newScaleFactor)
  54348. {
  54349. scaleFactor = newScaleFactor;
  54350. if (scaleFactor == 1.0)
  54351. {
  54352. holderComp->removeFromDesktop();
  54353. peer = 0;
  54354. addChildComponent (content);
  54355. childBoundsChanged (content);
  54356. }
  54357. else
  54358. {
  54359. holderComp->addAndMakeVisible (content);
  54360. holderComp->childBoundsChanged (content);
  54361. childBoundsChanged (holderComp);
  54362. holderComp->addToDesktop (0);
  54363. peer = holderComp->getPeer();
  54364. }
  54365. repaint();
  54366. }
  54367. }
  54368. void MagnifierComponent::paint (Graphics& g)
  54369. {
  54370. const int w = holderComp->getWidth();
  54371. const int h = holderComp->getHeight();
  54372. if (w == 0 || h == 0)
  54373. return;
  54374. const Rectangle r (g.getClipBounds());
  54375. const int srcX = (int) (r.getX() / scaleFactor);
  54376. const int srcY = (int) (r.getY() / scaleFactor);
  54377. int srcW = roundDoubleToInt (r.getRight() / scaleFactor) - srcX;
  54378. int srcH = roundDoubleToInt (r.getBottom() / scaleFactor) - srcY;
  54379. if (scaleFactor >= 1.0)
  54380. {
  54381. ++srcW;
  54382. ++srcH;
  54383. }
  54384. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  54385. temp.clear (srcX, srcY, srcW, srcH);
  54386. Graphics g2 (temp);
  54387. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  54388. holderComp->paintEntireComponent (g2);
  54389. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  54390. g.drawImage (&temp,
  54391. 0, 0, (int) (w * scaleFactor), (int) (h * scaleFactor),
  54392. 0, 0, w, h,
  54393. false);
  54394. }
  54395. void MagnifierComponent::childBoundsChanged (Component* c)
  54396. {
  54397. if (c != 0)
  54398. setSize (roundDoubleToInt (c->getWidth() * scaleFactor),
  54399. roundDoubleToInt (c->getHeight() * scaleFactor));
  54400. }
  54401. void MagnifierComponent::mouseDown (const MouseEvent& e)
  54402. {
  54403. if (peer != 0)
  54404. peer->handleMouseDown (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54405. }
  54406. void MagnifierComponent::mouseUp (const MouseEvent& e)
  54407. {
  54408. if (peer != 0)
  54409. peer->handleMouseUp (e.mods.getRawFlags(), scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54410. }
  54411. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  54412. {
  54413. if (peer != 0)
  54414. peer->handleMouseDrag (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54415. }
  54416. void MagnifierComponent::mouseMove (const MouseEvent& e)
  54417. {
  54418. if (peer != 0)
  54419. peer->handleMouseMove (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54420. }
  54421. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  54422. {
  54423. if (peer != 0)
  54424. peer->handleMouseEnter (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54425. }
  54426. void MagnifierComponent::mouseExit (const MouseEvent& e)
  54427. {
  54428. if (peer != 0)
  54429. peer->handleMouseExit (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  54430. }
  54431. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  54432. {
  54433. if (peer != 0)
  54434. peer->handleMouseWheel (roundFloatToInt (ix * 256.0f),
  54435. roundFloatToInt (iy * 256.0f),
  54436. e.eventTime.toMilliseconds());
  54437. else
  54438. Component::mouseWheelMove (e, ix, iy);
  54439. }
  54440. int MagnifierComponent::scaleInt (const int n) const throw()
  54441. {
  54442. return roundDoubleToInt (n / scaleFactor);
  54443. }
  54444. END_JUCE_NAMESPACE
  54445. /********* End of inlined file: juce_MagnifierComponent.cpp *********/
  54446. /********* Start of inlined file: juce_MidiKeyboardComponent.cpp *********/
  54447. BEGIN_JUCE_NAMESPACE
  54448. class MidiKeyboardUpDownButton : public Button
  54449. {
  54450. public:
  54451. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  54452. const int delta_)
  54453. : Button (String::empty),
  54454. owner (owner_),
  54455. delta (delta_)
  54456. {
  54457. setOpaque (true);
  54458. }
  54459. ~MidiKeyboardUpDownButton()
  54460. {
  54461. }
  54462. void clicked()
  54463. {
  54464. int note = owner->getLowestVisibleKey();
  54465. if (delta < 0)
  54466. note = (note - 1) / 12;
  54467. else
  54468. note = note / 12 + 1;
  54469. owner->setLowestVisibleKey (note * 12);
  54470. }
  54471. void paintButton (Graphics& g,
  54472. bool isMouseOverButton,
  54473. bool isButtonDown)
  54474. {
  54475. owner->drawUpDownButton (g, getWidth(), getHeight(),
  54476. isMouseOverButton, isButtonDown,
  54477. delta > 0);
  54478. }
  54479. private:
  54480. MidiKeyboardComponent* const owner;
  54481. const int delta;
  54482. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  54483. const MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  54484. };
  54485. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  54486. const Orientation orientation_)
  54487. : state (state_),
  54488. xOffset (0),
  54489. blackNoteLength (1),
  54490. keyWidth (16.0f),
  54491. orientation (orientation_),
  54492. midiChannel (1),
  54493. midiInChannelMask (0xffff),
  54494. velocity (1.0f),
  54495. noteUnderMouse (-1),
  54496. mouseDownNote (-1),
  54497. rangeStart (0),
  54498. rangeEnd (127),
  54499. firstKey (12 * 4),
  54500. canScroll (true),
  54501. mouseDragging (false),
  54502. keyPresses (4),
  54503. keyPressNotes (16),
  54504. keyMappingOctave (6),
  54505. octaveNumForMiddleC (3)
  54506. {
  54507. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  54508. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  54509. // initialise with a default set of querty key-mappings..
  54510. const char* const keymap = "awsedftgyhujkolp;";
  54511. for (int i = String (keymap).length(); --i >= 0;)
  54512. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  54513. setOpaque (true);
  54514. setWantsKeyboardFocus (true);
  54515. state.addListener (this);
  54516. }
  54517. MidiKeyboardComponent::~MidiKeyboardComponent()
  54518. {
  54519. state.removeListener (this);
  54520. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  54521. deleteAllChildren();
  54522. }
  54523. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  54524. {
  54525. keyWidth = widthInPixels;
  54526. resized();
  54527. }
  54528. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  54529. {
  54530. if (orientation != newOrientation)
  54531. {
  54532. orientation = newOrientation;
  54533. resized();
  54534. }
  54535. }
  54536. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  54537. const int highestNote)
  54538. {
  54539. jassert (lowestNote >= 0 && lowestNote <= 127);
  54540. jassert (highestNote >= 0 && highestNote <= 127);
  54541. jassert (lowestNote <= highestNote);
  54542. if (rangeStart != lowestNote || rangeEnd != highestNote)
  54543. {
  54544. rangeStart = jlimit (0, 127, lowestNote);
  54545. rangeEnd = jlimit (0, 127, highestNote);
  54546. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  54547. resized();
  54548. }
  54549. }
  54550. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  54551. {
  54552. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  54553. if (noteNumber != firstKey)
  54554. {
  54555. firstKey = noteNumber;
  54556. sendChangeMessage (this);
  54557. resized();
  54558. }
  54559. }
  54560. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  54561. {
  54562. if (canScroll != canScroll_)
  54563. {
  54564. canScroll = canScroll_;
  54565. resized();
  54566. }
  54567. }
  54568. void MidiKeyboardComponent::colourChanged()
  54569. {
  54570. repaint();
  54571. }
  54572. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  54573. {
  54574. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  54575. if (midiChannel != midiChannelNumber)
  54576. {
  54577. resetAnyKeysInUse();
  54578. midiChannel = jlimit (1, 16, midiChannelNumber);
  54579. }
  54580. }
  54581. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  54582. {
  54583. midiInChannelMask = midiChannelMask;
  54584. triggerAsyncUpdate();
  54585. }
  54586. void MidiKeyboardComponent::setVelocity (const float velocity_)
  54587. {
  54588. velocity = jlimit (0.0f, 1.0f, velocity_);
  54589. }
  54590. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth, int& x, int& w) const
  54591. {
  54592. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  54593. static const float blackNoteWidth = 0.7f;
  54594. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  54595. 1.0f, 2 - blackNoteWidth * 0.4f,
  54596. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  54597. 4.0f, 5 - blackNoteWidth * 0.5f,
  54598. 5.0f, 6 - blackNoteWidth * 0.3f,
  54599. 6.0f };
  54600. static const float widths[] = { 1.0f, blackNoteWidth,
  54601. 1.0f, blackNoteWidth,
  54602. 1.0f, 1.0f, blackNoteWidth,
  54603. 1.0f, blackNoteWidth,
  54604. 1.0f, blackNoteWidth,
  54605. 1.0f };
  54606. const int octave = midiNoteNumber / 12;
  54607. const int note = midiNoteNumber % 12;
  54608. x = roundFloatToInt (octave * 7.0f * keyWidth + notePos [note] * keyWidth);
  54609. w = roundFloatToInt (widths [note] * keyWidth);
  54610. }
  54611. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  54612. {
  54613. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  54614. int rx, rw;
  54615. getKeyPosition (rangeStart, keyWidth, rx, rw);
  54616. x -= xOffset + rx;
  54617. }
  54618. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  54619. {
  54620. int x, y;
  54621. getKeyPos (midiNoteNumber, x, y);
  54622. return x;
  54623. }
  54624. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  54625. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  54626. int MidiKeyboardComponent::xyToNote (int x, int y)
  54627. {
  54628. if (! reallyContains (x, y, false))
  54629. return -1;
  54630. if (orientation != horizontalKeyboard)
  54631. {
  54632. swapVariables (x, y);
  54633. if (orientation == verticalKeyboardFacingLeft)
  54634. y = getWidth() - y;
  54635. else
  54636. x = getHeight() - x;
  54637. }
  54638. return remappedXYToNote (x + xOffset, y);
  54639. }
  54640. int MidiKeyboardComponent::remappedXYToNote (int x, int y) const
  54641. {
  54642. if (y < blackNoteLength)
  54643. {
  54644. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  54645. {
  54646. for (int i = 0; i < 5; ++i)
  54647. {
  54648. const int note = octaveStart + blackNotes [i];
  54649. if (note >= rangeStart && note <= rangeEnd)
  54650. {
  54651. int kx, kw;
  54652. getKeyPos (note, kx, kw);
  54653. kx += xOffset;
  54654. if (x >= kx && x < kx + kw)
  54655. return note;
  54656. }
  54657. }
  54658. }
  54659. }
  54660. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  54661. {
  54662. for (int i = 0; i < 7; ++i)
  54663. {
  54664. const int note = octaveStart + whiteNotes [i];
  54665. if (note >= rangeStart && note <= rangeEnd)
  54666. {
  54667. int kx, kw;
  54668. getKeyPos (note, kx, kw);
  54669. kx += xOffset;
  54670. if (x >= kx && x < kx + kw)
  54671. return note;
  54672. }
  54673. }
  54674. }
  54675. return -1;
  54676. }
  54677. void MidiKeyboardComponent::repaintNote (const int noteNum)
  54678. {
  54679. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  54680. {
  54681. int x, w;
  54682. getKeyPos (noteNum, x, w);
  54683. if (orientation == horizontalKeyboard)
  54684. repaint (x, 0, w, getHeight());
  54685. else if (orientation == verticalKeyboardFacingLeft)
  54686. repaint (0, x, getWidth(), w);
  54687. else if (orientation == verticalKeyboardFacingRight)
  54688. repaint (0, getHeight() - x - w, getWidth(), w);
  54689. }
  54690. }
  54691. void MidiKeyboardComponent::paint (Graphics& g)
  54692. {
  54693. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  54694. const Colour lineColour (findColour (keySeparatorLineColourId));
  54695. const Colour textColour (findColour (textLabelColourId));
  54696. int x, w, octave;
  54697. for (octave = 0; octave < 128; octave += 12)
  54698. {
  54699. for (int white = 0; white < 7; ++white)
  54700. {
  54701. const int noteNum = octave + whiteNotes [white];
  54702. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  54703. {
  54704. getKeyPos (noteNum, x, w);
  54705. if (orientation == horizontalKeyboard)
  54706. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  54707. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54708. noteUnderMouse == noteNum,
  54709. lineColour, textColour);
  54710. else if (orientation == verticalKeyboardFacingLeft)
  54711. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  54712. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54713. noteUnderMouse == noteNum,
  54714. lineColour, textColour);
  54715. else if (orientation == verticalKeyboardFacingRight)
  54716. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  54717. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54718. noteUnderMouse == noteNum,
  54719. lineColour, textColour);
  54720. }
  54721. }
  54722. }
  54723. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54724. if (orientation == verticalKeyboardFacingLeft)
  54725. {
  54726. x1 = getWidth() - 1.0f;
  54727. x2 = getWidth() - 5.0f;
  54728. }
  54729. else if (orientation == verticalKeyboardFacingRight)
  54730. x2 = 5.0f;
  54731. else
  54732. y2 = 5.0f;
  54733. GradientBrush gb (Colours::black.withAlpha (0.3f), x1, y1,
  54734. Colours::transparentBlack, x2, y2, false);
  54735. g.setBrush (&gb);
  54736. getKeyPos (rangeEnd, x, w);
  54737. x += w;
  54738. if (orientation == verticalKeyboardFacingLeft)
  54739. g.fillRect (getWidth() - 5, 0, 5, x);
  54740. else if (orientation == verticalKeyboardFacingRight)
  54741. g.fillRect (0, 0, 5, x);
  54742. else
  54743. g.fillRect (0, 0, x, 5);
  54744. g.setColour (lineColour);
  54745. if (orientation == verticalKeyboardFacingLeft)
  54746. g.fillRect (0, 0, 1, x);
  54747. else if (orientation == verticalKeyboardFacingRight)
  54748. g.fillRect (getWidth() - 1, 0, 1, x);
  54749. else
  54750. g.fillRect (0, getHeight() - 1, x, 1);
  54751. const Colour blackNoteColour (findColour (blackNoteColourId));
  54752. for (octave = 0; octave < 128; octave += 12)
  54753. {
  54754. for (int black = 0; black < 5; ++black)
  54755. {
  54756. const int noteNum = octave + blackNotes [black];
  54757. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  54758. {
  54759. getKeyPos (noteNum, x, w);
  54760. if (orientation == horizontalKeyboard)
  54761. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  54762. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54763. noteUnderMouse == noteNum,
  54764. blackNoteColour);
  54765. else if (orientation == verticalKeyboardFacingLeft)
  54766. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  54767. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54768. noteUnderMouse == noteNum,
  54769. blackNoteColour);
  54770. else if (orientation == verticalKeyboardFacingRight)
  54771. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  54772. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54773. noteUnderMouse == noteNum,
  54774. blackNoteColour);
  54775. }
  54776. }
  54777. }
  54778. }
  54779. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  54780. Graphics& g, int x, int y, int w, int h,
  54781. bool isDown, bool isOver,
  54782. const Colour& lineColour,
  54783. const Colour& textColour)
  54784. {
  54785. Colour c (Colours::transparentWhite);
  54786. if (isDown)
  54787. c = findColour (keyDownOverlayColourId);
  54788. if (isOver)
  54789. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  54790. g.setColour (c);
  54791. g.fillRect (x, y, w, h);
  54792. const String text (getWhiteNoteText (midiNoteNumber));
  54793. if (! text.isEmpty())
  54794. {
  54795. g.setColour (textColour);
  54796. Font f (jmin (12.0f, keyWidth * 0.9f));
  54797. f.setHorizontalScale (0.8f);
  54798. g.setFont (f);
  54799. Justification justification (Justification::centredBottom);
  54800. if (orientation == verticalKeyboardFacingLeft)
  54801. justification = Justification::centredLeft;
  54802. else if (orientation == verticalKeyboardFacingRight)
  54803. justification = Justification::centredRight;
  54804. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  54805. }
  54806. g.setColour (lineColour);
  54807. if (orientation == horizontalKeyboard)
  54808. g.fillRect (x, y, 1, h);
  54809. else if (orientation == verticalKeyboardFacingLeft)
  54810. g.fillRect (x, y, w, 1);
  54811. else if (orientation == verticalKeyboardFacingRight)
  54812. g.fillRect (x, y + h - 1, w, 1);
  54813. if (midiNoteNumber == rangeEnd)
  54814. {
  54815. if (orientation == horizontalKeyboard)
  54816. g.fillRect (x + w, y, 1, h);
  54817. else if (orientation == verticalKeyboardFacingLeft)
  54818. g.fillRect (x, y + h, w, 1);
  54819. else if (orientation == verticalKeyboardFacingRight)
  54820. g.fillRect (x, y - 1, w, 1);
  54821. }
  54822. }
  54823. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  54824. Graphics& g, int x, int y, int w, int h,
  54825. bool isDown, bool isOver,
  54826. const Colour& noteFillColour)
  54827. {
  54828. Colour c (noteFillColour);
  54829. if (isDown)
  54830. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  54831. if (isOver)
  54832. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  54833. g.setColour (c);
  54834. g.fillRect (x, y, w, h);
  54835. if (isDown)
  54836. {
  54837. g.setColour (noteFillColour);
  54838. g.drawRect (x, y, w, h);
  54839. }
  54840. else
  54841. {
  54842. const int xIndent = jmax (1, jmin (w, h) / 8);
  54843. g.setColour (c.brighter());
  54844. if (orientation == horizontalKeyboard)
  54845. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  54846. else if (orientation == verticalKeyboardFacingLeft)
  54847. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  54848. else if (orientation == verticalKeyboardFacingRight)
  54849. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  54850. }
  54851. }
  54852. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_) throw()
  54853. {
  54854. octaveNumForMiddleC = octaveNumForMiddleC_;
  54855. repaint();
  54856. }
  54857. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  54858. {
  54859. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  54860. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  54861. return String::empty;
  54862. }
  54863. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  54864. const bool isMouseOver,
  54865. const bool isButtonDown,
  54866. const bool movesOctavesUp)
  54867. {
  54868. g.fillAll (findColour (upDownButtonBackgroundColourId));
  54869. float angle;
  54870. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  54871. angle = movesOctavesUp ? 0.0f : 0.5f;
  54872. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  54873. angle = movesOctavesUp ? 0.25f : 0.75f;
  54874. else
  54875. angle = movesOctavesUp ? 0.75f : 0.25f;
  54876. Path path;
  54877. path.lineTo (0.0f, 1.0f);
  54878. path.lineTo (1.0f, 0.5f);
  54879. path.closeSubPath();
  54880. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  54881. g.setColour (findColour (upDownButtonArrowColourId)
  54882. .withAlpha (isButtonDown ? 1.0f : (isMouseOver ? 0.6f : 0.4f)));
  54883. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  54884. w - 2.0f,
  54885. h - 2.0f,
  54886. true));
  54887. }
  54888. void MidiKeyboardComponent::resized()
  54889. {
  54890. int w = getWidth();
  54891. int h = getHeight();
  54892. if (w > 0 && h > 0)
  54893. {
  54894. if (orientation != horizontalKeyboard)
  54895. swapVariables (w, h);
  54896. blackNoteLength = roundFloatToInt (h * 0.7f);
  54897. int kx2, kw2;
  54898. getKeyPos (rangeEnd, kx2, kw2);
  54899. kx2 += kw2;
  54900. if (firstKey != rangeStart)
  54901. {
  54902. int kx1, kw1;
  54903. getKeyPos (rangeStart, kx1, kw1);
  54904. if (kx2 - kx1 <= w)
  54905. {
  54906. firstKey = rangeStart;
  54907. sendChangeMessage (this);
  54908. repaint();
  54909. }
  54910. }
  54911. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  54912. scrollDown->setVisible (showScrollButtons);
  54913. scrollUp->setVisible (showScrollButtons);
  54914. xOffset = 0;
  54915. if (showScrollButtons)
  54916. {
  54917. const int scrollButtonW = jmin (12, w / 2);
  54918. if (orientation == horizontalKeyboard)
  54919. {
  54920. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  54921. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  54922. }
  54923. else if (orientation == verticalKeyboardFacingLeft)
  54924. {
  54925. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  54926. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  54927. }
  54928. else if (orientation == verticalKeyboardFacingRight)
  54929. {
  54930. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  54931. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  54932. }
  54933. int endOfLastKey, kw;
  54934. getKeyPos (rangeEnd, endOfLastKey, kw);
  54935. endOfLastKey += kw;
  54936. const int spaceAvailable = w - scrollButtonW * 2;
  54937. const int lastStartKey = remappedXYToNote (endOfLastKey - spaceAvailable, 0) + 1;
  54938. if (lastStartKey >= 0 && firstKey > lastStartKey)
  54939. {
  54940. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  54941. sendChangeMessage (this);
  54942. }
  54943. int newOffset = 0;
  54944. getKeyPos (firstKey, newOffset, kw);
  54945. xOffset = newOffset - scrollButtonW;
  54946. }
  54947. else
  54948. {
  54949. firstKey = rangeStart;
  54950. }
  54951. timerCallback();
  54952. repaint();
  54953. }
  54954. }
  54955. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  54956. {
  54957. triggerAsyncUpdate();
  54958. }
  54959. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  54960. {
  54961. triggerAsyncUpdate();
  54962. }
  54963. void MidiKeyboardComponent::handleAsyncUpdate()
  54964. {
  54965. for (int i = rangeStart; i <= rangeEnd; ++i)
  54966. {
  54967. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  54968. {
  54969. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  54970. repaintNote (i);
  54971. }
  54972. }
  54973. }
  54974. void MidiKeyboardComponent::resetAnyKeysInUse()
  54975. {
  54976. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  54977. {
  54978. state.allNotesOff (midiChannel);
  54979. keysPressed.clear();
  54980. mouseDownNote = -1;
  54981. }
  54982. }
  54983. void MidiKeyboardComponent::updateNoteUnderMouse (int x, int y)
  54984. {
  54985. const int newNote = (mouseDragging || isMouseOver())
  54986. ? xyToNote (x, y) : -1;
  54987. if (noteUnderMouse != newNote)
  54988. {
  54989. if (mouseDownNote >= 0)
  54990. {
  54991. state.noteOff (midiChannel, mouseDownNote);
  54992. mouseDownNote = -1;
  54993. }
  54994. if (mouseDragging && newNote >= 0)
  54995. {
  54996. state.noteOn (midiChannel, newNote, velocity);
  54997. mouseDownNote = newNote;
  54998. }
  54999. repaintNote (noteUnderMouse);
  55000. noteUnderMouse = newNote;
  55001. repaintNote (noteUnderMouse);
  55002. }
  55003. else if (mouseDownNote >= 0 && ! mouseDragging)
  55004. {
  55005. state.noteOff (midiChannel, mouseDownNote);
  55006. mouseDownNote = -1;
  55007. }
  55008. }
  55009. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  55010. {
  55011. updateNoteUnderMouse (e.x, e.y);
  55012. stopTimer();
  55013. }
  55014. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  55015. {
  55016. const int newNote = xyToNote (e.x, e.y);
  55017. if (newNote >= 0)
  55018. mouseDraggedToKey (newNote, e);
  55019. updateNoteUnderMouse (e.x, e.y);
  55020. }
  55021. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  55022. {
  55023. return true;
  55024. }
  55025. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  55026. {
  55027. }
  55028. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  55029. {
  55030. const int newNote = xyToNote (e.x, e.y);
  55031. mouseDragging = false;
  55032. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  55033. {
  55034. repaintNote (noteUnderMouse);
  55035. noteUnderMouse = -1;
  55036. mouseDragging = true;
  55037. updateNoteUnderMouse (e.x, e.y);
  55038. startTimer (500);
  55039. }
  55040. }
  55041. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  55042. {
  55043. mouseDragging = false;
  55044. updateNoteUnderMouse (e.x, e.y);
  55045. stopTimer();
  55046. }
  55047. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  55048. {
  55049. updateNoteUnderMouse (e.x, e.y);
  55050. }
  55051. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  55052. {
  55053. updateNoteUnderMouse (e.x, e.y);
  55054. }
  55055. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  55056. {
  55057. setLowestVisibleKey (getLowestVisibleKey() + roundFloatToInt ((ix != 0 ? ix : iy) * 5.0f));
  55058. }
  55059. void MidiKeyboardComponent::timerCallback()
  55060. {
  55061. int mx, my;
  55062. getMouseXYRelative (mx, my);
  55063. updateNoteUnderMouse (mx, my);
  55064. }
  55065. void MidiKeyboardComponent::clearKeyMappings()
  55066. {
  55067. resetAnyKeysInUse();
  55068. keyPressNotes.clear();
  55069. keyPresses.clear();
  55070. }
  55071. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  55072. const int midiNoteOffsetFromC)
  55073. {
  55074. removeKeyPressForNote (midiNoteOffsetFromC);
  55075. keyPressNotes.add (midiNoteOffsetFromC);
  55076. keyPresses.add (key);
  55077. }
  55078. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  55079. {
  55080. for (int i = keyPressNotes.size(); --i >= 0;)
  55081. {
  55082. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  55083. {
  55084. keyPressNotes.remove (i);
  55085. keyPresses.remove (i);
  55086. }
  55087. }
  55088. }
  55089. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  55090. {
  55091. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  55092. keyMappingOctave = newOctaveNumber;
  55093. }
  55094. bool MidiKeyboardComponent::keyStateChanged()
  55095. {
  55096. bool keyPressUsed = false;
  55097. for (int i = keyPresses.size(); --i >= 0;)
  55098. {
  55099. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  55100. if (keyPresses.getReference(i).isCurrentlyDown())
  55101. {
  55102. if (! keysPressed [note])
  55103. {
  55104. keysPressed.setBit (note);
  55105. state.noteOn (midiChannel, note, velocity);
  55106. keyPressUsed = true;
  55107. }
  55108. }
  55109. else
  55110. {
  55111. if (keysPressed [note])
  55112. {
  55113. keysPressed.clearBit (note);
  55114. state.noteOff (midiChannel, note);
  55115. keyPressUsed = true;
  55116. }
  55117. }
  55118. }
  55119. return keyPressUsed;
  55120. }
  55121. void MidiKeyboardComponent::focusLost (FocusChangeType)
  55122. {
  55123. resetAnyKeysInUse();
  55124. }
  55125. END_JUCE_NAMESPACE
  55126. /********* End of inlined file: juce_MidiKeyboardComponent.cpp *********/
  55127. /********* Start of inlined file: juce_OpenGLComponent.cpp *********/
  55128. #if JUCE_OPENGL
  55129. BEGIN_JUCE_NAMESPACE
  55130. extern void juce_glViewport (const int w, const int h);
  55131. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  55132. const int alphaBits_,
  55133. const int depthBufferBits_,
  55134. const int stencilBufferBits_) throw()
  55135. : redBits (bitsPerRGBComponent),
  55136. greenBits (bitsPerRGBComponent),
  55137. blueBits (bitsPerRGBComponent),
  55138. alphaBits (alphaBits_),
  55139. depthBufferBits (depthBufferBits_),
  55140. stencilBufferBits (stencilBufferBits_),
  55141. accumulationBufferRedBits (0),
  55142. accumulationBufferGreenBits (0),
  55143. accumulationBufferBlueBits (0),
  55144. accumulationBufferAlphaBits (0),
  55145. fullSceneAntiAliasingNumSamples (0)
  55146. {
  55147. }
  55148. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const throw()
  55149. {
  55150. return memcmp (this, &other, sizeof (other)) == 0;
  55151. }
  55152. static VoidArray knownContexts;
  55153. OpenGLContext::OpenGLContext() throw()
  55154. {
  55155. knownContexts.add (this);
  55156. }
  55157. OpenGLContext::~OpenGLContext()
  55158. {
  55159. knownContexts.removeValue (this);
  55160. }
  55161. OpenGLContext* OpenGLContext::getCurrentContext()
  55162. {
  55163. for (int i = knownContexts.size(); --i >= 0;)
  55164. {
  55165. OpenGLContext* const oglc = (OpenGLContext*) knownContexts.getUnchecked(i);
  55166. if (oglc->isActive())
  55167. return oglc;
  55168. }
  55169. return 0;
  55170. }
  55171. class OpenGLComponentWatcher : public ComponentMovementWatcher
  55172. {
  55173. public:
  55174. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  55175. : ComponentMovementWatcher (owner_),
  55176. owner (owner_),
  55177. wasShowing (false)
  55178. {
  55179. }
  55180. ~OpenGLComponentWatcher() {}
  55181. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  55182. {
  55183. owner->updateContextPosition();
  55184. }
  55185. void componentPeerChanged()
  55186. {
  55187. const ScopedLock sl (owner->getContextLock());
  55188. owner->deleteContext();
  55189. }
  55190. void componentVisibilityChanged (Component&)
  55191. {
  55192. const bool isShowingNow = owner->isShowing();
  55193. if (wasShowing != isShowingNow)
  55194. {
  55195. wasShowing = isShowingNow;
  55196. owner->updateContextPosition();
  55197. }
  55198. }
  55199. juce_UseDebuggingNewOperator
  55200. private:
  55201. OpenGLComponent* const owner;
  55202. bool wasShowing;
  55203. };
  55204. OpenGLComponent::OpenGLComponent()
  55205. : context (0),
  55206. contextToShareListsWith (0),
  55207. needToUpdateViewport (true)
  55208. {
  55209. setOpaque (true);
  55210. componentWatcher = new OpenGLComponentWatcher (this);
  55211. }
  55212. OpenGLComponent::~OpenGLComponent()
  55213. {
  55214. deleteContext();
  55215. delete componentWatcher;
  55216. }
  55217. void OpenGLComponent::deleteContext()
  55218. {
  55219. const ScopedLock sl (contextLock);
  55220. deleteAndZero (context);
  55221. }
  55222. void OpenGLComponent::updateContextPosition()
  55223. {
  55224. needToUpdateViewport = true;
  55225. if (getWidth() > 0 && getHeight() > 0)
  55226. {
  55227. Component* const topComp = getTopLevelComponent();
  55228. if (topComp->getPeer() != 0)
  55229. {
  55230. const ScopedLock sl (contextLock);
  55231. if (context != 0)
  55232. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  55233. getScreenY() - topComp->getScreenY(),
  55234. getWidth(),
  55235. getHeight(),
  55236. topComp->getHeight());
  55237. }
  55238. }
  55239. }
  55240. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  55241. {
  55242. OpenGLPixelFormat pf;
  55243. const ScopedLock sl (contextLock);
  55244. if (context != 0)
  55245. pf = context->getPixelFormat();
  55246. return pf;
  55247. }
  55248. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  55249. {
  55250. if (! (preferredPixelFormat == formatToUse))
  55251. {
  55252. const ScopedLock sl (contextLock);
  55253. deleteContext();
  55254. preferredPixelFormat = formatToUse;
  55255. }
  55256. }
  55257. void OpenGLComponent::shareWith (OpenGLContext* context)
  55258. {
  55259. if (contextToShareListsWith != context)
  55260. {
  55261. const ScopedLock sl (contextLock);
  55262. deleteContext();
  55263. contextToShareListsWith = context;
  55264. }
  55265. }
  55266. bool OpenGLComponent::makeCurrentContextActive()
  55267. {
  55268. if (context == 0)
  55269. {
  55270. const ScopedLock sl (contextLock);
  55271. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  55272. {
  55273. context = OpenGLContext::createContextForWindow (this,
  55274. preferredPixelFormat,
  55275. contextToShareListsWith);
  55276. if (context != 0)
  55277. {
  55278. updateContextPosition();
  55279. if (context->makeActive())
  55280. newOpenGLContextCreated();
  55281. }
  55282. }
  55283. }
  55284. return context != 0 && context->makeActive();
  55285. }
  55286. void OpenGLComponent::makeCurrentContextInactive()
  55287. {
  55288. if (context != 0)
  55289. context->makeInactive();
  55290. }
  55291. bool OpenGLComponent::isActiveContext() const throw()
  55292. {
  55293. return context != 0 && context->isActive();
  55294. }
  55295. void OpenGLComponent::swapBuffers()
  55296. {
  55297. if (context != 0)
  55298. context->swapBuffers();
  55299. }
  55300. void OpenGLComponent::paint (Graphics&)
  55301. {
  55302. if (renderAndSwapBuffers())
  55303. {
  55304. ComponentPeer* const peer = getPeer();
  55305. if (peer != 0)
  55306. {
  55307. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  55308. getScreenY() - peer->getScreenY(),
  55309. getWidth(), getHeight());
  55310. }
  55311. }
  55312. }
  55313. bool OpenGLComponent::renderAndSwapBuffers()
  55314. {
  55315. const ScopedLock sl (contextLock);
  55316. if (! makeCurrentContextActive())
  55317. return false;
  55318. if (needToUpdateViewport)
  55319. {
  55320. needToUpdateViewport = false;
  55321. juce_glViewport (getWidth(), getHeight());
  55322. }
  55323. renderOpenGL();
  55324. swapBuffers();
  55325. return true;
  55326. }
  55327. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  55328. {
  55329. Component::internalRepaint (x, y, w, h);
  55330. if (context != 0)
  55331. context->repaint();
  55332. }
  55333. END_JUCE_NAMESPACE
  55334. #endif
  55335. /********* End of inlined file: juce_OpenGLComponent.cpp *********/
  55336. /********* Start of inlined file: juce_PreferencesPanel.cpp *********/
  55337. BEGIN_JUCE_NAMESPACE
  55338. PreferencesPanel::PreferencesPanel()
  55339. : currentPage (0),
  55340. buttonSize (70)
  55341. {
  55342. }
  55343. PreferencesPanel::~PreferencesPanel()
  55344. {
  55345. deleteAllChildren();
  55346. }
  55347. void PreferencesPanel::addSettingsPage (const String& title,
  55348. const Drawable* icon,
  55349. const Drawable* overIcon,
  55350. const Drawable* downIcon)
  55351. {
  55352. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  55353. button->setImages (icon, overIcon, downIcon);
  55354. button->setRadioGroupId (1);
  55355. button->addButtonListener (this);
  55356. button->setClickingTogglesState (true);
  55357. button->setWantsKeyboardFocus (false);
  55358. addAndMakeVisible (button);
  55359. resized();
  55360. }
  55361. void PreferencesPanel::addSettingsPage (const String& title,
  55362. const char* imageData,
  55363. const int imageDataSize)
  55364. {
  55365. DrawableImage icon, iconOver, iconDown;
  55366. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  55367. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  55368. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  55369. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  55370. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  55371. addSettingsPage (title, &icon, &iconOver, &iconDown);
  55372. if (currentPage == 0)
  55373. setCurrentPage (title);
  55374. }
  55375. class PrefsDialogWindow : public DialogWindow
  55376. {
  55377. public:
  55378. PrefsDialogWindow (const String& dialogtitle,
  55379. const Colour& backgroundColour)
  55380. : DialogWindow (dialogtitle, backgroundColour, true)
  55381. {
  55382. }
  55383. ~PrefsDialogWindow()
  55384. {
  55385. }
  55386. void closeButtonPressed()
  55387. {
  55388. exitModalState (0);
  55389. }
  55390. private:
  55391. PrefsDialogWindow (const PrefsDialogWindow&);
  55392. const PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  55393. };
  55394. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  55395. int dialogWidth,
  55396. int dialogHeight,
  55397. const Colour& backgroundColour)
  55398. {
  55399. setSize (dialogWidth, dialogHeight);
  55400. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  55401. dw.setContentComponent (this, true, true);
  55402. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  55403. dw.runModalLoop();
  55404. }
  55405. void PreferencesPanel::resized()
  55406. {
  55407. int x = 0;
  55408. for (int i = 0; i < getNumChildComponents(); ++i)
  55409. {
  55410. Component* c = getChildComponent (i);
  55411. if (dynamic_cast <DrawableButton*> (c) == 0)
  55412. {
  55413. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  55414. }
  55415. else
  55416. {
  55417. c->setBounds (x, 0, buttonSize, buttonSize);
  55418. x += buttonSize;
  55419. }
  55420. }
  55421. }
  55422. void PreferencesPanel::paint (Graphics& g)
  55423. {
  55424. g.setColour (Colours::grey);
  55425. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  55426. }
  55427. void PreferencesPanel::setCurrentPage (const String& pageName)
  55428. {
  55429. if (currentPageName != pageName)
  55430. {
  55431. currentPageName = pageName;
  55432. deleteAndZero (currentPage);
  55433. currentPage = createComponentForPage (pageName);
  55434. if (currentPage != 0)
  55435. {
  55436. addAndMakeVisible (currentPage);
  55437. currentPage->toBack();
  55438. resized();
  55439. }
  55440. for (int i = 0; i < getNumChildComponents(); ++i)
  55441. {
  55442. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  55443. if (db != 0 && db->getName() == pageName)
  55444. {
  55445. db->setToggleState (true, false);
  55446. break;
  55447. }
  55448. }
  55449. }
  55450. }
  55451. void PreferencesPanel::buttonClicked (Button*)
  55452. {
  55453. for (int i = 0; i < getNumChildComponents(); ++i)
  55454. {
  55455. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  55456. if (db != 0 && db->getToggleState())
  55457. {
  55458. setCurrentPage (db->getName());
  55459. break;
  55460. }
  55461. }
  55462. }
  55463. END_JUCE_NAMESPACE
  55464. /********* End of inlined file: juce_PreferencesPanel.cpp *********/
  55465. /********* Start of inlined file: juce_QuickTimeMovieComponent.cpp *********/
  55466. #if JUCE_QUICKTIME
  55467. #ifdef _MSC_VER
  55468. #pragma warning (disable: 4514)
  55469. #endif
  55470. #ifdef _WIN32
  55471. #include <windows.h>
  55472. #ifdef _MSC_VER
  55473. #pragma warning (push)
  55474. #pragma warning (disable : 4100)
  55475. #endif
  55476. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  55477. add its header directory to your include path.
  55478. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  55479. flag in juce_Config.h
  55480. */
  55481. #include <Movies.h>
  55482. #include <QTML.h>
  55483. #include <QuickTimeComponents.h>
  55484. #include <MediaHandlers.h>
  55485. #include <ImageCodec.h>
  55486. #ifdef _MSC_VER
  55487. #pragma warning (pop)
  55488. #endif
  55489. // If you've got QuickTime 7 installed, then these COM objects should be found in
  55490. // the "\Program Files\Quicktime" directory. You'll need to add this directory to
  55491. // your include search path to make these import statements work.
  55492. #import <QTOLibrary.dll>
  55493. #import <QTOControl.dll>
  55494. using namespace QTOLibrary;
  55495. using namespace QTOControlLib;
  55496. #else
  55497. #include <Carbon/Carbon.h>
  55498. #include <QuickTime/Movies.h>
  55499. #include <QuickTime/QuickTimeComponents.h>
  55500. #include <QuickTime/MediaHandlers.h>
  55501. #endif
  55502. BEGIN_JUCE_NAMESPACE
  55503. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  55504. static bool hasLoadedQT = false;
  55505. static bool isQTAvailable = false;
  55506. struct QTMovieCompInternal
  55507. {
  55508. QTMovieCompInternal()
  55509. : dataHandle (0)
  55510. {
  55511. #if JUCE_MAC
  55512. movie = 0;
  55513. controller = 0;
  55514. #endif
  55515. }
  55516. ~QTMovieCompInternal()
  55517. {
  55518. clearHandle();
  55519. }
  55520. #if JUCE_MAC
  55521. Movie movie;
  55522. MovieController controller;
  55523. #else
  55524. IQTControlPtr qtControlInternal;
  55525. IQTMoviePtr qtMovieInternal;
  55526. #endif
  55527. Handle dataHandle;
  55528. void clearHandle()
  55529. {
  55530. if (dataHandle != 0)
  55531. {
  55532. DisposeHandle (dataHandle);
  55533. dataHandle = 0;
  55534. }
  55535. }
  55536. };
  55537. #if JUCE_WIN32
  55538. #define qtControl (((QTMovieCompInternal*) internal)->qtControlInternal)
  55539. #define qtMovie (((QTMovieCompInternal*) internal)->qtMovieInternal)
  55540. QuickTimeMovieComponent::QuickTimeMovieComponent()
  55541. : movieLoaded (false),
  55542. controllerVisible (true)
  55543. {
  55544. internal = new QTMovieCompInternal();
  55545. setMouseEventsAllowed (false);
  55546. }
  55547. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  55548. {
  55549. closeMovie();
  55550. qtControl = 0;
  55551. deleteControl();
  55552. delete internal;
  55553. internal = 0;
  55554. }
  55555. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  55556. {
  55557. if (! hasLoadedQT)
  55558. {
  55559. hasLoadedQT = true;
  55560. isQTAvailable = (InitializeQTML (0) == noErr)
  55561. && (EnterMovies() == noErr);
  55562. }
  55563. return isQTAvailable;
  55564. }
  55565. void QuickTimeMovieComponent::createControlIfNeeded()
  55566. {
  55567. if (isShowing() && ! isControlCreated())
  55568. {
  55569. const IID qtIID = __uuidof (QTControl);
  55570. if (createControl (&qtIID))
  55571. {
  55572. const IID qtInterfaceIID = __uuidof (IQTControl);
  55573. qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  55574. if (qtControl != 0)
  55575. {
  55576. qtControl->Release(); // it has one ref too many at this point
  55577. qtControl->QuickTimeInitialize();
  55578. qtControl->PutSizing (qtMovieFitsControl);
  55579. if (movieFile != File::nonexistent)
  55580. loadMovie (movieFile, controllerVisible);
  55581. }
  55582. }
  55583. }
  55584. }
  55585. bool QuickTimeMovieComponent::isControlCreated() const
  55586. {
  55587. return isControlOpen();
  55588. }
  55589. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  55590. const bool isControllerVisible)
  55591. {
  55592. movieFile = File::nonexistent;
  55593. movieLoaded = false;
  55594. qtMovie = 0;
  55595. controllerVisible = isControllerVisible;
  55596. createControlIfNeeded();
  55597. if (isControlCreated())
  55598. {
  55599. if (qtControl != 0)
  55600. {
  55601. qtControl->Put_MovieHandle (0);
  55602. ((QTMovieCompInternal*) internal)->clearHandle();
  55603. Movie movie;
  55604. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, ((QTMovieCompInternal*) internal)->dataHandle))
  55605. {
  55606. qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  55607. qtMovie = qtControl->GetMovie();
  55608. if (qtMovie != 0)
  55609. qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  55610. : qtMovieControllerTypeNone);
  55611. }
  55612. if (movie == 0)
  55613. ((QTMovieCompInternal*) internal)->clearHandle();
  55614. }
  55615. movieLoaded = (qtMovie != 0);
  55616. }
  55617. else
  55618. {
  55619. // You're trying to open a movie when the control hasn't yet been created, probably because
  55620. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  55621. jassertfalse
  55622. }
  55623. delete movieStream;
  55624. return movieLoaded;
  55625. }
  55626. void QuickTimeMovieComponent::closeMovie()
  55627. {
  55628. stop();
  55629. movieFile = File::nonexistent;
  55630. movieLoaded = false;
  55631. qtMovie = 0;
  55632. if (qtControl != 0)
  55633. qtControl->Put_MovieHandle (0);
  55634. ((QTMovieCompInternal*) internal)->clearHandle();
  55635. }
  55636. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  55637. {
  55638. return movieFile;
  55639. }
  55640. bool QuickTimeMovieComponent::isMovieOpen() const
  55641. {
  55642. return movieLoaded;
  55643. }
  55644. double QuickTimeMovieComponent::getMovieDuration() const
  55645. {
  55646. if (qtMovie != 0)
  55647. return qtMovie->GetDuration() / (double) qtMovie->GetTimeScale();
  55648. return 0.0;
  55649. }
  55650. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  55651. {
  55652. if (qtMovie != 0)
  55653. {
  55654. struct QTRECT r = qtMovie->GetNaturalRect();
  55655. width = r.right - r.left;
  55656. height = r.bottom - r.top;
  55657. }
  55658. else
  55659. {
  55660. width = height = 0;
  55661. }
  55662. }
  55663. void QuickTimeMovieComponent::play()
  55664. {
  55665. if (qtMovie != 0)
  55666. qtMovie->Play();
  55667. }
  55668. void QuickTimeMovieComponent::stop()
  55669. {
  55670. if (qtMovie != 0)
  55671. qtMovie->Stop();
  55672. }
  55673. bool QuickTimeMovieComponent::isPlaying() const
  55674. {
  55675. return qtMovie != 0 && qtMovie->GetRate() != 0.0f;
  55676. }
  55677. void QuickTimeMovieComponent::setPosition (const double seconds)
  55678. {
  55679. if (qtMovie != 0)
  55680. qtMovie->PutTime ((long) (seconds * qtMovie->GetTimeScale()));
  55681. }
  55682. double QuickTimeMovieComponent::getPosition() const
  55683. {
  55684. if (qtMovie != 0)
  55685. return qtMovie->GetTime() / (double) qtMovie->GetTimeScale();
  55686. return 0.0;
  55687. }
  55688. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  55689. {
  55690. if (qtMovie != 0)
  55691. qtMovie->PutRate (newSpeed);
  55692. }
  55693. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  55694. {
  55695. if (qtMovie != 0)
  55696. {
  55697. qtMovie->PutAudioVolume (newVolume);
  55698. qtMovie->PutAudioMute (newVolume <= 0);
  55699. }
  55700. }
  55701. float QuickTimeMovieComponent::getMovieVolume() const
  55702. {
  55703. if (qtMovie != 0)
  55704. return qtMovie->GetAudioVolume();
  55705. return 0.0f;
  55706. }
  55707. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  55708. {
  55709. if (qtMovie != 0)
  55710. qtMovie->PutLoop (shouldLoop);
  55711. }
  55712. bool QuickTimeMovieComponent::isLooping() const
  55713. {
  55714. return qtMovie != 0 && qtMovie->GetLoop();
  55715. }
  55716. bool QuickTimeMovieComponent::isControllerVisible() const
  55717. {
  55718. return controllerVisible;
  55719. }
  55720. void QuickTimeMovieComponent::parentHierarchyChanged()
  55721. {
  55722. createControlIfNeeded();
  55723. QTWinBaseClass::parentHierarchyChanged();
  55724. }
  55725. void QuickTimeMovieComponent::visibilityChanged()
  55726. {
  55727. createControlIfNeeded();
  55728. QTWinBaseClass::visibilityChanged();
  55729. }
  55730. void QuickTimeMovieComponent::paint (Graphics& g)
  55731. {
  55732. if (! isControlCreated())
  55733. g.fillAll (Colours::black);
  55734. }
  55735. #endif
  55736. #if JUCE_MAC
  55737. static VoidArray activeQTWindows (2);
  55738. struct MacClickEventData
  55739. {
  55740. ::Point where;
  55741. long when;
  55742. long modifiers;
  55743. };
  55744. void OfferMouseClickToQuickTime (WindowRef window,
  55745. ::Point where, long when, long modifiers,
  55746. Component* topLevelComp)
  55747. {
  55748. if (hasLoadedQT)
  55749. {
  55750. for (int i = activeQTWindows.size(); --i >= 0;)
  55751. {
  55752. QuickTimeMovieComponent* const qtw = (QuickTimeMovieComponent*) activeQTWindows[i];
  55753. if (qtw->isVisible() && topLevelComp->isParentOf (qtw))
  55754. {
  55755. MacClickEventData data;
  55756. data.where = where;
  55757. data.when = when;
  55758. data.modifiers = modifiers;
  55759. qtw->handleMCEvent (&data);
  55760. }
  55761. }
  55762. }
  55763. }
  55764. QuickTimeMovieComponent::QuickTimeMovieComponent()
  55765. : internal (new QTMovieCompInternal()),
  55766. associatedWindow (0),
  55767. controllerVisible (false),
  55768. controllerAssignedToWindow (false),
  55769. reentrant (false)
  55770. {
  55771. if (! hasLoadedQT)
  55772. {
  55773. hasLoadedQT = true;
  55774. isQTAvailable = EnterMovies() == noErr;
  55775. }
  55776. setOpaque (true);
  55777. setVisible (true);
  55778. activeQTWindows.add (this);
  55779. }
  55780. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  55781. {
  55782. closeMovie();
  55783. activeQTWindows.removeValue ((void*) this);
  55784. QTMovieCompInternal* const i = (QTMovieCompInternal*) internal;
  55785. delete i;
  55786. if (activeQTWindows.size() == 0 && isQTAvailable)
  55787. {
  55788. isQTAvailable = false;
  55789. hasLoadedQT = false;
  55790. ExitMovies();
  55791. }
  55792. }
  55793. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  55794. {
  55795. if (! hasLoadedQT)
  55796. {
  55797. hasLoadedQT = true;
  55798. isQTAvailable = EnterMovies() == noErr;
  55799. }
  55800. return isQTAvailable;
  55801. }
  55802. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  55803. const bool controllerVisible_)
  55804. {
  55805. if (! isQTAvailable)
  55806. return false;
  55807. closeMovie();
  55808. movieFile = File::nonexistent;
  55809. if (getPeer() == 0)
  55810. {
  55811. // To open a movie, this component must be visible inside a functioning window, so that
  55812. // the QT control can be assigned to the window.
  55813. jassertfalse
  55814. return false;
  55815. }
  55816. controllerVisible = controllerVisible_;
  55817. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55818. GrafPtr savedPort;
  55819. GetPort (&savedPort);
  55820. bool result = false;
  55821. if (juce_OpenQuickTimeMovieFromStream (movieStream, qmci->movie, qmci->dataHandle))
  55822. {
  55823. qmci->controller = 0;
  55824. void* window = getWindowHandle();
  55825. if (window != associatedWindow && window != 0)
  55826. associatedWindow = window;
  55827. assignMovieToWindow();
  55828. SetMovieActive (qmci->movie, true);
  55829. SetMovieProgressProc (qmci->movie, (MovieProgressUPP) -1, 0);
  55830. startTimer (1000 / 50); // this needs to be quite a high frequency for smooth playback
  55831. result = true;
  55832. repaint();
  55833. }
  55834. MacSetPort (savedPort);
  55835. return result;
  55836. }
  55837. void QuickTimeMovieComponent::closeMovie()
  55838. {
  55839. stop();
  55840. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55841. if (qmci->controller != 0)
  55842. {
  55843. DisposeMovieController (qmci->controller);
  55844. qmci->controller = 0;
  55845. }
  55846. if (qmci->movie != 0)
  55847. {
  55848. DisposeMovie (qmci->movie);
  55849. qmci->movie = 0;
  55850. }
  55851. qmci->clearHandle();
  55852. stopTimer();
  55853. movieFile = File::nonexistent;
  55854. }
  55855. bool QuickTimeMovieComponent::isMovieOpen() const
  55856. {
  55857. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55858. return qmci->movie != 0 && qmci->controller != 0;
  55859. }
  55860. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  55861. {
  55862. return movieFile;
  55863. }
  55864. static GrafPtr getPortForWindow (void* window)
  55865. {
  55866. if (window == 0)
  55867. return 0;
  55868. return (GrafPtr) GetWindowPort ((WindowRef) window);
  55869. }
  55870. void QuickTimeMovieComponent::assignMovieToWindow()
  55871. {
  55872. if (reentrant)
  55873. return;
  55874. reentrant = true;
  55875. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55876. if (qmci->controller != 0)
  55877. {
  55878. DisposeMovieController (qmci->controller);
  55879. qmci->controller = 0;
  55880. }
  55881. controllerAssignedToWindow = false;
  55882. void* window = getWindowHandle();
  55883. GrafPtr port = getPortForWindow (window);
  55884. if (port != 0)
  55885. {
  55886. GrafPtr savedPort;
  55887. GetPort (&savedPort);
  55888. SetMovieGWorld (qmci->movie, (CGrafPtr) port, 0);
  55889. MacSetPort (port);
  55890. Rect r;
  55891. r.top = 0;
  55892. r.left = 0;
  55893. r.right = (short) jmax (1, getWidth());
  55894. r.bottom = (short) jmax (1, getHeight());
  55895. SetMovieBox (qmci->movie, &r);
  55896. // create the movie controller
  55897. qmci->controller = NewMovieController (qmci->movie, &r,
  55898. controllerVisible ? mcTopLeftMovie
  55899. : mcNotVisible);
  55900. if (qmci->controller != 0)
  55901. {
  55902. MCEnableEditing (qmci->controller, true);
  55903. MCDoAction (qmci->controller, mcActionSetUseBadge, (void*) false);
  55904. MCDoAction (qmci->controller, mcActionSetLoopIsPalindrome, (void*) false);
  55905. setLooping (looping);
  55906. MCDoAction (qmci->controller, mcActionSetFlags,
  55907. (void*) (pointer_sized_int) (mcFlagSuppressMovieFrame | (controllerVisible ? 0 : (mcFlagSuppressStepButtons | mcFlagSuppressSpeakerButton))));
  55908. MCSetControllerBoundsRect (qmci->controller, &r);
  55909. controllerAssignedToWindow = true;
  55910. resized();
  55911. }
  55912. MacSetPort (savedPort);
  55913. }
  55914. else
  55915. {
  55916. SetMovieGWorld (qmci->movie, 0, 0);
  55917. }
  55918. reentrant = false;
  55919. }
  55920. void QuickTimeMovieComponent::play()
  55921. {
  55922. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55923. if (qmci->movie != 0)
  55924. StartMovie (qmci->movie);
  55925. }
  55926. void QuickTimeMovieComponent::stop()
  55927. {
  55928. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55929. if (qmci->movie != 0)
  55930. StopMovie (qmci->movie);
  55931. }
  55932. bool QuickTimeMovieComponent::isPlaying() const
  55933. {
  55934. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55935. return qmci->movie != 0 && GetMovieRate (qmci->movie) != 0;
  55936. }
  55937. void QuickTimeMovieComponent::setPosition (const double seconds)
  55938. {
  55939. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55940. if (qmci->controller != 0)
  55941. {
  55942. TimeRecord time;
  55943. time.base = GetMovieTimeBase (qmci->movie);
  55944. time.scale = 100000;
  55945. const uint64 t = (uint64) (100000.0 * seconds);
  55946. time.value.lo = (UInt32) (t & 0xffffffff);
  55947. time.value.hi = (UInt32) (t >> 32);
  55948. SetMovieTime (qmci->movie, &time);
  55949. timerCallback(); // to call MCIdle
  55950. }
  55951. else
  55952. {
  55953. jassertfalse // no movie is open, so can't set the position.
  55954. }
  55955. }
  55956. double QuickTimeMovieComponent::getPosition() const
  55957. {
  55958. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55959. if (qmci->movie != 0)
  55960. {
  55961. TimeRecord time;
  55962. GetMovieTime (qmci->movie, &time);
  55963. return ((int64) (((uint64) time.value.hi << 32) | (uint64) time.value.lo))
  55964. / (double) time.scale;
  55965. }
  55966. return 0.0;
  55967. }
  55968. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  55969. {
  55970. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55971. if (qmci->movie != 0)
  55972. SetMovieRate (qmci->movie, (Fixed) (newSpeed * (Fixed) 0x00010000L));
  55973. }
  55974. double QuickTimeMovieComponent::getMovieDuration() const
  55975. {
  55976. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55977. if (qmci->movie != 0)
  55978. return GetMovieDuration (qmci->movie) / (double) GetMovieTimeScale (qmci->movie);
  55979. return 0.0;
  55980. }
  55981. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  55982. {
  55983. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55984. looping = shouldLoop;
  55985. if (qmci->controller != 0)
  55986. MCDoAction (qmci->controller, mcActionSetLooping, (void*) shouldLoop);
  55987. }
  55988. bool QuickTimeMovieComponent::isLooping() const
  55989. {
  55990. return looping;
  55991. }
  55992. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  55993. {
  55994. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55995. if (qmci->movie != 0)
  55996. SetMovieVolume (qmci->movie, jlimit ((short) 0, (short) 0x100, (short) (newVolume * 0x0100)));
  55997. }
  55998. float QuickTimeMovieComponent::getMovieVolume() const
  55999. {
  56000. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  56001. if (qmci->movie != 0)
  56002. return jmax (0.0f, GetMovieVolume (qmci->movie) / (float) 0x0100);
  56003. return 0.0f;
  56004. }
  56005. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  56006. {
  56007. width = 0;
  56008. height = 0;
  56009. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  56010. if (qmci->movie != 0)
  56011. {
  56012. Rect r;
  56013. GetMovieNaturalBoundsRect (qmci->movie, &r);
  56014. width = r.right - r.left;
  56015. height = r.bottom - r.top;
  56016. }
  56017. }
  56018. void QuickTimeMovieComponent::paint (Graphics& g)
  56019. {
  56020. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  56021. if (qmci->movie == 0 || qmci->controller == 0)
  56022. {
  56023. g.fillAll (Colours::black);
  56024. return;
  56025. }
  56026. GrafPtr savedPort;
  56027. GetPort (&savedPort);
  56028. MacSetPort (getPortForWindow (getWindowHandle()));
  56029. MCDraw (qmci->controller, (WindowRef) getWindowHandle());
  56030. MacSetPort (savedPort);
  56031. ComponentPeer* const peer = getPeer();
  56032. if (peer != 0)
  56033. {
  56034. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  56035. getScreenY() - peer->getScreenY(),
  56036. getWidth(), getHeight());
  56037. }
  56038. timerCallback();
  56039. }
  56040. static const Rectangle getMoviePos (Component* const c)
  56041. {
  56042. return Rectangle (c->getScreenX() - c->getTopLevelComponent()->getScreenX(),
  56043. c->getScreenY() - c->getTopLevelComponent()->getScreenY(),
  56044. jmax (1, c->getWidth()),
  56045. jmax (1, c->getHeight()));
  56046. }
  56047. void QuickTimeMovieComponent::moved()
  56048. {
  56049. resized();
  56050. }
  56051. void QuickTimeMovieComponent::resized()
  56052. {
  56053. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  56054. if (qmci->controller != 0 && isShowing())
  56055. {
  56056. checkWindowAssociation();
  56057. GrafPtr port = getPortForWindow (getWindowHandle());
  56058. if (port != 0)
  56059. {
  56060. GrafPtr savedPort;
  56061. GetPort (&savedPort);
  56062. SetMovieGWorld (qmci->movie, (CGrafPtr) port, 0);
  56063. MacSetPort (port);
  56064. lastPositionApplied = getMoviePos (this);
  56065. Rect r;
  56066. r.left = (short) lastPositionApplied.getX();
  56067. r.top = (short) lastPositionApplied.getY();
  56068. r.right = (short) lastPositionApplied.getRight();
  56069. r.bottom = (short) lastPositionApplied.getBottom();
  56070. if (MCGetVisible (qmci->controller))
  56071. MCSetControllerBoundsRect (qmci->controller, &r);
  56072. else
  56073. SetMovieBox (qmci->movie, &r);
  56074. if (! isPlaying())
  56075. timerCallback();
  56076. MacSetPort (savedPort);
  56077. repaint();
  56078. }
  56079. }
  56080. }
  56081. void QuickTimeMovieComponent::visibilityChanged()
  56082. {
  56083. checkWindowAssociation();
  56084. QTWinBaseClass::visibilityChanged();
  56085. }
  56086. void QuickTimeMovieComponent::timerCallback()
  56087. {
  56088. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  56089. if (qmci->controller != 0)
  56090. {
  56091. if (isTimerRunning())
  56092. startTimer (getTimerInterval());
  56093. MCIdle (qmci->controller);
  56094. if (lastPositionApplied != getMoviePos (this))
  56095. resized();
  56096. }
  56097. }
  56098. void QuickTimeMovieComponent::checkWindowAssociation()
  56099. {
  56100. void* const window = getWindowHandle();
  56101. if (window != associatedWindow
  56102. || (window != 0 && ! controllerAssignedToWindow))
  56103. {
  56104. associatedWindow = window;
  56105. assignMovieToWindow();
  56106. }
  56107. }
  56108. void QuickTimeMovieComponent::parentHierarchyChanged()
  56109. {
  56110. checkWindowAssociation();
  56111. }
  56112. void QuickTimeMovieComponent::handleMCEvent (void* ev)
  56113. {
  56114. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  56115. if (qmci->controller != 0 && isShowing())
  56116. {
  56117. MacClickEventData* data = (MacClickEventData*) ev;
  56118. data->where.h -= getTopLevelComponent()->getScreenX();
  56119. data->where.v -= getTopLevelComponent()->getScreenY();
  56120. Boolean b = false;
  56121. MCPtInController (qmci->controller, data->where, &b);
  56122. if (b)
  56123. {
  56124. const int oldTimeBeforeWaitCursor = MessageManager::getInstance()->getTimeBeforeShowingWaitCursor();
  56125. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (0);
  56126. MCClick (qmci->controller,
  56127. (WindowRef) getWindowHandle(),
  56128. data->where,
  56129. data->when,
  56130. data->modifiers);
  56131. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (oldTimeBeforeWaitCursor);
  56132. }
  56133. }
  56134. }
  56135. #endif
  56136. // (methods common to both platforms..)
  56137. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  56138. {
  56139. Handle dataRef = 0;
  56140. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  56141. if (err == noErr)
  56142. {
  56143. Str255 suffix;
  56144. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  56145. StringPtr name = suffix;
  56146. err = PtrAndHand (name, dataRef, name[0] + 1);
  56147. if (err == noErr)
  56148. {
  56149. long atoms[3];
  56150. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  56151. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  56152. atoms[2] = EndianU32_NtoB (MovieFileType);
  56153. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  56154. if (err == noErr)
  56155. return dataRef;
  56156. }
  56157. DisposeHandle (dataRef);
  56158. }
  56159. return 0;
  56160. }
  56161. static CFStringRef juceStringToCFString (const String& s)
  56162. {
  56163. const int len = s.length();
  56164. const juce_wchar* const t = (const juce_wchar*) s;
  56165. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  56166. for (int i = 0; i <= len; ++i)
  56167. temp[i] = t[i];
  56168. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  56169. juce_free (temp);
  56170. return result;
  56171. }
  56172. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  56173. {
  56174. Boolean trueBool = true;
  56175. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  56176. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  56177. props[prop].propValueSize = sizeof (trueBool);
  56178. props[prop].propValueAddress = &trueBool;
  56179. ++prop;
  56180. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  56181. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  56182. props[prop].propValueSize = sizeof (trueBool);
  56183. props[prop].propValueAddress = &trueBool;
  56184. ++prop;
  56185. Boolean isActive = true;
  56186. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  56187. props[prop].propID = kQTNewMoviePropertyID_Active;
  56188. props[prop].propValueSize = sizeof (isActive);
  56189. props[prop].propValueAddress = &isActive;
  56190. ++prop;
  56191. #if JUCE_MAC
  56192. SetPort (0);
  56193. #else
  56194. MacSetPort (0);
  56195. #endif
  56196. jassert (prop <= 5);
  56197. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  56198. return err == noErr;
  56199. }
  56200. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  56201. {
  56202. if (input == 0)
  56203. return false;
  56204. dataHandle = 0;
  56205. bool ok = false;
  56206. QTNewMoviePropertyElement props[5];
  56207. zeromem (props, sizeof (props));
  56208. int prop = 0;
  56209. DataReferenceRecord dr;
  56210. props[prop].propClass = kQTPropertyClass_DataLocation;
  56211. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  56212. props[prop].propValueSize = sizeof (dr);
  56213. props[prop].propValueAddress = (void*) &dr;
  56214. ++prop;
  56215. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  56216. if (fin != 0)
  56217. {
  56218. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  56219. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  56220. &dr.dataRef, &dr.dataRefType);
  56221. ok = openMovie (props, prop, movie);
  56222. DisposeHandle (dr.dataRef);
  56223. CFRelease (filePath);
  56224. }
  56225. else
  56226. {
  56227. // sanity-check because this currently needs to load the whole stream into memory..
  56228. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  56229. dataHandle = NewHandle ((Size) input->getTotalLength());
  56230. HLock (dataHandle);
  56231. // read the entire stream into memory - this is a pain, but can't get it to work
  56232. // properly using a custom callback to supply the data.
  56233. input->read (*dataHandle, (int) input->getTotalLength());
  56234. HUnlock (dataHandle);
  56235. // different types to get QT to try. (We should really be a bit smarter here by
  56236. // working out in advance which one the stream contains, rather than just trying
  56237. // each one)
  56238. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  56239. "\04.avi", "\04.m4a" };
  56240. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  56241. {
  56242. /* // this fails for some bizarre reason - it can be bodged to work with
  56243. // movies, but can't seem to do it for other file types..
  56244. QTNewMovieUserProcRecord procInfo;
  56245. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  56246. procInfo.getMovieUserProcRefcon = this;
  56247. procInfo.defaultDataRef.dataRef = dataRef;
  56248. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  56249. props[prop].propClass = kQTPropertyClass_DataLocation;
  56250. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  56251. props[prop].propValueSize = sizeof (procInfo);
  56252. props[prop].propValueAddress = (void*) &procInfo;
  56253. ++prop; */
  56254. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  56255. dr.dataRefType = HandleDataHandlerSubType;
  56256. ok = openMovie (props, prop, movie);
  56257. DisposeHandle (dr.dataRef);
  56258. }
  56259. }
  56260. return ok;
  56261. }
  56262. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  56263. const bool isControllerVisible)
  56264. {
  56265. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  56266. movieFile = movieFile_;
  56267. return ok;
  56268. }
  56269. void QuickTimeMovieComponent::goToStart()
  56270. {
  56271. setPosition (0.0);
  56272. }
  56273. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  56274. const RectanglePlacement& placement)
  56275. {
  56276. int normalWidth, normalHeight;
  56277. getMovieNormalSize (normalWidth, normalHeight);
  56278. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  56279. {
  56280. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  56281. placement.applyTo (x, y, w, h,
  56282. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  56283. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  56284. if (w > 0 && h > 0)
  56285. {
  56286. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  56287. roundDoubleToInt (w), roundDoubleToInt (h));
  56288. }
  56289. }
  56290. else
  56291. {
  56292. setBounds (spaceToFitWithin);
  56293. }
  56294. }
  56295. END_JUCE_NAMESPACE
  56296. #endif
  56297. /********* End of inlined file: juce_QuickTimeMovieComponent.cpp *********/
  56298. /********* Start of inlined file: juce_SystemTrayIconComponent.cpp *********/
  56299. #if JUCE_WIN32 || JUCE_LINUX
  56300. BEGIN_JUCE_NAMESPACE
  56301. SystemTrayIconComponent::SystemTrayIconComponent()
  56302. {
  56303. addToDesktop (0);
  56304. }
  56305. SystemTrayIconComponent::~SystemTrayIconComponent()
  56306. {
  56307. }
  56308. END_JUCE_NAMESPACE
  56309. #endif
  56310. /********* End of inlined file: juce_SystemTrayIconComponent.cpp *********/
  56311. /********* Start of inlined file: juce_AlertWindow.cpp *********/
  56312. BEGIN_JUCE_NAMESPACE
  56313. static const int titleH = 24;
  56314. static const int iconWidth = 80;
  56315. class AlertWindowTextEditor : public TextEditor
  56316. {
  56317. public:
  56318. #if JUCE_LINUX
  56319. #define PASSWORD_CHAR 0x2022
  56320. #else
  56321. #define PASSWORD_CHAR 0x25cf
  56322. #endif
  56323. AlertWindowTextEditor (const String& name,
  56324. const bool isPasswordBox)
  56325. : TextEditor (name,
  56326. isPasswordBox ? (const tchar) PASSWORD_CHAR
  56327. : (const tchar) 0)
  56328. {
  56329. setSelectAllWhenFocused (true);
  56330. }
  56331. ~AlertWindowTextEditor()
  56332. {
  56333. }
  56334. void returnPressed()
  56335. {
  56336. // pass these up the component hierarchy to be trigger the buttons
  56337. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, T('\n')));
  56338. }
  56339. void escapePressed()
  56340. {
  56341. // pass these up the component hierarchy to be trigger the buttons
  56342. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  56343. }
  56344. private:
  56345. AlertWindowTextEditor (const AlertWindowTextEditor&);
  56346. const AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  56347. };
  56348. AlertWindow::AlertWindow (const String& title,
  56349. const String& message,
  56350. AlertIconType iconType)
  56351. : TopLevelWindow (title, true),
  56352. alertIconType (iconType)
  56353. {
  56354. if (message.isEmpty())
  56355. text = T(" "); // to force an update if the message is empty
  56356. setMessage (message);
  56357. #if JUCE_MAC
  56358. setAlwaysOnTop (true);
  56359. #else
  56360. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  56361. {
  56362. Component* const c = Desktop::getInstance().getComponent (i);
  56363. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  56364. {
  56365. setAlwaysOnTop (true);
  56366. break;
  56367. }
  56368. }
  56369. #endif
  56370. lookAndFeelChanged();
  56371. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  56372. }
  56373. AlertWindow::~AlertWindow()
  56374. {
  56375. for (int i = customComps.size(); --i >= 0;)
  56376. removeChildComponent ((Component*) customComps[i]);
  56377. deleteAllChildren();
  56378. }
  56379. void AlertWindow::setMessage (const String& message)
  56380. {
  56381. const String newMessage (message.substring (0, 2048));
  56382. if (text != newMessage)
  56383. {
  56384. text = newMessage;
  56385. font.setHeight (15.0f);
  56386. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  56387. textLayout.setText (getName() + T("\n\n"), titleFont);
  56388. textLayout.appendText (text, font);
  56389. updateLayout (true);
  56390. repaint();
  56391. }
  56392. }
  56393. void AlertWindow::buttonClicked (Button* button)
  56394. {
  56395. for (int i = 0; i < buttons.size(); i++)
  56396. {
  56397. TextButton* const c = (TextButton*) buttons[i];
  56398. if (button->getName() == c->getName())
  56399. {
  56400. if (c->getParentComponent() != 0)
  56401. c->getParentComponent()->exitModalState (c->getCommandID());
  56402. break;
  56403. }
  56404. }
  56405. }
  56406. void AlertWindow::addButton (const String& name,
  56407. const int returnValue,
  56408. const KeyPress& shortcutKey1,
  56409. const KeyPress& shortcutKey2)
  56410. {
  56411. TextButton* const b = new TextButton (name, String::empty);
  56412. b->setWantsKeyboardFocus (true);
  56413. b->setMouseClickGrabsKeyboardFocus (false);
  56414. b->setCommandToTrigger (0, returnValue, false);
  56415. b->addShortcut (shortcutKey1);
  56416. b->addShortcut (shortcutKey2);
  56417. b->addButtonListener (this);
  56418. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  56419. addAndMakeVisible (b, 0);
  56420. buttons.add (b);
  56421. updateLayout (false);
  56422. }
  56423. int AlertWindow::getNumButtons() const
  56424. {
  56425. return buttons.size();
  56426. }
  56427. void AlertWindow::addTextEditor (const String& name,
  56428. const String& initialContents,
  56429. const String& onScreenLabel,
  56430. const bool isPasswordBox)
  56431. {
  56432. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  56433. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  56434. tc->setFont (font);
  56435. tc->setText (initialContents);
  56436. tc->setCaretPosition (initialContents.length());
  56437. addAndMakeVisible (tc);
  56438. textBoxes.add (tc);
  56439. allComps.add (tc);
  56440. textboxNames.add (onScreenLabel);
  56441. updateLayout (false);
  56442. }
  56443. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  56444. {
  56445. for (int i = textBoxes.size(); --i >= 0;)
  56446. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  56447. return ((TextEditor*)textBoxes[i])->getText();
  56448. return String::empty;
  56449. }
  56450. void AlertWindow::addComboBox (const String& name,
  56451. const StringArray& items,
  56452. const String& onScreenLabel)
  56453. {
  56454. ComboBox* const cb = new ComboBox (name);
  56455. for (int i = 0; i < items.size(); ++i)
  56456. cb->addItem (items[i], i + 1);
  56457. addAndMakeVisible (cb);
  56458. cb->setSelectedItemIndex (0);
  56459. comboBoxes.add (cb);
  56460. allComps.add (cb);
  56461. comboBoxNames.add (onScreenLabel);
  56462. updateLayout (false);
  56463. }
  56464. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  56465. {
  56466. for (int i = comboBoxes.size(); --i >= 0;)
  56467. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  56468. return (ComboBox*) comboBoxes[i];
  56469. return 0;
  56470. }
  56471. class AlertTextComp : public TextEditor
  56472. {
  56473. AlertTextComp (const AlertTextComp&);
  56474. const AlertTextComp& operator= (const AlertTextComp&);
  56475. int bestWidth;
  56476. public:
  56477. AlertTextComp (const String& message,
  56478. const Font& font)
  56479. {
  56480. setReadOnly (true);
  56481. setMultiLine (true, true);
  56482. setCaretVisible (false);
  56483. setScrollbarsShown (true);
  56484. lookAndFeelChanged();
  56485. setWantsKeyboardFocus (false);
  56486. setFont (font);
  56487. setText (message, false);
  56488. bestWidth = 2 * (int) sqrt (font.getHeight() * font.getStringWidth (message));
  56489. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  56490. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  56491. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  56492. }
  56493. ~AlertTextComp()
  56494. {
  56495. }
  56496. int getPreferredWidth() const throw() { return bestWidth; }
  56497. void updateLayout (const int width)
  56498. {
  56499. TextLayout text;
  56500. text.appendText (getText(), getFont());
  56501. text.layout (width - 8, Justification::topLeft, true);
  56502. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  56503. }
  56504. };
  56505. void AlertWindow::addTextBlock (const String& text)
  56506. {
  56507. AlertTextComp* const c = new AlertTextComp (text, font);
  56508. textBlocks.add (c);
  56509. allComps.add (c);
  56510. addAndMakeVisible (c);
  56511. updateLayout (false);
  56512. }
  56513. void AlertWindow::addProgressBarComponent (double& progressValue)
  56514. {
  56515. ProgressBar* const pb = new ProgressBar (progressValue);
  56516. progressBars.add (pb);
  56517. allComps.add (pb);
  56518. addAndMakeVisible (pb);
  56519. updateLayout (false);
  56520. }
  56521. void AlertWindow::addCustomComponent (Component* const component)
  56522. {
  56523. customComps.add (component);
  56524. allComps.add (component);
  56525. addAndMakeVisible (component);
  56526. updateLayout (false);
  56527. }
  56528. int AlertWindow::getNumCustomComponents() const
  56529. {
  56530. return customComps.size();
  56531. }
  56532. Component* AlertWindow::getCustomComponent (const int index) const
  56533. {
  56534. return (Component*) customComps [index];
  56535. }
  56536. Component* AlertWindow::removeCustomComponent (const int index)
  56537. {
  56538. Component* const c = getCustomComponent (index);
  56539. if (c != 0)
  56540. {
  56541. customComps.removeValue (c);
  56542. allComps.removeValue (c);
  56543. removeChildComponent (c);
  56544. updateLayout (false);
  56545. }
  56546. return c;
  56547. }
  56548. void AlertWindow::paint (Graphics& g)
  56549. {
  56550. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  56551. g.setColour (findColour (textColourId));
  56552. g.setFont (getLookAndFeel().getAlertWindowFont());
  56553. int i;
  56554. for (i = textBoxes.size(); --i >= 0;)
  56555. {
  56556. if (textboxNames[i].isNotEmpty())
  56557. {
  56558. const TextEditor* const te = (TextEditor*) textBoxes[i];
  56559. g.drawFittedText (textboxNames[i],
  56560. te->getX(), te->getY() - 14,
  56561. te->getWidth(), 14,
  56562. Justification::centredLeft, 1);
  56563. }
  56564. }
  56565. for (i = comboBoxNames.size(); --i >= 0;)
  56566. {
  56567. if (comboBoxNames[i].isNotEmpty())
  56568. {
  56569. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  56570. g.drawFittedText (comboBoxNames[i],
  56571. cb->getX(), cb->getY() - 14,
  56572. cb->getWidth(), 14,
  56573. Justification::centredLeft, 1);
  56574. }
  56575. }
  56576. }
  56577. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  56578. {
  56579. const int wid = jmax (font.getStringWidth (text),
  56580. font.getStringWidth (getName()));
  56581. const int sw = (int) sqrt (font.getHeight() * wid);
  56582. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  56583. const int edgeGap = 10;
  56584. int iconSpace;
  56585. if (alertIconType == NoIcon)
  56586. {
  56587. textLayout.layout (w, Justification::horizontallyCentred, true);
  56588. iconSpace = 0;
  56589. }
  56590. else
  56591. {
  56592. textLayout.layout (w, Justification::left, true);
  56593. iconSpace = iconWidth;
  56594. }
  56595. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  56596. w = jmin (w, (int) (getParentWidth() * 0.7f));
  56597. const int textLayoutH = textLayout.getHeight();
  56598. const int textBottom = 16 + titleH + textLayoutH;
  56599. int h = textBottom;
  56600. int buttonW = 40;
  56601. int i;
  56602. for (i = 0; i < buttons.size(); ++i)
  56603. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  56604. w = jmax (buttonW, w);
  56605. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  56606. if (buttons.size() > 0)
  56607. h += 20 + ((TextButton*) buttons[0])->getHeight();
  56608. for (i = customComps.size(); --i >= 0;)
  56609. {
  56610. w = jmax (w, ((Component*) customComps[i])->getWidth() + 40);
  56611. h += 10 + ((Component*) customComps[i])->getHeight();
  56612. }
  56613. for (i = textBlocks.size(); --i >= 0;)
  56614. {
  56615. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  56616. w = jmax (w, ac->getPreferredWidth());
  56617. }
  56618. w = jmin (w, (int) (getParentWidth() * 0.7f));
  56619. for (i = textBlocks.size(); --i >= 0;)
  56620. {
  56621. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  56622. ac->updateLayout ((int) (w * 0.8f));
  56623. h += ac->getHeight() + 10;
  56624. }
  56625. h = jmin (getParentHeight() - 50, h);
  56626. if (onlyIncreaseSize)
  56627. {
  56628. w = jmax (w, getWidth());
  56629. h = jmax (h, getHeight());
  56630. }
  56631. if (! isVisible())
  56632. {
  56633. centreAroundComponent (0, w, h);
  56634. }
  56635. else
  56636. {
  56637. const int cx = getX() + getWidth() / 2;
  56638. const int cy = getY() + getHeight() / 2;
  56639. setBounds (cx - w / 2,
  56640. cy - h / 2,
  56641. w, h);
  56642. }
  56643. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  56644. const int spacer = 16;
  56645. int totalWidth = -spacer;
  56646. for (i = buttons.size(); --i >= 0;)
  56647. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  56648. int x = (w - totalWidth) / 2;
  56649. int y = (int) (getHeight() * 0.95f);
  56650. for (i = 0; i < buttons.size(); ++i)
  56651. {
  56652. TextButton* const c = (TextButton*) buttons[i];
  56653. int ny = proportionOfHeight (0.95f) - c->getHeight();
  56654. c->setTopLeftPosition (x, ny);
  56655. if (ny < y)
  56656. y = ny;
  56657. x += c->getWidth() + spacer;
  56658. c->toFront (false);
  56659. }
  56660. y = textBottom;
  56661. for (i = 0; i < allComps.size(); ++i)
  56662. {
  56663. Component* const c = (Component*) allComps[i];
  56664. const int h = 22;
  56665. const int comboIndex = comboBoxes.indexOf (c);
  56666. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  56667. y += 18;
  56668. const int tbIndex = textBoxes.indexOf (c);
  56669. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  56670. y += 18;
  56671. if (customComps.contains (c) || textBlocks.contains (c))
  56672. {
  56673. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  56674. y += c->getHeight() + 10;
  56675. }
  56676. else
  56677. {
  56678. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  56679. y += h + 10;
  56680. }
  56681. }
  56682. setWantsKeyboardFocus (getNumChildComponents() == 0);
  56683. }
  56684. bool AlertWindow::containsAnyExtraComponents() const
  56685. {
  56686. return textBoxes.size()
  56687. + comboBoxes.size()
  56688. + progressBars.size()
  56689. + customComps.size() > 0;
  56690. }
  56691. void AlertWindow::mouseDown (const MouseEvent&)
  56692. {
  56693. dragger.startDraggingComponent (this, &constrainer);
  56694. }
  56695. void AlertWindow::mouseDrag (const MouseEvent& e)
  56696. {
  56697. dragger.dragComponent (this, e);
  56698. }
  56699. bool AlertWindow::keyPressed (const KeyPress& key)
  56700. {
  56701. for (int i = buttons.size(); --i >= 0;)
  56702. {
  56703. TextButton* const b = (TextButton*) buttons[i];
  56704. if (b->isRegisteredForShortcut (key))
  56705. {
  56706. b->triggerClick();
  56707. return true;
  56708. }
  56709. }
  56710. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  56711. {
  56712. exitModalState (0);
  56713. return true;
  56714. }
  56715. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  56716. {
  56717. ((TextButton*) buttons.getFirst())->triggerClick();
  56718. return true;
  56719. }
  56720. return false;
  56721. }
  56722. void AlertWindow::lookAndFeelChanged()
  56723. {
  56724. const int flags = getLookAndFeel().getAlertBoxWindowFlags();
  56725. setUsingNativeTitleBar ((flags & ComponentPeer::windowHasTitleBar) != 0);
  56726. setDropShadowEnabled ((flags & ComponentPeer::windowHasDropShadow) != 0);
  56727. }
  56728. struct AlertWindowInfo
  56729. {
  56730. String title, message, button1, button2, button3;
  56731. AlertWindow::AlertIconType iconType;
  56732. int numButtons;
  56733. int run() const
  56734. {
  56735. return (int) (pointer_sized_int)
  56736. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  56737. }
  56738. private:
  56739. int show() const
  56740. {
  56741. AlertWindow aw (title, message, iconType);
  56742. if (numButtons == 1)
  56743. {
  56744. aw.addButton (button1, 0,
  56745. KeyPress (KeyPress::escapeKey, 0, 0),
  56746. KeyPress (KeyPress::returnKey, 0, 0));
  56747. }
  56748. else
  56749. {
  56750. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  56751. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  56752. if (button1ShortCut == button2ShortCut)
  56753. button2ShortCut = KeyPress();
  56754. if (numButtons == 2)
  56755. {
  56756. aw.addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  56757. aw.addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  56758. }
  56759. else
  56760. {
  56761. jassert (numButtons == 3);
  56762. aw.addButton (button1, 1, button1ShortCut);
  56763. aw.addButton (button2, 2, button2ShortCut);
  56764. aw.addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  56765. }
  56766. }
  56767. return aw.runModalLoop();
  56768. }
  56769. static void* showCallback (void* userData)
  56770. {
  56771. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  56772. }
  56773. };
  56774. void AlertWindow::showMessageBox (AlertIconType iconType,
  56775. const String& title,
  56776. const String& message,
  56777. const String& buttonText)
  56778. {
  56779. AlertWindowInfo info;
  56780. info.title = title;
  56781. info.message = message;
  56782. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  56783. info.iconType = iconType;
  56784. info.numButtons = 1;
  56785. info.run();
  56786. }
  56787. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  56788. const String& title,
  56789. const String& message,
  56790. const String& button1Text,
  56791. const String& button2Text)
  56792. {
  56793. AlertWindowInfo info;
  56794. info.title = title;
  56795. info.message = message;
  56796. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  56797. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  56798. info.iconType = iconType;
  56799. info.numButtons = 2;
  56800. return info.run() != 0;
  56801. }
  56802. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  56803. const String& title,
  56804. const String& message,
  56805. const String& button1Text,
  56806. const String& button2Text,
  56807. const String& button3Text)
  56808. {
  56809. AlertWindowInfo info;
  56810. info.title = title;
  56811. info.message = message;
  56812. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  56813. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  56814. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  56815. info.iconType = iconType;
  56816. info.numButtons = 3;
  56817. return info.run();
  56818. }
  56819. END_JUCE_NAMESPACE
  56820. /********* End of inlined file: juce_AlertWindow.cpp *********/
  56821. /********* Start of inlined file: juce_ComponentPeer.cpp *********/
  56822. BEGIN_JUCE_NAMESPACE
  56823. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  56824. // these are over in juce_component.cpp
  56825. extern int64 juce_recentMouseDownTimes[4];
  56826. extern int juce_recentMouseDownX [4];
  56827. extern int juce_recentMouseDownY [4];
  56828. extern Component* juce_recentMouseDownComponent [4];
  56829. extern int juce_LastMousePosX;
  56830. extern int juce_LastMousePosY;
  56831. extern int juce_MouseClickCounter;
  56832. extern bool juce_MouseHasMovedSignificantlySincePressed;
  56833. static const int fakeMouseMoveMessage = 0x7fff00ff;
  56834. static VoidArray heavyweightPeers (4);
  56835. ComponentPeer::ComponentPeer (Component* const component_,
  56836. const int styleFlags_) throw()
  56837. : component (component_),
  56838. styleFlags (styleFlags_),
  56839. lastPaintTime (0),
  56840. constrainer (0),
  56841. lastFocusedComponent (0),
  56842. dragAndDropTargetComponent (0),
  56843. lastDragAndDropCompUnderMouse (0),
  56844. fakeMouseMessageSent (false),
  56845. isWindowMinimised (false)
  56846. {
  56847. heavyweightPeers.add (this);
  56848. }
  56849. ComponentPeer::~ComponentPeer()
  56850. {
  56851. heavyweightPeers.removeValue (this);
  56852. delete dragAndDropTargetComponent;
  56853. }
  56854. int ComponentPeer::getNumPeers() throw()
  56855. {
  56856. return heavyweightPeers.size();
  56857. }
  56858. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  56859. {
  56860. return (ComponentPeer*) heavyweightPeers [index];
  56861. }
  56862. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  56863. {
  56864. for (int i = heavyweightPeers.size(); --i >= 0;)
  56865. {
  56866. ComponentPeer* const peer = (ComponentPeer*) heavyweightPeers.getUnchecked(i);
  56867. if (peer->getComponent() == component)
  56868. return peer;
  56869. }
  56870. return 0;
  56871. }
  56872. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  56873. {
  56874. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  56875. }
  56876. void ComponentPeer::updateCurrentModifiers() throw()
  56877. {
  56878. ModifierKeys::updateCurrentModifiers();
  56879. }
  56880. void ComponentPeer::handleMouseEnter (int x, int y, const int64 time)
  56881. {
  56882. jassert (component->isValidComponent());
  56883. updateCurrentModifiers();
  56884. Component* c = component->getComponentAt (x, y);
  56885. const ComponentDeletionWatcher deletionChecker (component);
  56886. if (c != Component::componentUnderMouse && Component::componentUnderMouse != 0)
  56887. {
  56888. jassert (Component::componentUnderMouse->isValidComponent());
  56889. const int oldX = x;
  56890. const int oldY = y;
  56891. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56892. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56893. Component::componentUnderMouse = 0;
  56894. if (deletionChecker.hasBeenDeleted())
  56895. return;
  56896. c = component->getComponentAt (oldX, oldY);
  56897. }
  56898. Component::componentUnderMouse = c;
  56899. if (Component::componentUnderMouse != 0)
  56900. {
  56901. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56902. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  56903. }
  56904. }
  56905. void ComponentPeer::handleMouseMove (int x, int y, const int64 time)
  56906. {
  56907. jassert (component->isValidComponent());
  56908. updateCurrentModifiers();
  56909. fakeMouseMessageSent = false;
  56910. const ComponentDeletionWatcher deletionChecker (component);
  56911. Component* c = component->getComponentAt (x, y);
  56912. if (c != Component::componentUnderMouse)
  56913. {
  56914. const int oldX = x;
  56915. const int oldY = y;
  56916. if (Component::componentUnderMouse != 0)
  56917. {
  56918. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56919. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56920. x = oldX;
  56921. y = oldY;
  56922. Component::componentUnderMouse = 0;
  56923. if (deletionChecker.hasBeenDeleted())
  56924. return; // if this window has just been deleted..
  56925. c = component->getComponentAt (x, y);
  56926. }
  56927. Component::componentUnderMouse = c;
  56928. if (c != 0)
  56929. {
  56930. component->relativePositionToOtherComponent (c, x, y);
  56931. c->internalMouseEnter (x, y, time);
  56932. x = oldX;
  56933. y = oldY;
  56934. if (deletionChecker.hasBeenDeleted())
  56935. return; // if this window has just been deleted..
  56936. }
  56937. }
  56938. if (Component::componentUnderMouse != 0)
  56939. {
  56940. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56941. Component::componentUnderMouse->internalMouseMove (x, y, time);
  56942. }
  56943. }
  56944. void ComponentPeer::handleMouseDown (int x, int y, const int64 time)
  56945. {
  56946. ++juce_MouseClickCounter;
  56947. updateCurrentModifiers();
  56948. int numMouseButtonsDown = 0;
  56949. if (ModifierKeys::getCurrentModifiers().isLeftButtonDown())
  56950. ++numMouseButtonsDown;
  56951. if (ModifierKeys::getCurrentModifiers().isRightButtonDown())
  56952. ++numMouseButtonsDown;
  56953. if (ModifierKeys::getCurrentModifiers().isMiddleButtonDown())
  56954. ++numMouseButtonsDown;
  56955. if (numMouseButtonsDown == 1)
  56956. {
  56957. Component::componentUnderMouse = component->getComponentAt (x, y);
  56958. if (Component::componentUnderMouse != 0)
  56959. {
  56960. // can't set these in the mouseDownInt() method, because it's re-entrant, so do it here..
  56961. for (int i = numElementsInArray (juce_recentMouseDownTimes); --i > 0;)
  56962. {
  56963. juce_recentMouseDownTimes [i] = juce_recentMouseDownTimes [i - 1];
  56964. juce_recentMouseDownX [i] = juce_recentMouseDownX [i - 1];
  56965. juce_recentMouseDownY [i] = juce_recentMouseDownY [i - 1];
  56966. juce_recentMouseDownComponent [i] = juce_recentMouseDownComponent [i - 1];
  56967. }
  56968. juce_recentMouseDownTimes[0] = time;
  56969. juce_recentMouseDownX[0] = x;
  56970. juce_recentMouseDownY[0] = y;
  56971. juce_recentMouseDownComponent[0] = Component::componentUnderMouse;
  56972. relativePositionToGlobal (juce_recentMouseDownX[0], juce_recentMouseDownY[0]);
  56973. juce_MouseHasMovedSignificantlySincePressed = false;
  56974. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56975. Component::componentUnderMouse->internalMouseDown (x, y);
  56976. }
  56977. }
  56978. }
  56979. void ComponentPeer::handleMouseDrag (int x, int y, const int64 time)
  56980. {
  56981. updateCurrentModifiers();
  56982. if (Component::componentUnderMouse != 0)
  56983. {
  56984. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56985. Component::componentUnderMouse->internalMouseDrag (x, y, time);
  56986. }
  56987. }
  56988. void ComponentPeer::handleMouseUp (const int oldModifiers, int x, int y, const int64 time)
  56989. {
  56990. updateCurrentModifiers();
  56991. int numMouseButtonsDown = 0;
  56992. if ((oldModifiers & ModifierKeys::leftButtonModifier) != 0)
  56993. ++numMouseButtonsDown;
  56994. if ((oldModifiers & ModifierKeys::rightButtonModifier) != 0)
  56995. ++numMouseButtonsDown;
  56996. if ((oldModifiers & ModifierKeys::middleButtonModifier) != 0)
  56997. ++numMouseButtonsDown;
  56998. if (numMouseButtonsDown == 1)
  56999. {
  57000. const ComponentDeletionWatcher deletionChecker (component);
  57001. Component* c = component->getComponentAt (x, y);
  57002. if (c != Component::componentUnderMouse)
  57003. {
  57004. const int oldX = x;
  57005. const int oldY = y;
  57006. if (Component::componentUnderMouse != 0)
  57007. {
  57008. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  57009. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  57010. x = oldX;
  57011. y = oldY;
  57012. if (Component::componentUnderMouse != 0)
  57013. Component::componentUnderMouse->internalMouseExit (x, y, time);
  57014. if (deletionChecker.hasBeenDeleted())
  57015. return;
  57016. c = component->getComponentAt (oldX, oldY);
  57017. }
  57018. Component::componentUnderMouse = c;
  57019. if (Component::componentUnderMouse != 0)
  57020. {
  57021. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  57022. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  57023. }
  57024. }
  57025. else
  57026. {
  57027. if (Component::componentUnderMouse != 0)
  57028. {
  57029. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  57030. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  57031. }
  57032. }
  57033. }
  57034. }
  57035. void ComponentPeer::handleMouseExit (int x, int y, const int64 time)
  57036. {
  57037. jassert (component->isValidComponent());
  57038. updateCurrentModifiers();
  57039. if (Component::componentUnderMouse != 0)
  57040. {
  57041. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  57042. Component::componentUnderMouse->internalMouseExit (x, y, time);
  57043. Component::componentUnderMouse = 0;
  57044. }
  57045. }
  57046. void ComponentPeer::handleMouseWheel (const int amountX, const int amountY, const int64 time)
  57047. {
  57048. updateCurrentModifiers();
  57049. if (Component::componentUnderMouse != 0)
  57050. Component::componentUnderMouse->internalMouseWheel (amountX, amountY, time);
  57051. }
  57052. void ComponentPeer::sendFakeMouseMove() throw()
  57053. {
  57054. if ((! fakeMouseMessageSent)
  57055. && component->flags.hasHeavyweightPeerFlag
  57056. && ! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  57057. {
  57058. if (! isMinimised())
  57059. {
  57060. int realX, realY, realW, realH;
  57061. getBounds (realX, realY, realW, realH);
  57062. component->bounds_.setBounds (realX, realY, realW, realH);
  57063. }
  57064. int x, y;
  57065. component->getMouseXYRelative (x, y);
  57066. if (((unsigned int) x) < (unsigned int) component->getWidth()
  57067. && ((unsigned int) y) < (unsigned int) component->getHeight()
  57068. && contains (x, y, false))
  57069. {
  57070. postMessage (new Message (fakeMouseMoveMessage, x, y, 0));
  57071. }
  57072. fakeMouseMessageSent = true;
  57073. }
  57074. }
  57075. void ComponentPeer::handleMessage (const Message& message)
  57076. {
  57077. if (message.intParameter1 == fakeMouseMoveMessage)
  57078. {
  57079. handleMouseMove (message.intParameter2,
  57080. message.intParameter3,
  57081. Time::currentTimeMillis());
  57082. }
  57083. }
  57084. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  57085. {
  57086. Graphics g (&contextToPaintTo);
  57087. #if JUCE_ENABLE_REPAINT_DEBUGGING
  57088. g.saveState();
  57089. #endif
  57090. JUCE_TRY
  57091. {
  57092. component->paintEntireComponent (g);
  57093. }
  57094. JUCE_CATCH_EXCEPTION
  57095. #if JUCE_ENABLE_REPAINT_DEBUGGING
  57096. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  57097. // clearly when things are being repainted.
  57098. {
  57099. g.restoreState();
  57100. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  57101. (uint8) Random::getSystemRandom().nextInt (255),
  57102. (uint8) Random::getSystemRandom().nextInt (255),
  57103. (uint8) 0x50));
  57104. }
  57105. #endif
  57106. }
  57107. bool ComponentPeer::handleKeyPress (const int keyCode,
  57108. const juce_wchar textCharacter)
  57109. {
  57110. updateCurrentModifiers();
  57111. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  57112. ? Component::currentlyFocusedComponent
  57113. : component;
  57114. if (target->isCurrentlyBlockedByAnotherModalComponent())
  57115. {
  57116. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  57117. if (currentModalComp != 0)
  57118. target = currentModalComp;
  57119. }
  57120. const KeyPress keyInfo (keyCode,
  57121. ModifierKeys::getCurrentModifiers().getRawFlags()
  57122. & ModifierKeys::allKeyboardModifiers,
  57123. textCharacter);
  57124. bool keyWasUsed = false;
  57125. while (target != 0)
  57126. {
  57127. const ComponentDeletionWatcher deletionChecker (target);
  57128. if (target->keyListeners_ != 0)
  57129. {
  57130. for (int i = target->keyListeners_->size(); --i >= 0;)
  57131. {
  57132. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyPressed (keyInfo, target);
  57133. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  57134. return keyWasUsed;
  57135. i = jmin (i, target->keyListeners_->size());
  57136. }
  57137. }
  57138. keyWasUsed = target->keyPressed (keyInfo);
  57139. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  57140. break;
  57141. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  57142. {
  57143. Component::getCurrentlyFocusedComponent()
  57144. ->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  57145. keyWasUsed = true;
  57146. break;
  57147. }
  57148. target = target->parentComponent_;
  57149. }
  57150. return keyWasUsed;
  57151. }
  57152. bool ComponentPeer::handleKeyUpOrDown()
  57153. {
  57154. updateCurrentModifiers();
  57155. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  57156. ? Component::currentlyFocusedComponent
  57157. : component;
  57158. if (target->isCurrentlyBlockedByAnotherModalComponent())
  57159. {
  57160. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  57161. if (currentModalComp != 0)
  57162. target = currentModalComp;
  57163. }
  57164. bool keyWasUsed = false;
  57165. while (target != 0)
  57166. {
  57167. const ComponentDeletionWatcher deletionChecker (target);
  57168. keyWasUsed = target->keyStateChanged();
  57169. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  57170. break;
  57171. if (target->keyListeners_ != 0)
  57172. {
  57173. for (int i = target->keyListeners_->size(); --i >= 0;)
  57174. {
  57175. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyStateChanged (target);
  57176. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  57177. return keyWasUsed;
  57178. i = jmin (i, target->keyListeners_->size());
  57179. }
  57180. }
  57181. target = target->parentComponent_;
  57182. }
  57183. return keyWasUsed;
  57184. }
  57185. void ComponentPeer::handleModifierKeysChange()
  57186. {
  57187. updateCurrentModifiers();
  57188. Component* target = Component::getComponentUnderMouse();
  57189. if (target == 0)
  57190. target = Component::getCurrentlyFocusedComponent();
  57191. if (target == 0)
  57192. target = component;
  57193. if (target->isValidComponent())
  57194. target->internalModifierKeysChanged();
  57195. }
  57196. void ComponentPeer::handleBroughtToFront()
  57197. {
  57198. updateCurrentModifiers();
  57199. if (component != 0)
  57200. component->internalBroughtToFront();
  57201. }
  57202. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  57203. {
  57204. constrainer = newConstrainer;
  57205. }
  57206. void ComponentPeer::handleMovedOrResized()
  57207. {
  57208. jassert (component->isValidComponent());
  57209. updateCurrentModifiers();
  57210. const bool nowMinimised = isMinimised();
  57211. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  57212. {
  57213. const ComponentDeletionWatcher deletionChecker (component);
  57214. int realX, realY, realW, realH;
  57215. getBounds (realX, realY, realW, realH);
  57216. const bool wasMoved = (component->getX() != realX || component->getY() != realY);
  57217. const bool wasResized = (component->getWidth() != realW || component->getHeight() != realH);
  57218. if (wasMoved || wasResized)
  57219. {
  57220. component->bounds_.setBounds (realX, realY, realW, realH);
  57221. if (wasResized)
  57222. component->repaint();
  57223. component->sendMovedResizedMessages (wasMoved, wasResized);
  57224. if (deletionChecker.hasBeenDeleted())
  57225. return;
  57226. }
  57227. }
  57228. if (isWindowMinimised != nowMinimised)
  57229. {
  57230. isWindowMinimised = nowMinimised;
  57231. component->minimisationStateChanged (nowMinimised);
  57232. component->sendVisibilityChangeMessage();
  57233. }
  57234. if (! isFullScreen())
  57235. lastNonFullscreenBounds = component->getBounds();
  57236. }
  57237. void ComponentPeer::handleFocusGain()
  57238. {
  57239. updateCurrentModifiers();
  57240. if (component->isParentOf (lastFocusedComponent))
  57241. {
  57242. Component::currentlyFocusedComponent = lastFocusedComponent;
  57243. Desktop::getInstance().triggerFocusCallback();
  57244. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  57245. }
  57246. else
  57247. {
  57248. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  57249. {
  57250. component->grabKeyboardFocus();
  57251. }
  57252. else
  57253. {
  57254. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  57255. if (currentModalComp != 0)
  57256. currentModalComp->toFront (! currentModalComp->hasKeyboardFocus (true));
  57257. }
  57258. }
  57259. }
  57260. void ComponentPeer::handleFocusLoss()
  57261. {
  57262. updateCurrentModifiers();
  57263. if (component->hasKeyboardFocus (true))
  57264. {
  57265. lastFocusedComponent = Component::currentlyFocusedComponent;
  57266. if (lastFocusedComponent != 0)
  57267. {
  57268. Component::currentlyFocusedComponent = 0;
  57269. Desktop::getInstance().triggerFocusCallback();
  57270. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  57271. }
  57272. }
  57273. }
  57274. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  57275. {
  57276. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  57277. ? lastFocusedComponent
  57278. : component;
  57279. }
  57280. void ComponentPeer::handleScreenSizeChange()
  57281. {
  57282. updateCurrentModifiers();
  57283. component->parentSizeChanged();
  57284. handleMovedOrResized();
  57285. }
  57286. void ComponentPeer::setNonFullScreenBounds (const Rectangle& newBounds) throw()
  57287. {
  57288. lastNonFullscreenBounds = newBounds;
  57289. }
  57290. const Rectangle& ComponentPeer::getNonFullScreenBounds() const throw()
  57291. {
  57292. return lastNonFullscreenBounds;
  57293. }
  57294. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  57295. const StringArray& files,
  57296. FileDragAndDropTarget* const lastOne)
  57297. {
  57298. while (c != 0)
  57299. {
  57300. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  57301. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  57302. return t;
  57303. c = c->getParentComponent();
  57304. }
  57305. return 0;
  57306. }
  57307. void ComponentPeer::handleFileDragMove (const StringArray& files, int x, int y)
  57308. {
  57309. updateCurrentModifiers();
  57310. FileDragAndDropTarget* lastTarget = 0;
  57311. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  57312. lastTarget = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  57313. FileDragAndDropTarget* newTarget = 0;
  57314. Component* const compUnderMouse = component->getComponentAt (x, y);
  57315. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  57316. {
  57317. lastDragAndDropCompUnderMouse = compUnderMouse;
  57318. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  57319. if (newTarget != lastTarget)
  57320. {
  57321. if (lastTarget != 0)
  57322. lastTarget->fileDragExit (files);
  57323. deleteAndZero (dragAndDropTargetComponent);
  57324. if (newTarget != 0)
  57325. {
  57326. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  57327. int mx = x, my = y;
  57328. component->relativePositionToOtherComponent (targetComp, mx, my);
  57329. dragAndDropTargetComponent = new ComponentDeletionWatcher (dynamic_cast <Component*> (newTarget));
  57330. newTarget->fileDragEnter (files, mx, my);
  57331. }
  57332. }
  57333. }
  57334. else
  57335. {
  57336. newTarget = lastTarget;
  57337. }
  57338. if (newTarget != 0)
  57339. {
  57340. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  57341. component->relativePositionToOtherComponent (targetComp, x, y);
  57342. newTarget->fileDragMove (files, x, y);
  57343. }
  57344. }
  57345. void ComponentPeer::handleFileDragExit (const StringArray& files)
  57346. {
  57347. handleFileDragMove (files, -1, -1);
  57348. jassert (dragAndDropTargetComponent == 0);
  57349. lastDragAndDropCompUnderMouse = 0;
  57350. }
  57351. void ComponentPeer::handleFileDragDrop (const StringArray& files, int x, int y)
  57352. {
  57353. handleFileDragMove (files, x, y);
  57354. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  57355. {
  57356. FileDragAndDropTarget* const target = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  57357. deleteAndZero (dragAndDropTargetComponent);
  57358. lastDragAndDropCompUnderMouse = 0;
  57359. if (target != 0)
  57360. {
  57361. Component* const targetComp = dynamic_cast <Component*> (target);
  57362. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  57363. {
  57364. targetComp->internalModalInputAttempt();
  57365. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  57366. return;
  57367. }
  57368. component->relativePositionToOtherComponent (targetComp, x, y);
  57369. target->filesDropped (files, x, y);
  57370. }
  57371. }
  57372. }
  57373. void ComponentPeer::handleUserClosingWindow()
  57374. {
  57375. updateCurrentModifiers();
  57376. component->userTriedToCloseWindow();
  57377. }
  57378. void ComponentPeer::clearMaskedRegion() throw()
  57379. {
  57380. maskedRegion.clear();
  57381. }
  57382. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h) throw()
  57383. {
  57384. maskedRegion.add (x, y, w, h);
  57385. }
  57386. END_JUCE_NAMESPACE
  57387. /********* End of inlined file: juce_ComponentPeer.cpp *********/
  57388. /********* Start of inlined file: juce_DialogWindow.cpp *********/
  57389. BEGIN_JUCE_NAMESPACE
  57390. DialogWindow::DialogWindow (const String& name,
  57391. const Colour& backgroundColour_,
  57392. const bool escapeKeyTriggersCloseButton_,
  57393. const bool addToDesktop_)
  57394. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  57395. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  57396. {
  57397. }
  57398. DialogWindow::~DialogWindow()
  57399. {
  57400. }
  57401. void DialogWindow::resized()
  57402. {
  57403. DocumentWindow::resized();
  57404. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  57405. if (escapeKeyTriggersCloseButton
  57406. && getCloseButton() != 0
  57407. && ! getCloseButton()->isRegisteredForShortcut (esc))
  57408. {
  57409. getCloseButton()->addShortcut (esc);
  57410. }
  57411. }
  57412. class TempDialogWindow : public DialogWindow
  57413. {
  57414. public:
  57415. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  57416. : DialogWindow (title, colour, escapeCloses, true)
  57417. {
  57418. }
  57419. ~TempDialogWindow()
  57420. {
  57421. }
  57422. void closeButtonPressed()
  57423. {
  57424. setVisible (false);
  57425. }
  57426. private:
  57427. TempDialogWindow (const TempDialogWindow&);
  57428. const TempDialogWindow& operator= (const TempDialogWindow&);
  57429. };
  57430. int DialogWindow::showModalDialog (const String& dialogTitle,
  57431. Component* contentComponent,
  57432. Component* componentToCentreAround,
  57433. const Colour& colour,
  57434. const bool escapeKeyTriggersCloseButton,
  57435. const bool shouldBeResizable,
  57436. const bool useBottomRightCornerResizer)
  57437. {
  57438. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  57439. dw.setContentComponent (contentComponent, true, true);
  57440. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  57441. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  57442. const int result = dw.runModalLoop();
  57443. dw.setContentComponent (0, false);
  57444. return result;
  57445. }
  57446. END_JUCE_NAMESPACE
  57447. /********* End of inlined file: juce_DialogWindow.cpp *********/
  57448. /********* Start of inlined file: juce_DocumentWindow.cpp *********/
  57449. BEGIN_JUCE_NAMESPACE
  57450. DocumentWindow::DocumentWindow (const String& title,
  57451. const Colour& backgroundColour,
  57452. const int requiredButtons_,
  57453. const bool addToDesktop_)
  57454. : ResizableWindow (title, backgroundColour, addToDesktop_),
  57455. titleBarHeight (26),
  57456. menuBarHeight (24),
  57457. requiredButtons (requiredButtons_),
  57458. #if JUCE_MAC
  57459. positionTitleBarButtonsOnLeft (true),
  57460. #else
  57461. positionTitleBarButtonsOnLeft (false),
  57462. #endif
  57463. drawTitleTextCentred (true),
  57464. titleBarIcon (0),
  57465. menuBar (0),
  57466. menuBarModel (0)
  57467. {
  57468. zeromem (titleBarButtons, sizeof (titleBarButtons));
  57469. setResizeLimits (128, 128, 32768, 32768);
  57470. lookAndFeelChanged();
  57471. }
  57472. DocumentWindow::~DocumentWindow()
  57473. {
  57474. for (int i = 0; i < 3; ++i)
  57475. delete titleBarButtons[i];
  57476. delete titleBarIcon;
  57477. delete menuBar;
  57478. }
  57479. void DocumentWindow::repaintTitleBar()
  57480. {
  57481. const int border = getBorderSize();
  57482. repaint (border, border, getWidth() - border * 2, getTitleBarHeight());
  57483. }
  57484. void DocumentWindow::setName (const String& newName)
  57485. {
  57486. if (newName != getName())
  57487. {
  57488. Component::setName (newName);
  57489. repaintTitleBar();
  57490. }
  57491. }
  57492. void DocumentWindow::setIcon (const Image* imageToUse)
  57493. {
  57494. deleteAndZero (titleBarIcon);
  57495. if (imageToUse != 0)
  57496. titleBarIcon = imageToUse->createCopy();
  57497. repaintTitleBar();
  57498. }
  57499. void DocumentWindow::setTitleBarHeight (const int newHeight)
  57500. {
  57501. titleBarHeight = newHeight;
  57502. resized();
  57503. repaintTitleBar();
  57504. }
  57505. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  57506. const bool positionTitleBarButtonsOnLeft_)
  57507. {
  57508. requiredButtons = requiredButtons_;
  57509. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  57510. lookAndFeelChanged();
  57511. }
  57512. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  57513. {
  57514. drawTitleTextCentred = textShouldBeCentred;
  57515. repaintTitleBar();
  57516. }
  57517. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  57518. const int menuBarHeight_)
  57519. {
  57520. if (menuBarModel != menuBarModel_)
  57521. {
  57522. delete menuBar;
  57523. menuBar = 0;
  57524. menuBarModel = menuBarModel_;
  57525. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  57526. : getLookAndFeel().getDefaultMenuBarHeight();
  57527. if (menuBarModel != 0)
  57528. {
  57529. // (call the Component method directly to avoid the assertion in ResizableWindow)
  57530. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  57531. menuBar->setEnabled (isActiveWindow());
  57532. }
  57533. resized();
  57534. }
  57535. }
  57536. void DocumentWindow::closeButtonPressed()
  57537. {
  57538. /* If you've got a close button, you have to override this method to get
  57539. rid of your window!
  57540. If the window is just a pop-up, you should override this method and make
  57541. it delete the window in whatever way is appropriate for your app. E.g. you
  57542. might just want to call "delete this".
  57543. If your app is centred around this window such that the whole app should quit when
  57544. the window is closed, then you will probably want to use this method as an opportunity
  57545. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  57546. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  57547. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  57548. or closing it via the taskbar icon on Windows).
  57549. */
  57550. jassertfalse
  57551. }
  57552. void DocumentWindow::minimiseButtonPressed()
  57553. {
  57554. setMinimised (true);
  57555. }
  57556. void DocumentWindow::maximiseButtonPressed()
  57557. {
  57558. setFullScreen (! isFullScreen());
  57559. }
  57560. void DocumentWindow::paint (Graphics& g)
  57561. {
  57562. ResizableWindow::paint (g);
  57563. if (resizableBorder == 0 && getBorderSize() == 1)
  57564. {
  57565. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  57566. g.drawRect (0, 0, getWidth(), getHeight());
  57567. }
  57568. const int border = getBorderSize();
  57569. g.setOrigin (border, border);
  57570. g.reduceClipRegion (0, 0, getWidth() - border * 2, getTitleBarHeight());
  57571. int titleSpaceX1 = 6;
  57572. int titleSpaceX2 = getWidth() - 6;
  57573. for (int i = 0; i < 3; ++i)
  57574. {
  57575. if (titleBarButtons[i] != 0)
  57576. {
  57577. if (positionTitleBarButtonsOnLeft)
  57578. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  57579. else
  57580. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  57581. }
  57582. }
  57583. getLookAndFeel()
  57584. .drawDocumentWindowTitleBar (*this, g,
  57585. getWidth() - border * 2,
  57586. getTitleBarHeight(),
  57587. titleSpaceX1, jmax (1, titleSpaceX2 - titleSpaceX1),
  57588. titleBarIcon, ! drawTitleTextCentred);
  57589. }
  57590. void DocumentWindow::resized()
  57591. {
  57592. ResizableWindow::resized();
  57593. if (titleBarButtons[1] != 0)
  57594. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  57595. const int border = getBorderSize();
  57596. getLookAndFeel()
  57597. .positionDocumentWindowButtons (*this,
  57598. border, border,
  57599. getWidth() - border * 2, getTitleBarHeight(),
  57600. titleBarButtons[0],
  57601. titleBarButtons[1],
  57602. titleBarButtons[2],
  57603. positionTitleBarButtonsOnLeft);
  57604. if (menuBar != 0)
  57605. menuBar->setBounds (border, border + getTitleBarHeight(),
  57606. getWidth() - border * 2, menuBarHeight);
  57607. }
  57608. Button* DocumentWindow::getCloseButton() const throw()
  57609. {
  57610. return titleBarButtons[2];
  57611. }
  57612. Button* DocumentWindow::getMinimiseButton() const throw()
  57613. {
  57614. return titleBarButtons[0];
  57615. }
  57616. Button* DocumentWindow::getMaximiseButton() const throw()
  57617. {
  57618. return titleBarButtons[1];
  57619. }
  57620. int DocumentWindow::getDesktopWindowStyleFlags() const
  57621. {
  57622. int flags = ResizableWindow::getDesktopWindowStyleFlags();
  57623. if ((requiredButtons & minimiseButton) != 0)
  57624. flags |= ComponentPeer::windowHasMinimiseButton;
  57625. if ((requiredButtons & maximiseButton) != 0)
  57626. flags |= ComponentPeer::windowHasMaximiseButton;
  57627. if ((requiredButtons & closeButton) != 0)
  57628. flags |= ComponentPeer::windowHasCloseButton;
  57629. return flags;
  57630. }
  57631. void DocumentWindow::lookAndFeelChanged()
  57632. {
  57633. int i;
  57634. for (i = 0; i < 3; ++i)
  57635. deleteAndZero (titleBarButtons[i]);
  57636. if (! isUsingNativeTitleBar())
  57637. {
  57638. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  57639. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  57640. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  57641. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  57642. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  57643. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  57644. for (i = 0; i < 3; ++i)
  57645. {
  57646. if (titleBarButtons[i] != 0)
  57647. {
  57648. buttonListener.owner = this;
  57649. titleBarButtons[i]->addButtonListener (&buttonListener);
  57650. titleBarButtons[i]->setWantsKeyboardFocus (false);
  57651. // (call the Component method directly to avoid the assertion in ResizableWindow)
  57652. Component::addAndMakeVisible (titleBarButtons[i]);
  57653. }
  57654. }
  57655. if (getCloseButton() != 0)
  57656. {
  57657. #if JUCE_MAC
  57658. getCloseButton()->addShortcut (KeyPress (T('w'), ModifierKeys::commandModifier, 0));
  57659. #else
  57660. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  57661. #endif
  57662. }
  57663. }
  57664. activeWindowStatusChanged();
  57665. ResizableWindow::lookAndFeelChanged();
  57666. }
  57667. void DocumentWindow::parentHierarchyChanged()
  57668. {
  57669. lookAndFeelChanged();
  57670. }
  57671. void DocumentWindow::activeWindowStatusChanged()
  57672. {
  57673. ResizableWindow::activeWindowStatusChanged();
  57674. for (int i = 0; i < 3; ++i)
  57675. if (titleBarButtons[i] != 0)
  57676. titleBarButtons[i]->setEnabled (isActiveWindow());
  57677. if (menuBar != 0)
  57678. menuBar->setEnabled (isActiveWindow());
  57679. }
  57680. const BorderSize DocumentWindow::getBorderThickness()
  57681. {
  57682. return BorderSize (getBorderSize());
  57683. }
  57684. const BorderSize DocumentWindow::getContentComponentBorder()
  57685. {
  57686. const int size = getBorderSize();
  57687. return BorderSize (size
  57688. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  57689. + (menuBar != 0 ? menuBarHeight : 0),
  57690. size, size, size);
  57691. }
  57692. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  57693. {
  57694. const int border = getBorderSize();
  57695. if (e.x >= border
  57696. && e.y >= border
  57697. && e.x < getWidth() - border
  57698. && e.y < border + getTitleBarHeight()
  57699. && getMaximiseButton() != 0)
  57700. {
  57701. getMaximiseButton()->triggerClick();
  57702. }
  57703. }
  57704. void DocumentWindow::userTriedToCloseWindow()
  57705. {
  57706. closeButtonPressed();
  57707. }
  57708. int DocumentWindow::getTitleBarHeight() const
  57709. {
  57710. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  57711. }
  57712. int DocumentWindow::getBorderSize() const
  57713. {
  57714. return (isFullScreen() || isUsingNativeTitleBar()) ? 0 : (resizableBorder != 0 ? 4 : 1);
  57715. }
  57716. DocumentWindow::ButtonListenerProxy::ButtonListenerProxy()
  57717. {
  57718. }
  57719. void DocumentWindow::ButtonListenerProxy::buttonClicked (Button* button)
  57720. {
  57721. if (button == owner->getMinimiseButton())
  57722. {
  57723. owner->minimiseButtonPressed();
  57724. }
  57725. else if (button == owner->getMaximiseButton())
  57726. {
  57727. owner->maximiseButtonPressed();
  57728. }
  57729. else if (button == owner->getCloseButton())
  57730. {
  57731. owner->closeButtonPressed();
  57732. }
  57733. }
  57734. END_JUCE_NAMESPACE
  57735. /********* End of inlined file: juce_DocumentWindow.cpp *********/
  57736. /********* Start of inlined file: juce_ResizableWindow.cpp *********/
  57737. BEGIN_JUCE_NAMESPACE
  57738. ResizableWindow::ResizableWindow (const String& name,
  57739. const Colour& backgroundColour_,
  57740. const bool addToDesktop_)
  57741. : TopLevelWindow (name, addToDesktop_),
  57742. resizableCorner (0),
  57743. resizableBorder (0),
  57744. contentComponent (0),
  57745. resizeToFitContent (false),
  57746. fullscreen (false),
  57747. constrainer (0)
  57748. #ifdef JUCE_DEBUG
  57749. , hasBeenResized (false)
  57750. #endif
  57751. {
  57752. setBackgroundColour (backgroundColour_);
  57753. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  57754. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  57755. if (addToDesktop_)
  57756. Component::addToDesktop (getDesktopWindowStyleFlags());
  57757. }
  57758. ResizableWindow::~ResizableWindow()
  57759. {
  57760. deleteAndZero (resizableCorner);
  57761. deleteAndZero (resizableBorder);
  57762. deleteAndZero (contentComponent);
  57763. // have you been adding your own components directly to this window..? tut tut tut.
  57764. // Read the instructions for using a ResizableWindow!
  57765. jassert (getNumChildComponents() == 0);
  57766. }
  57767. int ResizableWindow::getDesktopWindowStyleFlags() const
  57768. {
  57769. int flags = TopLevelWindow::getDesktopWindowStyleFlags();
  57770. if (isResizable() && (flags & ComponentPeer::windowHasTitleBar) != 0)
  57771. flags |= ComponentPeer::windowIsResizable;
  57772. return flags;
  57773. }
  57774. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  57775. const bool deleteOldOne,
  57776. const bool resizeToFit)
  57777. {
  57778. resizeToFitContent = resizeToFit;
  57779. if (contentComponent != newContentComponent)
  57780. {
  57781. if (deleteOldOne)
  57782. delete contentComponent;
  57783. else
  57784. removeChildComponent (contentComponent);
  57785. contentComponent = newContentComponent;
  57786. Component::addAndMakeVisible (contentComponent);
  57787. }
  57788. if (resizeToFit)
  57789. childBoundsChanged (contentComponent);
  57790. resized(); // must always be called to position the new content comp
  57791. }
  57792. void ResizableWindow::setContentComponentSize (int width, int height)
  57793. {
  57794. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  57795. const BorderSize border (getContentComponentBorder());
  57796. setSize (width + border.getLeftAndRight(),
  57797. height + border.getTopAndBottom());
  57798. }
  57799. const BorderSize ResizableWindow::getBorderThickness()
  57800. {
  57801. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  57802. }
  57803. const BorderSize ResizableWindow::getContentComponentBorder()
  57804. {
  57805. return getBorderThickness();
  57806. }
  57807. void ResizableWindow::moved()
  57808. {
  57809. updateLastPos();
  57810. }
  57811. void ResizableWindow::visibilityChanged()
  57812. {
  57813. TopLevelWindow::visibilityChanged();
  57814. updateLastPos();
  57815. }
  57816. void ResizableWindow::resized()
  57817. {
  57818. if (resizableBorder != 0)
  57819. {
  57820. resizableBorder->setVisible (! isFullScreen());
  57821. resizableBorder->setBorderThickness (getBorderThickness());
  57822. resizableBorder->setSize (getWidth(), getHeight());
  57823. resizableBorder->toBack();
  57824. }
  57825. if (resizableCorner != 0)
  57826. {
  57827. resizableCorner->setVisible (! isFullScreen());
  57828. const int resizerSize = 18;
  57829. resizableCorner->setBounds (getWidth() - resizerSize,
  57830. getHeight() - resizerSize,
  57831. resizerSize, resizerSize);
  57832. }
  57833. if (contentComponent != 0)
  57834. contentComponent->setBoundsInset (getContentComponentBorder());
  57835. updateLastPos();
  57836. #ifdef JUCE_DEBUG
  57837. hasBeenResized = true;
  57838. #endif
  57839. }
  57840. void ResizableWindow::childBoundsChanged (Component* child)
  57841. {
  57842. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  57843. {
  57844. // not going to look very good if this component has a zero size..
  57845. jassert (child->getWidth() > 0);
  57846. jassert (child->getHeight() > 0);
  57847. const BorderSize borders (getContentComponentBorder());
  57848. setSize (child->getWidth() + borders.getLeftAndRight(),
  57849. child->getHeight() + borders.getTopAndBottom());
  57850. }
  57851. }
  57852. void ResizableWindow::activeWindowStatusChanged()
  57853. {
  57854. const BorderSize borders (getContentComponentBorder());
  57855. repaint (0, 0, getWidth(), borders.getTop());
  57856. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  57857. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  57858. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  57859. }
  57860. void ResizableWindow::setResizable (const bool shouldBeResizable,
  57861. const bool useBottomRightCornerResizer)
  57862. {
  57863. if (shouldBeResizable)
  57864. {
  57865. if (useBottomRightCornerResizer)
  57866. {
  57867. deleteAndZero (resizableBorder);
  57868. if (resizableCorner == 0)
  57869. {
  57870. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  57871. resizableCorner->setAlwaysOnTop (true);
  57872. }
  57873. }
  57874. else
  57875. {
  57876. deleteAndZero (resizableCorner);
  57877. if (resizableBorder == 0)
  57878. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  57879. }
  57880. }
  57881. else
  57882. {
  57883. deleteAndZero (resizableCorner);
  57884. deleteAndZero (resizableBorder);
  57885. }
  57886. if (isUsingNativeTitleBar())
  57887. recreateDesktopWindow();
  57888. childBoundsChanged (contentComponent);
  57889. resized();
  57890. }
  57891. bool ResizableWindow::isResizable() const throw()
  57892. {
  57893. return resizableCorner != 0
  57894. || resizableBorder != 0;
  57895. }
  57896. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  57897. const int newMinimumHeight,
  57898. const int newMaximumWidth,
  57899. const int newMaximumHeight) throw()
  57900. {
  57901. // if you've set up a custom constrainer then these settings won't have any effect..
  57902. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  57903. if (constrainer == 0)
  57904. setConstrainer (&defaultConstrainer);
  57905. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  57906. newMaximumWidth, newMaximumHeight);
  57907. setBoundsConstrained (getX(), getY(), getWidth(), getHeight());
  57908. }
  57909. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  57910. {
  57911. if (constrainer != newConstrainer)
  57912. {
  57913. constrainer = newConstrainer;
  57914. const bool useBottomRightCornerResizer = resizableCorner != 0;
  57915. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  57916. deleteAndZero (resizableCorner);
  57917. deleteAndZero (resizableBorder);
  57918. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  57919. ComponentPeer* const peer = getPeer();
  57920. if (peer != 0)
  57921. peer->setConstrainer (newConstrainer);
  57922. }
  57923. }
  57924. void ResizableWindow::setBoundsConstrained (int x, int y, int w, int h)
  57925. {
  57926. if (constrainer != 0)
  57927. constrainer->setBoundsForComponent (this, x, y, w, h, false, false, false, false);
  57928. else
  57929. setBounds (x, y, w, h);
  57930. }
  57931. void ResizableWindow::paint (Graphics& g)
  57932. {
  57933. g.fillAll (backgroundColour);
  57934. if (! isFullScreen())
  57935. {
  57936. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  57937. getBorderThickness(), *this);
  57938. }
  57939. #ifdef JUCE_DEBUG
  57940. /* If this fails, then you've probably written a subclass with a resized()
  57941. callback but forgotten to make it call its parent class's resized() method.
  57942. It's important when you override methods like resized(), moved(),
  57943. etc., that you make sure the base class methods also get called.
  57944. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  57945. because your content should all be inside the content component - and it's the
  57946. content component's resized() method that you should be using to do your
  57947. layout.
  57948. */
  57949. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  57950. #endif
  57951. }
  57952. void ResizableWindow::lookAndFeelChanged()
  57953. {
  57954. resized();
  57955. if (isOnDesktop())
  57956. {
  57957. Component::addToDesktop (getDesktopWindowStyleFlags());
  57958. ComponentPeer* const peer = getPeer();
  57959. if (peer != 0)
  57960. peer->setConstrainer (constrainer);
  57961. }
  57962. }
  57963. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  57964. {
  57965. if (Desktop::canUseSemiTransparentWindows())
  57966. backgroundColour = newColour;
  57967. else
  57968. backgroundColour = newColour.withAlpha (1.0f);
  57969. setOpaque (backgroundColour.isOpaque());
  57970. repaint();
  57971. }
  57972. bool ResizableWindow::isFullScreen() const
  57973. {
  57974. if (isOnDesktop())
  57975. {
  57976. ComponentPeer* const peer = getPeer();
  57977. return peer != 0 && peer->isFullScreen();
  57978. }
  57979. return fullscreen;
  57980. }
  57981. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  57982. {
  57983. if (shouldBeFullScreen != isFullScreen())
  57984. {
  57985. updateLastPos();
  57986. fullscreen = shouldBeFullScreen;
  57987. if (isOnDesktop())
  57988. {
  57989. ComponentPeer* const peer = getPeer();
  57990. if (peer != 0)
  57991. {
  57992. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  57993. const Rectangle lastPos (lastNonFullScreenPos);
  57994. peer->setFullScreen (shouldBeFullScreen);
  57995. if (! shouldBeFullScreen)
  57996. setBounds (lastPos);
  57997. }
  57998. else
  57999. {
  58000. jassertfalse
  58001. }
  58002. }
  58003. else
  58004. {
  58005. if (shouldBeFullScreen)
  58006. setBounds (0, 0, getParentWidth(), getParentHeight());
  58007. else
  58008. setBounds (lastNonFullScreenPos);
  58009. }
  58010. resized();
  58011. }
  58012. }
  58013. bool ResizableWindow::isMinimised() const
  58014. {
  58015. ComponentPeer* const peer = getPeer();
  58016. return (peer != 0) && peer->isMinimised();
  58017. }
  58018. void ResizableWindow::setMinimised (const bool shouldMinimise)
  58019. {
  58020. if (shouldMinimise != isMinimised())
  58021. {
  58022. ComponentPeer* const peer = getPeer();
  58023. if (peer != 0)
  58024. {
  58025. updateLastPos();
  58026. peer->setMinimised (shouldMinimise);
  58027. }
  58028. else
  58029. {
  58030. jassertfalse
  58031. }
  58032. }
  58033. }
  58034. void ResizableWindow::updateLastPos()
  58035. {
  58036. if (isShowing() && ! (isFullScreen() || isMinimised()))
  58037. {
  58038. lastNonFullScreenPos = getBounds();
  58039. }
  58040. }
  58041. void ResizableWindow::parentSizeChanged()
  58042. {
  58043. if (isFullScreen() && getParentComponent() != 0)
  58044. {
  58045. setBounds (0, 0, getParentWidth(), getParentHeight());
  58046. }
  58047. }
  58048. const String ResizableWindow::getWindowStateAsString()
  58049. {
  58050. updateLastPos();
  58051. String s;
  58052. if (isFullScreen())
  58053. s << "fs ";
  58054. s << lastNonFullScreenPos.getX() << T(' ')
  58055. << lastNonFullScreenPos.getY() << T(' ')
  58056. << lastNonFullScreenPos.getWidth() << T(' ')
  58057. << lastNonFullScreenPos.getHeight();
  58058. return s;
  58059. }
  58060. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  58061. {
  58062. StringArray tokens;
  58063. tokens.addTokens (s, false);
  58064. tokens.removeEmptyStrings();
  58065. tokens.trim();
  58066. const bool fs = tokens[0].startsWithIgnoreCase (T("fs"));
  58067. const int n = fs ? 1 : 0;
  58068. if (tokens.size() != 4 + n)
  58069. return false;
  58070. Rectangle r (tokens[n].getIntValue(),
  58071. tokens[n + 1].getIntValue(),
  58072. tokens[n + 2].getIntValue(),
  58073. tokens[n + 3].getIntValue());
  58074. if (r.isEmpty())
  58075. return false;
  58076. const Rectangle screen (Desktop::getInstance().getMonitorAreaContaining (r.getX(), r.getY()));
  58077. r = r.getIntersection (screen);
  58078. lastNonFullScreenPos = r;
  58079. if (isOnDesktop())
  58080. {
  58081. ComponentPeer* const peer = getPeer();
  58082. if (peer != 0)
  58083. peer->setNonFullScreenBounds (r);
  58084. }
  58085. setFullScreen (fs);
  58086. if (! fs)
  58087. setBoundsConstrained (r.getX(),
  58088. r.getY(),
  58089. r.getWidth(),
  58090. r.getHeight());
  58091. return true;
  58092. }
  58093. void ResizableWindow::mouseDown (const MouseEvent&)
  58094. {
  58095. if (! isFullScreen())
  58096. dragger.startDraggingComponent (this, constrainer);
  58097. }
  58098. void ResizableWindow::mouseDrag (const MouseEvent& e)
  58099. {
  58100. if (! isFullScreen())
  58101. dragger.dragComponent (this, e);
  58102. }
  58103. #ifdef JUCE_DEBUG
  58104. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  58105. {
  58106. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  58107. manages its child components automatically, and if you add your own it'll cause
  58108. trouble. Instead, use setContentComponent() to give it a component which
  58109. will be automatically resized and kept in the right place - then you can add
  58110. subcomponents to the content comp. See the notes for the ResizableWindow class
  58111. for more info.
  58112. If you really know what you're doing and want to avoid this assertion, just call
  58113. Component::addChildComponent directly.
  58114. */
  58115. jassertfalse
  58116. Component::addChildComponent (child, zOrder);
  58117. }
  58118. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  58119. {
  58120. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  58121. manages its child components automatically, and if you add your own it'll cause
  58122. trouble. Instead, use setContentComponent() to give it a component which
  58123. will be automatically resized and kept in the right place - then you can add
  58124. subcomponents to the content comp. See the notes for the ResizableWindow class
  58125. for more info.
  58126. If you really know what you're doing and want to avoid this assertion, just call
  58127. Component::addAndMakeVisible directly.
  58128. */
  58129. jassertfalse
  58130. Component::addAndMakeVisible (child, zOrder);
  58131. }
  58132. #endif
  58133. END_JUCE_NAMESPACE
  58134. /********* End of inlined file: juce_ResizableWindow.cpp *********/
  58135. /********* Start of inlined file: juce_SplashScreen.cpp *********/
  58136. BEGIN_JUCE_NAMESPACE
  58137. SplashScreen::SplashScreen()
  58138. : backgroundImage (0),
  58139. isImageInCache (false)
  58140. {
  58141. setOpaque (true);
  58142. }
  58143. SplashScreen::~SplashScreen()
  58144. {
  58145. if (isImageInCache)
  58146. ImageCache::release (backgroundImage);
  58147. else
  58148. delete backgroundImage;
  58149. }
  58150. void SplashScreen::show (const String& title,
  58151. Image* const backgroundImage_,
  58152. const int minimumTimeToDisplayFor,
  58153. const bool useDropShadow,
  58154. const bool removeOnMouseClick)
  58155. {
  58156. backgroundImage = backgroundImage_;
  58157. jassert (backgroundImage_ != 0);
  58158. if (backgroundImage_ != 0)
  58159. {
  58160. isImageInCache = ImageCache::isImageInCache (backgroundImage_);
  58161. setOpaque (! backgroundImage_->hasAlphaChannel());
  58162. show (title,
  58163. backgroundImage_->getWidth(),
  58164. backgroundImage_->getHeight(),
  58165. minimumTimeToDisplayFor,
  58166. useDropShadow,
  58167. removeOnMouseClick);
  58168. }
  58169. }
  58170. void SplashScreen::show (const String& title,
  58171. const int width,
  58172. const int height,
  58173. const int minimumTimeToDisplayFor,
  58174. const bool useDropShadow,
  58175. const bool removeOnMouseClick)
  58176. {
  58177. setName (title);
  58178. setAlwaysOnTop (true);
  58179. setVisible (true);
  58180. centreWithSize (width, height);
  58181. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  58182. toFront (false);
  58183. MessageManager::getInstance()->dispatchPendingMessages();
  58184. repaint();
  58185. originalClickCounter = removeOnMouseClick
  58186. ? Desktop::getMouseButtonClickCounter()
  58187. : INT_MAX;
  58188. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  58189. startTimer (50);
  58190. }
  58191. void SplashScreen::paint (Graphics& g)
  58192. {
  58193. if (backgroundImage != 0)
  58194. {
  58195. g.setOpacity (1.0f);
  58196. g.drawImage (backgroundImage,
  58197. 0, 0, getWidth(), getHeight(),
  58198. 0, 0, backgroundImage->getWidth(), backgroundImage->getHeight());
  58199. }
  58200. }
  58201. void SplashScreen::timerCallback()
  58202. {
  58203. if (Time::getCurrentTime() > earliestTimeToDelete
  58204. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  58205. {
  58206. delete this;
  58207. }
  58208. }
  58209. END_JUCE_NAMESPACE
  58210. /********* End of inlined file: juce_SplashScreen.cpp *********/
  58211. /********* Start of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  58212. BEGIN_JUCE_NAMESPACE
  58213. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  58214. const bool hasProgressBar,
  58215. const bool hasCancelButton,
  58216. const int timeOutMsWhenCancelling_,
  58217. const String& cancelButtonText)
  58218. : Thread ("Juce Progress Window"),
  58219. progress (0.0),
  58220. alertWindow (title, String::empty, AlertWindow::NoIcon),
  58221. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  58222. {
  58223. if (hasProgressBar)
  58224. alertWindow.addProgressBarComponent (progress);
  58225. if (hasCancelButton)
  58226. alertWindow.addButton (cancelButtonText, 1);
  58227. }
  58228. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  58229. {
  58230. stopThread (timeOutMsWhenCancelling);
  58231. }
  58232. bool ThreadWithProgressWindow::runThread (const int priority)
  58233. {
  58234. startThread (priority);
  58235. startTimer (100);
  58236. {
  58237. const ScopedLock sl (messageLock);
  58238. alertWindow.setMessage (message);
  58239. }
  58240. const bool wasCancelled = alertWindow.runModalLoop() != 0;
  58241. stopThread (timeOutMsWhenCancelling);
  58242. alertWindow.setVisible (false);
  58243. return ! wasCancelled;
  58244. }
  58245. void ThreadWithProgressWindow::setProgress (const double newProgress)
  58246. {
  58247. progress = newProgress;
  58248. }
  58249. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  58250. {
  58251. const ScopedLock sl (messageLock);
  58252. message = newStatusMessage;
  58253. }
  58254. void ThreadWithProgressWindow::timerCallback()
  58255. {
  58256. if (! isThreadRunning())
  58257. {
  58258. // thread has finished normally..
  58259. alertWindow.exitModalState (0);
  58260. alertWindow.setVisible (false);
  58261. }
  58262. else
  58263. {
  58264. const ScopedLock sl (messageLock);
  58265. alertWindow.setMessage (message);
  58266. }
  58267. }
  58268. END_JUCE_NAMESPACE
  58269. /********* End of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  58270. /********* Start of inlined file: juce_TooltipWindow.cpp *********/
  58271. BEGIN_JUCE_NAMESPACE
  58272. TooltipWindow::TooltipWindow (Component* const parentComponent,
  58273. const int millisecondsBeforeTipAppears_)
  58274. : Component ("tooltip"),
  58275. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  58276. mouseX (0),
  58277. mouseY (0),
  58278. lastMouseMoveTime (0),
  58279. lastHideTime (0),
  58280. lastComponentUnderMouse (0),
  58281. changedCompsSinceShown (true)
  58282. {
  58283. startTimer (123);
  58284. setAlwaysOnTop (true);
  58285. setOpaque (true);
  58286. if (parentComponent != 0)
  58287. {
  58288. parentComponent->addChildComponent (this);
  58289. }
  58290. else
  58291. {
  58292. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  58293. addToDesktop (ComponentPeer::windowHasDropShadow
  58294. | ComponentPeer::windowIsTemporary);
  58295. }
  58296. }
  58297. TooltipWindow::~TooltipWindow()
  58298. {
  58299. }
  58300. void TooltipWindow::paint (Graphics& g)
  58301. {
  58302. getLookAndFeel().drawTooltip (g, tip, getWidth(), getHeight());
  58303. }
  58304. void TooltipWindow::mouseEnter (const MouseEvent&)
  58305. {
  58306. setVisible (false);
  58307. }
  58308. void TooltipWindow::showFor (Component* const c)
  58309. {
  58310. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  58311. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  58312. tip = ttc->getTooltip();
  58313. else
  58314. tip = String::empty;
  58315. if (tip.isEmpty())
  58316. {
  58317. setVisible (false);
  58318. }
  58319. else
  58320. {
  58321. int mx, my;
  58322. Desktop::getMousePosition (mx, my);
  58323. if (getParentComponent() != 0)
  58324. getParentComponent()->globalPositionToRelative (mx, my);
  58325. int x, y, w, h;
  58326. getLookAndFeel().getTooltipSize (tip, w, h);
  58327. if (mx > getParentWidth() / 2)
  58328. x = mx - (w + 12);
  58329. else
  58330. x = mx + 24;
  58331. if (my > getParentHeight() / 2)
  58332. y = my - (h + 6);
  58333. else
  58334. y = my + 6;
  58335. setBounds (x, y, w, h);
  58336. setVisible (true);
  58337. toFront (false);
  58338. }
  58339. }
  58340. void TooltipWindow::timerCallback()
  58341. {
  58342. int mx, my;
  58343. Desktop::getMousePosition (mx, my);
  58344. const unsigned int now = Time::getApproximateMillisecondCounter();
  58345. Component* const underMouse = Component::getComponentUnderMouse();
  58346. const bool changedComp = (underMouse != lastComponentUnderMouse);
  58347. lastComponentUnderMouse = underMouse;
  58348. if (changedComp
  58349. || abs (mx - mouseX) > 4
  58350. || abs (my - mouseY) > 4
  58351. || Desktop::getInstance().getMouseButtonClickCounter() > mouseClicks)
  58352. {
  58353. lastMouseMoveTime = now;
  58354. if (isVisible())
  58355. {
  58356. lastHideTime = now;
  58357. setVisible (false);
  58358. }
  58359. changedCompsSinceShown = changedCompsSinceShown || changedComp;
  58360. tip = String::empty;
  58361. mouseX = mx;
  58362. mouseY = my;
  58363. }
  58364. if (changedCompsSinceShown)
  58365. {
  58366. if ((now > lastMouseMoveTime + millisecondsBeforeTipAppears
  58367. || now < lastHideTime + 500)
  58368. && ! isVisible())
  58369. {
  58370. if (underMouse->isValidComponent())
  58371. showFor (underMouse);
  58372. changedCompsSinceShown = false;
  58373. }
  58374. }
  58375. mouseClicks = Desktop::getInstance().getMouseButtonClickCounter();
  58376. }
  58377. END_JUCE_NAMESPACE
  58378. /********* End of inlined file: juce_TooltipWindow.cpp *********/
  58379. /********* Start of inlined file: juce_TopLevelWindow.cpp *********/
  58380. BEGIN_JUCE_NAMESPACE
  58381. /** Keeps track of the active top level window.
  58382. */
  58383. class TopLevelWindowManager : public Timer,
  58384. public DeletedAtShutdown
  58385. {
  58386. public:
  58387. TopLevelWindowManager()
  58388. : windows (8),
  58389. currentActive (0)
  58390. {
  58391. }
  58392. ~TopLevelWindowManager()
  58393. {
  58394. clearSingletonInstance();
  58395. }
  58396. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  58397. void timerCallback()
  58398. {
  58399. startTimer (1731);
  58400. TopLevelWindow* active = 0;
  58401. if (Process::isForegroundProcess())
  58402. {
  58403. active = currentActive;
  58404. Component* const c = Component::getCurrentlyFocusedComponent();
  58405. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  58406. if (tlw == 0 && c != 0)
  58407. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  58408. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  58409. if (tlw != 0)
  58410. active = tlw;
  58411. }
  58412. if (active != currentActive)
  58413. {
  58414. currentActive = active;
  58415. for (int i = windows.size(); --i >= 0;)
  58416. {
  58417. TopLevelWindow* const tlw = (TopLevelWindow*) windows.getUnchecked (i);
  58418. tlw->setWindowActive (isWindowActive (tlw));
  58419. i = jmin (i, windows.size() - 1);
  58420. }
  58421. Desktop::getInstance().triggerFocusCallback();
  58422. }
  58423. }
  58424. bool addWindow (TopLevelWindow* const w) throw()
  58425. {
  58426. windows.add (w);
  58427. startTimer (10);
  58428. return isWindowActive (w);
  58429. }
  58430. void removeWindow (TopLevelWindow* const w) throw()
  58431. {
  58432. startTimer (10);
  58433. if (currentActive == w)
  58434. currentActive = 0;
  58435. windows.removeValue (w);
  58436. if (windows.size() == 0)
  58437. deleteInstance();
  58438. }
  58439. VoidArray windows;
  58440. private:
  58441. TopLevelWindow* currentActive;
  58442. bool isWindowActive (TopLevelWindow* const tlw) const throw()
  58443. {
  58444. return (tlw == currentActive
  58445. || tlw->isParentOf (currentActive)
  58446. || tlw->hasKeyboardFocus (true))
  58447. && tlw->isShowing();
  58448. }
  58449. TopLevelWindowManager (const TopLevelWindowManager&);
  58450. const TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  58451. };
  58452. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  58453. void juce_CheckCurrentlyFocusedTopLevelWindow() throw()
  58454. {
  58455. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  58456. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  58457. }
  58458. TopLevelWindow::TopLevelWindow (const String& name,
  58459. const bool addToDesktop_)
  58460. : Component (name),
  58461. useDropShadow (true),
  58462. useNativeTitleBar (false),
  58463. windowIsActive_ (false),
  58464. shadower (0)
  58465. {
  58466. setOpaque (true);
  58467. if (addToDesktop_)
  58468. Component::addToDesktop (getDesktopWindowStyleFlags());
  58469. else
  58470. setDropShadowEnabled (true);
  58471. setWantsKeyboardFocus (true);
  58472. setBroughtToFrontOnMouseClick (true);
  58473. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  58474. }
  58475. TopLevelWindow::~TopLevelWindow()
  58476. {
  58477. deleteAndZero (shadower);
  58478. TopLevelWindowManager::getInstance()->removeWindow (this);
  58479. }
  58480. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  58481. {
  58482. if (hasKeyboardFocus (true))
  58483. TopLevelWindowManager::getInstance()->timerCallback();
  58484. else
  58485. TopLevelWindowManager::getInstance()->startTimer (10);
  58486. }
  58487. void TopLevelWindow::setWindowActive (const bool isNowActive) throw()
  58488. {
  58489. if (windowIsActive_ != isNowActive)
  58490. {
  58491. windowIsActive_ = isNowActive;
  58492. activeWindowStatusChanged();
  58493. }
  58494. }
  58495. void TopLevelWindow::activeWindowStatusChanged()
  58496. {
  58497. }
  58498. void TopLevelWindow::parentHierarchyChanged()
  58499. {
  58500. setDropShadowEnabled (useDropShadow);
  58501. }
  58502. void TopLevelWindow::visibilityChanged()
  58503. {
  58504. if (isShowing())
  58505. toFront (true);
  58506. }
  58507. int TopLevelWindow::getDesktopWindowStyleFlags() const
  58508. {
  58509. int flags = ComponentPeer::windowAppearsOnTaskbar;
  58510. if (useDropShadow)
  58511. flags |= ComponentPeer::windowHasDropShadow;
  58512. if (useNativeTitleBar)
  58513. flags |= ComponentPeer::windowHasTitleBar;
  58514. return flags;
  58515. }
  58516. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  58517. {
  58518. useDropShadow = useShadow;
  58519. if (isOnDesktop())
  58520. {
  58521. deleteAndZero (shadower);
  58522. Component::addToDesktop (getDesktopWindowStyleFlags());
  58523. }
  58524. else
  58525. {
  58526. if (useShadow && isOpaque())
  58527. {
  58528. if (shadower == 0)
  58529. {
  58530. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  58531. if (shadower != 0)
  58532. shadower->setOwner (this);
  58533. }
  58534. }
  58535. else
  58536. {
  58537. deleteAndZero (shadower);
  58538. }
  58539. }
  58540. }
  58541. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  58542. {
  58543. if (useNativeTitleBar != useNativeTitleBar_)
  58544. {
  58545. useNativeTitleBar = useNativeTitleBar_;
  58546. recreateDesktopWindow();
  58547. sendLookAndFeelChange();
  58548. }
  58549. }
  58550. void TopLevelWindow::recreateDesktopWindow()
  58551. {
  58552. if (isOnDesktop())
  58553. {
  58554. Component::addToDesktop (getDesktopWindowStyleFlags());
  58555. toFront (true);
  58556. }
  58557. }
  58558. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  58559. {
  58560. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  58561. because this class needs to make sure its layout corresponds with settings like whether
  58562. it's got a native title bar or not.
  58563. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  58564. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  58565. method, then add or remove whatever flags are necessary from this value before returning it.
  58566. */
  58567. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  58568. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  58569. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  58570. if (windowStyleFlags != getDesktopWindowStyleFlags())
  58571. sendLookAndFeelChange();
  58572. }
  58573. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  58574. {
  58575. if (c == 0)
  58576. c = TopLevelWindow::getActiveTopLevelWindow();
  58577. if (c == 0)
  58578. {
  58579. centreWithSize (width, height);
  58580. }
  58581. else
  58582. {
  58583. int x = (c->getWidth() - width) / 2;
  58584. int y = (c->getHeight() - height) / 2;
  58585. c->relativePositionToGlobal (x, y);
  58586. Rectangle parentArea (c->getParentMonitorArea());
  58587. if (getParentComponent() != 0)
  58588. {
  58589. getParentComponent()->globalPositionToRelative (x, y);
  58590. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  58591. }
  58592. parentArea.reduce (12, 12);
  58593. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), x),
  58594. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), y),
  58595. width, height);
  58596. }
  58597. }
  58598. int TopLevelWindow::getNumTopLevelWindows() throw()
  58599. {
  58600. return TopLevelWindowManager::getInstance()->windows.size();
  58601. }
  58602. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  58603. {
  58604. return (TopLevelWindow*) TopLevelWindowManager::getInstance()->windows [index];
  58605. }
  58606. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  58607. {
  58608. TopLevelWindow* best = 0;
  58609. int bestNumTWLParents = -1;
  58610. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  58611. {
  58612. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  58613. if (tlw->isActiveWindow())
  58614. {
  58615. int numTWLParents = 0;
  58616. const Component* c = tlw->getParentComponent();
  58617. while (c != 0)
  58618. {
  58619. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  58620. ++numTWLParents;
  58621. c = c->getParentComponent();
  58622. }
  58623. if (bestNumTWLParents < numTWLParents)
  58624. {
  58625. best = tlw;
  58626. bestNumTWLParents = numTWLParents;
  58627. }
  58628. }
  58629. }
  58630. return best;
  58631. }
  58632. END_JUCE_NAMESPACE
  58633. /********* End of inlined file: juce_TopLevelWindow.cpp *********/
  58634. /********* Start of inlined file: juce_Brush.cpp *********/
  58635. BEGIN_JUCE_NAMESPACE
  58636. Brush::Brush() throw()
  58637. {
  58638. }
  58639. Brush::~Brush() throw()
  58640. {
  58641. }
  58642. void Brush::paintVerticalLine (LowLevelGraphicsContext& context,
  58643. int x, float y1, float y2) throw()
  58644. {
  58645. Path p;
  58646. p.addRectangle ((float) x, y1, 1.0f, y2 - y1);
  58647. paintPath (context, p, AffineTransform::identity);
  58648. }
  58649. void Brush::paintHorizontalLine (LowLevelGraphicsContext& context,
  58650. int y, float x1, float x2) throw()
  58651. {
  58652. Path p;
  58653. p.addRectangle (x1, (float) y, x2 - x1, 1.0f);
  58654. paintPath (context, p, AffineTransform::identity);
  58655. }
  58656. void Brush::paintLine (LowLevelGraphicsContext& context,
  58657. float x1, float y1, float x2, float y2) throw()
  58658. {
  58659. Path p;
  58660. p.addLineSegment (x1, y1, x2, y2, 1.0f);
  58661. paintPath (context, p, AffineTransform::identity);
  58662. }
  58663. END_JUCE_NAMESPACE
  58664. /********* End of inlined file: juce_Brush.cpp *********/
  58665. /********* Start of inlined file: juce_GradientBrush.cpp *********/
  58666. BEGIN_JUCE_NAMESPACE
  58667. GradientBrush::GradientBrush (const Colour& colour1,
  58668. const float x1,
  58669. const float y1,
  58670. const Colour& colour2,
  58671. const float x2,
  58672. const float y2,
  58673. const bool isRadial) throw()
  58674. : gradient (colour1, x1, y1,
  58675. colour2, x2, y2,
  58676. isRadial)
  58677. {
  58678. }
  58679. GradientBrush::GradientBrush (const ColourGradient& gradient_) throw()
  58680. : gradient (gradient_)
  58681. {
  58682. }
  58683. GradientBrush::~GradientBrush() throw()
  58684. {
  58685. }
  58686. Brush* GradientBrush::createCopy() const throw()
  58687. {
  58688. return new GradientBrush (gradient);
  58689. }
  58690. void GradientBrush::applyTransform (const AffineTransform& transform) throw()
  58691. {
  58692. gradient.transform = gradient.transform.followedBy (transform);
  58693. }
  58694. void GradientBrush::multiplyOpacity (const float multiple) throw()
  58695. {
  58696. gradient.multiplyOpacity (multiple);
  58697. }
  58698. bool GradientBrush::isInvisible() const throw()
  58699. {
  58700. return gradient.isInvisible();
  58701. }
  58702. void GradientBrush::paintPath (LowLevelGraphicsContext& context,
  58703. const Path& path, const AffineTransform& transform) throw()
  58704. {
  58705. context.fillPathWithGradient (path, transform, gradient, EdgeTable::Oversampling_4times);
  58706. }
  58707. void GradientBrush::paintRectangle (LowLevelGraphicsContext& context,
  58708. int x, int y, int w, int h) throw()
  58709. {
  58710. context.fillRectWithGradient (x, y, w, h, gradient);
  58711. }
  58712. void GradientBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  58713. const Image& alphaChannelImage, int imageX, int imageY,
  58714. int x, int y, int w, int h) throw()
  58715. {
  58716. context.saveState();
  58717. if (context.reduceClipRegion (x, y, w, h))
  58718. context.fillAlphaChannelWithGradient (alphaChannelImage, imageX, imageY, gradient);
  58719. context.restoreState();
  58720. }
  58721. END_JUCE_NAMESPACE
  58722. /********* End of inlined file: juce_GradientBrush.cpp *********/
  58723. /********* Start of inlined file: juce_ImageBrush.cpp *********/
  58724. BEGIN_JUCE_NAMESPACE
  58725. ImageBrush::ImageBrush (Image* const image_,
  58726. const int anchorX_,
  58727. const int anchorY_,
  58728. const float opacity_) throw()
  58729. : image (image_),
  58730. anchorX (anchorX_),
  58731. anchorY (anchorY_),
  58732. opacity (opacity_)
  58733. {
  58734. jassert (image != 0); // not much point creating a brush without an image, is there?
  58735. if (image != 0)
  58736. {
  58737. if (image->getWidth() == 0 || image->getHeight() == 0)
  58738. {
  58739. jassertfalse // you've passed in an empty image - not exactly brilliant for tiling.
  58740. image = 0;
  58741. }
  58742. }
  58743. }
  58744. ImageBrush::~ImageBrush() throw()
  58745. {
  58746. }
  58747. Brush* ImageBrush::createCopy() const throw()
  58748. {
  58749. return new ImageBrush (image, anchorX, anchorY, opacity);
  58750. }
  58751. void ImageBrush::multiplyOpacity (const float multiple) throw()
  58752. {
  58753. opacity *= multiple;
  58754. }
  58755. bool ImageBrush::isInvisible() const throw()
  58756. {
  58757. return opacity == 0.0f;
  58758. }
  58759. void ImageBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  58760. {
  58761. //xxx should probably be smarter and warp the image
  58762. }
  58763. void ImageBrush::getStartXY (int& x, int& y) const throw()
  58764. {
  58765. x -= anchorX;
  58766. y -= anchorY;
  58767. const int iw = image->getWidth();
  58768. const int ih = image->getHeight();
  58769. if (x < 0)
  58770. x = ((x / iw) - 1) * iw;
  58771. else
  58772. x = (x / iw) * iw;
  58773. if (y < 0)
  58774. y = ((y / ih) - 1) * ih;
  58775. else
  58776. y = (y / ih) * ih;
  58777. x += anchorX;
  58778. y += anchorY;
  58779. }
  58780. void ImageBrush::paintRectangle (LowLevelGraphicsContext& context,
  58781. int x, int y, int w, int h) throw()
  58782. {
  58783. context.saveState();
  58784. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  58785. {
  58786. const int right = x + w;
  58787. const int bottom = y + h;
  58788. const int iw = image->getWidth();
  58789. const int ih = image->getHeight();
  58790. int startX = x;
  58791. getStartXY (startX, y);
  58792. while (y < bottom)
  58793. {
  58794. x = startX;
  58795. while (x < right)
  58796. {
  58797. context.blendImage (*image, x, y, iw, ih, 0, 0, opacity);
  58798. x += iw;
  58799. }
  58800. y += ih;
  58801. }
  58802. }
  58803. context.restoreState();
  58804. }
  58805. void ImageBrush::paintPath (LowLevelGraphicsContext& context,
  58806. const Path& path, const AffineTransform& transform) throw()
  58807. {
  58808. if (image != 0)
  58809. {
  58810. Rectangle clip (context.getClipBounds());
  58811. {
  58812. float x, y, w, h;
  58813. path.getBoundsTransformed (transform, x, y, w, h);
  58814. clip = clip.getIntersection (Rectangle ((int) floorf (x),
  58815. (int) floorf (y),
  58816. 2 + (int) floorf (w),
  58817. 2 + (int) floorf (h)));
  58818. }
  58819. int x = clip.getX();
  58820. int y = clip.getY();
  58821. const int right = clip.getRight();
  58822. const int bottom = clip.getBottom();
  58823. const int iw = image->getWidth();
  58824. const int ih = image->getHeight();
  58825. int startX = x;
  58826. getStartXY (startX, y);
  58827. while (y < bottom)
  58828. {
  58829. x = startX;
  58830. while (x < right)
  58831. {
  58832. context.fillPathWithImage (path, transform, *image, x, y, opacity, EdgeTable::Oversampling_4times);
  58833. x += iw;
  58834. }
  58835. y += ih;
  58836. }
  58837. }
  58838. }
  58839. void ImageBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  58840. const Image& alphaChannelImage, int imageX, int imageY,
  58841. int x, int y, int w, int h) throw()
  58842. {
  58843. context.saveState();
  58844. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  58845. {
  58846. const Rectangle clip (context.getClipBounds());
  58847. x = clip.getX();
  58848. y = clip.getY();
  58849. const int right = clip.getRight();
  58850. const int bottom = clip.getBottom();
  58851. const int iw = image->getWidth();
  58852. const int ih = image->getHeight();
  58853. int startX = x;
  58854. getStartXY (startX, y);
  58855. while (y < bottom)
  58856. {
  58857. x = startX;
  58858. while (x < right)
  58859. {
  58860. context.fillAlphaChannelWithImage (alphaChannelImage,
  58861. imageX, imageY, *image,
  58862. x, y, opacity);
  58863. x += iw;
  58864. }
  58865. y += ih;
  58866. }
  58867. }
  58868. context.restoreState();
  58869. }
  58870. END_JUCE_NAMESPACE
  58871. /********* End of inlined file: juce_ImageBrush.cpp *********/
  58872. /********* Start of inlined file: juce_SolidColourBrush.cpp *********/
  58873. BEGIN_JUCE_NAMESPACE
  58874. SolidColourBrush::SolidColourBrush() throw()
  58875. : colour (0xff000000)
  58876. {
  58877. }
  58878. SolidColourBrush::SolidColourBrush (const Colour& colour_) throw()
  58879. : colour (colour_)
  58880. {
  58881. }
  58882. SolidColourBrush::~SolidColourBrush() throw()
  58883. {
  58884. }
  58885. Brush* SolidColourBrush::createCopy() const throw()
  58886. {
  58887. return new SolidColourBrush (colour);
  58888. }
  58889. void SolidColourBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  58890. {
  58891. }
  58892. void SolidColourBrush::multiplyOpacity (const float multiple) throw()
  58893. {
  58894. colour = colour.withMultipliedAlpha (multiple);
  58895. }
  58896. bool SolidColourBrush::isInvisible() const throw()
  58897. {
  58898. return colour.isTransparent();
  58899. }
  58900. void SolidColourBrush::paintPath (LowLevelGraphicsContext& context,
  58901. const Path& path, const AffineTransform& transform) throw()
  58902. {
  58903. if (! colour.isTransparent())
  58904. context.fillPathWithColour (path, transform, colour, EdgeTable::Oversampling_4times);
  58905. }
  58906. void SolidColourBrush::paintRectangle (LowLevelGraphicsContext& context,
  58907. int x, int y, int w, int h) throw()
  58908. {
  58909. if (! colour.isTransparent())
  58910. context.fillRectWithColour (x, y, w, h, colour, false);
  58911. }
  58912. void SolidColourBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  58913. const Image& alphaChannelImage, int imageX, int imageY,
  58914. int x, int y, int w, int h) throw()
  58915. {
  58916. if (! colour.isTransparent())
  58917. {
  58918. context.saveState();
  58919. if (context.reduceClipRegion (x, y, w, h))
  58920. context.fillAlphaChannelWithColour (alphaChannelImage, imageX, imageY, colour);
  58921. context.restoreState();
  58922. }
  58923. }
  58924. void SolidColourBrush::paintVerticalLine (LowLevelGraphicsContext& context,
  58925. int x, float y1, float y2) throw()
  58926. {
  58927. context.drawVerticalLine (x, y1, y2, colour);
  58928. }
  58929. void SolidColourBrush::paintHorizontalLine (LowLevelGraphicsContext& context,
  58930. int y, float x1, float x2) throw()
  58931. {
  58932. context.drawHorizontalLine (y, x1, x2, colour);
  58933. }
  58934. void SolidColourBrush::paintLine (LowLevelGraphicsContext& context,
  58935. float x1, float y1, float x2, float y2) throw()
  58936. {
  58937. context.drawLine (x1, y1, x2, y2, colour);
  58938. }
  58939. END_JUCE_NAMESPACE
  58940. /********* End of inlined file: juce_SolidColourBrush.cpp *********/
  58941. /********* Start of inlined file: juce_Colour.cpp *********/
  58942. BEGIN_JUCE_NAMESPACE
  58943. static forcedinline uint8 floatAlphaToInt (const float alpha)
  58944. {
  58945. return (uint8) jlimit (0, 0xff, roundFloatToInt (alpha * 255.0f));
  58946. }
  58947. static const float oneOver255 = 1.0f / 255.0f;
  58948. Colour::Colour() throw()
  58949. : argb (0)
  58950. {
  58951. }
  58952. Colour::Colour (const Colour& other) throw()
  58953. : argb (other.argb)
  58954. {
  58955. }
  58956. const Colour& Colour::operator= (const Colour& other) throw()
  58957. {
  58958. argb = other.argb;
  58959. return *this;
  58960. }
  58961. bool Colour::operator== (const Colour& other) const throw()
  58962. {
  58963. return argb.getARGB() == other.argb.getARGB();
  58964. }
  58965. bool Colour::operator!= (const Colour& other) const throw()
  58966. {
  58967. return argb.getARGB() != other.argb.getARGB();
  58968. }
  58969. Colour::Colour (const uint32 argb_) throw()
  58970. : argb (argb_)
  58971. {
  58972. }
  58973. Colour::Colour (const uint8 red,
  58974. const uint8 green,
  58975. const uint8 blue) throw()
  58976. {
  58977. argb.setARGB (0xff, red, green, blue);
  58978. }
  58979. const Colour Colour::fromRGB (const uint8 red,
  58980. const uint8 green,
  58981. const uint8 blue) throw()
  58982. {
  58983. return Colour (red, green, blue);
  58984. }
  58985. Colour::Colour (const uint8 red,
  58986. const uint8 green,
  58987. const uint8 blue,
  58988. const uint8 alpha) throw()
  58989. {
  58990. argb.setARGB (alpha, red, green, blue);
  58991. }
  58992. const Colour Colour::fromRGBA (const uint8 red,
  58993. const uint8 green,
  58994. const uint8 blue,
  58995. const uint8 alpha) throw()
  58996. {
  58997. return Colour (red, green, blue, alpha);
  58998. }
  58999. Colour::Colour (const uint8 red,
  59000. const uint8 green,
  59001. const uint8 blue,
  59002. const float alpha) throw()
  59003. {
  59004. argb.setARGB (floatAlphaToInt (alpha), red, green, blue);
  59005. }
  59006. const Colour Colour::fromRGBAFloat (const uint8 red,
  59007. const uint8 green,
  59008. const uint8 blue,
  59009. const float alpha) throw()
  59010. {
  59011. return Colour (red, green, blue, alpha);
  59012. }
  59013. static void convertHSBtoRGB (float h, const float s, float v,
  59014. uint8& r, uint8& g, uint8& b) throw()
  59015. {
  59016. v *= 255.0f;
  59017. const uint8 intV = (uint8) roundFloatToInt (v);
  59018. if (s == 0)
  59019. {
  59020. r = intV;
  59021. g = intV;
  59022. b = intV;
  59023. }
  59024. else
  59025. {
  59026. h = (h - floorf (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  59027. const float f = h - floorf (h);
  59028. const uint8 x = (uint8) roundFloatToInt (v * (1.0f - s));
  59029. const float y = v * (1.0f - s * f);
  59030. const float z = v * (1.0f - (s * (1.0f - f)));
  59031. if (h < 1.0f)
  59032. {
  59033. r = intV;
  59034. g = (uint8) roundFloatToInt (z);
  59035. b = x;
  59036. }
  59037. else if (h < 2.0f)
  59038. {
  59039. r = (uint8) roundFloatToInt (y);
  59040. g = intV;
  59041. b = x;
  59042. }
  59043. else if (h < 3.0f)
  59044. {
  59045. r = x;
  59046. g = intV;
  59047. b = (uint8) roundFloatToInt (z);
  59048. }
  59049. else if (h < 4.0f)
  59050. {
  59051. r = x;
  59052. g = (uint8) roundFloatToInt (y);
  59053. b = intV;
  59054. }
  59055. else if (h < 5.0f)
  59056. {
  59057. r = (uint8) roundFloatToInt (z);
  59058. g = x;
  59059. b = intV;
  59060. }
  59061. else if (h < 6.0f)
  59062. {
  59063. r = intV;
  59064. g = x;
  59065. b = (uint8) roundFloatToInt (y);
  59066. }
  59067. else
  59068. {
  59069. r = 0;
  59070. g = 0;
  59071. b = 0;
  59072. }
  59073. }
  59074. }
  59075. Colour::Colour (const float hue,
  59076. const float saturation,
  59077. const float brightness,
  59078. const float alpha) throw()
  59079. {
  59080. uint8 r = getRed(), g = getGreen(), b = getBlue();
  59081. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  59082. argb.setARGB (floatAlphaToInt (alpha), r, g, b);
  59083. }
  59084. const Colour Colour::fromHSV (const float hue,
  59085. const float saturation,
  59086. const float brightness,
  59087. const float alpha) throw()
  59088. {
  59089. return Colour (hue, saturation, brightness, alpha);
  59090. }
  59091. Colour::Colour (const float hue,
  59092. const float saturation,
  59093. const float brightness,
  59094. const uint8 alpha) throw()
  59095. {
  59096. uint8 r = getRed(), g = getGreen(), b = getBlue();
  59097. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  59098. argb.setARGB (alpha, r, g, b);
  59099. }
  59100. Colour::~Colour() throw()
  59101. {
  59102. }
  59103. const PixelARGB Colour::getPixelARGB() const throw()
  59104. {
  59105. PixelARGB p (argb);
  59106. p.premultiply();
  59107. return p;
  59108. }
  59109. uint32 Colour::getARGB() const throw()
  59110. {
  59111. return argb.getARGB();
  59112. }
  59113. bool Colour::isTransparent() const throw()
  59114. {
  59115. return getAlpha() == 0;
  59116. }
  59117. bool Colour::isOpaque() const throw()
  59118. {
  59119. return getAlpha() == 0xff;
  59120. }
  59121. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  59122. {
  59123. PixelARGB newCol (argb);
  59124. newCol.setAlpha (newAlpha);
  59125. return Colour (newCol.getARGB());
  59126. }
  59127. const Colour Colour::withAlpha (const float newAlpha) const throw()
  59128. {
  59129. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  59130. PixelARGB newCol (argb);
  59131. newCol.setAlpha (floatAlphaToInt (newAlpha));
  59132. return Colour (newCol.getARGB());
  59133. }
  59134. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  59135. {
  59136. jassert (alphaMultiplier >= 0);
  59137. PixelARGB newCol (argb);
  59138. newCol.setAlpha ((uint8) jmin (0xff, roundFloatToInt (alphaMultiplier * newCol.getAlpha())));
  59139. return Colour (newCol.getARGB());
  59140. }
  59141. const Colour Colour::overlaidWith (const Colour& src) const throw()
  59142. {
  59143. const int destAlpha = getAlpha();
  59144. if (destAlpha > 0)
  59145. {
  59146. const int invA = 0xff - (int) src.getAlpha();
  59147. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  59148. if (resA > 0)
  59149. {
  59150. const int da = (invA * destAlpha) / resA;
  59151. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  59152. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  59153. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  59154. (uint8) resA);
  59155. }
  59156. return *this;
  59157. }
  59158. else
  59159. {
  59160. return src;
  59161. }
  59162. }
  59163. float Colour::getFloatRed() const throw()
  59164. {
  59165. return getRed() * oneOver255;
  59166. }
  59167. float Colour::getFloatGreen() const throw()
  59168. {
  59169. return getGreen() * oneOver255;
  59170. }
  59171. float Colour::getFloatBlue() const throw()
  59172. {
  59173. return getBlue() * oneOver255;
  59174. }
  59175. float Colour::getFloatAlpha() const throw()
  59176. {
  59177. return getAlpha() * oneOver255;
  59178. }
  59179. void Colour::getHSB (float& h, float& s, float& v) const throw()
  59180. {
  59181. const int r = getRed();
  59182. const int g = getGreen();
  59183. const int b = getBlue();
  59184. const int hi = jmax (r, g, b);
  59185. const int lo = jmin (r, g, b);
  59186. if (hi != 0)
  59187. {
  59188. s = (hi - lo) / (float) hi;
  59189. if (s != 0)
  59190. {
  59191. const float invDiff = 1.0f / (hi - lo);
  59192. const float red = (hi - r) * invDiff;
  59193. const float green = (hi - g) * invDiff;
  59194. const float blue = (hi - b) * invDiff;
  59195. if (r == hi)
  59196. h = blue - green;
  59197. else if (g == hi)
  59198. h = 2.0f + red - blue;
  59199. else
  59200. h = 4.0f + green - red;
  59201. h *= 1.0f / 6.0f;
  59202. if (h < 0)
  59203. ++h;
  59204. }
  59205. else
  59206. {
  59207. h = 0;
  59208. }
  59209. }
  59210. else
  59211. {
  59212. s = 0;
  59213. h = 0;
  59214. }
  59215. v = hi * oneOver255;
  59216. }
  59217. float Colour::getHue() const throw()
  59218. {
  59219. float h, s, b;
  59220. getHSB (h, s, b);
  59221. return h;
  59222. }
  59223. const Colour Colour::withHue (const float hue) const throw()
  59224. {
  59225. float h, s, b;
  59226. getHSB (h, s, b);
  59227. return Colour (hue, s, b, getAlpha());
  59228. }
  59229. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  59230. {
  59231. float h, s, b;
  59232. getHSB (h, s, b);
  59233. h += amountToRotate;
  59234. h -= floorf (h);
  59235. return Colour (h, s, b, getAlpha());
  59236. }
  59237. float Colour::getSaturation() const throw()
  59238. {
  59239. float h, s, b;
  59240. getHSB (h, s, b);
  59241. return s;
  59242. }
  59243. const Colour Colour::withSaturation (const float saturation) const throw()
  59244. {
  59245. float h, s, b;
  59246. getHSB (h, s, b);
  59247. return Colour (h, saturation, b, getAlpha());
  59248. }
  59249. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  59250. {
  59251. float h, s, b;
  59252. getHSB (h, s, b);
  59253. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  59254. }
  59255. float Colour::getBrightness() const throw()
  59256. {
  59257. float h, s, b;
  59258. getHSB (h, s, b);
  59259. return b;
  59260. }
  59261. const Colour Colour::withBrightness (const float brightness) const throw()
  59262. {
  59263. float h, s, b;
  59264. getHSB (h, s, b);
  59265. return Colour (h, s, brightness, getAlpha());
  59266. }
  59267. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  59268. {
  59269. float h, s, b;
  59270. getHSB (h, s, b);
  59271. b *= amount;
  59272. if (b > 1.0f)
  59273. b = 1.0f;
  59274. return Colour (h, s, b, getAlpha());
  59275. }
  59276. const Colour Colour::brighter (float amount) const throw()
  59277. {
  59278. amount = 1.0f / (1.0f + amount);
  59279. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  59280. (uint8) (255 - (amount * (255 - getGreen()))),
  59281. (uint8) (255 - (amount * (255 - getBlue()))),
  59282. getAlpha());
  59283. }
  59284. const Colour Colour::darker (float amount) const throw()
  59285. {
  59286. amount = 1.0f / (1.0f + amount);
  59287. return Colour ((uint8) (amount * getRed()),
  59288. (uint8) (amount * getGreen()),
  59289. (uint8) (amount * getBlue()),
  59290. getAlpha());
  59291. }
  59292. const Colour Colour::greyLevel (const float brightness) throw()
  59293. {
  59294. const uint8 level
  59295. = (uint8) jlimit (0x00, 0xff, roundFloatToInt (brightness * 255.0f));
  59296. return Colour (level, level, level);
  59297. }
  59298. const Colour Colour::contrasting (const float amount) const throw()
  59299. {
  59300. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  59301. ? Colours::black
  59302. : Colours::white).withAlpha (amount));
  59303. }
  59304. const Colour Colour::contrasting (const Colour& colour1,
  59305. const Colour& colour2) throw()
  59306. {
  59307. const float b1 = colour1.getBrightness();
  59308. const float b2 = colour2.getBrightness();
  59309. float best = 0.0f;
  59310. float bestDist = 0.0f;
  59311. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  59312. {
  59313. const float d1 = fabsf (i - b1);
  59314. const float d2 = fabsf (i - b2);
  59315. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  59316. if (dist > bestDist)
  59317. {
  59318. best = i;
  59319. bestDist = dist;
  59320. }
  59321. }
  59322. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  59323. .withBrightness (best);
  59324. }
  59325. const String Colour::toString() const throw()
  59326. {
  59327. return String::toHexString ((int) argb.getARGB());
  59328. }
  59329. const Colour Colour::fromString (const String& encodedColourString)
  59330. {
  59331. return Colour ((uint32) encodedColourString.getHexValue32());
  59332. }
  59333. END_JUCE_NAMESPACE
  59334. /********* End of inlined file: juce_Colour.cpp *********/
  59335. /********* Start of inlined file: juce_ColourGradient.cpp *********/
  59336. BEGIN_JUCE_NAMESPACE
  59337. ColourGradient::ColourGradient() throw()
  59338. : colours (4)
  59339. {
  59340. #ifdef JUCE_DEBUG
  59341. x1 = 987654.0f;
  59342. #endif
  59343. }
  59344. ColourGradient::ColourGradient (const Colour& colour1,
  59345. const float x1_,
  59346. const float y1_,
  59347. const Colour& colour2,
  59348. const float x2_,
  59349. const float y2_,
  59350. const bool isRadial_) throw()
  59351. : x1 (x1_),
  59352. y1 (y1_),
  59353. x2 (x2_),
  59354. y2 (y2_),
  59355. isRadial (isRadial_),
  59356. colours (4)
  59357. {
  59358. colours.add (0);
  59359. colours.add (colour1.getPixelARGB().getARGB());
  59360. colours.add (1 << 16);
  59361. colours.add (colour2.getPixelARGB().getARGB());
  59362. }
  59363. ColourGradient::~ColourGradient() throw()
  59364. {
  59365. }
  59366. void ColourGradient::clearColours() throw()
  59367. {
  59368. colours.clear();
  59369. }
  59370. void ColourGradient::addColour (const double proportionAlongGradient,
  59371. const Colour& colour) throw()
  59372. {
  59373. // must be within the two end-points
  59374. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  59375. const uint32 pos = jlimit (0, 65535, roundDoubleToInt (proportionAlongGradient * 65536.0));
  59376. int i;
  59377. for (i = 0; i < colours.size(); i += 2)
  59378. if (colours.getUnchecked(i) > pos)
  59379. break;
  59380. colours.insert (i, pos);
  59381. colours.insert (i + 1, colour.getPixelARGB().getARGB());
  59382. }
  59383. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  59384. {
  59385. for (int i = 1; i < colours.size(); i += 2)
  59386. {
  59387. PixelARGB pix (colours.getUnchecked(i));
  59388. pix.multiplyAlpha (multiplier);
  59389. colours.set (i, pix.getARGB());
  59390. }
  59391. }
  59392. int ColourGradient::getNumColours() const throw()
  59393. {
  59394. return colours.size() >> 1;
  59395. }
  59396. double ColourGradient::getColourPosition (const int index) const throw()
  59397. {
  59398. return colours [index << 1];
  59399. }
  59400. const Colour ColourGradient::getColour (const int index) const throw()
  59401. {
  59402. PixelARGB pix (colours [(index << 1) + 1]);
  59403. pix.unpremultiply();
  59404. return Colour (pix.getARGB());
  59405. }
  59406. PixelARGB* ColourGradient::createLookupTable (int& numEntries) const throw()
  59407. {
  59408. #ifdef JUCE_DEBUG
  59409. // trying to use the object without setting its co-ordinates? Have a careful read of
  59410. // the comments for the constructors.
  59411. jassert (x1 != 987654.0f);
  59412. #endif
  59413. const int numColours = colours.size() >> 1;
  59414. float tx1 = x1, ty1 = y1, tx2 = x2, ty2 = y2;
  59415. transform.transformPoint (tx1, ty1);
  59416. transform.transformPoint (tx2, ty2);
  59417. const double distance = juce_hypot (tx1 - tx2, ty1 - ty2);
  59418. numEntries = jlimit (1, (numColours - 1) << 8, 3 * (int) distance);
  59419. PixelARGB* const lookupTable = (PixelARGB*) juce_calloc (numEntries * sizeof (PixelARGB));
  59420. if (numColours >= 2)
  59421. {
  59422. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  59423. PixelARGB pix1 (colours.getUnchecked (1));
  59424. int index = 0;
  59425. for (int j = 2; j < colours.size(); j += 2)
  59426. {
  59427. const int numToDo = ((colours.getUnchecked (j) * numEntries) >> 16) - index;
  59428. const PixelARGB pix2 (colours.getUnchecked (j + 1));
  59429. for (int i = 0; i < numToDo; ++i)
  59430. {
  59431. jassert (index >= 0 && index < numEntries);
  59432. lookupTable[index] = pix1;
  59433. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  59434. ++index;
  59435. }
  59436. pix1 = pix2;
  59437. }
  59438. while (index < numEntries)
  59439. lookupTable [index++] = pix1;
  59440. }
  59441. else
  59442. {
  59443. jassertfalse // no colours specified!
  59444. }
  59445. return lookupTable;
  59446. }
  59447. bool ColourGradient::isOpaque() const throw()
  59448. {
  59449. for (int i = 1; i < colours.size(); i += 2)
  59450. if (PixelARGB (colours.getUnchecked(i)).getAlpha() < 0xff)
  59451. return false;
  59452. return true;
  59453. }
  59454. bool ColourGradient::isInvisible() const throw()
  59455. {
  59456. for (int i = 1; i < colours.size(); i += 2)
  59457. if (PixelARGB (colours.getUnchecked(i)).getAlpha() > 0)
  59458. return false;
  59459. return true;
  59460. }
  59461. END_JUCE_NAMESPACE
  59462. /********* End of inlined file: juce_ColourGradient.cpp *********/
  59463. /********* Start of inlined file: juce_Colours.cpp *********/
  59464. BEGIN_JUCE_NAMESPACE
  59465. const Colour Colours::transparentBlack (0);
  59466. const Colour Colours::transparentWhite (0x00ffffff);
  59467. const Colour Colours::aliceblue (0xfff0f8ff);
  59468. const Colour Colours::antiquewhite (0xfffaebd7);
  59469. const Colour Colours::aqua (0xff00ffff);
  59470. const Colour Colours::aquamarine (0xff7fffd4);
  59471. const Colour Colours::azure (0xfff0ffff);
  59472. const Colour Colours::beige (0xfff5f5dc);
  59473. const Colour Colours::bisque (0xffffe4c4);
  59474. const Colour Colours::black (0xff000000);
  59475. const Colour Colours::blanchedalmond (0xffffebcd);
  59476. const Colour Colours::blue (0xff0000ff);
  59477. const Colour Colours::blueviolet (0xff8a2be2);
  59478. const Colour Colours::brown (0xffa52a2a);
  59479. const Colour Colours::burlywood (0xffdeb887);
  59480. const Colour Colours::cadetblue (0xff5f9ea0);
  59481. const Colour Colours::chartreuse (0xff7fff00);
  59482. const Colour Colours::chocolate (0xffd2691e);
  59483. const Colour Colours::coral (0xffff7f50);
  59484. const Colour Colours::cornflowerblue (0xff6495ed);
  59485. const Colour Colours::cornsilk (0xfffff8dc);
  59486. const Colour Colours::crimson (0xffdc143c);
  59487. const Colour Colours::cyan (0xff00ffff);
  59488. const Colour Colours::darkblue (0xff00008b);
  59489. const Colour Colours::darkcyan (0xff008b8b);
  59490. const Colour Colours::darkgoldenrod (0xffb8860b);
  59491. const Colour Colours::darkgrey (0xff555555);
  59492. const Colour Colours::darkgreen (0xff006400);
  59493. const Colour Colours::darkkhaki (0xffbdb76b);
  59494. const Colour Colours::darkmagenta (0xff8b008b);
  59495. const Colour Colours::darkolivegreen (0xff556b2f);
  59496. const Colour Colours::darkorange (0xffff8c00);
  59497. const Colour Colours::darkorchid (0xff9932cc);
  59498. const Colour Colours::darkred (0xff8b0000);
  59499. const Colour Colours::darksalmon (0xffe9967a);
  59500. const Colour Colours::darkseagreen (0xff8fbc8f);
  59501. const Colour Colours::darkslateblue (0xff483d8b);
  59502. const Colour Colours::darkslategrey (0xff2f4f4f);
  59503. const Colour Colours::darkturquoise (0xff00ced1);
  59504. const Colour Colours::darkviolet (0xff9400d3);
  59505. const Colour Colours::deeppink (0xffff1493);
  59506. const Colour Colours::deepskyblue (0xff00bfff);
  59507. const Colour Colours::dimgrey (0xff696969);
  59508. const Colour Colours::dodgerblue (0xff1e90ff);
  59509. const Colour Colours::firebrick (0xffb22222);
  59510. const Colour Colours::floralwhite (0xfffffaf0);
  59511. const Colour Colours::forestgreen (0xff228b22);
  59512. const Colour Colours::fuchsia (0xffff00ff);
  59513. const Colour Colours::gainsboro (0xffdcdcdc);
  59514. const Colour Colours::gold (0xffffd700);
  59515. const Colour Colours::goldenrod (0xffdaa520);
  59516. const Colour Colours::grey (0xff808080);
  59517. const Colour Colours::green (0xff008000);
  59518. const Colour Colours::greenyellow (0xffadff2f);
  59519. const Colour Colours::honeydew (0xfff0fff0);
  59520. const Colour Colours::hotpink (0xffff69b4);
  59521. const Colour Colours::indianred (0xffcd5c5c);
  59522. const Colour Colours::indigo (0xff4b0082);
  59523. const Colour Colours::ivory (0xfffffff0);
  59524. const Colour Colours::khaki (0xfff0e68c);
  59525. const Colour Colours::lavender (0xffe6e6fa);
  59526. const Colour Colours::lavenderblush (0xfffff0f5);
  59527. const Colour Colours::lemonchiffon (0xfffffacd);
  59528. const Colour Colours::lightblue (0xffadd8e6);
  59529. const Colour Colours::lightcoral (0xfff08080);
  59530. const Colour Colours::lightcyan (0xffe0ffff);
  59531. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  59532. const Colour Colours::lightgreen (0xff90ee90);
  59533. const Colour Colours::lightgrey (0xffd3d3d3);
  59534. const Colour Colours::lightpink (0xffffb6c1);
  59535. const Colour Colours::lightsalmon (0xffffa07a);
  59536. const Colour Colours::lightseagreen (0xff20b2aa);
  59537. const Colour Colours::lightskyblue (0xff87cefa);
  59538. const Colour Colours::lightslategrey (0xff778899);
  59539. const Colour Colours::lightsteelblue (0xffb0c4de);
  59540. const Colour Colours::lightyellow (0xffffffe0);
  59541. const Colour Colours::lime (0xff00ff00);
  59542. const Colour Colours::limegreen (0xff32cd32);
  59543. const Colour Colours::linen (0xfffaf0e6);
  59544. const Colour Colours::magenta (0xffff00ff);
  59545. const Colour Colours::maroon (0xff800000);
  59546. const Colour Colours::mediumaquamarine (0xff66cdaa);
  59547. const Colour Colours::mediumblue (0xff0000cd);
  59548. const Colour Colours::mediumorchid (0xffba55d3);
  59549. const Colour Colours::mediumpurple (0xff9370db);
  59550. const Colour Colours::mediumseagreen (0xff3cb371);
  59551. const Colour Colours::mediumslateblue (0xff7b68ee);
  59552. const Colour Colours::mediumspringgreen (0xff00fa9a);
  59553. const Colour Colours::mediumturquoise (0xff48d1cc);
  59554. const Colour Colours::mediumvioletred (0xffc71585);
  59555. const Colour Colours::midnightblue (0xff191970);
  59556. const Colour Colours::mintcream (0xfff5fffa);
  59557. const Colour Colours::mistyrose (0xffffe4e1);
  59558. const Colour Colours::navajowhite (0xffffdead);
  59559. const Colour Colours::navy (0xff000080);
  59560. const Colour Colours::oldlace (0xfffdf5e6);
  59561. const Colour Colours::olive (0xff808000);
  59562. const Colour Colours::olivedrab (0xff6b8e23);
  59563. const Colour Colours::orange (0xffffa500);
  59564. const Colour Colours::orangered (0xffff4500);
  59565. const Colour Colours::orchid (0xffda70d6);
  59566. const Colour Colours::palegoldenrod (0xffeee8aa);
  59567. const Colour Colours::palegreen (0xff98fb98);
  59568. const Colour Colours::paleturquoise (0xffafeeee);
  59569. const Colour Colours::palevioletred (0xffdb7093);
  59570. const Colour Colours::papayawhip (0xffffefd5);
  59571. const Colour Colours::peachpuff (0xffffdab9);
  59572. const Colour Colours::peru (0xffcd853f);
  59573. const Colour Colours::pink (0xffffc0cb);
  59574. const Colour Colours::plum (0xffdda0dd);
  59575. const Colour Colours::powderblue (0xffb0e0e6);
  59576. const Colour Colours::purple (0xff800080);
  59577. const Colour Colours::red (0xffff0000);
  59578. const Colour Colours::rosybrown (0xffbc8f8f);
  59579. const Colour Colours::royalblue (0xff4169e1);
  59580. const Colour Colours::saddlebrown (0xff8b4513);
  59581. const Colour Colours::salmon (0xfffa8072);
  59582. const Colour Colours::sandybrown (0xfff4a460);
  59583. const Colour Colours::seagreen (0xff2e8b57);
  59584. const Colour Colours::seashell (0xfffff5ee);
  59585. const Colour Colours::sienna (0xffa0522d);
  59586. const Colour Colours::silver (0xffc0c0c0);
  59587. const Colour Colours::skyblue (0xff87ceeb);
  59588. const Colour Colours::slateblue (0xff6a5acd);
  59589. const Colour Colours::slategrey (0xff708090);
  59590. const Colour Colours::snow (0xfffffafa);
  59591. const Colour Colours::springgreen (0xff00ff7f);
  59592. const Colour Colours::steelblue (0xff4682b4);
  59593. const Colour Colours::tan (0xffd2b48c);
  59594. const Colour Colours::teal (0xff008080);
  59595. const Colour Colours::thistle (0xffd8bfd8);
  59596. const Colour Colours::tomato (0xffff6347);
  59597. const Colour Colours::turquoise (0xff40e0d0);
  59598. const Colour Colours::violet (0xffee82ee);
  59599. const Colour Colours::wheat (0xfff5deb3);
  59600. const Colour Colours::white (0xffffffff);
  59601. const Colour Colours::whitesmoke (0xfff5f5f5);
  59602. const Colour Colours::yellow (0xffffff00);
  59603. const Colour Colours::yellowgreen (0xff9acd32);
  59604. const Colour Colours::findColourForName (const String& colourName,
  59605. const Colour& defaultColour)
  59606. {
  59607. static const int presets[] =
  59608. {
  59609. // (first value is the string's hashcode, second is ARGB)
  59610. 0x05978fff, 0xff000000, /* black */
  59611. 0x06bdcc29, 0xffffffff, /* white */
  59612. 0x002e305a, 0xff0000ff, /* blue */
  59613. 0x00308adf, 0xff808080, /* grey */
  59614. 0x05e0cf03, 0xff008000, /* green */
  59615. 0x0001b891, 0xffff0000, /* red */
  59616. 0xd43c6474, 0xffffff00, /* yellow */
  59617. 0x620886da, 0xfff0f8ff, /* aliceblue */
  59618. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  59619. 0x002dcebc, 0xff00ffff, /* aqua */
  59620. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  59621. 0x0590228f, 0xfff0ffff, /* azure */
  59622. 0x05947fe4, 0xfff5f5dc, /* beige */
  59623. 0xad388e35, 0xffffe4c4, /* bisque */
  59624. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  59625. 0x39129959, 0xff8a2be2, /* blueviolet */
  59626. 0x059a8136, 0xffa52a2a, /* brown */
  59627. 0x89cea8f9, 0xffdeb887, /* burlywood */
  59628. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  59629. 0x6b748956, 0xff7fff00, /* chartreuse */
  59630. 0x2903623c, 0xffd2691e, /* chocolate */
  59631. 0x05a74431, 0xffff7f50, /* coral */
  59632. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  59633. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  59634. 0x3d8c4edf, 0xffdc143c, /* crimson */
  59635. 0x002ed323, 0xff00ffff, /* cyan */
  59636. 0x67cc74d0, 0xff00008b, /* darkblue */
  59637. 0x67cd1799, 0xff008b8b, /* darkcyan */
  59638. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  59639. 0x67cecf55, 0xff555555, /* darkgrey */
  59640. 0x920b194d, 0xff006400, /* darkgreen */
  59641. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  59642. 0x5c293873, 0xff8b008b, /* darkmagenta */
  59643. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  59644. 0xbcfd2524, 0xffff8c00, /* darkorange */
  59645. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  59646. 0x55ee0d5b, 0xff8b0000, /* darkred */
  59647. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  59648. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  59649. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  59650. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  59651. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  59652. 0xc8769375, 0xff9400d3, /* darkviolet */
  59653. 0x25832862, 0xffff1493, /* deeppink */
  59654. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  59655. 0x634c8b67, 0xff696969, /* dimgrey */
  59656. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  59657. 0xef19e3cb, 0xffb22222, /* firebrick */
  59658. 0xb852b195, 0xfffffaf0, /* floralwhite */
  59659. 0xd086fd06, 0xff228b22, /* forestgreen */
  59660. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  59661. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  59662. 0x00308060, 0xffffd700, /* gold */
  59663. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  59664. 0xbab8a537, 0xffadff2f, /* greenyellow */
  59665. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  59666. 0x41892743, 0xffff69b4, /* hotpink */
  59667. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  59668. 0xb969fed2, 0xff4b0082, /* indigo */
  59669. 0x05fef6a9, 0xfffffff0, /* ivory */
  59670. 0x06149302, 0xfff0e68c, /* khaki */
  59671. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  59672. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  59673. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  59674. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  59675. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  59676. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  59677. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  59678. 0xf40157ad, 0xff90ee90, /* lightgreen */
  59679. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  59680. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  59681. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  59682. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  59683. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  59684. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  59685. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  59686. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  59687. 0x0032afd5, 0xff00ff00, /* lime */
  59688. 0x607bbc4e, 0xff32cd32, /* limegreen */
  59689. 0x06234efa, 0xfffaf0e6, /* linen */
  59690. 0x316858a9, 0xffff00ff, /* magenta */
  59691. 0xbf8ca470, 0xff800000, /* maroon */
  59692. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  59693. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  59694. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  59695. 0x07556b71, 0xff9370db, /* mediumpurple */
  59696. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  59697. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  59698. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  59699. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  59700. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  59701. 0x168eb32a, 0xff191970, /* midnightblue */
  59702. 0x4306b960, 0xfff5fffa, /* mintcream */
  59703. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  59704. 0xe97218a6, 0xffffdead, /* navajowhite */
  59705. 0x00337bb6, 0xff000080, /* navy */
  59706. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  59707. 0x064ee1db, 0xff808000, /* olive */
  59708. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  59709. 0xc3de262e, 0xffffa500, /* orange */
  59710. 0x58bebba3, 0xffff4500, /* orangered */
  59711. 0xc3def8a3, 0xffda70d6, /* orchid */
  59712. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  59713. 0x3d9dd619, 0xff98fb98, /* palegreen */
  59714. 0x74022737, 0xffafeeee, /* paleturquoise */
  59715. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  59716. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  59717. 0x93e1b776, 0xffffdab9, /* peachpuff */
  59718. 0x003472f8, 0xffcd853f, /* peru */
  59719. 0x00348176, 0xffffc0cb, /* pink */
  59720. 0x00348d94, 0xffdda0dd, /* plum */
  59721. 0xd036be93, 0xffb0e0e6, /* powderblue */
  59722. 0xc5c507bc, 0xff800080, /* purple */
  59723. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  59724. 0xbd9413e1, 0xff4169e1, /* royalblue */
  59725. 0xf456044f, 0xff8b4513, /* saddlebrown */
  59726. 0xc9c6f66e, 0xfffa8072, /* salmon */
  59727. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  59728. 0x34636c14, 0xff2e8b57, /* seagreen */
  59729. 0x3507fb41, 0xfffff5ee, /* seashell */
  59730. 0xca348772, 0xffa0522d, /* sienna */
  59731. 0xca37d30d, 0xffc0c0c0, /* silver */
  59732. 0x80da74fb, 0xff87ceeb, /* skyblue */
  59733. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  59734. 0x44ab37f8, 0xff708090, /* slategrey */
  59735. 0x0035f183, 0xfffffafa, /* snow */
  59736. 0xd5440d16, 0xff00ff7f, /* springgreen */
  59737. 0x3e1524a5, 0xff4682b4, /* steelblue */
  59738. 0x0001bfa1, 0xffd2b48c, /* tan */
  59739. 0x0036425c, 0xff008080, /* teal */
  59740. 0xafc8858f, 0xffd8bfd8, /* thistle */
  59741. 0xcc41600a, 0xffff6347, /* tomato */
  59742. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  59743. 0xcf57947f, 0xffee82ee, /* violet */
  59744. 0x06bdbae7, 0xfff5deb3, /* wheat */
  59745. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  59746. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  59747. };
  59748. const int hash = colourName.trim().toLowerCase().hashCode();
  59749. for (int i = 0; i < numElementsInArray (presets); i += 2)
  59750. if (presets [i] == hash)
  59751. return Colour (presets [i + 1]);
  59752. return defaultColour;
  59753. }
  59754. END_JUCE_NAMESPACE
  59755. /********* End of inlined file: juce_Colours.cpp *********/
  59756. /********* Start of inlined file: juce_EdgeTable.cpp *********/
  59757. BEGIN_JUCE_NAMESPACE
  59758. EdgeTable::EdgeTable (const int top_,
  59759. const int height_,
  59760. const OversamplingLevel oversampling_,
  59761. const int expectedEdgesPerLine) throw()
  59762. : top (top_),
  59763. height (height_),
  59764. maxEdgesPerLine (expectedEdgesPerLine),
  59765. lineStrideElements ((expectedEdgesPerLine << 1) + 1),
  59766. oversampling (oversampling_)
  59767. {
  59768. table = (int*) juce_calloc ((height << (int)oversampling_)
  59769. * lineStrideElements * sizeof (int));
  59770. }
  59771. EdgeTable::EdgeTable (const EdgeTable& other) throw()
  59772. : table (0)
  59773. {
  59774. operator= (other);
  59775. }
  59776. const EdgeTable& EdgeTable::operator= (const EdgeTable& other) throw()
  59777. {
  59778. juce_free (table);
  59779. top = other.top;
  59780. height = other.height;
  59781. maxEdgesPerLine = other.maxEdgesPerLine;
  59782. lineStrideElements = other.lineStrideElements;
  59783. oversampling = other.oversampling;
  59784. const int tableSize = (height << (int)oversampling)
  59785. * lineStrideElements * sizeof (int);
  59786. table = (int*) juce_malloc (tableSize);
  59787. memcpy (table, other.table, tableSize);
  59788. return *this;
  59789. }
  59790. EdgeTable::~EdgeTable() throw()
  59791. {
  59792. juce_free (table);
  59793. }
  59794. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  59795. {
  59796. if (newNumEdgesPerLine != maxEdgesPerLine)
  59797. {
  59798. maxEdgesPerLine = newNumEdgesPerLine;
  59799. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  59800. int* const newTable = (int*) juce_malloc ((height << (int) oversampling)
  59801. * newLineStrideElements * sizeof (int));
  59802. for (int i = 0; i < (height << (int) oversampling); ++i)
  59803. {
  59804. const int* srcLine = table + lineStrideElements * i;
  59805. int* dstLine = newTable + newLineStrideElements * i;
  59806. int num = *srcLine++;
  59807. *dstLine++ = num;
  59808. num <<= 1;
  59809. while (--num >= 0)
  59810. *dstLine++ = *srcLine++;
  59811. }
  59812. juce_free (table);
  59813. table = newTable;
  59814. lineStrideElements = newLineStrideElements;
  59815. }
  59816. }
  59817. void EdgeTable::optimiseTable() throw()
  59818. {
  59819. int maxLineElements = 0;
  59820. for (int i = height; --i >= 0;)
  59821. maxLineElements = jmax (maxLineElements,
  59822. table [i * lineStrideElements]);
  59823. remapTableForNumEdges (maxLineElements);
  59824. }
  59825. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  59826. {
  59827. jassert (y >= 0 && y < (height << oversampling))
  59828. int* lineStart = table + lineStrideElements * y;
  59829. int n = lineStart[0];
  59830. if (n >= maxEdgesPerLine)
  59831. {
  59832. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  59833. lineStart = table + lineStrideElements * y;
  59834. }
  59835. n <<= 1;
  59836. int* const line = lineStart + 1;
  59837. while (n > 0)
  59838. {
  59839. const int cx = line [n - 2];
  59840. if (cx <= x)
  59841. break;
  59842. line [n] = cx;
  59843. line [n + 1] = line [n - 1];
  59844. n -= 2;
  59845. }
  59846. line [n] = x;
  59847. line [n + 1] = winding;
  59848. lineStart[0]++;
  59849. }
  59850. void EdgeTable::addPath (const Path& path,
  59851. const AffineTransform& transform) throw()
  59852. {
  59853. const int windingAmount = 256 / (1 << (int) oversampling);
  59854. const float timesOversampling = (float) (1 << (int) oversampling);
  59855. const int bottomLimit = (height << (int) oversampling);
  59856. PathFlatteningIterator iter (path, transform);
  59857. while (iter.next())
  59858. {
  59859. int y1 = roundFloatToInt (iter.y1 * timesOversampling) - (top << (int) oversampling);
  59860. int y2 = roundFloatToInt (iter.y2 * timesOversampling) - (top << (int) oversampling);
  59861. if (y1 != y2)
  59862. {
  59863. const double x1 = 256.0 * iter.x1;
  59864. const double x2 = 256.0 * iter.x2;
  59865. const double multiplier = (x2 - x1) / (y2 - y1);
  59866. const int oldY1 = y1;
  59867. int winding;
  59868. if (y1 > y2)
  59869. {
  59870. swapVariables (y1, y2);
  59871. winding = windingAmount;
  59872. }
  59873. else
  59874. {
  59875. winding = -windingAmount;
  59876. }
  59877. jassert (y1 < y2);
  59878. if (y1 < 0)
  59879. y1 = 0;
  59880. if (y2 > bottomLimit)
  59881. y2 = bottomLimit;
  59882. while (y1 < y2)
  59883. {
  59884. addEdgePoint (roundDoubleToInt (x1 + multiplier * (y1 - oldY1)),
  59885. y1,
  59886. winding);
  59887. ++y1;
  59888. }
  59889. }
  59890. }
  59891. if (! path.isUsingNonZeroWinding())
  59892. {
  59893. // if it's an alternate-winding path, we need to go through and
  59894. // make sure all the windings are alternating.
  59895. int* lineStart = table;
  59896. for (int i = height << (int) oversampling; --i >= 0;)
  59897. {
  59898. int* line = lineStart;
  59899. lineStart += lineStrideElements;
  59900. int num = *line;
  59901. while (--num >= 0)
  59902. {
  59903. line += 2;
  59904. *line = abs (*line);
  59905. if (--num >= 0)
  59906. {
  59907. line += 2;
  59908. *line = -abs (*line);
  59909. }
  59910. }
  59911. }
  59912. }
  59913. }
  59914. END_JUCE_NAMESPACE
  59915. /********* End of inlined file: juce_EdgeTable.cpp *********/
  59916. /********* Start of inlined file: juce_Graphics.cpp *********/
  59917. BEGIN_JUCE_NAMESPACE
  59918. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  59919. #define MINIMUM_COORD -0x3fffffff
  59920. #define MAXIMUM_COORD 0x3fffffff
  59921. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  59922. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  59923. jassert ((int) x >= MINIMUM_COORD \
  59924. && (int) x <= MAXIMUM_COORD \
  59925. && (int) y >= MINIMUM_COORD \
  59926. && (int) y <= MAXIMUM_COORD \
  59927. && (int) w >= MINIMUM_COORD \
  59928. && (int) w <= MAXIMUM_COORD \
  59929. && (int) h >= MINIMUM_COORD \
  59930. && (int) h <= MAXIMUM_COORD);
  59931. LowLevelGraphicsContext::LowLevelGraphicsContext()
  59932. {
  59933. }
  59934. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  59935. {
  59936. }
  59937. Graphics::Graphics (Image& imageToDrawOnto) throw()
  59938. : context (imageToDrawOnto.createLowLevelContext()),
  59939. ownsContext (true),
  59940. state (new GraphicsState()),
  59941. saveStatePending (false)
  59942. {
  59943. }
  59944. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  59945. : context (internalContext),
  59946. ownsContext (false),
  59947. state (new GraphicsState()),
  59948. saveStatePending (false)
  59949. {
  59950. }
  59951. Graphics::~Graphics() throw()
  59952. {
  59953. delete state;
  59954. if (ownsContext)
  59955. delete context;
  59956. }
  59957. void Graphics::resetToDefaultState() throw()
  59958. {
  59959. setColour (Colours::black);
  59960. state->font.resetToDefaultState();
  59961. state->quality = defaultQuality;
  59962. }
  59963. bool Graphics::isVectorDevice() const throw()
  59964. {
  59965. return context->isVectorDevice();
  59966. }
  59967. bool Graphics::reduceClipRegion (const int x, const int y,
  59968. const int w, const int h) throw()
  59969. {
  59970. saveStateIfPending();
  59971. return context->reduceClipRegion (x, y, w, h);
  59972. }
  59973. bool Graphics::reduceClipRegion (const RectangleList& clipRegion) throw()
  59974. {
  59975. saveStateIfPending();
  59976. return context->reduceClipRegion (clipRegion);
  59977. }
  59978. void Graphics::excludeClipRegion (const int x, const int y,
  59979. const int w, const int h) throw()
  59980. {
  59981. saveStateIfPending();
  59982. context->excludeClipRegion (x, y, w, h);
  59983. }
  59984. bool Graphics::isClipEmpty() const throw()
  59985. {
  59986. return context->isClipEmpty();
  59987. }
  59988. const Rectangle Graphics::getClipBounds() const throw()
  59989. {
  59990. return context->getClipBounds();
  59991. }
  59992. void Graphics::saveState() throw()
  59993. {
  59994. saveStateIfPending();
  59995. saveStatePending = true;
  59996. }
  59997. void Graphics::restoreState() throw()
  59998. {
  59999. if (saveStatePending)
  60000. {
  60001. saveStatePending = false;
  60002. }
  60003. else
  60004. {
  60005. const int stackSize = stateStack.size();
  60006. if (stackSize > 0)
  60007. {
  60008. context->restoreState();
  60009. delete state;
  60010. state = stateStack.getUnchecked (stackSize - 1);
  60011. stateStack.removeLast (1, false);
  60012. }
  60013. else
  60014. {
  60015. // Trying to call restoreState() more times than you've called saveState() !
  60016. // Be careful to correctly match each saveState() with exactly one call to restoreState().
  60017. jassertfalse
  60018. }
  60019. }
  60020. }
  60021. void Graphics::saveStateIfPending() throw()
  60022. {
  60023. if (saveStatePending)
  60024. {
  60025. saveStatePending = false;
  60026. context->saveState();
  60027. stateStack.add (new GraphicsState (*state));
  60028. }
  60029. }
  60030. void Graphics::setOrigin (const int newOriginX,
  60031. const int newOriginY) throw()
  60032. {
  60033. saveStateIfPending();
  60034. context->setOrigin (newOriginX, newOriginY);
  60035. }
  60036. bool Graphics::clipRegionIntersects (const int x, const int y,
  60037. const int w, const int h) const throw()
  60038. {
  60039. return context->clipRegionIntersects (x, y, w, h);
  60040. }
  60041. void Graphics::setColour (const Colour& newColour) throw()
  60042. {
  60043. saveStateIfPending();
  60044. state->colour = newColour;
  60045. deleteAndZero (state->brush);
  60046. }
  60047. const Colour& Graphics::getCurrentColour() const throw()
  60048. {
  60049. return state->colour;
  60050. }
  60051. void Graphics::setOpacity (const float newOpacity) throw()
  60052. {
  60053. saveStateIfPending();
  60054. state->colour = state->colour.withAlpha (newOpacity);
  60055. }
  60056. void Graphics::setBrush (const Brush* const newBrush) throw()
  60057. {
  60058. saveStateIfPending();
  60059. delete state->brush;
  60060. if (newBrush != 0)
  60061. state->brush = newBrush->createCopy();
  60062. else
  60063. state->brush = 0;
  60064. }
  60065. Graphics::GraphicsState::GraphicsState() throw()
  60066. : colour (Colours::black),
  60067. brush (0),
  60068. quality (defaultQuality)
  60069. {
  60070. }
  60071. Graphics::GraphicsState::GraphicsState (const GraphicsState& other) throw()
  60072. : colour (other.colour),
  60073. brush (other.brush != 0 ? other.brush->createCopy() : 0),
  60074. font (other.font),
  60075. quality (other.quality)
  60076. {
  60077. }
  60078. Graphics::GraphicsState::~GraphicsState() throw()
  60079. {
  60080. delete brush;
  60081. }
  60082. void Graphics::setFont (const Font& newFont) throw()
  60083. {
  60084. saveStateIfPending();
  60085. state->font = newFont;
  60086. }
  60087. void Graphics::setFont (const float newFontHeight,
  60088. const int newFontStyleFlags) throw()
  60089. {
  60090. saveStateIfPending();
  60091. state->font.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0.0f);
  60092. }
  60093. const Font& Graphics::getCurrentFont() const throw()
  60094. {
  60095. return state->font;
  60096. }
  60097. void Graphics::drawSingleLineText (const String& text,
  60098. const int startX,
  60099. const int baselineY) const throw()
  60100. {
  60101. if (text.isNotEmpty()
  60102. && startX < context->getClipBounds().getRight())
  60103. {
  60104. GlyphArrangement arr;
  60105. arr.addLineOfText (state->font, text, (float) startX, (float) baselineY);
  60106. arr.draw (*this);
  60107. }
  60108. }
  60109. void Graphics::drawTextAsPath (const String& text,
  60110. const AffineTransform& transform) const throw()
  60111. {
  60112. if (text.isNotEmpty())
  60113. {
  60114. GlyphArrangement arr;
  60115. arr.addLineOfText (state->font, text, 0.0f, 0.0f);
  60116. arr.draw (*this, transform);
  60117. }
  60118. }
  60119. void Graphics::drawMultiLineText (const String& text,
  60120. const int startX,
  60121. const int baselineY,
  60122. const int maximumLineWidth) const throw()
  60123. {
  60124. if (text.isNotEmpty()
  60125. && startX < context->getClipBounds().getRight())
  60126. {
  60127. GlyphArrangement arr;
  60128. arr.addJustifiedText (state->font, text,
  60129. (float) startX, (float) baselineY, (float) maximumLineWidth,
  60130. Justification::left);
  60131. arr.draw (*this);
  60132. }
  60133. }
  60134. void Graphics::drawText (const String& text,
  60135. const int x,
  60136. const int y,
  60137. const int width,
  60138. const int height,
  60139. const Justification& justificationType,
  60140. const bool useEllipsesIfTooBig) const throw()
  60141. {
  60142. if (text.isNotEmpty() && context->clipRegionIntersects (x, y, width, height))
  60143. {
  60144. GlyphArrangement arr;
  60145. arr.addCurtailedLineOfText (state->font, text,
  60146. 0.0f, 0.0f, (float)width,
  60147. useEllipsesIfTooBig);
  60148. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  60149. (float) x, (float) y,
  60150. (float) width, (float) height,
  60151. justificationType);
  60152. arr.draw (*this);
  60153. }
  60154. }
  60155. void Graphics::drawFittedText (const String& text,
  60156. const int x,
  60157. const int y,
  60158. const int width,
  60159. const int height,
  60160. const Justification& justification,
  60161. const int maximumNumberOfLines,
  60162. const float minimumHorizontalScale) const throw()
  60163. {
  60164. if (text.isNotEmpty()
  60165. && width > 0 && height > 0
  60166. && context->clipRegionIntersects (x, y, width, height))
  60167. {
  60168. GlyphArrangement arr;
  60169. arr.addFittedText (state->font, text,
  60170. (float) x, (float) y,
  60171. (float) width, (float) height,
  60172. justification,
  60173. maximumNumberOfLines,
  60174. minimumHorizontalScale);
  60175. arr.draw (*this);
  60176. }
  60177. }
  60178. void Graphics::fillRect (int x,
  60179. int y,
  60180. int width,
  60181. int height) const throw()
  60182. {
  60183. // passing in a silly number can cause maths problems in rendering!
  60184. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60185. SolidColourBrush colourBrush (state->colour);
  60186. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, width, height);
  60187. }
  60188. void Graphics::fillRect (const Rectangle& r) const throw()
  60189. {
  60190. fillRect (r.getX(),
  60191. r.getY(),
  60192. r.getWidth(),
  60193. r.getHeight());
  60194. }
  60195. void Graphics::fillRect (const float x,
  60196. const float y,
  60197. const float width,
  60198. const float height) const throw()
  60199. {
  60200. // passing in a silly number can cause maths problems in rendering!
  60201. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60202. Path p;
  60203. p.addRectangle (x, y, width, height);
  60204. fillPath (p);
  60205. }
  60206. void Graphics::setPixel (int x, int y) const throw()
  60207. {
  60208. if (context->clipRegionIntersects (x, y, 1, 1))
  60209. {
  60210. SolidColourBrush colourBrush (state->colour);
  60211. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, 1, 1);
  60212. }
  60213. }
  60214. void Graphics::fillAll() const throw()
  60215. {
  60216. fillRect (context->getClipBounds());
  60217. }
  60218. void Graphics::fillAll (const Colour& colourToUse) const throw()
  60219. {
  60220. if (! colourToUse.isTransparent())
  60221. {
  60222. const Rectangle clip (context->getClipBounds());
  60223. context->fillRectWithColour (clip.getX(), clip.getY(), clip.getWidth(), clip.getHeight(),
  60224. colourToUse, false);
  60225. }
  60226. }
  60227. void Graphics::fillPath (const Path& path,
  60228. const AffineTransform& transform) const throw()
  60229. {
  60230. if ((! context->isClipEmpty()) && ! path.isEmpty())
  60231. {
  60232. SolidColourBrush colourBrush (state->colour);
  60233. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintPath (*context, path, transform);
  60234. }
  60235. }
  60236. void Graphics::strokePath (const Path& path,
  60237. const PathStrokeType& strokeType,
  60238. const AffineTransform& transform) const throw()
  60239. {
  60240. if (! state->colour.isTransparent())
  60241. {
  60242. Path stroke;
  60243. strokeType.createStrokedPath (stroke, path, transform);
  60244. fillPath (stroke);
  60245. }
  60246. }
  60247. void Graphics::drawRect (const int x,
  60248. const int y,
  60249. const int width,
  60250. const int height,
  60251. const int lineThickness) const throw()
  60252. {
  60253. // passing in a silly number can cause maths problems in rendering!
  60254. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60255. SolidColourBrush colourBrush (state->colour);
  60256. Brush& b = (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush);
  60257. b.paintRectangle (*context, x, y, width, lineThickness);
  60258. b.paintRectangle (*context, x, y + lineThickness, lineThickness, height - lineThickness * 2);
  60259. b.paintRectangle (*context, x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2);
  60260. b.paintRectangle (*context, x, y + height - lineThickness, width, lineThickness);
  60261. }
  60262. void Graphics::drawRect (const float x,
  60263. const float y,
  60264. const float width,
  60265. const float height,
  60266. const float lineThickness) const throw()
  60267. {
  60268. // passing in a silly number can cause maths problems in rendering!
  60269. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60270. Path p;
  60271. p.addRectangle (x, y, width, lineThickness);
  60272. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  60273. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  60274. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  60275. fillPath (p);
  60276. }
  60277. void Graphics::drawRect (const Rectangle& r,
  60278. const int lineThickness) const throw()
  60279. {
  60280. drawRect (r.getX(), r.getY(),
  60281. r.getWidth(), r.getHeight(),
  60282. lineThickness);
  60283. }
  60284. void Graphics::drawBevel (const int x,
  60285. const int y,
  60286. const int width,
  60287. const int height,
  60288. const int bevelThickness,
  60289. const Colour& topLeftColour,
  60290. const Colour& bottomRightColour,
  60291. const bool useGradient) const throw()
  60292. {
  60293. // passing in a silly number can cause maths problems in rendering!
  60294. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60295. if (clipRegionIntersects (x, y, width, height))
  60296. {
  60297. const float oldOpacity = state->colour.getFloatAlpha();
  60298. const float ramp = oldOpacity / bevelThickness;
  60299. for (int i = bevelThickness; --i >= 0;)
  60300. {
  60301. const float op = useGradient ? ramp * (bevelThickness - i)
  60302. : oldOpacity;
  60303. context->fillRectWithColour (x + i, y + i, width - i * 2, 1, topLeftColour.withMultipliedAlpha (op), false);
  60304. context->fillRectWithColour (x + i, y + i + 1, 1, height - i * 2 - 2, topLeftColour.withMultipliedAlpha (op * 0.75f), false);
  60305. context->fillRectWithColour (x + i, y + height - i - 1, width - i * 2, 1, bottomRightColour.withMultipliedAlpha (op), false);
  60306. context->fillRectWithColour (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2, bottomRightColour.withMultipliedAlpha (op * 0.75f), false);
  60307. }
  60308. }
  60309. }
  60310. void Graphics::fillEllipse (const float x,
  60311. const float y,
  60312. const float width,
  60313. const float height) const throw()
  60314. {
  60315. // passing in a silly number can cause maths problems in rendering!
  60316. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60317. Path p;
  60318. p.addEllipse (x, y, width, height);
  60319. fillPath (p);
  60320. }
  60321. void Graphics::drawEllipse (const float x,
  60322. const float y,
  60323. const float width,
  60324. const float height,
  60325. const float lineThickness) const throw()
  60326. {
  60327. // passing in a silly number can cause maths problems in rendering!
  60328. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60329. Path p;
  60330. p.addEllipse (x, y, width, height);
  60331. strokePath (p, PathStrokeType (lineThickness));
  60332. }
  60333. void Graphics::fillRoundedRectangle (const float x,
  60334. const float y,
  60335. const float width,
  60336. const float height,
  60337. const float cornerSize) const throw()
  60338. {
  60339. // passing in a silly number can cause maths problems in rendering!
  60340. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60341. Path p;
  60342. p.addRoundedRectangle (x, y, width, height, cornerSize);
  60343. fillPath (p);
  60344. }
  60345. void Graphics::fillRoundedRectangle (const Rectangle& r,
  60346. const float cornerSize) const throw()
  60347. {
  60348. fillRoundedRectangle ((float) r.getX(),
  60349. (float) r.getY(),
  60350. (float) r.getWidth(),
  60351. (float) r.getHeight(),
  60352. cornerSize);
  60353. }
  60354. void Graphics::drawRoundedRectangle (const float x,
  60355. const float y,
  60356. const float width,
  60357. const float height,
  60358. const float cornerSize,
  60359. const float lineThickness) const throw()
  60360. {
  60361. // passing in a silly number can cause maths problems in rendering!
  60362. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60363. Path p;
  60364. p.addRoundedRectangle (x, y, width, height, cornerSize);
  60365. strokePath (p, PathStrokeType (lineThickness));
  60366. }
  60367. void Graphics::drawRoundedRectangle (const Rectangle& r,
  60368. const float cornerSize,
  60369. const float lineThickness) const throw()
  60370. {
  60371. drawRoundedRectangle ((float) r.getX(),
  60372. (float) r.getY(),
  60373. (float) r.getWidth(),
  60374. (float) r.getHeight(),
  60375. cornerSize, lineThickness);
  60376. }
  60377. void Graphics::drawArrow (const float startX,
  60378. const float startY,
  60379. const float endX,
  60380. const float endY,
  60381. const float lineThickness,
  60382. const float arrowheadWidth,
  60383. const float arrowheadLength) const throw()
  60384. {
  60385. Path p;
  60386. p.addArrow (startX, startY, endX, endY,
  60387. lineThickness, arrowheadWidth, arrowheadLength);
  60388. fillPath (p);
  60389. }
  60390. void Graphics::fillCheckerBoard (int x, int y,
  60391. int width, int height,
  60392. const int checkWidth,
  60393. const int checkHeight,
  60394. const Colour& colour1,
  60395. const Colour& colour2) const throw()
  60396. {
  60397. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  60398. if (checkWidth > 0 && checkHeight > 0)
  60399. {
  60400. if (colour1 == colour2)
  60401. {
  60402. context->fillRectWithColour (x, y, width, height, colour1, false);
  60403. }
  60404. else
  60405. {
  60406. const Rectangle clip (context->getClipBounds());
  60407. const int right = jmin (x + width, clip.getRight());
  60408. const int bottom = jmin (y + height, clip.getBottom());
  60409. int cy = 0;
  60410. while (y < bottom)
  60411. {
  60412. int cx = cy;
  60413. for (int xx = x; xx < right; xx += checkWidth)
  60414. context->fillRectWithColour (xx, y,
  60415. jmin (checkWidth, right - xx),
  60416. jmin (checkHeight, bottom - y),
  60417. ((cx++ & 1) == 0) ? colour1 : colour2,
  60418. false);
  60419. ++cy;
  60420. y += checkHeight;
  60421. }
  60422. }
  60423. }
  60424. }
  60425. void Graphics::drawVerticalLine (const int x, float top, float bottom) const throw()
  60426. {
  60427. SolidColourBrush colourBrush (state->colour);
  60428. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintVerticalLine (*context, x, top, bottom);
  60429. }
  60430. void Graphics::drawHorizontalLine (const int y, float left, float right) const throw()
  60431. {
  60432. SolidColourBrush colourBrush (state->colour);
  60433. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintHorizontalLine (*context, y, left, right);
  60434. }
  60435. void Graphics::drawLine (float x1, float y1,
  60436. float x2, float y2) const throw()
  60437. {
  60438. if (! context->isClipEmpty())
  60439. {
  60440. SolidColourBrush colourBrush (state->colour);
  60441. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintLine (*context, x1, y1, x2, y2);
  60442. }
  60443. }
  60444. void Graphics::drawLine (const float startX,
  60445. const float startY,
  60446. const float endX,
  60447. const float endY,
  60448. const float lineThickness) const throw()
  60449. {
  60450. Path p;
  60451. p.addLineSegment (startX, startY, endX, endY, lineThickness);
  60452. fillPath (p);
  60453. }
  60454. void Graphics::drawLine (const Line& line) const throw()
  60455. {
  60456. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  60457. }
  60458. void Graphics::drawLine (const Line& line,
  60459. const float lineThickness) const throw()
  60460. {
  60461. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), lineThickness);
  60462. }
  60463. void Graphics::drawDashedLine (const float startX,
  60464. const float startY,
  60465. const float endX,
  60466. const float endY,
  60467. const float* const dashLengths,
  60468. const int numDashLengths,
  60469. const float lineThickness) const throw()
  60470. {
  60471. const double dx = endX - startX;
  60472. const double dy = endY - startY;
  60473. const double totalLen = juce_hypot (dx, dy);
  60474. if (totalLen >= 0.5)
  60475. {
  60476. const double onePixAlpha = 1.0 / totalLen;
  60477. double alpha = 0.0;
  60478. float x = startX;
  60479. float y = startY;
  60480. int n = 0;
  60481. while (alpha < 1.0f)
  60482. {
  60483. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  60484. n = n % numDashLengths;
  60485. const float oldX = x;
  60486. const float oldY = y;
  60487. x = (float) (startX + dx * alpha);
  60488. y = (float) (startY + dy * alpha);
  60489. if ((n & 1) != 0)
  60490. {
  60491. if (lineThickness != 1.0f)
  60492. drawLine (oldX, oldY, x, y, lineThickness);
  60493. else
  60494. drawLine (oldX, oldY, x, y);
  60495. }
  60496. }
  60497. }
  60498. }
  60499. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality) throw()
  60500. {
  60501. saveStateIfPending();
  60502. state->quality = newQuality;
  60503. }
  60504. void Graphics::drawImageAt (const Image* const imageToDraw,
  60505. const int topLeftX,
  60506. const int topLeftY,
  60507. const bool fillAlphaChannelWithCurrentBrush) const throw()
  60508. {
  60509. if (imageToDraw != 0)
  60510. {
  60511. const int imageW = imageToDraw->getWidth();
  60512. const int imageH = imageToDraw->getHeight();
  60513. drawImage (imageToDraw,
  60514. topLeftX, topLeftY, imageW, imageH,
  60515. 0, 0, imageW, imageH,
  60516. fillAlphaChannelWithCurrentBrush);
  60517. }
  60518. }
  60519. void Graphics::drawImageWithin (const Image* const imageToDraw,
  60520. const int destX,
  60521. const int destY,
  60522. const int destW,
  60523. const int destH,
  60524. const RectanglePlacement& placementWithinTarget,
  60525. const bool fillAlphaChannelWithCurrentBrush) const throw()
  60526. {
  60527. // passing in a silly number can cause maths problems in rendering!
  60528. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (destX, destY, destW, destH);
  60529. if (imageToDraw != 0)
  60530. {
  60531. const int imageW = imageToDraw->getWidth();
  60532. const int imageH = imageToDraw->getHeight();
  60533. if (imageW > 0 && imageH > 0)
  60534. {
  60535. double newX = 0.0, newY = 0.0;
  60536. double newW = imageW;
  60537. double newH = imageH;
  60538. placementWithinTarget.applyTo (newX, newY, newW, newH,
  60539. destX, destY, destW, destH);
  60540. if (newW > 0 && newH > 0)
  60541. {
  60542. drawImage (imageToDraw,
  60543. roundDoubleToInt (newX), roundDoubleToInt (newY),
  60544. roundDoubleToInt (newW), roundDoubleToInt (newH),
  60545. 0, 0, imageW, imageH,
  60546. fillAlphaChannelWithCurrentBrush);
  60547. }
  60548. }
  60549. }
  60550. }
  60551. void Graphics::drawImage (const Image* const imageToDraw,
  60552. int dx, int dy, int dw, int dh,
  60553. int sx, int sy, int sw, int sh,
  60554. const bool fillAlphaChannelWithCurrentBrush) const throw()
  60555. {
  60556. // passing in a silly number can cause maths problems in rendering!
  60557. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (dx, dy, dw, dh);
  60558. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (sx, sy, sw, sh);
  60559. if (imageToDraw == 0 || ! context->clipRegionIntersects (dx, dy, dw, dh))
  60560. return;
  60561. if (sw == dw && sh == dh)
  60562. {
  60563. if (sx < 0)
  60564. {
  60565. dx -= sx;
  60566. dw += sx;
  60567. sw += sx;
  60568. sx = 0;
  60569. }
  60570. if (sx + sw > imageToDraw->getWidth())
  60571. {
  60572. const int amount = sx + sw - imageToDraw->getWidth();
  60573. dw -= amount;
  60574. sw -= amount;
  60575. }
  60576. if (sy < 0)
  60577. {
  60578. dy -= sy;
  60579. dh += sy;
  60580. sh += sy;
  60581. sy = 0;
  60582. }
  60583. if (sy + sh > imageToDraw->getHeight())
  60584. {
  60585. const int amount = sy + sh - imageToDraw->getHeight();
  60586. dh -= amount;
  60587. sh -= amount;
  60588. }
  60589. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  60590. return;
  60591. if (fillAlphaChannelWithCurrentBrush)
  60592. {
  60593. SolidColourBrush colourBrush (state->colour);
  60594. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  60595. .paintAlphaChannel (*context, *imageToDraw,
  60596. dx - sx, dy - sy,
  60597. dx, dy,
  60598. dw, dh);
  60599. }
  60600. else
  60601. {
  60602. context->blendImage (*imageToDraw,
  60603. dx, dy, dw, dh, sx, sy,
  60604. state->colour.getFloatAlpha());
  60605. }
  60606. }
  60607. else
  60608. {
  60609. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  60610. return;
  60611. if (fillAlphaChannelWithCurrentBrush)
  60612. {
  60613. if (imageToDraw->isRGB())
  60614. {
  60615. fillRect (dx, dy, dw, dh);
  60616. }
  60617. else
  60618. {
  60619. int tx = dx;
  60620. int ty = dy;
  60621. int tw = dw;
  60622. int th = dh;
  60623. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  60624. {
  60625. Image temp (imageToDraw->getFormat(), tw, th, true);
  60626. Graphics g (temp);
  60627. g.setImageResamplingQuality (state->quality);
  60628. g.setOrigin (dx - tx, dy - ty);
  60629. g.drawImage (imageToDraw,
  60630. 0, 0, dw, dh,
  60631. sx, sy, sw, sh,
  60632. false);
  60633. SolidColourBrush colourBrush (state->colour);
  60634. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  60635. .paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  60636. }
  60637. }
  60638. }
  60639. else
  60640. {
  60641. context->blendImageRescaling (*imageToDraw,
  60642. dx, dy, dw, dh,
  60643. sx, sy, sw, sh,
  60644. state->colour.getFloatAlpha(),
  60645. state->quality);
  60646. }
  60647. }
  60648. }
  60649. void Graphics::drawImageTransformed (const Image* const imageToDraw,
  60650. int sourceClipX,
  60651. int sourceClipY,
  60652. int sourceClipWidth,
  60653. int sourceClipHeight,
  60654. const AffineTransform& transform,
  60655. const bool fillAlphaChannelWithCurrentBrush) const throw()
  60656. {
  60657. if (imageToDraw != 0
  60658. && (! context->isClipEmpty())
  60659. && ! transform.isSingularity())
  60660. {
  60661. if (fillAlphaChannelWithCurrentBrush)
  60662. {
  60663. Path p;
  60664. p.addRectangle ((float) sourceClipX, (float) sourceClipY,
  60665. (float) sourceClipWidth, (float) sourceClipHeight);
  60666. p.applyTransform (transform);
  60667. float dx, dy, dw, dh;
  60668. p.getBounds (dx, dy, dw, dh);
  60669. int tx = (int) dx;
  60670. int ty = (int) dy;
  60671. int tw = roundFloatToInt (dw) + 2;
  60672. int th = roundFloatToInt (dh) + 2;
  60673. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  60674. {
  60675. Image temp (imageToDraw->getFormat(), tw, th, true);
  60676. Graphics g (temp);
  60677. g.setImageResamplingQuality (state->quality);
  60678. g.drawImageTransformed (imageToDraw,
  60679. sourceClipX,
  60680. sourceClipY,
  60681. sourceClipWidth,
  60682. sourceClipHeight,
  60683. transform.translated ((float) -tx, (float) -ty),
  60684. false);
  60685. SolidColourBrush colourBrush (state->colour);
  60686. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  60687. }
  60688. }
  60689. else
  60690. {
  60691. context->blendImageWarping (*imageToDraw,
  60692. sourceClipX,
  60693. sourceClipY,
  60694. sourceClipWidth,
  60695. sourceClipHeight,
  60696. transform,
  60697. state->colour.getFloatAlpha(),
  60698. state->quality);
  60699. }
  60700. }
  60701. }
  60702. END_JUCE_NAMESPACE
  60703. /********* End of inlined file: juce_Graphics.cpp *********/
  60704. /********* Start of inlined file: juce_Justification.cpp *********/
  60705. BEGIN_JUCE_NAMESPACE
  60706. Justification::Justification (const Justification& other) throw()
  60707. : flags (other.flags)
  60708. {
  60709. }
  60710. const Justification& Justification::operator= (const Justification& other) throw()
  60711. {
  60712. flags = other.flags;
  60713. return *this;
  60714. }
  60715. int Justification::getOnlyVerticalFlags() const throw()
  60716. {
  60717. return flags & (top | bottom | verticallyCentred);
  60718. }
  60719. int Justification::getOnlyHorizontalFlags() const throw()
  60720. {
  60721. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  60722. }
  60723. void Justification::applyToRectangle (int& x, int& y,
  60724. const int w, const int h,
  60725. const int spaceX, const int spaceY,
  60726. const int spaceW, const int spaceH) const throw()
  60727. {
  60728. if ((flags & horizontallyCentred) != 0)
  60729. {
  60730. x = spaceX + ((spaceW - w) >> 1);
  60731. }
  60732. else if ((flags & right) != 0)
  60733. {
  60734. x = spaceX + spaceW - w;
  60735. }
  60736. else
  60737. {
  60738. x = spaceX;
  60739. }
  60740. if ((flags & verticallyCentred) != 0)
  60741. {
  60742. y = spaceY + ((spaceH - h) >> 1);
  60743. }
  60744. else if ((flags & bottom) != 0)
  60745. {
  60746. y = spaceY + spaceH - h;
  60747. }
  60748. else
  60749. {
  60750. y = spaceY;
  60751. }
  60752. }
  60753. END_JUCE_NAMESPACE
  60754. /********* End of inlined file: juce_Justification.cpp *********/
  60755. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  60756. BEGIN_JUCE_NAMESPACE
  60757. #if JUCE_MSVC
  60758. #pragma warning (disable: 4996) // deprecated sprintf warning
  60759. #endif
  60760. // this will throw an assertion if you try to draw something that's not
  60761. // possible in postscript
  60762. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  60763. #if defined (JUCE_DEBUG) && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  60764. #define notPossibleInPostscriptAssert jassertfalse
  60765. #else
  60766. #define notPossibleInPostscriptAssert
  60767. #endif
  60768. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  60769. const String& documentTitle,
  60770. const int totalWidth_,
  60771. const int totalHeight_)
  60772. : out (resultingPostScript),
  60773. totalWidth (totalWidth_),
  60774. totalHeight (totalHeight_),
  60775. xOffset (0),
  60776. yOffset (0),
  60777. needToClip (true)
  60778. {
  60779. clip = new RectangleList (Rectangle (0, 0, totalWidth_, totalHeight_));
  60780. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  60781. out << "%!PS-Adobe-3.0 EPSF-3.0"
  60782. "\n%%BoundingBox: 0 0 600 824"
  60783. "\n%%Pages: 0"
  60784. "\n%%Creator: Raw Material Software JUCE"
  60785. "\n%%Title: " << documentTitle <<
  60786. "\n%%CreationDate: none"
  60787. "\n%%LanguageLevel: 2"
  60788. "\n%%EndComments"
  60789. "\n%%BeginProlog"
  60790. "\n%%BeginResource: JRes"
  60791. "\n/bd {bind def} bind def"
  60792. "\n/c {setrgbcolor} bd"
  60793. "\n/m {moveto} bd"
  60794. "\n/l {lineto} bd"
  60795. "\n/rl {rlineto} bd"
  60796. "\n/ct {curveto} bd"
  60797. "\n/cp {closepath} bd"
  60798. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  60799. "\n/doclip {initclip newpath} bd"
  60800. "\n/endclip {clip newpath} bd"
  60801. "\n%%EndResource"
  60802. "\n%%EndProlog"
  60803. "\n%%BeginSetup"
  60804. "\n%%EndSetup"
  60805. "\n%%Page: 1 1"
  60806. "\n%%BeginPageSetup"
  60807. "\n%%EndPageSetup\n\n"
  60808. << "40 800 translate\n"
  60809. << scale << ' ' << scale << " scale\n\n";
  60810. }
  60811. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  60812. {
  60813. delete clip;
  60814. }
  60815. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  60816. {
  60817. return true;
  60818. }
  60819. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  60820. {
  60821. if (x != 0 || y != 0)
  60822. {
  60823. xOffset += x;
  60824. yOffset += y;
  60825. needToClip = true;
  60826. }
  60827. }
  60828. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (int x, int y, int w, int h)
  60829. {
  60830. needToClip = true;
  60831. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  60832. }
  60833. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (const RectangleList& clipRegion)
  60834. {
  60835. needToClip = true;
  60836. return clip->clipTo (clipRegion);
  60837. }
  60838. void LowLevelGraphicsPostScriptRenderer::excludeClipRegion (int x, int y, int w, int h)
  60839. {
  60840. needToClip = true;
  60841. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  60842. }
  60843. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (int x, int y, int w, int h)
  60844. {
  60845. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  60846. }
  60847. const Rectangle LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  60848. {
  60849. return clip->getBounds().translated (-xOffset, -yOffset);
  60850. }
  60851. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  60852. {
  60853. return clip->isEmpty();
  60854. }
  60855. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState (RectangleList* const clip_,
  60856. const int xOffset_, const int yOffset_)
  60857. : clip (clip_),
  60858. xOffset (xOffset_),
  60859. yOffset (yOffset_)
  60860. {
  60861. }
  60862. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  60863. {
  60864. delete clip;
  60865. }
  60866. void LowLevelGraphicsPostScriptRenderer::saveState()
  60867. {
  60868. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  60869. }
  60870. void LowLevelGraphicsPostScriptRenderer::restoreState()
  60871. {
  60872. SavedState* const top = stateStack.getLast();
  60873. if (top != 0)
  60874. {
  60875. clip->swapWith (*top->clip);
  60876. xOffset = top->xOffset;
  60877. yOffset = top->yOffset;
  60878. stateStack.removeLast();
  60879. needToClip = true;
  60880. }
  60881. else
  60882. {
  60883. jassertfalse // trying to pop with an empty stack!
  60884. }
  60885. }
  60886. void LowLevelGraphicsPostScriptRenderer::writeClip()
  60887. {
  60888. if (needToClip)
  60889. {
  60890. needToClip = false;
  60891. out << "doclip ";
  60892. int itemsOnLine = 0;
  60893. for (RectangleList::Iterator i (*clip); i.next();)
  60894. {
  60895. if (++itemsOnLine == 6)
  60896. {
  60897. itemsOnLine = 0;
  60898. out << '\n';
  60899. }
  60900. const Rectangle& r = *i.getRectangle();
  60901. out << r.getX() << ' ' << -r.getY() << ' '
  60902. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  60903. }
  60904. out << "endclip\n";
  60905. }
  60906. }
  60907. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  60908. {
  60909. Colour c (Colours::white.overlaidWith (colour));
  60910. if (lastColour != c)
  60911. {
  60912. lastColour = c;
  60913. out << String (c.getFloatRed(), 3) << ' '
  60914. << String (c.getFloatGreen(), 3) << ' '
  60915. << String (c.getFloatBlue(), 3) << " c\n";
  60916. }
  60917. }
  60918. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  60919. {
  60920. out << String (x, 2) << ' '
  60921. << String (-y, 2) << ' ';
  60922. }
  60923. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  60924. {
  60925. out << "newpath ";
  60926. float lastX = 0.0f;
  60927. float lastY = 0.0f;
  60928. int itemsOnLine = 0;
  60929. Path::Iterator i (path);
  60930. while (i.next())
  60931. {
  60932. if (++itemsOnLine == 4)
  60933. {
  60934. itemsOnLine = 0;
  60935. out << '\n';
  60936. }
  60937. switch (i.elementType)
  60938. {
  60939. case Path::Iterator::startNewSubPath:
  60940. writeXY (i.x1, i.y1);
  60941. lastX = i.x1;
  60942. lastY = i.y1;
  60943. out << "m ";
  60944. break;
  60945. case Path::Iterator::lineTo:
  60946. writeXY (i.x1, i.y1);
  60947. lastX = i.x1;
  60948. lastY = i.y1;
  60949. out << "l ";
  60950. break;
  60951. case Path::Iterator::quadraticTo:
  60952. {
  60953. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  60954. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  60955. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  60956. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  60957. writeXY (cp1x, cp1y);
  60958. writeXY (cp2x, cp2y);
  60959. writeXY (i.x2, i.y2);
  60960. out << "ct ";
  60961. lastX = i.x2;
  60962. lastY = i.y2;
  60963. }
  60964. break;
  60965. case Path::Iterator::cubicTo:
  60966. writeXY (i.x1, i.y1);
  60967. writeXY (i.x2, i.y2);
  60968. writeXY (i.x3, i.y3);
  60969. out << "ct ";
  60970. lastX = i.x3;
  60971. lastY = i.y3;
  60972. break;
  60973. case Path::Iterator::closePath:
  60974. out << "cp ";
  60975. break;
  60976. default:
  60977. jassertfalse
  60978. break;
  60979. }
  60980. }
  60981. out << '\n';
  60982. }
  60983. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  60984. {
  60985. out << "[ "
  60986. << trans.mat00 << ' '
  60987. << trans.mat10 << ' '
  60988. << trans.mat01 << ' '
  60989. << trans.mat11 << ' '
  60990. << trans.mat02 << ' '
  60991. << trans.mat12 << " ] concat ";
  60992. }
  60993. void LowLevelGraphicsPostScriptRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool /*replaceExistingContents*/)
  60994. {
  60995. writeClip();
  60996. writeColour (colour);
  60997. x += xOffset;
  60998. y += yOffset;
  60999. out << x << ' ' << -(y + h) << ' ' << w << ' ' << h << " rectfill\n";
  61000. }
  61001. void LowLevelGraphicsPostScriptRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  61002. {
  61003. Path p;
  61004. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  61005. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_256times);
  61006. }
  61007. void LowLevelGraphicsPostScriptRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  61008. const Colour& colour, EdgeTable::OversamplingLevel /*quality*/)
  61009. {
  61010. writeClip();
  61011. Path p (path);
  61012. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  61013. writePath (p);
  61014. writeColour (colour);
  61015. out << "fill\n";
  61016. }
  61017. void LowLevelGraphicsPostScriptRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel /*quality*/)
  61018. {
  61019. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  61020. // postscript can't do semi-transparent ones.
  61021. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  61022. writeClip();
  61023. out << "gsave ";
  61024. {
  61025. Path p (path);
  61026. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  61027. writePath (p);
  61028. out << "clip\n";
  61029. }
  61030. int numColours = 256;
  61031. PixelARGB* const colours = gradient.createLookupTable (numColours);
  61032. for (int i = numColours; --i >= 0;)
  61033. colours[i].unpremultiply();
  61034. const Rectangle bounds (clip->getBounds());
  61035. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  61036. // time-being, this just fills it with the average colour..
  61037. writeColour (Colour (colours [numColours / 2].getARGB()));
  61038. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  61039. juce_free (colours);
  61040. out << "grestore\n";
  61041. }
  61042. void LowLevelGraphicsPostScriptRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  61043. const Image& sourceImage,
  61044. int imageX, int imageY,
  61045. float opacity, EdgeTable::OversamplingLevel /*quality*/)
  61046. {
  61047. writeClip();
  61048. out << "gsave ";
  61049. Path p (path);
  61050. p.applyTransform (transform.translated ((float) xOffset, (float) yOffset));
  61051. writePath (p);
  61052. out << "clip\n";
  61053. blendImage (sourceImage, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight(), 0, 0, opacity);
  61054. out << "grestore\n";
  61055. }
  61056. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithColour (const Image& /*clipImage*/, int x, int y, const Colour& colour)
  61057. {
  61058. x += xOffset;
  61059. y += yOffset;
  61060. writeClip();
  61061. writeColour (colour);
  61062. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  61063. }
  61064. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithGradient (const Image& /*alphaChannelImage*/, int imageX, int imageY, const ColourGradient& /*gradient*/)
  61065. {
  61066. imageX += xOffset;
  61067. imageY += yOffset;
  61068. writeClip();
  61069. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  61070. }
  61071. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithImage (const Image& /*alphaImage*/, int alphaImageX, int alphaImageY,
  61072. const Image& /*fillerImage*/, int fillerImageX, int fillerImageY, float /*opacity*/)
  61073. {
  61074. alphaImageX += xOffset;
  61075. alphaImageY += yOffset;
  61076. fillerImageX += xOffset;
  61077. fillerImageY += yOffset;
  61078. writeClip();
  61079. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  61080. }
  61081. void LowLevelGraphicsPostScriptRenderer::blendImageRescaling (const Image& sourceImage,
  61082. int dx, int dy, int dw, int dh,
  61083. int sx, int sy, int sw, int sh,
  61084. float alpha,
  61085. const Graphics::ResamplingQuality quality)
  61086. {
  61087. if (sw > 0 && sh > 0)
  61088. {
  61089. jassert (sx >= 0 && sx + sw <= sourceImage.getWidth());
  61090. jassert (sy >= 0 && sy + sh <= sourceImage.getHeight());
  61091. if (sw == dw && sh == dh)
  61092. {
  61093. blendImage (sourceImage,
  61094. dx, dy, dw, dh,
  61095. sx, sy, alpha);
  61096. }
  61097. else
  61098. {
  61099. blendImageWarping (sourceImage,
  61100. sx, sy, sw, sh,
  61101. AffineTransform::scale (dw / (float) sw,
  61102. dh / (float) sh)
  61103. .translated ((float) (dx - sx),
  61104. (float) (dy - sy)),
  61105. alpha,
  61106. quality);
  61107. }
  61108. }
  61109. }
  61110. void LowLevelGraphicsPostScriptRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  61111. {
  61112. blendImageWarping (sourceImage,
  61113. sx, sy, dw, dh,
  61114. AffineTransform::translation ((float) dx, (float) dy),
  61115. opacity, Graphics::highResamplingQuality);
  61116. }
  61117. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  61118. const int sx, const int sy,
  61119. const int maxW, const int maxH) const
  61120. {
  61121. out << "{<\n";
  61122. const int w = jmin (maxW, im.getWidth());
  61123. const int h = jmin (maxH, im.getHeight());
  61124. int charsOnLine = 0;
  61125. int lineStride, pixelStride;
  61126. const uint8* data = im.lockPixelDataReadOnly (0, 0, w, h, lineStride, pixelStride);
  61127. Colour pixel;
  61128. for (int y = h; --y >= 0;)
  61129. {
  61130. for (int x = 0; x < w; ++x)
  61131. {
  61132. const uint8* pixelData = data + lineStride * y + pixelStride * x;
  61133. if (x >= sx && y >= sy)
  61134. {
  61135. if (im.isARGB())
  61136. {
  61137. PixelARGB p (*(const PixelARGB*) pixelData);
  61138. p.unpremultiply();
  61139. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  61140. }
  61141. else if (im.isRGB())
  61142. {
  61143. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  61144. }
  61145. else
  61146. {
  61147. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  61148. }
  61149. }
  61150. else
  61151. {
  61152. pixel = Colours::transparentWhite;
  61153. }
  61154. char colourString [16];
  61155. sprintf (colourString, "%x%x%x", pixel.getRed(), pixel.getGreen(), pixel.getBlue());
  61156. out << (const char*) colourString;
  61157. charsOnLine += 3;
  61158. if (charsOnLine > 100)
  61159. {
  61160. out << '\n';
  61161. charsOnLine = 0;
  61162. }
  61163. }
  61164. }
  61165. im.releasePixelDataReadOnly (data);
  61166. out << "\n>}\n";
  61167. }
  61168. void LowLevelGraphicsPostScriptRenderer::blendImageWarping (const Image& sourceImage,
  61169. int srcClipX, int srcClipY,
  61170. int srcClipW, int srcClipH,
  61171. const AffineTransform& t,
  61172. float /*opacity*/,
  61173. const Graphics::ResamplingQuality /*quality*/)
  61174. {
  61175. const int w = jmin (sourceImage.getWidth(), srcClipX + srcClipW);
  61176. const int h = jmin (sourceImage.getHeight(), srcClipY + srcClipH);
  61177. writeClip();
  61178. out << "gsave ";
  61179. writeTransform (t.translated ((float) xOffset, (float) yOffset)
  61180. .scaled (1.0f, -1.0f));
  61181. RectangleList imageClip;
  61182. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  61183. imageClip.clipTo (Rectangle (srcClipX, srcClipY, srcClipW, srcClipH));
  61184. out << "newpath ";
  61185. int itemsOnLine = 0;
  61186. for (RectangleList::Iterator i (imageClip); i.next();)
  61187. {
  61188. if (++itemsOnLine == 6)
  61189. {
  61190. out << '\n';
  61191. itemsOnLine = 0;
  61192. }
  61193. const Rectangle& r = *i.getRectangle();
  61194. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  61195. }
  61196. out << " clip newpath\n";
  61197. out << w << ' ' << h << " scale\n";
  61198. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  61199. writeImage (sourceImage, srcClipX, srcClipY, srcClipW, srcClipH);
  61200. out << "false 3 colorimage grestore\n";
  61201. needToClip = true;
  61202. }
  61203. void LowLevelGraphicsPostScriptRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  61204. {
  61205. Path p;
  61206. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  61207. fillPathWithColour (p, AffineTransform::identity, colour, EdgeTable::Oversampling_256times);
  61208. }
  61209. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  61210. {
  61211. drawLine (x, top, x, bottom, col);
  61212. }
  61213. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  61214. {
  61215. drawLine (left, y, right, y, col);
  61216. }
  61217. END_JUCE_NAMESPACE
  61218. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  61219. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  61220. BEGIN_JUCE_NAMESPACE
  61221. #if ! (defined (JUCE_MAC) || (defined (JUCE_WIN32) && defined (JUCE_64BIT)))
  61222. #define JUCE_USE_SSE_INSTRUCTIONS 1
  61223. #endif
  61224. #if defined (JUCE_DEBUG) && JUCE_MSVC
  61225. #pragma warning (disable: 4714)
  61226. #endif
  61227. #define MINIMUM_COORD -0x3fffffff
  61228. #define MAXIMUM_COORD 0x3fffffff
  61229. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  61230. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  61231. jassert ((int) x >= MINIMUM_COORD \
  61232. && (int) x <= MAXIMUM_COORD \
  61233. && (int) y >= MINIMUM_COORD \
  61234. && (int) y <= MAXIMUM_COORD \
  61235. && (int) w >= 0 \
  61236. && (int) w < MAXIMUM_COORD \
  61237. && (int) h >= 0 \
  61238. && (int) h < MAXIMUM_COORD);
  61239. static void replaceRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  61240. {
  61241. const PixelARGB blendColour (colour.getPixelARGB());
  61242. if (w < 32)
  61243. {
  61244. while (--h >= 0)
  61245. {
  61246. PixelRGB* dest = (PixelRGB*) pixels;
  61247. for (int i = w; --i >= 0;)
  61248. (dest++)->set (blendColour);
  61249. pixels += stride;
  61250. }
  61251. }
  61252. else
  61253. {
  61254. // for wider fills, it's worth using some optimisations..
  61255. const uint8 r = blendColour.getRed();
  61256. const uint8 g = blendColour.getGreen();
  61257. const uint8 b = blendColour.getBlue();
  61258. if (r == g && r == b) // if all the component values are the same, we can cheat..
  61259. {
  61260. while (--h >= 0)
  61261. {
  61262. memset (pixels, r, w * 3);
  61263. pixels += stride;
  61264. }
  61265. }
  61266. else
  61267. {
  61268. PixelRGB filler [4];
  61269. filler[0].set (blendColour);
  61270. filler[1].set (blendColour);
  61271. filler[2].set (blendColour);
  61272. filler[3].set (blendColour);
  61273. const int* const intFiller = (const int*) filler;
  61274. while (--h >= 0)
  61275. {
  61276. uint8* dest = (uint8*) pixels;
  61277. int i = w;
  61278. while ((i > 8) && (((pointer_sized_int) dest & 7) != 0))
  61279. {
  61280. ((PixelRGB*) dest)->set (blendColour);
  61281. dest += 3;
  61282. --i;
  61283. }
  61284. while (i >= 4)
  61285. {
  61286. ((int*) dest) [0] = intFiller[0];
  61287. ((int*) dest) [1] = intFiller[1];
  61288. ((int*) dest) [2] = intFiller[2];
  61289. dest += 12;
  61290. i -= 4;
  61291. }
  61292. while (--i >= 0)
  61293. {
  61294. ((PixelRGB*) dest)->set (blendColour);
  61295. dest += 3;
  61296. }
  61297. pixels += stride;
  61298. }
  61299. }
  61300. }
  61301. }
  61302. static void replaceRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  61303. {
  61304. const PixelARGB blendColour (colour.getPixelARGB());
  61305. while (--h >= 0)
  61306. {
  61307. PixelARGB* const dest = (PixelARGB*) pixels;
  61308. for (int i = 0; i < w; ++i)
  61309. dest[i] = blendColour;
  61310. pixels += stride;
  61311. }
  61312. }
  61313. static void blendRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  61314. {
  61315. if (colour.isOpaque())
  61316. {
  61317. replaceRectRGB (pixels, w, h, stride, colour);
  61318. }
  61319. else
  61320. {
  61321. const PixelARGB blendColour (colour.getPixelARGB());
  61322. const int alpha = blendColour.getAlpha();
  61323. if (alpha <= 0)
  61324. return;
  61325. #if defined (JUCE_USE_SSE_INSTRUCTIONS) && ! JUCE_64BIT
  61326. if (SystemStats::hasSSE())
  61327. {
  61328. int64 rgb0 = (((int64) blendColour.getRed()) << 32)
  61329. | (int64) ((blendColour.getGreen() << 16)
  61330. | blendColour.getBlue());
  61331. const int invAlpha = 0xff - alpha;
  61332. int64 aaaa = (invAlpha << 16) | invAlpha;
  61333. aaaa = (aaaa << 16) | aaaa;
  61334. #ifndef JUCE_GCC
  61335. __asm
  61336. {
  61337. movq mm1, aaaa
  61338. movq mm2, rgb0
  61339. pxor mm7, mm7
  61340. }
  61341. while (--h >= 0)
  61342. {
  61343. __asm
  61344. {
  61345. mov edx, pixels
  61346. mov ebx, w
  61347. pixloop:
  61348. prefetchnta [edx]
  61349. mov ax, [edx + 1]
  61350. shl eax, 8
  61351. mov al, [edx]
  61352. movd mm0, eax
  61353. punpcklbw mm0, mm7
  61354. pmullw mm0, mm1
  61355. psrlw mm0, 8
  61356. paddw mm0, mm2
  61357. packuswb mm0, mm7
  61358. movd eax, mm0
  61359. mov [edx], al
  61360. inc edx
  61361. shr eax, 8
  61362. mov [edx], ax
  61363. add edx, 2
  61364. dec ebx
  61365. jg pixloop
  61366. }
  61367. pixels += stride;
  61368. }
  61369. __asm emms
  61370. #else
  61371. __asm__ __volatile__ (
  61372. "movq %[aaaa], %%mm1 \n"
  61373. "\tmovq %[rgb0], %%mm2 \n"
  61374. "\tpxor %%mm7, %%mm7 \n"
  61375. ".lineLoop2: \n"
  61376. "\tmovl %%esi,%%edx \n"
  61377. "\tmovl %[w], %%ebx \n"
  61378. ".pixLoop2: \n"
  61379. "\tprefetchnta (%%edx) \n"
  61380. "\tmov (%%edx), %%ax \n"
  61381. "\tshl $8, %%eax \n"
  61382. "\tmov 2(%%edx), %%al \n"
  61383. "\tmovd %%eax, %%mm0 \n"
  61384. "\tpunpcklbw %%mm7, %%mm0 \n"
  61385. "\tpmullw %%mm1, %%mm0 \n"
  61386. "\tpsrlw $8, %%mm0 \n"
  61387. "\tpaddw %%mm2, %%mm0 \n"
  61388. "\tpackuswb %%mm7, %%mm0 \n"
  61389. "\tmovd %%mm0, %%eax \n"
  61390. "\tmovb %%al, (%%edx) \n"
  61391. "\tinc %%edx \n"
  61392. "\tshr $8, %%eax \n"
  61393. "\tmovw %%ax, (%%edx) \n"
  61394. "\tadd $2, %%edx \n"
  61395. "\tdec %%ebx \n"
  61396. "\tjg .pixLoop2 \n"
  61397. "\tadd %%edi, %%esi \n"
  61398. "\tdec %%ecx \n"
  61399. "\tjg .lineLoop2 \n"
  61400. "\temms \n"
  61401. : /* No output registers */
  61402. : [aaaa] "m" (aaaa), /* Input registers */
  61403. [rgb0] "m" (rgb0),
  61404. [w] "m" (w),
  61405. "c" (h),
  61406. [stride] "D" (stride),
  61407. [pixels] "S" (pixels)
  61408. : "cc", "eax", "edx", "memory" /* Clobber list */
  61409. );
  61410. #endif
  61411. }
  61412. else
  61413. #endif
  61414. {
  61415. while (--h >= 0)
  61416. {
  61417. PixelRGB* dest = (PixelRGB*) pixels;
  61418. for (int i = w; --i >= 0;)
  61419. (dest++)->blend (blendColour);
  61420. pixels += stride;
  61421. }
  61422. }
  61423. }
  61424. }
  61425. static void blendRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  61426. {
  61427. if (colour.isOpaque())
  61428. {
  61429. replaceRectARGB (pixels, w, h, stride, colour);
  61430. }
  61431. else
  61432. {
  61433. const PixelARGB blendColour (colour.getPixelARGB());
  61434. const int alpha = blendColour.getAlpha();
  61435. if (alpha <= 0)
  61436. return;
  61437. while (--h >= 0)
  61438. {
  61439. PixelARGB* dest = (PixelARGB*) pixels;
  61440. for (int i = w; --i >= 0;)
  61441. (dest++)->blend (blendColour);
  61442. pixels += stride;
  61443. }
  61444. }
  61445. }
  61446. static void blendAlphaMapARGB (uint8* destPixel, const int imageStride,
  61447. const uint8* alphaValues, const int w, int h,
  61448. const int pixelStride, const int lineStride,
  61449. const Colour& colour) throw()
  61450. {
  61451. const PixelARGB srcPix (colour.getPixelARGB());
  61452. while (--h >= 0)
  61453. {
  61454. PixelARGB* dest = (PixelARGB*) destPixel;
  61455. const uint8* src = alphaValues;
  61456. int i = w;
  61457. while (--i >= 0)
  61458. {
  61459. unsigned int srcAlpha = *src;
  61460. src += pixelStride;
  61461. if (srcAlpha > 0)
  61462. dest->blend (srcPix, srcAlpha);
  61463. ++dest;
  61464. }
  61465. alphaValues += lineStride;
  61466. destPixel += imageStride;
  61467. }
  61468. }
  61469. static void blendAlphaMapRGB (uint8* destPixel, const int imageStride,
  61470. const uint8* alphaValues, int const width, int height,
  61471. const int pixelStride, const int lineStride,
  61472. const Colour& colour) throw()
  61473. {
  61474. const PixelARGB srcPix (colour.getPixelARGB());
  61475. while (--height >= 0)
  61476. {
  61477. PixelRGB* dest = (PixelRGB*) destPixel;
  61478. const uint8* src = alphaValues;
  61479. int i = width;
  61480. while (--i >= 0)
  61481. {
  61482. unsigned int srcAlpha = *src;
  61483. src += pixelStride;
  61484. if (srcAlpha > 0)
  61485. dest->blend (srcPix, srcAlpha);
  61486. ++dest;
  61487. }
  61488. alphaValues += lineStride;
  61489. destPixel += imageStride;
  61490. }
  61491. }
  61492. template <class PixelType>
  61493. class SolidColourEdgeTableRenderer
  61494. {
  61495. uint8* const data;
  61496. const int stride;
  61497. PixelType* linePixels;
  61498. PixelARGB sourceColour;
  61499. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  61500. const SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  61501. public:
  61502. SolidColourEdgeTableRenderer (uint8* const data_,
  61503. const int stride_,
  61504. const Colour& colour) throw()
  61505. : data (data_),
  61506. stride (stride_),
  61507. sourceColour (colour.getPixelARGB())
  61508. {
  61509. }
  61510. forcedinline void setEdgeTableYPos (const int y) throw()
  61511. {
  61512. linePixels = (PixelType*) (data + stride * y);
  61513. }
  61514. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  61515. {
  61516. linePixels[x].blend (sourceColour, alphaLevel);
  61517. }
  61518. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  61519. {
  61520. PixelARGB p (sourceColour);
  61521. p.multiplyAlpha (alphaLevel);
  61522. PixelType* dest = linePixels + x;
  61523. if (p.getAlpha() < 0xff)
  61524. {
  61525. do
  61526. {
  61527. dest->blend (p);
  61528. ++dest;
  61529. } while (--width > 0);
  61530. }
  61531. else
  61532. {
  61533. do
  61534. {
  61535. dest->set (p);
  61536. ++dest;
  61537. } while (--width > 0);
  61538. }
  61539. }
  61540. };
  61541. class AlphaBitmapRenderer
  61542. {
  61543. uint8* data;
  61544. int stride;
  61545. uint8* lineStart;
  61546. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  61547. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  61548. public:
  61549. AlphaBitmapRenderer (uint8* const data_,
  61550. const int stride_) throw()
  61551. : data (data_),
  61552. stride (stride_)
  61553. {
  61554. }
  61555. forcedinline void setEdgeTableYPos (const int y) throw()
  61556. {
  61557. lineStart = data + (stride * y);
  61558. }
  61559. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  61560. {
  61561. lineStart [x] = (uint8) alphaLevel;
  61562. }
  61563. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  61564. {
  61565. uint8* d = lineStart + x;
  61566. while (--width >= 0)
  61567. *d++ = (uint8) alphaLevel;
  61568. }
  61569. };
  61570. static const int numScaleBits = 12;
  61571. class LinearGradientPixelGenerator
  61572. {
  61573. const PixelARGB* const lookupTable;
  61574. const int numEntries;
  61575. PixelARGB linePix;
  61576. int start, scale;
  61577. double grad, yTerm;
  61578. bool vertical, horizontal;
  61579. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  61580. const LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  61581. public:
  61582. LinearGradientPixelGenerator (const ColourGradient& gradient,
  61583. const PixelARGB* const lookupTable_, const int numEntries_)
  61584. : lookupTable (lookupTable_),
  61585. numEntries (numEntries_)
  61586. {
  61587. jassert (numEntries_ >= 0);
  61588. float x1 = gradient.x1;
  61589. float y1 = gradient.y1;
  61590. float x2 = gradient.x2;
  61591. float y2 = gradient.y2;
  61592. if (! gradient.transform.isIdentity())
  61593. {
  61594. Line l (x2, y2, x1, y1);
  61595. const Point p3 = l.getPointAlongLine (0.0, 100.0f);
  61596. float x3 = p3.getX();
  61597. float y3 = p3.getY();
  61598. gradient.transform.transformPoint (x1, y1);
  61599. gradient.transform.transformPoint (x2, y2);
  61600. gradient.transform.transformPoint (x3, y3);
  61601. Line l2 (x2, y2, x3, y3);
  61602. float prop = l2.findNearestPointTo (x1, y1);
  61603. const Point newP2 (l2.getPointAlongLineProportionally (prop));
  61604. x2 = newP2.getX();
  61605. y2 = newP2.getY();
  61606. }
  61607. vertical = fabs (x1 - x2) < 0.001f;
  61608. horizontal = fabs (y1 - y2) < 0.001f;
  61609. if (vertical)
  61610. {
  61611. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (y2 - y1));
  61612. start = roundDoubleToInt (y1 * scale);
  61613. }
  61614. else if (horizontal)
  61615. {
  61616. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (x2 - x1));
  61617. start = roundDoubleToInt (x1 * scale);
  61618. }
  61619. else
  61620. {
  61621. grad = (y2 - y1) / (double) (x1 - x2);
  61622. yTerm = y1 - x1 / grad;
  61623. scale = roundDoubleToInt ((numEntries << numScaleBits) / (yTerm * grad - (y2 * grad - x2)));
  61624. grad *= scale;
  61625. }
  61626. }
  61627. forcedinline void setY (const int y) throw()
  61628. {
  61629. if (vertical)
  61630. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> numScaleBits)];
  61631. else if (! horizontal)
  61632. start = roundDoubleToInt ((y - yTerm) * grad);
  61633. }
  61634. forcedinline const PixelARGB getPixel (const int x) const throw()
  61635. {
  61636. if (vertical)
  61637. return linePix;
  61638. return lookupTable [jlimit (0, numEntries, (x * scale - start) >> numScaleBits)];
  61639. }
  61640. };
  61641. class RadialGradientPixelGenerator
  61642. {
  61643. protected:
  61644. const PixelARGB* const lookupTable;
  61645. const int numEntries;
  61646. const double gx1, gy1;
  61647. double maxDist, invScale;
  61648. double dy;
  61649. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  61650. const RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  61651. public:
  61652. RadialGradientPixelGenerator (const ColourGradient& gradient,
  61653. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  61654. : lookupTable (lookupTable_),
  61655. numEntries (numEntries_),
  61656. gx1 (gradient.x1),
  61657. gy1 (gradient.y1)
  61658. {
  61659. jassert (numEntries_ >= 0);
  61660. const float dx = gradient.x1 - gradient.x2;
  61661. const float dy = gradient.y1 - gradient.y2;
  61662. maxDist = dx * dx + dy * dy;
  61663. invScale = (numEntries + 1) / sqrt (maxDist);
  61664. }
  61665. forcedinline void setY (const int y) throw()
  61666. {
  61667. dy = y - gy1;
  61668. dy *= dy;
  61669. }
  61670. forcedinline const PixelARGB getPixel (const int px) const throw()
  61671. {
  61672. double x = px - gx1;
  61673. x *= x;
  61674. x += dy;
  61675. if (x >= maxDist)
  61676. return lookupTable [numEntries];
  61677. else
  61678. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  61679. }
  61680. };
  61681. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  61682. {
  61683. double tM10, tM00, lineYM01, lineYM11;
  61684. AffineTransform inverseTransform;
  61685. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  61686. const TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  61687. public:
  61688. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient,
  61689. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  61690. : RadialGradientPixelGenerator (gradient, lookupTable_, numEntries_),
  61691. inverseTransform (gradient.transform.inverted())
  61692. {
  61693. tM10 = inverseTransform.mat10;
  61694. tM00 = inverseTransform.mat00;
  61695. }
  61696. forcedinline void setY (const int y) throw()
  61697. {
  61698. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  61699. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  61700. }
  61701. forcedinline const PixelARGB getPixel (const int px) const throw()
  61702. {
  61703. double x = px;
  61704. const double y = tM10 * x + lineYM11;
  61705. x = tM00 * x + lineYM01;
  61706. x *= x;
  61707. x += y * y;
  61708. if (x >= maxDist)
  61709. return lookupTable [numEntries];
  61710. else
  61711. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  61712. }
  61713. };
  61714. template <class PixelType, class GradientType>
  61715. class GradientEdgeTableRenderer : public GradientType
  61716. {
  61717. uint8* const data;
  61718. const int stride;
  61719. PixelType* linePixels;
  61720. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  61721. const GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  61722. public:
  61723. GradientEdgeTableRenderer (uint8* const data_,
  61724. const int stride_,
  61725. const ColourGradient& gradient,
  61726. const PixelARGB* const lookupTable, const int numEntries) throw()
  61727. : GradientType (gradient, lookupTable, numEntries - 1),
  61728. data (data_),
  61729. stride (stride_)
  61730. {
  61731. }
  61732. forcedinline void setEdgeTableYPos (const int y) throw()
  61733. {
  61734. linePixels = (PixelType*) (data + stride * y);
  61735. GradientType::setY (y);
  61736. }
  61737. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  61738. {
  61739. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  61740. }
  61741. forcedinline void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  61742. {
  61743. PixelType* dest = linePixels + x;
  61744. if (alphaLevel < 0xff)
  61745. {
  61746. do
  61747. {
  61748. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  61749. } while (--width > 0);
  61750. }
  61751. else
  61752. {
  61753. do
  61754. {
  61755. (dest++)->blend (GradientType::getPixel (x++));
  61756. } while (--width > 0);
  61757. }
  61758. }
  61759. };
  61760. template <class DestPixelType, class SrcPixelType>
  61761. class ImageFillEdgeTableRenderer
  61762. {
  61763. uint8* const destImageData;
  61764. const uint8* srcImageData;
  61765. int stride, srcStride, extraAlpha;
  61766. DestPixelType* linePixels;
  61767. SrcPixelType* sourceLineStart;
  61768. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  61769. const ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  61770. public:
  61771. ImageFillEdgeTableRenderer (uint8* const destImageData_,
  61772. const int stride_,
  61773. const uint8* srcImageData_,
  61774. const int srcStride_,
  61775. int extraAlpha_,
  61776. SrcPixelType*) throw() // dummy param to avoid compiler error
  61777. : destImageData (destImageData_),
  61778. srcImageData (srcImageData_),
  61779. stride (stride_),
  61780. srcStride (srcStride_),
  61781. extraAlpha (extraAlpha_)
  61782. {
  61783. }
  61784. forcedinline void setEdgeTableYPos (int y) throw()
  61785. {
  61786. linePixels = (DestPixelType*) (destImageData + stride * y);
  61787. sourceLineStart = (SrcPixelType*) (srcImageData + srcStride * y);
  61788. }
  61789. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  61790. {
  61791. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  61792. linePixels[x].blend (sourceLineStart [x], alphaLevel);
  61793. }
  61794. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  61795. {
  61796. DestPixelType* dest = linePixels + x;
  61797. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  61798. if (alphaLevel < 0xfe)
  61799. {
  61800. do
  61801. {
  61802. dest++ ->blend (sourceLineStart [x++], alphaLevel);
  61803. } while (--width > 0);
  61804. }
  61805. else
  61806. {
  61807. do
  61808. {
  61809. dest++ ->blend (sourceLineStart [x++]);
  61810. } while (--width > 0);
  61811. }
  61812. }
  61813. };
  61814. static void blendRowOfPixels (PixelARGB* dst,
  61815. const PixelRGB* src,
  61816. int width) throw()
  61817. {
  61818. while (--width >= 0)
  61819. (dst++)->set (*src++);
  61820. }
  61821. static void blendRowOfPixels (PixelRGB* dst,
  61822. const PixelRGB* src,
  61823. int width) throw()
  61824. {
  61825. memcpy (dst, src, 3 * width);
  61826. }
  61827. static void blendRowOfPixels (PixelRGB* dst,
  61828. const PixelARGB* src,
  61829. int width) throw()
  61830. {
  61831. while (--width >= 0)
  61832. (dst++)->blend (*src++);
  61833. }
  61834. static void blendRowOfPixels (PixelARGB* dst,
  61835. const PixelARGB* src,
  61836. int width) throw()
  61837. {
  61838. while (--width >= 0)
  61839. (dst++)->blend (*src++);
  61840. }
  61841. static void blendRowOfPixels (PixelARGB* dst,
  61842. const PixelRGB* src,
  61843. int width,
  61844. const uint8 alpha) throw()
  61845. {
  61846. while (--width >= 0)
  61847. (dst++)->blend (*src++, alpha);
  61848. }
  61849. static void blendRowOfPixels (PixelRGB* dst,
  61850. const PixelRGB* src,
  61851. int width,
  61852. const uint8 alpha) throw()
  61853. {
  61854. uint8* d = (uint8*) dst;
  61855. const uint8* s = (const uint8*) src;
  61856. const int inverseAlpha = 0xff - alpha;
  61857. while (--width >= 0)
  61858. {
  61859. d[0] = (uint8) (s[0] + (((d[0] - s[0]) * inverseAlpha) >> 8));
  61860. d[1] = (uint8) (s[1] + (((d[1] - s[1]) * inverseAlpha) >> 8));
  61861. d[2] = (uint8) (s[2] + (((d[2] - s[2]) * inverseAlpha) >> 8));
  61862. d += 3;
  61863. s += 3;
  61864. }
  61865. }
  61866. static void blendRowOfPixels (PixelRGB* dst,
  61867. const PixelARGB* src,
  61868. int width,
  61869. const uint8 alpha) throw()
  61870. {
  61871. while (--width >= 0)
  61872. (dst++)->blend (*src++, alpha);
  61873. }
  61874. static void blendRowOfPixels (PixelARGB* dst,
  61875. const PixelARGB* src,
  61876. int width,
  61877. const uint8 alpha) throw()
  61878. {
  61879. while (--width >= 0)
  61880. (dst++)->blend (*src++, alpha);
  61881. }
  61882. template <class DestPixelType, class SrcPixelType>
  61883. static void overlayImage (DestPixelType* dest,
  61884. const int destStride,
  61885. const SrcPixelType* src,
  61886. const int srcStride,
  61887. const int width,
  61888. int height,
  61889. const uint8 alpha) throw()
  61890. {
  61891. if (alpha < 0xff)
  61892. {
  61893. while (--height >= 0)
  61894. {
  61895. blendRowOfPixels (dest, src, width, alpha);
  61896. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  61897. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  61898. }
  61899. }
  61900. else
  61901. {
  61902. while (--height >= 0)
  61903. {
  61904. blendRowOfPixels (dest, src, width);
  61905. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  61906. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  61907. }
  61908. }
  61909. }
  61910. template <class DestPixelType, class SrcPixelType>
  61911. static void transformedImageRender (Image& destImage,
  61912. const Image& sourceImage,
  61913. const int destClipX, const int destClipY,
  61914. const int destClipW, const int destClipH,
  61915. const int srcClipX, const int srcClipY,
  61916. const int srcClipWidth, const int srcClipHeight,
  61917. double srcX, double srcY,
  61918. const double lineDX, const double lineDY,
  61919. const double pixelDX, const double pixelDY,
  61920. const uint8 alpha,
  61921. const Graphics::ResamplingQuality quality,
  61922. DestPixelType*,
  61923. SrcPixelType*) throw() // forced by a compiler bug to include dummy
  61924. // parameters of the templated classes to
  61925. // make it use the correct instance of this function..
  61926. {
  61927. int destStride, destPixelStride;
  61928. uint8* const destPixels = destImage.lockPixelDataReadWrite (destClipX, destClipY, destClipW, destClipH, destStride, destPixelStride);
  61929. int srcStride, srcPixelStride;
  61930. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (srcClipX, srcClipY, srcClipWidth, srcClipHeight, srcStride, srcPixelStride);
  61931. if (quality == Graphics::lowResamplingQuality) // nearest-neighbour..
  61932. {
  61933. for (int y = 0; y < destClipH; ++y)
  61934. {
  61935. double sx = srcX;
  61936. double sy = srcY;
  61937. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  61938. for (int x = 0; x < destClipW; ++x)
  61939. {
  61940. const int ix = roundDoubleToInt (floor (sx)) - srcClipX;
  61941. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  61942. {
  61943. const int iy = roundDoubleToInt (floor (sy)) - srcClipY;
  61944. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  61945. {
  61946. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  61947. dest->blend (*src, alpha);
  61948. }
  61949. }
  61950. ++dest;
  61951. sx += pixelDX;
  61952. sy += pixelDY;
  61953. }
  61954. srcX += lineDX;
  61955. srcY += lineDY;
  61956. }
  61957. }
  61958. else
  61959. {
  61960. jassert (quality == Graphics::mediumResamplingQuality); // (only bilinear is implemented, so that's what you'll get here..)
  61961. for (int y = 0; y < destClipH; ++y)
  61962. {
  61963. double sx = srcX;
  61964. double sy = srcY;
  61965. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  61966. for (int x = 0; x < destClipW; ++x)
  61967. {
  61968. const double fx = floor (sx);
  61969. const double fy = floor (sy);
  61970. const int ix = roundDoubleToInt (fx) - srcClipX;
  61971. const int iy = roundDoubleToInt (fy) - srcClipY;
  61972. if (ix < srcClipWidth && iy < srcClipHeight)
  61973. {
  61974. PixelARGB p1 (0), p2 (0), p3 (0), p4 (0);
  61975. const SrcPixelType* src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  61976. if (iy >= 0)
  61977. {
  61978. if (ix >= 0)
  61979. p1.set (src[0]);
  61980. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  61981. p2.set (src[1]);
  61982. }
  61983. if (((unsigned int) (iy + 1)) < (unsigned int) srcClipHeight)
  61984. {
  61985. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  61986. if (ix >= 0)
  61987. p3.set (src[0]);
  61988. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  61989. p4.set (src[1]);
  61990. }
  61991. const int dx = roundDoubleToInt ((sx - fx) * 255.0);
  61992. p1.tween (p2, dx);
  61993. p3.tween (p4, dx);
  61994. p1.tween (p3, roundDoubleToInt ((sy - fy) * 255.0));
  61995. if (p1.getAlpha() > 0)
  61996. dest->blend (p1, alpha);
  61997. }
  61998. ++dest;
  61999. sx += pixelDX;
  62000. sy += pixelDY;
  62001. }
  62002. srcX += lineDX;
  62003. srcY += lineDY;
  62004. }
  62005. }
  62006. destImage.releasePixelDataReadWrite (destPixels);
  62007. sourceImage.releasePixelDataReadOnly (srcPixels);
  62008. }
  62009. template <class SrcPixelType, class DestPixelType>
  62010. static void renderAlphaMap (DestPixelType* destPixels,
  62011. int destStride,
  62012. SrcPixelType* srcPixels,
  62013. int srcStride,
  62014. const uint8* alphaValues,
  62015. const int lineStride, const int pixelStride,
  62016. int width, int height,
  62017. const int extraAlpha) throw()
  62018. {
  62019. while (--height >= 0)
  62020. {
  62021. SrcPixelType* srcPix = srcPixels;
  62022. srcPixels = (SrcPixelType*) (((const uint8*) srcPixels) + srcStride);
  62023. DestPixelType* destPix = destPixels;
  62024. destPixels = (DestPixelType*) (((uint8*) destPixels) + destStride);
  62025. const uint8* alpha = alphaValues;
  62026. alphaValues += lineStride;
  62027. if (extraAlpha < 0x100)
  62028. {
  62029. for (int i = width; --i >= 0;)
  62030. {
  62031. destPix++ ->blend (*srcPix++, (extraAlpha * *alpha) >> 8);
  62032. alpha += pixelStride;
  62033. }
  62034. }
  62035. else
  62036. {
  62037. for (int i = width; --i >= 0;)
  62038. {
  62039. destPix++ ->blend (*srcPix++, *alpha);
  62040. alpha += pixelStride;
  62041. }
  62042. }
  62043. }
  62044. }
  62045. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_)
  62046. : image (image_),
  62047. xOffset (0),
  62048. yOffset (0),
  62049. stateStack (20)
  62050. {
  62051. clip = new RectangleList (Rectangle (0, 0, image_.getWidth(), image_.getHeight()));
  62052. }
  62053. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  62054. {
  62055. delete clip;
  62056. }
  62057. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  62058. {
  62059. return false;
  62060. }
  62061. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  62062. {
  62063. xOffset += x;
  62064. yOffset += y;
  62065. }
  62066. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (int x, int y, int w, int h)
  62067. {
  62068. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  62069. }
  62070. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (const RectangleList& clipRegion)
  62071. {
  62072. RectangleList temp (clipRegion);
  62073. temp.offsetAll (xOffset, yOffset);
  62074. return clip->clipTo (temp);
  62075. }
  62076. void LowLevelGraphicsSoftwareRenderer::excludeClipRegion (int x, int y, int w, int h)
  62077. {
  62078. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  62079. }
  62080. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (int x, int y, int w, int h)
  62081. {
  62082. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  62083. }
  62084. const Rectangle LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  62085. {
  62086. return clip->getBounds().translated (-xOffset, -yOffset);
  62087. }
  62088. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  62089. {
  62090. return clip->isEmpty();
  62091. }
  62092. LowLevelGraphicsSoftwareRenderer::SavedState::SavedState (RectangleList* const clip_,
  62093. const int xOffset_, const int yOffset_)
  62094. : clip (clip_),
  62095. xOffset (xOffset_),
  62096. yOffset (yOffset_)
  62097. {
  62098. }
  62099. LowLevelGraphicsSoftwareRenderer::SavedState::~SavedState()
  62100. {
  62101. delete clip;
  62102. }
  62103. void LowLevelGraphicsSoftwareRenderer::saveState()
  62104. {
  62105. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  62106. }
  62107. void LowLevelGraphicsSoftwareRenderer::restoreState()
  62108. {
  62109. SavedState* const top = stateStack.getLast();
  62110. if (top != 0)
  62111. {
  62112. clip->swapWith (*top->clip);
  62113. xOffset = top->xOffset;
  62114. yOffset = top->yOffset;
  62115. stateStack.removeLast();
  62116. }
  62117. else
  62118. {
  62119. jassertfalse // trying to pop with an empty stack!
  62120. }
  62121. }
  62122. void LowLevelGraphicsSoftwareRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  62123. {
  62124. x += xOffset;
  62125. y += yOffset;
  62126. for (RectangleList::Iterator i (*clip); i.next();)
  62127. {
  62128. clippedFillRectWithColour (*i.getRectangle(), x, y, w, h, colour, replaceExistingContents);
  62129. }
  62130. }
  62131. void LowLevelGraphicsSoftwareRenderer::clippedFillRectWithColour (const Rectangle& clipRect,
  62132. int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  62133. {
  62134. if (clipRect.intersectRectangle (x, y, w, h))
  62135. {
  62136. int stride, pixelStride;
  62137. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  62138. if (image.getFormat() == Image::RGB)
  62139. {
  62140. if (replaceExistingContents)
  62141. replaceRectRGB (pixels, w, h, stride, colour);
  62142. else
  62143. blendRectRGB (pixels, w, h, stride, colour);
  62144. }
  62145. else if (image.getFormat() == Image::ARGB)
  62146. {
  62147. if (replaceExistingContents)
  62148. replaceRectARGB (pixels, w, h, stride, colour);
  62149. else
  62150. blendRectARGB (pixels, w, h, stride, colour);
  62151. }
  62152. else
  62153. {
  62154. jassertfalse // not done!
  62155. }
  62156. image.releasePixelDataReadWrite (pixels);
  62157. }
  62158. }
  62159. void LowLevelGraphicsSoftwareRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  62160. {
  62161. Path p;
  62162. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  62163. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_none);
  62164. }
  62165. bool LowLevelGraphicsSoftwareRenderer::getPathBounds (int clipX, int clipY, int clipW, int clipH,
  62166. const Path& path, const AffineTransform& transform,
  62167. int& x, int& y, int& w, int& h) const
  62168. {
  62169. float tx, ty, tw, th;
  62170. path.getBoundsTransformed (transform, tx, ty, tw, th);
  62171. x = roundDoubleToInt (tx) - 1;
  62172. y = roundDoubleToInt (ty) - 1;
  62173. w = roundDoubleToInt (tw) + 2;
  62174. h = roundDoubleToInt (th) + 2;
  62175. // seems like this operation is using some crazy out-of-range numbers..
  62176. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, w, h);
  62177. return Rectangle::intersectRectangles (x, y, w, h, clipX, clipY, clipW, clipH);
  62178. }
  62179. void LowLevelGraphicsSoftwareRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  62180. const Colour& colour, EdgeTable::OversamplingLevel quality)
  62181. {
  62182. for (RectangleList::Iterator i (*clip); i.next();)
  62183. {
  62184. const Rectangle& r = *i.getRectangle();
  62185. clippedFillPathWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(), path, t, colour, quality);
  62186. }
  62187. }
  62188. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  62189. const Colour& colour, EdgeTable::OversamplingLevel quality)
  62190. {
  62191. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  62192. int cx, cy, cw, ch;
  62193. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  62194. {
  62195. EdgeTable edgeTable (0, ch, quality);
  62196. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  62197. int stride, pixelStride;
  62198. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  62199. if (image.getFormat() == Image::RGB)
  62200. {
  62201. jassert (pixelStride == 3);
  62202. SolidColourEdgeTableRenderer <PixelRGB> renderer (pixels, stride, colour);
  62203. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62204. }
  62205. else if (image.getFormat() == Image::ARGB)
  62206. {
  62207. jassert (pixelStride == 4);
  62208. SolidColourEdgeTableRenderer <PixelARGB> renderer (pixels, stride, colour);
  62209. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62210. }
  62211. else if (image.getFormat() == Image::SingleChannel)
  62212. {
  62213. jassert (pixelStride == 1);
  62214. AlphaBitmapRenderer renderer (pixels, stride);
  62215. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62216. }
  62217. image.releasePixelDataReadWrite (pixels);
  62218. }
  62219. }
  62220. void LowLevelGraphicsSoftwareRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  62221. {
  62222. for (RectangleList::Iterator i (*clip); i.next();)
  62223. {
  62224. const Rectangle& r = *i.getRectangle();
  62225. clippedFillPathWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62226. path, t, gradient, quality);
  62227. }
  62228. }
  62229. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  62230. const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  62231. {
  62232. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  62233. int cx, cy, cw, ch;
  62234. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  62235. {
  62236. int stride, pixelStride;
  62237. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  62238. ColourGradient g2 (gradient);
  62239. const bool isIdentity = g2.transform.isIdentity();
  62240. if (isIdentity)
  62241. {
  62242. g2.x1 += xOffset - cx;
  62243. g2.x2 += xOffset - cx;
  62244. g2.y1 += yOffset - cy;
  62245. g2.y2 += yOffset - cy;
  62246. }
  62247. else
  62248. {
  62249. g2.transform = g2.transform.translated ((float) (xOffset - cx),
  62250. (float) (yOffset - cy));
  62251. }
  62252. int numLookupEntries;
  62253. PixelARGB* const lookupTable = g2.createLookupTable (numLookupEntries);
  62254. jassert (numLookupEntries > 0);
  62255. EdgeTable edgeTable (0, ch, quality);
  62256. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  62257. if (image.getFormat() == Image::RGB)
  62258. {
  62259. jassert (pixelStride == 3);
  62260. if (g2.isRadial)
  62261. {
  62262. if (isIdentity)
  62263. {
  62264. GradientEdgeTableRenderer <PixelRGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62265. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62266. }
  62267. else
  62268. {
  62269. GradientEdgeTableRenderer <PixelRGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62270. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62271. }
  62272. }
  62273. else
  62274. {
  62275. GradientEdgeTableRenderer <PixelRGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62276. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62277. }
  62278. }
  62279. else if (image.getFormat() == Image::ARGB)
  62280. {
  62281. jassert (pixelStride == 4);
  62282. if (g2.isRadial)
  62283. {
  62284. if (isIdentity)
  62285. {
  62286. GradientEdgeTableRenderer <PixelARGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62287. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62288. }
  62289. else
  62290. {
  62291. GradientEdgeTableRenderer <PixelARGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62292. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62293. }
  62294. }
  62295. else
  62296. {
  62297. GradientEdgeTableRenderer <PixelARGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62298. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62299. }
  62300. }
  62301. else if (image.getFormat() == Image::SingleChannel)
  62302. {
  62303. jassertfalse // not done!
  62304. }
  62305. juce_free (lookupTable);
  62306. image.releasePixelDataReadWrite (pixels);
  62307. }
  62308. }
  62309. void LowLevelGraphicsSoftwareRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  62310. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  62311. {
  62312. imageX += xOffset;
  62313. imageY += yOffset;
  62314. for (RectangleList::Iterator i (*clip); i.next();)
  62315. {
  62316. const Rectangle& r = *i.getRectangle();
  62317. clippedFillPathWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62318. path, transform, sourceImage, imageX, imageY, opacity, quality);
  62319. }
  62320. }
  62321. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithImage (int x, int y, int w, int h, const Path& path, const AffineTransform& transform,
  62322. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  62323. {
  62324. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight()))
  62325. {
  62326. EdgeTable edgeTable (0, h, quality);
  62327. edgeTable.addPath (path, transform.translated ((float) (xOffset - x), (float) (yOffset - y)));
  62328. int stride, pixelStride;
  62329. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  62330. int srcStride, srcPixelStride;
  62331. const uint8* const srcPix = (const uint8*) sourceImage.lockPixelDataReadOnly (x - imageX, y - imageY, w, h, srcStride, srcPixelStride);
  62332. const int alpha = jlimit (0, 255, roundDoubleToInt (opacity * 255.0f));
  62333. if (image.getFormat() == Image::RGB)
  62334. {
  62335. if (sourceImage.getFormat() == Image::RGB)
  62336. {
  62337. ImageFillEdgeTableRenderer <PixelRGB, PixelRGB> renderer (pixels, stride,
  62338. srcPix, srcStride,
  62339. alpha, (PixelRGB*) 0);
  62340. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  62341. }
  62342. else if (sourceImage.getFormat() == Image::ARGB)
  62343. {
  62344. ImageFillEdgeTableRenderer <PixelRGB, PixelARGB> renderer (pixels, stride,
  62345. srcPix, srcStride,
  62346. alpha, (PixelARGB*) 0);
  62347. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  62348. }
  62349. else
  62350. {
  62351. jassertfalse // not done!
  62352. }
  62353. }
  62354. else if (image.getFormat() == Image::ARGB)
  62355. {
  62356. if (sourceImage.getFormat() == Image::RGB)
  62357. {
  62358. ImageFillEdgeTableRenderer <PixelARGB, PixelRGB> renderer (pixels, stride,
  62359. srcPix, srcStride,
  62360. alpha, (PixelRGB*) 0);
  62361. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  62362. }
  62363. else if (sourceImage.getFormat() == Image::ARGB)
  62364. {
  62365. ImageFillEdgeTableRenderer <PixelARGB, PixelARGB> renderer (pixels, stride,
  62366. srcPix, srcStride,
  62367. alpha, (PixelARGB*) 0);
  62368. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  62369. }
  62370. else
  62371. {
  62372. jassertfalse // not done!
  62373. }
  62374. }
  62375. else
  62376. {
  62377. jassertfalse // not done!
  62378. }
  62379. sourceImage.releasePixelDataReadOnly (srcPix);
  62380. image.releasePixelDataReadWrite (pixels);
  62381. }
  62382. }
  62383. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithColour (const Image& clipImage, int x, int y, const Colour& colour)
  62384. {
  62385. x += xOffset;
  62386. y += yOffset;
  62387. for (RectangleList::Iterator i (*clip); i.next();)
  62388. {
  62389. const Rectangle& r = *i.getRectangle();
  62390. clippedFillAlphaChannelWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62391. clipImage, x, y, colour);
  62392. }
  62393. }
  62394. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& clipImage, int x, int y, const Colour& colour)
  62395. {
  62396. int w = clipImage.getWidth();
  62397. int h = clipImage.getHeight();
  62398. int sx = 0;
  62399. int sy = 0;
  62400. if (x < clipX)
  62401. {
  62402. sx = clipX - x;
  62403. w -= clipX - x;
  62404. x = clipX;
  62405. }
  62406. if (y < clipY)
  62407. {
  62408. sy = clipY - y;
  62409. h -= clipY - y;
  62410. y = clipY;
  62411. }
  62412. if (x + w > clipX + clipW)
  62413. w = clipX + clipW - x;
  62414. if (y + h > clipY + clipH)
  62415. h = clipY + clipH - y;
  62416. if (w > 0 && h > 0)
  62417. {
  62418. int stride, alphaStride, pixelStride;
  62419. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  62420. const uint8* const alphaValues
  62421. = clipImage.lockPixelDataReadOnly (sx, sy, w, h, alphaStride, pixelStride);
  62422. #if JUCE_BIG_ENDIAN
  62423. const uint8* const alphas = alphaValues;
  62424. #else
  62425. const uint8* const alphas = alphaValues + (clipImage.getFormat() == Image::ARGB ? 3 : 0);
  62426. #endif
  62427. if (image.getFormat() == Image::RGB)
  62428. {
  62429. blendAlphaMapRGB (pixels, stride,
  62430. alphas, w, h,
  62431. pixelStride, alphaStride,
  62432. colour);
  62433. }
  62434. else if (image.getFormat() == Image::ARGB)
  62435. {
  62436. blendAlphaMapARGB (pixels, stride,
  62437. alphas, w, h,
  62438. pixelStride, alphaStride,
  62439. colour);
  62440. }
  62441. else
  62442. {
  62443. jassertfalse // not done!
  62444. }
  62445. clipImage.releasePixelDataReadOnly (alphaValues);
  62446. image.releasePixelDataReadWrite (pixels);
  62447. }
  62448. }
  62449. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithGradient (const Image& alphaChannelImage, int imageX, int imageY, const ColourGradient& gradient)
  62450. {
  62451. imageX += xOffset;
  62452. imageY += yOffset;
  62453. for (RectangleList::Iterator i (*clip); i.next();)
  62454. {
  62455. const Rectangle& r = *i.getRectangle();
  62456. clippedFillAlphaChannelWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62457. alphaChannelImage, imageX, imageY, gradient);
  62458. }
  62459. }
  62460. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithGradient (int x, int y, int w, int h,
  62461. const Image& alphaChannelImage,
  62462. int imageX, int imageY, const ColourGradient& gradient)
  62463. {
  62464. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, alphaChannelImage.getWidth(), alphaChannelImage.getHeight()))
  62465. {
  62466. ColourGradient g2 (gradient);
  62467. g2.x1 += xOffset - x;
  62468. g2.x2 += xOffset - x;
  62469. g2.y1 += yOffset - y;
  62470. g2.y2 += yOffset - y;
  62471. Image temp (g2.isOpaque() ? Image::RGB : Image::ARGB, w, h, true);
  62472. LowLevelGraphicsSoftwareRenderer tempG (temp);
  62473. tempG.fillRectWithGradient (0, 0, w, h, g2);
  62474. clippedFillAlphaChannelWithImage (x, y, w, h,
  62475. alphaChannelImage, imageX, imageY,
  62476. temp, x, y, 1.0f);
  62477. }
  62478. }
  62479. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  62480. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  62481. {
  62482. alphaImageX += xOffset;
  62483. alphaImageY += yOffset;
  62484. fillerImageX += xOffset;
  62485. fillerImageY += yOffset;
  62486. for (RectangleList::Iterator i (*clip); i.next();)
  62487. {
  62488. const Rectangle& r = *i.getRectangle();
  62489. clippedFillAlphaChannelWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62490. alphaImage, alphaImageX, alphaImageY,
  62491. fillerImage, fillerImageX, fillerImageY, opacity);
  62492. }
  62493. }
  62494. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithImage (int x, int y, int w, int h, const Image& alphaImage, int alphaImageX, int alphaImageY,
  62495. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  62496. {
  62497. if (Rectangle::intersectRectangles (x, y, w, h, alphaImageX, alphaImageY, alphaImage.getWidth(), alphaImage.getHeight())
  62498. && Rectangle::intersectRectangles (x, y, w, h, fillerImageX, fillerImageY, fillerImage.getWidth(), fillerImage.getHeight()))
  62499. {
  62500. int dstStride, dstPixStride;
  62501. uint8* const dstPix = image.lockPixelDataReadWrite (x, y, w, h, dstStride, dstPixStride);
  62502. int srcStride, srcPixStride;
  62503. const uint8* const srcPix = fillerImage.lockPixelDataReadOnly (x - fillerImageX, y - fillerImageY, w, h, srcStride, srcPixStride);
  62504. int maskStride, maskPixStride;
  62505. const uint8* const alpha
  62506. = alphaImage.lockPixelDataReadOnly (x - alphaImageX, y - alphaImageY, w, h, maskStride, maskPixStride);
  62507. #if JUCE_BIG_ENDIAN
  62508. const uint8* const alphaValues = alpha;
  62509. #else
  62510. const uint8* const alphaValues = alpha + (alphaImage.getFormat() == Image::ARGB ? 3 : 0);
  62511. #endif
  62512. const int extraAlpha = jlimit (0, 0x100, roundDoubleToInt (opacity * 256.0f));
  62513. if (image.getFormat() == Image::RGB)
  62514. {
  62515. if (fillerImage.getFormat() == Image::RGB)
  62516. {
  62517. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  62518. }
  62519. else if (fillerImage.getFormat() == Image::ARGB)
  62520. {
  62521. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  62522. }
  62523. else
  62524. {
  62525. jassertfalse // not done!
  62526. }
  62527. }
  62528. else if (image.getFormat() == Image::ARGB)
  62529. {
  62530. if (fillerImage.getFormat() == Image::RGB)
  62531. {
  62532. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  62533. }
  62534. else if (fillerImage.getFormat() == Image::ARGB)
  62535. {
  62536. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  62537. }
  62538. else
  62539. {
  62540. jassertfalse // not done!
  62541. }
  62542. }
  62543. else
  62544. {
  62545. jassertfalse // not done!
  62546. }
  62547. alphaImage.releasePixelDataReadOnly (alphaValues);
  62548. fillerImage.releasePixelDataReadOnly (srcPix);
  62549. image.releasePixelDataReadWrite (dstPix);
  62550. }
  62551. }
  62552. void LowLevelGraphicsSoftwareRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  62553. {
  62554. dx += xOffset;
  62555. dy += yOffset;
  62556. for (RectangleList::Iterator i (*clip); i.next();)
  62557. {
  62558. const Rectangle& r = *i.getRectangle();
  62559. clippedBlendImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62560. sourceImage, dx, dy, dw, dh, sx, sy, opacity);
  62561. }
  62562. }
  62563. void LowLevelGraphicsSoftwareRenderer::clippedBlendImage (int clipX, int clipY, int clipW, int clipH,
  62564. const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  62565. {
  62566. if (dx < clipX)
  62567. {
  62568. sx += clipX - dx;
  62569. dw -= clipX - dx;
  62570. dx = clipX;
  62571. }
  62572. if (dy < clipY)
  62573. {
  62574. sy += clipY - dy;
  62575. dh -= clipY - dy;
  62576. dy = clipY;
  62577. }
  62578. if (dx + dw > clipX + clipW)
  62579. dw = clipX + clipW - dx;
  62580. if (dy + dh > clipY + clipH)
  62581. dh = clipY + clipH - dy;
  62582. if (dw <= 0 || dh <= 0)
  62583. return;
  62584. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  62585. if (alpha == 0)
  62586. return;
  62587. int dstStride, dstPixelStride;
  62588. uint8* const dstPixels = image.lockPixelDataReadWrite (dx, dy, dw, dh, dstStride, dstPixelStride);
  62589. int srcStride, srcPixelStride;
  62590. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (sx, sy, dw, dh, srcStride, srcPixelStride);
  62591. if (image.getFormat() == Image::ARGB)
  62592. {
  62593. if (sourceImage.getFormat() == Image::ARGB)
  62594. {
  62595. overlayImage ((PixelARGB*) dstPixels, dstStride,
  62596. (PixelARGB*) srcPixels, srcStride,
  62597. dw, dh, alpha);
  62598. }
  62599. else if (sourceImage.getFormat() == Image::RGB)
  62600. {
  62601. overlayImage ((PixelARGB*) dstPixels, dstStride,
  62602. (PixelRGB*) srcPixels, srcStride,
  62603. dw, dh, alpha);
  62604. }
  62605. else
  62606. {
  62607. jassertfalse
  62608. }
  62609. }
  62610. else if (image.getFormat() == Image::RGB)
  62611. {
  62612. if (sourceImage.getFormat() == Image::ARGB)
  62613. {
  62614. overlayImage ((PixelRGB*) dstPixels, dstStride,
  62615. (PixelARGB*) srcPixels, srcStride,
  62616. dw, dh, alpha);
  62617. }
  62618. else if (sourceImage.getFormat() == Image::RGB)
  62619. {
  62620. overlayImage ((PixelRGB*) dstPixels, dstStride,
  62621. (PixelRGB*) srcPixels, srcStride,
  62622. dw, dh, alpha);
  62623. }
  62624. else
  62625. {
  62626. jassertfalse
  62627. }
  62628. }
  62629. else
  62630. {
  62631. jassertfalse
  62632. }
  62633. image.releasePixelDataReadWrite (dstPixels);
  62634. sourceImage.releasePixelDataReadOnly (srcPixels);
  62635. }
  62636. void LowLevelGraphicsSoftwareRenderer::blendImageRescaling (const Image& sourceImage,
  62637. int dx, int dy, int dw, int dh,
  62638. int sx, int sy, int sw, int sh,
  62639. float alpha,
  62640. const Graphics::ResamplingQuality quality)
  62641. {
  62642. if (sw > 0 && sh > 0)
  62643. {
  62644. if (sw == dw && sh == dh)
  62645. {
  62646. blendImage (sourceImage,
  62647. dx, dy, dw, dh,
  62648. sx, sy, alpha);
  62649. }
  62650. else
  62651. {
  62652. blendImageWarping (sourceImage,
  62653. sx, sy, sw, sh,
  62654. AffineTransform::translation ((float) -sx,
  62655. (float) -sy)
  62656. .scaled (dw / (float) sw,
  62657. dh / (float) sh)
  62658. .translated ((float) dx,
  62659. (float) dy),
  62660. alpha,
  62661. quality);
  62662. }
  62663. }
  62664. }
  62665. void LowLevelGraphicsSoftwareRenderer::blendImageWarping (const Image& sourceImage,
  62666. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  62667. const AffineTransform& t,
  62668. float opacity,
  62669. const Graphics::ResamplingQuality quality)
  62670. {
  62671. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  62672. for (RectangleList::Iterator i (*clip); i.next();)
  62673. {
  62674. const Rectangle& r = *i.getRectangle();
  62675. clippedBlendImageWarping (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62676. sourceImage, srcClipX, srcClipY, srcClipW, srcClipH,
  62677. transform, opacity, quality);
  62678. }
  62679. }
  62680. void LowLevelGraphicsSoftwareRenderer::clippedBlendImageWarping (int destClipX, int destClipY, int destClipW, int destClipH,
  62681. const Image& sourceImage,
  62682. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  62683. const AffineTransform& transform,
  62684. float opacity,
  62685. const Graphics::ResamplingQuality quality)
  62686. {
  62687. if (opacity > 0 && destClipW > 0 && destClipH > 0 && ! transform.isSingularity())
  62688. {
  62689. Rectangle::intersectRectangles (srcClipX, srcClipY, srcClipW, srcClipH,
  62690. 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  62691. if (srcClipW <= 0 || srcClipH <= 0)
  62692. return;
  62693. jassert (srcClipX >= 0 && srcClipY >= 0);
  62694. Path imageBounds;
  62695. imageBounds.addRectangle ((float) srcClipX, (float) srcClipY, (float) srcClipW, (float) srcClipH);
  62696. imageBounds.applyTransform (transform);
  62697. float imX, imY, imW, imH;
  62698. imageBounds.getBounds (imX, imY, imW, imH);
  62699. if (Rectangle::intersectRectangles (destClipX, destClipY, destClipW, destClipH,
  62700. (int) floorf (imX),
  62701. (int) floorf (imY),
  62702. 1 + roundDoubleToInt (imW),
  62703. 1 + roundDoubleToInt (imH)))
  62704. {
  62705. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  62706. float srcX1 = (float) destClipX;
  62707. float srcY1 = (float) destClipY;
  62708. float srcX2 = (float) (destClipX + destClipW);
  62709. float srcY2 = srcY1;
  62710. float srcX3 = srcX1;
  62711. float srcY3 = (float) (destClipY + destClipH);
  62712. AffineTransform inverse (transform.inverted());
  62713. inverse.transformPoint (srcX1, srcY1);
  62714. inverse.transformPoint (srcX2, srcY2);
  62715. inverse.transformPoint (srcX3, srcY3);
  62716. const double lineDX = (double) (srcX3 - srcX1) / destClipH;
  62717. const double lineDY = (double) (srcY3 - srcY1) / destClipH;
  62718. const double pixelDX = (double) (srcX2 - srcX1) / destClipW;
  62719. const double pixelDY = (double) (srcY2 - srcY1) / destClipW;
  62720. if (image.getFormat() == Image::ARGB)
  62721. {
  62722. if (sourceImage.getFormat() == Image::ARGB)
  62723. {
  62724. transformedImageRender (image, sourceImage,
  62725. destClipX, destClipY, destClipW, destClipH,
  62726. srcClipX, srcClipY, srcClipW, srcClipH,
  62727. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62728. alpha, quality, (PixelARGB*)0, (PixelARGB*)0);
  62729. }
  62730. else if (sourceImage.getFormat() == Image::RGB)
  62731. {
  62732. transformedImageRender (image, sourceImage,
  62733. destClipX, destClipY, destClipW, destClipH,
  62734. srcClipX, srcClipY, srcClipW, srcClipH,
  62735. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62736. alpha, quality, (PixelARGB*)0, (PixelRGB*)0);
  62737. }
  62738. else
  62739. {
  62740. jassertfalse
  62741. }
  62742. }
  62743. else if (image.getFormat() == Image::RGB)
  62744. {
  62745. if (sourceImage.getFormat() == Image::ARGB)
  62746. {
  62747. transformedImageRender (image, sourceImage,
  62748. destClipX, destClipY, destClipW, destClipH,
  62749. srcClipX, srcClipY, srcClipW, srcClipH,
  62750. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62751. alpha, quality, (PixelRGB*)0, (PixelARGB*)0);
  62752. }
  62753. else if (sourceImage.getFormat() == Image::RGB)
  62754. {
  62755. transformedImageRender (image, sourceImage,
  62756. destClipX, destClipY, destClipW, destClipH,
  62757. srcClipX, srcClipY, srcClipW, srcClipH,
  62758. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62759. alpha, quality, (PixelRGB*)0, (PixelRGB*)0);
  62760. }
  62761. else
  62762. {
  62763. jassertfalse
  62764. }
  62765. }
  62766. else
  62767. {
  62768. jassertfalse
  62769. }
  62770. }
  62771. }
  62772. }
  62773. void LowLevelGraphicsSoftwareRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  62774. {
  62775. x1 += xOffset;
  62776. y1 += yOffset;
  62777. x2 += xOffset;
  62778. y2 += yOffset;
  62779. for (RectangleList::Iterator i (*clip); i.next();)
  62780. {
  62781. const Rectangle& r = *i.getRectangle();
  62782. clippedDrawLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62783. x1, y1, x2, y2, colour);
  62784. }
  62785. }
  62786. void LowLevelGraphicsSoftwareRenderer::clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour)
  62787. {
  62788. if (clipW > 0 && clipH > 0)
  62789. {
  62790. if (x1 == x2)
  62791. {
  62792. if (y2 < y1)
  62793. swapVariables (y1, y2);
  62794. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (x1), y1, y2, colour);
  62795. }
  62796. else if (y1 == y2)
  62797. {
  62798. if (x2 < x1)
  62799. swapVariables (x1, x2);
  62800. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (y1), x1, x2, colour);
  62801. }
  62802. else
  62803. {
  62804. double gradient = (y2 - y1) / (x2 - x1);
  62805. if (fabs (gradient) > 1.0)
  62806. {
  62807. gradient = 1.0 / gradient;
  62808. int y = roundDoubleToInt (y1);
  62809. const int startY = y;
  62810. int endY = roundDoubleToInt (y2);
  62811. if (y > endY)
  62812. swapVariables (y, endY);
  62813. while (y < endY)
  62814. {
  62815. const double x = x1 + gradient * (y - startY);
  62816. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, y, x, x + 1.0, colour);
  62817. ++y;
  62818. }
  62819. }
  62820. else
  62821. {
  62822. int x = roundDoubleToInt (x1);
  62823. const int startX = x;
  62824. int endX = roundDoubleToInt (x2);
  62825. if (x > endX)
  62826. swapVariables (x, endX);
  62827. while (x < endX)
  62828. {
  62829. const double y = y1 + gradient * (x - startX);
  62830. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, x, y, y + 1.0, colour);
  62831. ++x;
  62832. }
  62833. }
  62834. }
  62835. }
  62836. }
  62837. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  62838. {
  62839. for (RectangleList::Iterator i (*clip); i.next();)
  62840. {
  62841. const Rectangle& r = *i.getRectangle();
  62842. clippedDrawVerticalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62843. x + xOffset, top + yOffset, bottom + yOffset, col);
  62844. }
  62845. }
  62846. void LowLevelGraphicsSoftwareRenderer::clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH,
  62847. const int x, double top, double bottom, const Colour& col)
  62848. {
  62849. jassert (top <= bottom);
  62850. if (((unsigned int) (x - clipX)) < (unsigned int) clipW
  62851. && top < clipY + clipH
  62852. && bottom > clipY
  62853. && clipW > 0)
  62854. {
  62855. if (top < clipY)
  62856. top = clipY;
  62857. if (bottom > clipY + clipH)
  62858. bottom = clipY + clipH;
  62859. if (bottom > top)
  62860. drawVertical (x, top, bottom, col);
  62861. }
  62862. }
  62863. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  62864. {
  62865. for (RectangleList::Iterator i (*clip); i.next();)
  62866. {
  62867. const Rectangle& r = *i.getRectangle();
  62868. clippedDrawHorizontalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62869. y + yOffset, left + xOffset, right + xOffset, col);
  62870. }
  62871. }
  62872. void LowLevelGraphicsSoftwareRenderer::clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH,
  62873. const int y, double left, double right, const Colour& col)
  62874. {
  62875. jassert (left <= right);
  62876. if (((unsigned int) (y - clipY)) < (unsigned int) clipH
  62877. && left < clipX + clipW
  62878. && right > clipX
  62879. && clipW > 0)
  62880. {
  62881. if (left < clipX)
  62882. left = clipX;
  62883. if (right > clipX + clipW)
  62884. right = clipX + clipW;
  62885. if (right > left)
  62886. drawHorizontal (y, left, right, col);
  62887. }
  62888. }
  62889. void LowLevelGraphicsSoftwareRenderer::drawVertical (const int x,
  62890. const double top,
  62891. const double bottom,
  62892. const Colour& col)
  62893. {
  62894. int wholeStart = (int) top;
  62895. const int wholeEnd = (int) bottom;
  62896. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  62897. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  62898. if (totalPixels <= 0)
  62899. return;
  62900. int lineStride, dstPixelStride;
  62901. uint8* const dstPixels = image.lockPixelDataReadWrite (x, wholeStart, 1, totalPixels, lineStride, dstPixelStride);
  62902. uint8* dest = dstPixels;
  62903. PixelARGB colour (col.getPixelARGB());
  62904. if (wholeEnd == wholeStart)
  62905. {
  62906. if (image.getFormat() == Image::ARGB)
  62907. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62908. else if (image.getFormat() == Image::RGB)
  62909. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62910. else
  62911. {
  62912. jassertfalse
  62913. }
  62914. }
  62915. else
  62916. {
  62917. if (image.getFormat() == Image::ARGB)
  62918. {
  62919. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62920. ++wholeStart;
  62921. dest += lineStride;
  62922. if (colour.getAlpha() == 0xff)
  62923. {
  62924. while (wholeEnd > wholeStart)
  62925. {
  62926. ((PixelARGB*) dest)->set (colour);
  62927. ++wholeStart;
  62928. dest += lineStride;
  62929. }
  62930. }
  62931. else
  62932. {
  62933. while (wholeEnd > wholeStart)
  62934. {
  62935. ((PixelARGB*) dest)->blend (colour);
  62936. ++wholeStart;
  62937. dest += lineStride;
  62938. }
  62939. }
  62940. if (lastAlpha > 0)
  62941. {
  62942. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  62943. }
  62944. }
  62945. else if (image.getFormat() == Image::RGB)
  62946. {
  62947. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62948. ++wholeStart;
  62949. dest += lineStride;
  62950. if (colour.getAlpha() == 0xff)
  62951. {
  62952. while (wholeEnd > wholeStart)
  62953. {
  62954. ((PixelRGB*) dest)->set (colour);
  62955. ++wholeStart;
  62956. dest += lineStride;
  62957. }
  62958. }
  62959. else
  62960. {
  62961. while (wholeEnd > wholeStart)
  62962. {
  62963. ((PixelRGB*) dest)->blend (colour);
  62964. ++wholeStart;
  62965. dest += lineStride;
  62966. }
  62967. }
  62968. if (lastAlpha > 0)
  62969. {
  62970. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  62971. }
  62972. }
  62973. else
  62974. {
  62975. jassertfalse
  62976. }
  62977. }
  62978. image.releasePixelDataReadWrite (dstPixels);
  62979. }
  62980. void LowLevelGraphicsSoftwareRenderer::drawHorizontal (const int y,
  62981. const double top,
  62982. const double bottom,
  62983. const Colour& col)
  62984. {
  62985. int wholeStart = (int) top;
  62986. const int wholeEnd = (int) bottom;
  62987. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  62988. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  62989. if (totalPixels <= 0)
  62990. return;
  62991. int lineStride, dstPixelStride;
  62992. uint8* const dstPixels = image.lockPixelDataReadWrite (wholeStart, y, totalPixels, 1, lineStride, dstPixelStride);
  62993. uint8* dest = dstPixels;
  62994. PixelARGB colour (col.getPixelARGB());
  62995. if (wholeEnd == wholeStart)
  62996. {
  62997. if (image.getFormat() == Image::ARGB)
  62998. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62999. else if (image.getFormat() == Image::RGB)
  63000. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  63001. else
  63002. {
  63003. jassertfalse
  63004. }
  63005. }
  63006. else
  63007. {
  63008. if (image.getFormat() == Image::ARGB)
  63009. {
  63010. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  63011. dest += dstPixelStride;
  63012. ++wholeStart;
  63013. if (colour.getAlpha() == 0xff)
  63014. {
  63015. while (wholeEnd > wholeStart)
  63016. {
  63017. ((PixelARGB*) dest)->set (colour);
  63018. dest += dstPixelStride;
  63019. ++wholeStart;
  63020. }
  63021. }
  63022. else
  63023. {
  63024. while (wholeEnd > wholeStart)
  63025. {
  63026. ((PixelARGB*) dest)->blend (colour);
  63027. dest += dstPixelStride;
  63028. ++wholeStart;
  63029. }
  63030. }
  63031. if (lastAlpha > 0)
  63032. {
  63033. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  63034. }
  63035. }
  63036. else if (image.getFormat() == Image::RGB)
  63037. {
  63038. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  63039. dest += dstPixelStride;
  63040. ++wholeStart;
  63041. if (colour.getAlpha() == 0xff)
  63042. {
  63043. while (wholeEnd > wholeStart)
  63044. {
  63045. ((PixelRGB*) dest)->set (colour);
  63046. dest += dstPixelStride;
  63047. ++wholeStart;
  63048. }
  63049. }
  63050. else
  63051. {
  63052. while (wholeEnd > wholeStart)
  63053. {
  63054. ((PixelRGB*) dest)->blend (colour);
  63055. dest += dstPixelStride;
  63056. ++wholeStart;
  63057. }
  63058. }
  63059. if (lastAlpha > 0)
  63060. {
  63061. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  63062. }
  63063. }
  63064. else
  63065. {
  63066. jassertfalse
  63067. }
  63068. }
  63069. image.releasePixelDataReadWrite (dstPixels);
  63070. }
  63071. END_JUCE_NAMESPACE
  63072. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  63073. /********* Start of inlined file: juce_RectanglePlacement.cpp *********/
  63074. BEGIN_JUCE_NAMESPACE
  63075. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  63076. : flags (other.flags)
  63077. {
  63078. }
  63079. const RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  63080. {
  63081. flags = other.flags;
  63082. return *this;
  63083. }
  63084. void RectanglePlacement::applyTo (double& x, double& y,
  63085. double& w, double& h,
  63086. const double dx, const double dy,
  63087. const double dw, const double dh) const throw()
  63088. {
  63089. if (w == 0 || h == 0)
  63090. return;
  63091. if ((flags & stretchToFit) != 0)
  63092. {
  63093. x = dx;
  63094. y = dy;
  63095. w = dw;
  63096. h = dh;
  63097. }
  63098. else
  63099. {
  63100. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  63101. : jmin (dw / w, dh / h);
  63102. if ((flags & onlyReduceInSize) != 0)
  63103. scale = jmin (scale, 1.0);
  63104. if ((flags & onlyIncreaseInSize) != 0)
  63105. scale = jmax (scale, 1.0);
  63106. w *= scale;
  63107. h *= scale;
  63108. if ((flags & xLeft) != 0)
  63109. x = dx;
  63110. else if ((flags & xRight) != 0)
  63111. x = dx + dw - w;
  63112. else
  63113. x = dx + (dw - w) * 0.5;
  63114. if ((flags & yTop) != 0)
  63115. y = dy;
  63116. else if ((flags & yBottom) != 0)
  63117. y = dy + dh - h;
  63118. else
  63119. y = dy + (dh - h) * 0.5;
  63120. }
  63121. }
  63122. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  63123. float w, float h,
  63124. const float dx, const float dy,
  63125. const float dw, const float dh) const throw()
  63126. {
  63127. if (w == 0 || h == 0)
  63128. return AffineTransform::identity;
  63129. const float scaleX = dw / w;
  63130. const float scaleY = dh / h;
  63131. if ((flags & stretchToFit) != 0)
  63132. {
  63133. return AffineTransform::translation (-x, -y)
  63134. .scaled (scaleX, scaleY)
  63135. .translated (dx - x, dy - y);
  63136. }
  63137. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  63138. : jmin (scaleX, scaleY);
  63139. if ((flags & onlyReduceInSize) != 0)
  63140. scale = jmin (scale, 1.0f);
  63141. if ((flags & onlyIncreaseInSize) != 0)
  63142. scale = jmax (scale, 1.0f);
  63143. w *= scale;
  63144. h *= scale;
  63145. float newX = dx;
  63146. if ((flags & xRight) != 0)
  63147. newX += dw - w; // right
  63148. else if ((flags & xLeft) == 0)
  63149. newX += (dw - w) / 2.0f; // centre
  63150. float newY = dy;
  63151. if ((flags & yBottom) != 0)
  63152. newY += dh - h; // bottom
  63153. else if ((flags & yTop) == 0)
  63154. newY += (dh - h) / 2.0f; // centre
  63155. return AffineTransform::translation (-x, -y)
  63156. .scaled (scale, scale)
  63157. .translated (newX, newY);
  63158. }
  63159. END_JUCE_NAMESPACE
  63160. /********* End of inlined file: juce_RectanglePlacement.cpp *********/
  63161. /********* Start of inlined file: juce_Drawable.cpp *********/
  63162. BEGIN_JUCE_NAMESPACE
  63163. Drawable::Drawable()
  63164. {
  63165. }
  63166. Drawable::~Drawable()
  63167. {
  63168. }
  63169. void Drawable::drawAt (Graphics& g, const float x, const float y) const
  63170. {
  63171. draw (g, AffineTransform::translation (x, y));
  63172. }
  63173. void Drawable::drawWithin (Graphics& g,
  63174. const int destX,
  63175. const int destY,
  63176. const int destW,
  63177. const int destH,
  63178. const RectanglePlacement& placement) const
  63179. {
  63180. if (destW > 0 && destH > 0)
  63181. {
  63182. float x, y, w, h;
  63183. getBounds (x, y, w, h);
  63184. draw (g, placement.getTransformToFit (x, y, w, h,
  63185. (float) destX, (float) destY,
  63186. (float) destW, (float) destH));
  63187. }
  63188. }
  63189. Drawable* Drawable::createFromImageData (const void* data, const int numBytes)
  63190. {
  63191. Drawable* result = 0;
  63192. Image* const image = ImageFileFormat::loadFrom (data, numBytes);
  63193. if (image != 0)
  63194. {
  63195. DrawableImage* const di = new DrawableImage();
  63196. di->setImage (image, true);
  63197. result = di;
  63198. }
  63199. else
  63200. {
  63201. const String asString (String::createStringFromData (data, numBytes));
  63202. XmlDocument doc (asString);
  63203. XmlElement* const outer = doc.getDocumentElement (true);
  63204. if (outer != 0 && outer->hasTagName (T("svg")))
  63205. {
  63206. XmlElement* const svg = doc.getDocumentElement();
  63207. if (svg != 0)
  63208. {
  63209. result = Drawable::createFromSVG (*svg);
  63210. delete svg;
  63211. }
  63212. }
  63213. delete outer;
  63214. }
  63215. return result;
  63216. }
  63217. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  63218. {
  63219. MemoryBlock mb;
  63220. dataSource.readIntoMemoryBlock (mb);
  63221. return createFromImageData (mb.getData(), mb.getSize());
  63222. }
  63223. Drawable* Drawable::createFromImageFile (const File& file)
  63224. {
  63225. FileInputStream* fin = file.createInputStream();
  63226. if (fin == 0)
  63227. return 0;
  63228. Drawable* d = createFromImageDataStream (*fin);
  63229. delete fin;
  63230. return d;
  63231. }
  63232. END_JUCE_NAMESPACE
  63233. /********* End of inlined file: juce_Drawable.cpp *********/
  63234. /********* Start of inlined file: juce_DrawableComposite.cpp *********/
  63235. BEGIN_JUCE_NAMESPACE
  63236. DrawableComposite::DrawableComposite()
  63237. {
  63238. }
  63239. DrawableComposite::~DrawableComposite()
  63240. {
  63241. }
  63242. void DrawableComposite::insertDrawable (Drawable* drawable,
  63243. const AffineTransform& transform,
  63244. const int index)
  63245. {
  63246. if (drawable != 0)
  63247. {
  63248. if (! drawables.contains (drawable))
  63249. {
  63250. drawables.insert (index, drawable);
  63251. if (transform.isIdentity())
  63252. transforms.insert (index, 0);
  63253. else
  63254. transforms.insert (index, new AffineTransform (transform));
  63255. }
  63256. else
  63257. {
  63258. jassertfalse // trying to add a drawable that's already in here!
  63259. }
  63260. }
  63261. }
  63262. void DrawableComposite::insertDrawable (const Drawable& drawable,
  63263. const AffineTransform& transform,
  63264. const int index)
  63265. {
  63266. insertDrawable (drawable.createCopy(), transform, index);
  63267. }
  63268. void DrawableComposite::removeDrawable (const int index)
  63269. {
  63270. drawables.remove (index);
  63271. transforms.remove (index);
  63272. }
  63273. void DrawableComposite::bringToFront (const int index)
  63274. {
  63275. if (index >= 0 && index < drawables.size() - 1)
  63276. {
  63277. drawables.move (index, -1);
  63278. transforms.move (index, -1);
  63279. }
  63280. }
  63281. void DrawableComposite::draw (Graphics& g, const AffineTransform& transform) const
  63282. {
  63283. for (int i = 0; i < drawables.size(); ++i)
  63284. {
  63285. const AffineTransform* const t = transforms.getUnchecked(i);
  63286. drawables.getUnchecked(i)->draw (g, t == 0 ? transform
  63287. : t->followedBy (transform));
  63288. }
  63289. }
  63290. void DrawableComposite::getBounds (float& x, float& y, float& width, float& height) const
  63291. {
  63292. Path totalPath;
  63293. for (int i = 0; i < drawables.size(); ++i)
  63294. {
  63295. drawables.getUnchecked(i)->getBounds (x, y, width, height);
  63296. if (width > 0.0f && height > 0.0f)
  63297. {
  63298. Path outline;
  63299. outline.addRectangle (x, y, width, height);
  63300. const AffineTransform* const t = transforms.getUnchecked(i);
  63301. if (t == 0)
  63302. totalPath.addPath (outline);
  63303. else
  63304. totalPath.addPath (outline, *t);
  63305. }
  63306. }
  63307. totalPath.getBounds (x, y, width, height);
  63308. }
  63309. bool DrawableComposite::hitTest (float x, float y) const
  63310. {
  63311. for (int i = 0; i < drawables.size(); ++i)
  63312. {
  63313. float tx = x;
  63314. float ty = y;
  63315. const AffineTransform* const t = transforms.getUnchecked(i);
  63316. if (t != 0)
  63317. t->inverted().transformPoint (tx, ty);
  63318. if (drawables.getUnchecked(i)->hitTest (tx, ty))
  63319. return true;
  63320. }
  63321. return false;
  63322. }
  63323. Drawable* DrawableComposite::createCopy() const
  63324. {
  63325. DrawableComposite* const dc = new DrawableComposite();
  63326. for (int i = 0; i < drawables.size(); ++i)
  63327. {
  63328. dc->drawables.add (drawables.getUnchecked(i)->createCopy());
  63329. const AffineTransform* const t = transforms.getUnchecked(i);
  63330. dc->transforms.add (t != 0 ? new AffineTransform (*t) : 0);
  63331. }
  63332. return dc;
  63333. }
  63334. END_JUCE_NAMESPACE
  63335. /********* End of inlined file: juce_DrawableComposite.cpp *********/
  63336. /********* Start of inlined file: juce_DrawableImage.cpp *********/
  63337. BEGIN_JUCE_NAMESPACE
  63338. DrawableImage::DrawableImage()
  63339. : image (0),
  63340. canDeleteImage (false),
  63341. opacity (1.0f),
  63342. overlayColour (0x00000000)
  63343. {
  63344. }
  63345. DrawableImage::~DrawableImage()
  63346. {
  63347. clearImage();
  63348. }
  63349. void DrawableImage::clearImage()
  63350. {
  63351. if (canDeleteImage && image != 0)
  63352. {
  63353. if (ImageCache::isImageInCache (image))
  63354. ImageCache::release (image);
  63355. else
  63356. delete image;
  63357. }
  63358. image = 0;
  63359. }
  63360. void DrawableImage::setImage (const Image& imageToCopy)
  63361. {
  63362. clearImage();
  63363. image = new Image (imageToCopy);
  63364. canDeleteImage = true;
  63365. }
  63366. void DrawableImage::setImage (Image* imageToUse,
  63367. const bool releaseWhenNotNeeded)
  63368. {
  63369. clearImage();
  63370. image = imageToUse;
  63371. canDeleteImage = releaseWhenNotNeeded;
  63372. }
  63373. void DrawableImage::setOpacity (const float newOpacity)
  63374. {
  63375. opacity = newOpacity;
  63376. }
  63377. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  63378. {
  63379. overlayColour = newOverlayColour;
  63380. }
  63381. void DrawableImage::draw (Graphics& g, const AffineTransform& transform) const
  63382. {
  63383. if (image != 0)
  63384. {
  63385. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  63386. if (opacity > 0.0f && ! overlayColour.isOpaque())
  63387. {
  63388. g.setColour (oldColour.withMultipliedAlpha (opacity));
  63389. g.drawImageTransformed (image,
  63390. 0, 0, image->getWidth(), image->getHeight(),
  63391. transform, false);
  63392. }
  63393. if (! overlayColour.isTransparent())
  63394. {
  63395. g.setColour (overlayColour.withMultipliedAlpha (oldColour.getFloatAlpha()));
  63396. g.drawImageTransformed (image,
  63397. 0, 0, image->getWidth(), image->getHeight(),
  63398. transform, true);
  63399. }
  63400. g.setColour (oldColour);
  63401. }
  63402. }
  63403. void DrawableImage::getBounds (float& x, float& y, float& width, float& height) const
  63404. {
  63405. x = 0.0f;
  63406. y = 0.0f;
  63407. width = 0.0f;
  63408. height = 0.0f;
  63409. if (image != 0)
  63410. {
  63411. width = (float) image->getWidth();
  63412. height = (float) image->getHeight();
  63413. }
  63414. }
  63415. bool DrawableImage::hitTest (float x, float y) const
  63416. {
  63417. return image != 0
  63418. && x >= 0.0f
  63419. && y >= 0.0f
  63420. && x < image->getWidth()
  63421. && y < image->getHeight()
  63422. && image->getPixelAt (roundFloatToInt (x), roundFloatToInt (y)).getAlpha() >= 127;
  63423. }
  63424. Drawable* DrawableImage::createCopy() const
  63425. {
  63426. DrawableImage* const di = new DrawableImage();
  63427. di->opacity = opacity;
  63428. di->overlayColour = overlayColour;
  63429. if (image != 0)
  63430. {
  63431. if ((! canDeleteImage) || ! ImageCache::isImageInCache (image))
  63432. {
  63433. di->setImage (*image);
  63434. }
  63435. else
  63436. {
  63437. ImageCache::incReferenceCount (image);
  63438. di->setImage (image, true);
  63439. }
  63440. }
  63441. return di;
  63442. }
  63443. END_JUCE_NAMESPACE
  63444. /********* End of inlined file: juce_DrawableImage.cpp *********/
  63445. /********* Start of inlined file: juce_DrawablePath.cpp *********/
  63446. BEGIN_JUCE_NAMESPACE
  63447. DrawablePath::DrawablePath()
  63448. : fillBrush (new SolidColourBrush (Colours::black)),
  63449. strokeBrush (0),
  63450. strokeType (0.0f)
  63451. {
  63452. }
  63453. DrawablePath::~DrawablePath()
  63454. {
  63455. delete fillBrush;
  63456. delete strokeBrush;
  63457. }
  63458. void DrawablePath::setPath (const Path& newPath)
  63459. {
  63460. path = newPath;
  63461. updateOutline();
  63462. }
  63463. void DrawablePath::setSolidFill (const Colour& newColour)
  63464. {
  63465. delete fillBrush;
  63466. fillBrush = new SolidColourBrush (newColour);
  63467. }
  63468. void DrawablePath::setFillBrush (const Brush& newBrush)
  63469. {
  63470. delete fillBrush;
  63471. fillBrush = newBrush.createCopy();
  63472. }
  63473. void DrawablePath::setOutline (const float thickness, const Colour& colour)
  63474. {
  63475. strokeType = PathStrokeType (thickness);
  63476. delete strokeBrush;
  63477. strokeBrush = new SolidColourBrush (colour);
  63478. updateOutline();
  63479. }
  63480. void DrawablePath::setOutline (const PathStrokeType& strokeType_, const Brush& newStrokeBrush)
  63481. {
  63482. strokeType = strokeType_;
  63483. delete strokeBrush;
  63484. strokeBrush = newStrokeBrush.createCopy();
  63485. updateOutline();
  63486. }
  63487. void DrawablePath::draw (Graphics& g, const AffineTransform& transform) const
  63488. {
  63489. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  63490. const float currentOpacity = oldColour.getFloatAlpha();
  63491. {
  63492. Brush* const tempBrush = fillBrush->createCopy();
  63493. tempBrush->applyTransform (transform);
  63494. tempBrush->multiplyOpacity (currentOpacity);
  63495. g.setBrush (tempBrush);
  63496. g.fillPath (path, transform);
  63497. delete tempBrush;
  63498. }
  63499. if (strokeBrush != 0 && strokeType.getStrokeThickness() > 0.0f)
  63500. {
  63501. Brush* const tempBrush = strokeBrush->createCopy();
  63502. tempBrush->applyTransform (transform);
  63503. tempBrush->multiplyOpacity (currentOpacity);
  63504. g.setBrush (tempBrush);
  63505. g.fillPath (outline, transform);
  63506. delete tempBrush;
  63507. }
  63508. g.setColour (oldColour);
  63509. }
  63510. void DrawablePath::updateOutline()
  63511. {
  63512. outline.clear();
  63513. strokeType.createStrokedPath (outline, path, AffineTransform::identity, 4.0f);
  63514. }
  63515. void DrawablePath::getBounds (float& x, float& y, float& width, float& height) const
  63516. {
  63517. if (strokeType.getStrokeThickness() > 0.0f)
  63518. outline.getBounds (x, y, width, height);
  63519. else
  63520. path.getBounds (x, y, width, height);
  63521. }
  63522. bool DrawablePath::hitTest (float x, float y) const
  63523. {
  63524. return path.contains (x, y)
  63525. || outline.contains (x, y);
  63526. }
  63527. Drawable* DrawablePath::createCopy() const
  63528. {
  63529. DrawablePath* const dp = new DrawablePath();
  63530. dp->path = path;
  63531. dp->setFillBrush (*fillBrush);
  63532. if (strokeBrush != 0)
  63533. dp->setOutline (strokeType, *strokeBrush);
  63534. return dp;
  63535. }
  63536. END_JUCE_NAMESPACE
  63537. /********* End of inlined file: juce_DrawablePath.cpp *********/
  63538. /********* Start of inlined file: juce_DrawableText.cpp *********/
  63539. BEGIN_JUCE_NAMESPACE
  63540. DrawableText::DrawableText()
  63541. : colour (Colours::white)
  63542. {
  63543. }
  63544. DrawableText::~DrawableText()
  63545. {
  63546. }
  63547. void DrawableText::setText (const GlyphArrangement& newText)
  63548. {
  63549. text = newText;
  63550. }
  63551. void DrawableText::setText (const String& newText, const Font& fontToUse)
  63552. {
  63553. text.clear();
  63554. text.addLineOfText (fontToUse, newText, 0.0f, 0.0f);
  63555. }
  63556. void DrawableText::setColour (const Colour& newColour)
  63557. {
  63558. colour = newColour;
  63559. }
  63560. void DrawableText::draw (Graphics& g, const AffineTransform& transform) const
  63561. {
  63562. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  63563. g.setColour (colour.withMultipliedAlpha (oldColour.getFloatAlpha()));
  63564. text.draw (g, transform);
  63565. g.setColour (oldColour);
  63566. }
  63567. void DrawableText::getBounds (float& x, float& y, float& width, float& height) const
  63568. {
  63569. text.getBoundingBox (0, -1, x, y, width, height, false); // (really returns top, left, bottom, right)
  63570. width -= x;
  63571. height -= y;
  63572. }
  63573. bool DrawableText::hitTest (float x, float y) const
  63574. {
  63575. return text.findGlyphIndexAt (x, y) >= 0;
  63576. }
  63577. Drawable* DrawableText::createCopy() const
  63578. {
  63579. DrawableText* const dt = new DrawableText();
  63580. dt->text = text;
  63581. dt->colour = colour;
  63582. return dt;
  63583. }
  63584. END_JUCE_NAMESPACE
  63585. /********* End of inlined file: juce_DrawableText.cpp *********/
  63586. /********* Start of inlined file: juce_SVGParser.cpp *********/
  63587. BEGIN_JUCE_NAMESPACE
  63588. class SVGState
  63589. {
  63590. public:
  63591. SVGState (const XmlElement* const topLevel)
  63592. : topLevelXml (topLevel),
  63593. x (0), y (0),
  63594. width (512), height (512),
  63595. viewBoxW (0), viewBoxH (0)
  63596. {
  63597. }
  63598. ~SVGState()
  63599. {
  63600. }
  63601. Drawable* parseSVGElement (const XmlElement& xml)
  63602. {
  63603. if (! xml.hasTagName (T("svg")))
  63604. return 0;
  63605. DrawableComposite* const drawable = new DrawableComposite();
  63606. drawable->setName (xml.getStringAttribute (T("id")));
  63607. SVGState newState (*this);
  63608. if (xml.hasAttribute (T("transform")))
  63609. newState.addTransform (xml);
  63610. newState.x = getCoordLength (xml.getStringAttribute (T("x"), String (newState.x)), viewBoxW);
  63611. newState.y = getCoordLength (xml.getStringAttribute (T("y"), String (newState.y)), viewBoxH);
  63612. newState.width = getCoordLength (xml.getStringAttribute (T("width"), String (newState.width)), viewBoxW);
  63613. newState.height = getCoordLength (xml.getStringAttribute (T("height"), String (newState.height)), viewBoxH);
  63614. if (xml.hasAttribute (T("viewBox")))
  63615. {
  63616. const String viewParams (xml.getStringAttribute (T("viewBox")));
  63617. int i = 0;
  63618. float vx, vy, vw, vh;
  63619. if (parseCoords (viewParams, vx, vy, i, true)
  63620. && parseCoords (viewParams, vw, vh, i, true)
  63621. && vw > 0
  63622. && vh > 0)
  63623. {
  63624. newState.viewBoxW = vw;
  63625. newState.viewBoxH = vh;
  63626. int placementFlags = 0;
  63627. const String aspect (xml.getStringAttribute (T("preserveAspectRatio")));
  63628. if (aspect.containsIgnoreCase (T("none")))
  63629. {
  63630. placementFlags = RectanglePlacement::stretchToFit;
  63631. }
  63632. else
  63633. {
  63634. if (aspect.containsIgnoreCase (T("slice")))
  63635. placementFlags |= RectanglePlacement::fillDestination;
  63636. if (aspect.containsIgnoreCase (T("xMin")))
  63637. placementFlags |= RectanglePlacement::xLeft;
  63638. else if (aspect.containsIgnoreCase (T("xMax")))
  63639. placementFlags |= RectanglePlacement::xRight;
  63640. else
  63641. placementFlags |= RectanglePlacement::xMid;
  63642. if (aspect.containsIgnoreCase (T("yMin")))
  63643. placementFlags |= RectanglePlacement::yTop;
  63644. else if (aspect.containsIgnoreCase (T("yMax")))
  63645. placementFlags |= RectanglePlacement::yBottom;
  63646. else
  63647. placementFlags |= RectanglePlacement::yMid;
  63648. }
  63649. const RectanglePlacement placement (placementFlags);
  63650. newState.transform
  63651. = placement.getTransformToFit (vx, vy, vw, vh,
  63652. 0.0f, 0.0f, newState.width, newState.height)
  63653. .followedBy (newState.transform);
  63654. }
  63655. }
  63656. else
  63657. {
  63658. if (viewBoxW == 0)
  63659. newState.viewBoxW = newState.width;
  63660. if (viewBoxH == 0)
  63661. newState.viewBoxH = newState.height;
  63662. }
  63663. newState.parseSubElements (xml, drawable);
  63664. return drawable;
  63665. }
  63666. private:
  63667. const XmlElement* const topLevelXml;
  63668. float x, y, width, height, viewBoxW, viewBoxH;
  63669. AffineTransform transform;
  63670. String cssStyleText;
  63671. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  63672. {
  63673. forEachXmlChildElement (xml, e)
  63674. {
  63675. Drawable* d = 0;
  63676. if (e->hasTagName (T("g")))
  63677. d = parseGroupElement (*e);
  63678. else if (e->hasTagName (T("svg")))
  63679. d = parseSVGElement (*e);
  63680. else if (e->hasTagName (T("path")))
  63681. d = parsePath (*e);
  63682. else if (e->hasTagName (T("rect")))
  63683. d = parseRect (*e);
  63684. else if (e->hasTagName (T("circle")))
  63685. d = parseCircle (*e);
  63686. else if (e->hasTagName (T("ellipse")))
  63687. d = parseEllipse (*e);
  63688. else if (e->hasTagName (T("line")))
  63689. d = parseLine (*e);
  63690. else if (e->hasTagName (T("polyline")))
  63691. d = parsePolygon (*e, true);
  63692. else if (e->hasTagName (T("polygon")))
  63693. d = parsePolygon (*e, false);
  63694. else if (e->hasTagName (T("text")))
  63695. d = parseText (*e);
  63696. else if (e->hasTagName (T("switch")))
  63697. d = parseSwitch (*e);
  63698. else if (e->hasTagName (T("style")))
  63699. parseCSSStyle (*e);
  63700. parentDrawable->insertDrawable (d);
  63701. }
  63702. }
  63703. DrawableComposite* parseSwitch (const XmlElement& xml)
  63704. {
  63705. const XmlElement* const group = xml.getChildByName (T("g"));
  63706. if (group != 0)
  63707. return parseGroupElement (*group);
  63708. return 0;
  63709. }
  63710. DrawableComposite* parseGroupElement (const XmlElement& xml)
  63711. {
  63712. DrawableComposite* const drawable = new DrawableComposite();
  63713. drawable->setName (xml.getStringAttribute (T("id")));
  63714. if (xml.hasAttribute (T("transform")))
  63715. {
  63716. SVGState newState (*this);
  63717. newState.addTransform (xml);
  63718. newState.parseSubElements (xml, drawable);
  63719. }
  63720. else
  63721. {
  63722. parseSubElements (xml, drawable);
  63723. }
  63724. return drawable;
  63725. }
  63726. Drawable* parsePath (const XmlElement& xml) const
  63727. {
  63728. const String d (xml.getStringAttribute (T("d")).trimStart());
  63729. Path path;
  63730. if (getStyleAttribute (&xml, T("fill-rule")).trim().equalsIgnoreCase (T("evenodd")))
  63731. path.setUsingNonZeroWinding (false);
  63732. int index = 0;
  63733. float lastX = 0, lastY = 0;
  63734. float lastX2 = 0, lastY2 = 0;
  63735. tchar lastCommandChar = 0;
  63736. bool carryOn = true;
  63737. const String validCommandChars (T("MmLlHhVvCcSsQqTtAaZz"));
  63738. for (;;)
  63739. {
  63740. float x, y, x2, y2, x3, y3;
  63741. const bool isRelative = (d[index] >= 'a' && d[index] <= 'z');
  63742. if (validCommandChars.containsChar (d[index]))
  63743. lastCommandChar = d [index++];
  63744. switch (lastCommandChar)
  63745. {
  63746. case T('M'):
  63747. case T('m'):
  63748. case T('L'):
  63749. case T('l'):
  63750. if (parseCoords (d, x, y, index, false))
  63751. {
  63752. if (isRelative)
  63753. {
  63754. x += lastX;
  63755. y += lastY;
  63756. }
  63757. if (lastCommandChar == T('M') || lastCommandChar == T('m'))
  63758. path.startNewSubPath (x, y);
  63759. else
  63760. path.lineTo (x, y);
  63761. lastX2 = lastX;
  63762. lastY2 = lastY;
  63763. lastX = x;
  63764. lastY = y;
  63765. }
  63766. else
  63767. {
  63768. ++index;
  63769. }
  63770. break;
  63771. case T('H'):
  63772. case T('h'):
  63773. if (parseCoord (d, x, index, false, true))
  63774. {
  63775. if (isRelative)
  63776. x += lastX;
  63777. path.lineTo (x, lastY);
  63778. lastX2 = lastX;
  63779. lastX = x;
  63780. }
  63781. else
  63782. {
  63783. ++index;
  63784. }
  63785. break;
  63786. case T('V'):
  63787. case T('v'):
  63788. if (parseCoord (d, y, index, false, false))
  63789. {
  63790. if (isRelative)
  63791. y += lastY;
  63792. path.lineTo (lastX, y);
  63793. lastY2 = lastY;
  63794. lastY = y;
  63795. }
  63796. else
  63797. {
  63798. ++index;
  63799. }
  63800. break;
  63801. case T('C'):
  63802. case T('c'):
  63803. if (parseCoords (d, x, y, index, false)
  63804. && parseCoords (d, x2, y2, index, false)
  63805. && parseCoords (d, x3, y3, index, false))
  63806. {
  63807. if (isRelative)
  63808. {
  63809. x += lastX;
  63810. y += lastY;
  63811. x2 += lastX;
  63812. y2 += lastY;
  63813. x3 += lastX;
  63814. y3 += lastY;
  63815. }
  63816. path.cubicTo (x, y, x2, y2, x3, y3);
  63817. lastX2 = x2;
  63818. lastY2 = y2;
  63819. lastX = x3;
  63820. lastY = y3;
  63821. }
  63822. else
  63823. {
  63824. ++index;
  63825. }
  63826. break;
  63827. case T('S'):
  63828. case T('s'):
  63829. if (parseCoords (d, x, y, index, false)
  63830. && parseCoords (d, x3, y3, index, false))
  63831. {
  63832. if (isRelative)
  63833. {
  63834. x += lastX;
  63835. y += lastY;
  63836. x3 += lastX;
  63837. y3 += lastY;
  63838. }
  63839. x2 = lastX + (lastX - lastX2);
  63840. y2 = lastY + (lastY - lastY2);
  63841. path.cubicTo (x2, y2, x, y, x3, y3);
  63842. lastX2 = x2;
  63843. lastY2 = y2;
  63844. lastX = x3;
  63845. lastY = y3;
  63846. }
  63847. else
  63848. {
  63849. ++index;
  63850. }
  63851. break;
  63852. case T('Q'):
  63853. case T('q'):
  63854. if (parseCoords (d, x, y, index, false)
  63855. && parseCoords (d, x2, y2, index, false))
  63856. {
  63857. if (isRelative)
  63858. {
  63859. x += lastX;
  63860. y += lastY;
  63861. x2 += lastX;
  63862. y2 += lastY;
  63863. }
  63864. path.quadraticTo (x, y, x2, y2);
  63865. lastX2 = x;
  63866. lastY2 = y;
  63867. lastX = x2;
  63868. lastY = y2;
  63869. }
  63870. else
  63871. {
  63872. ++index;
  63873. }
  63874. break;
  63875. case T('T'):
  63876. case T('t'):
  63877. if (parseCoords (d, x, y, index, false))
  63878. {
  63879. if (isRelative)
  63880. {
  63881. x += lastX;
  63882. y += lastY;
  63883. }
  63884. x2 = lastX + (lastX - lastX2);
  63885. y2 = lastY + (lastY - lastY2);
  63886. path.quadraticTo (x2, y2, x, y);
  63887. lastX2 = x2;
  63888. lastY2 = y2;
  63889. lastX = x;
  63890. lastY = y;
  63891. }
  63892. else
  63893. {
  63894. ++index;
  63895. }
  63896. break;
  63897. case T('A'):
  63898. case T('a'):
  63899. if (parseCoords (d, x, y, index, false))
  63900. {
  63901. String num;
  63902. if (parseNextNumber (d, num, index, false))
  63903. {
  63904. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  63905. if (parseNextNumber (d, num, index, false))
  63906. {
  63907. const bool largeArc = num.getIntValue() != 0;
  63908. if (parseNextNumber (d, num, index, false))
  63909. {
  63910. const bool sweep = num.getIntValue() != 0;
  63911. if (parseCoords (d, x2, y2, index, false))
  63912. {
  63913. if (isRelative)
  63914. {
  63915. x2 += lastX;
  63916. y2 += lastY;
  63917. }
  63918. if (lastX != x2 || lastY != y2)
  63919. {
  63920. double centreX, centreY, startAngle, deltaAngle;
  63921. double rx = x, ry = y;
  63922. endpointToCentreParameters (lastX, lastY, x2, y2,
  63923. angle, largeArc, sweep,
  63924. rx, ry, centreX, centreY,
  63925. startAngle, deltaAngle);
  63926. path.addCentredArc ((float) centreX, (float) centreY,
  63927. (float) rx, (float) ry,
  63928. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  63929. false);
  63930. path.lineTo (x2, y2);
  63931. }
  63932. lastX2 = lastX;
  63933. lastY2 = lastY;
  63934. lastX = x2;
  63935. lastY = y2;
  63936. }
  63937. }
  63938. }
  63939. }
  63940. }
  63941. else
  63942. {
  63943. ++index;
  63944. }
  63945. break;
  63946. case T('Z'):
  63947. case T('z'):
  63948. path.closeSubPath();
  63949. while (CharacterFunctions::isWhitespace (d [index]))
  63950. ++index;
  63951. break;
  63952. default:
  63953. carryOn = false;
  63954. break;
  63955. }
  63956. if (! carryOn)
  63957. break;
  63958. }
  63959. return parseShape (xml, path);
  63960. }
  63961. Drawable* parseRect (const XmlElement& xml) const
  63962. {
  63963. Path rect;
  63964. const bool hasRX = xml.hasAttribute (T("rx"));
  63965. const bool hasRY = xml.hasAttribute (T("ry"));
  63966. if (hasRX || hasRY)
  63967. {
  63968. float rx = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  63969. float ry = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  63970. if (! hasRX)
  63971. rx = ry;
  63972. else if (! hasRY)
  63973. ry = rx;
  63974. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  63975. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  63976. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  63977. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH),
  63978. rx, ry);
  63979. }
  63980. else
  63981. {
  63982. rect.addRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  63983. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  63984. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  63985. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH));
  63986. }
  63987. return parseShape (xml, rect);
  63988. }
  63989. Drawable* parseCircle (const XmlElement& xml) const
  63990. {
  63991. Path circle;
  63992. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  63993. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  63994. const float radius = getCoordLength (xml.getStringAttribute (T("r")), viewBoxW);
  63995. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  63996. return parseShape (xml, circle);
  63997. }
  63998. Drawable* parseEllipse (const XmlElement& xml) const
  63999. {
  64000. Path ellipse;
  64001. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  64002. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  64003. const float radiusX = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  64004. const float radiusY = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  64005. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  64006. return parseShape (xml, ellipse);
  64007. }
  64008. Drawable* parseLine (const XmlElement& xml) const
  64009. {
  64010. Path line;
  64011. const float x1 = getCoordLength (xml.getStringAttribute (T("x1")), viewBoxW);
  64012. const float y1 = getCoordLength (xml.getStringAttribute (T("y1")), viewBoxH);
  64013. const float x2 = getCoordLength (xml.getStringAttribute (T("x2")), viewBoxW);
  64014. const float y2 = getCoordLength (xml.getStringAttribute (T("y2")), viewBoxH);
  64015. line.startNewSubPath (x1, y1);
  64016. line.lineTo (x2, y2);
  64017. return parseShape (xml, line);
  64018. }
  64019. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  64020. {
  64021. const String points (xml.getStringAttribute (T("points")));
  64022. Path path;
  64023. int index = 0;
  64024. float x, y;
  64025. if (parseCoords (points, x, y, index, true))
  64026. {
  64027. float firstX = x;
  64028. float firstY = y;
  64029. float lastX = 0, lastY = 0;
  64030. path.startNewSubPath (x, y);
  64031. while (parseCoords (points, x, y, index, true))
  64032. {
  64033. lastX = x;
  64034. lastY = y;
  64035. path.lineTo (x, y);
  64036. }
  64037. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  64038. path.closeSubPath();
  64039. }
  64040. return parseShape (xml, path);
  64041. }
  64042. Drawable* parseShape (const XmlElement& xml, Path& path,
  64043. const bool parseTransform = true) const
  64044. {
  64045. if (parseTransform && xml.hasAttribute (T("transform")))
  64046. {
  64047. SVGState newState (*this);
  64048. newState.addTransform (xml);
  64049. return newState.parseShape (xml, path, false);
  64050. }
  64051. DrawablePath* dp = new DrawablePath();
  64052. dp->setSolidFill (Colours::transparentBlack);
  64053. path.applyTransform (transform);
  64054. dp->setPath (path);
  64055. Path::Iterator iter (path);
  64056. bool containsClosedSubPath = false;
  64057. while (iter.next())
  64058. {
  64059. if (iter.elementType == Path::Iterator::closePath)
  64060. {
  64061. containsClosedSubPath = true;
  64062. break;
  64063. }
  64064. }
  64065. Brush* const fillBrush
  64066. = getBrushForFill (path,
  64067. getStyleAttribute (&xml, T("fill")),
  64068. getStyleAttribute (&xml, T("fill-opacity")),
  64069. getStyleAttribute (&xml, T("opacity")),
  64070. containsClosedSubPath ? Colours::black
  64071. : Colours::transparentBlack);
  64072. if (fillBrush != 0)
  64073. {
  64074. if (! fillBrush->isInvisible())
  64075. {
  64076. fillBrush->applyTransform (transform);
  64077. dp->setFillBrush (*fillBrush);
  64078. }
  64079. delete fillBrush;
  64080. }
  64081. const String strokeType (getStyleAttribute (&xml, T("stroke")));
  64082. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase (T("none")))
  64083. {
  64084. Brush* const strokeBrush
  64085. = getBrushForFill (path, strokeType,
  64086. getStyleAttribute (&xml, T("stroke-opacity")),
  64087. getStyleAttribute (&xml, T("opacity")),
  64088. Colours::transparentBlack);
  64089. if (strokeBrush != 0)
  64090. {
  64091. const PathStrokeType stroke (getStrokeFor (&xml));
  64092. if (! strokeBrush->isInvisible())
  64093. {
  64094. strokeBrush->applyTransform (transform);
  64095. dp->setOutline (stroke, *strokeBrush);
  64096. }
  64097. delete strokeBrush;
  64098. }
  64099. }
  64100. return dp;
  64101. }
  64102. const XmlElement* findLinkedElement (const XmlElement* e) const
  64103. {
  64104. const String id (e->getStringAttribute (T("xlink:href")));
  64105. if (! id.startsWithChar (T('#')))
  64106. return 0;
  64107. return findElementForId (topLevelXml, id.substring (1));
  64108. }
  64109. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  64110. {
  64111. if (fillXml == 0)
  64112. return;
  64113. forEachXmlChildElementWithTagName (*fillXml, e, T("stop"))
  64114. {
  64115. int index = 0;
  64116. Colour col (parseColour (getStyleAttribute (e, T("stop-color")), index, Colours::black));
  64117. const String opacity (getStyleAttribute (e, T("stop-opacity"), T("1")));
  64118. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  64119. double offset = e->getDoubleAttribute (T("offset"));
  64120. if (e->getStringAttribute (T("offset")).containsChar (T('%')))
  64121. offset *= 0.01;
  64122. cg.addColour (jlimit (0.0, 1.0, offset), col);
  64123. }
  64124. }
  64125. Brush* getBrushForFill (const Path& path,
  64126. const String& fill,
  64127. const String& fillOpacity,
  64128. const String& overallOpacity,
  64129. const Colour& defaultColour) const
  64130. {
  64131. float opacity = 1.0f;
  64132. if (overallOpacity.isNotEmpty())
  64133. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  64134. if (fillOpacity.isNotEmpty())
  64135. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  64136. if (fill.startsWithIgnoreCase (T("url")))
  64137. {
  64138. const String id (fill.fromFirstOccurrenceOf (T("#"), false, false)
  64139. .upToLastOccurrenceOf (T(")"), false, false).trim());
  64140. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  64141. if (fillXml != 0
  64142. && (fillXml->hasTagName (T("linearGradient"))
  64143. || fillXml->hasTagName (T("radialGradient"))))
  64144. {
  64145. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  64146. ColourGradient cg;
  64147. addGradientStopsIn (cg, inheritedFrom);
  64148. addGradientStopsIn (cg, fillXml);
  64149. if (cg.getNumColours() > 0)
  64150. {
  64151. cg.addColour (0.0, cg.getColour (0));
  64152. cg.addColour (1.0, cg.getColour (cg.getNumColours() - 1));
  64153. }
  64154. else
  64155. {
  64156. cg.addColour (0.0, Colours::black);
  64157. cg.addColour (1.0, Colours::black);
  64158. }
  64159. if (overallOpacity.isNotEmpty())
  64160. cg.multiplyOpacity (overallOpacity.getFloatValue());
  64161. jassert (cg.getNumColours() > 0);
  64162. cg.isRadial = fillXml->hasTagName (T("radialGradient"));
  64163. cg.transform = parseTransform (fillXml->getStringAttribute (T("gradientTransform")));
  64164. float width = viewBoxW;
  64165. float height = viewBoxH;
  64166. float dx = 0.0;
  64167. float dy = 0.0;
  64168. const bool userSpace = fillXml->getStringAttribute (T("gradientUnits")).equalsIgnoreCase (T("userSpaceOnUse"));
  64169. if (! userSpace)
  64170. path.getBounds (dx, dy, width, height);
  64171. if (cg.isRadial)
  64172. {
  64173. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("cx"), T("50%")), width);
  64174. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("cy"), T("50%")), height);
  64175. const float radius = getCoordLength (fillXml->getStringAttribute (T("r"), T("50%")), width);
  64176. cg.x2 = cg.x1 + radius;
  64177. cg.y2 = cg.y1;
  64178. //xxx (the fx, fy focal point isn't handled properly here..)
  64179. }
  64180. else
  64181. {
  64182. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("x1"), T("0%")), width);
  64183. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("y1"), T("0%")), height);
  64184. cg.x2 = dx + getCoordLength (fillXml->getStringAttribute (T("x2"), T("100%")), width);
  64185. cg.y2 = dy + getCoordLength (fillXml->getStringAttribute (T("y2"), T("0%")), height);
  64186. if (cg.x1 == cg.x2 && cg.y1 == cg.y2)
  64187. return new SolidColourBrush (cg.getColour (cg.getNumColours() - 1));
  64188. }
  64189. return new GradientBrush (cg);
  64190. }
  64191. }
  64192. if (fill.equalsIgnoreCase (T("none")))
  64193. return new SolidColourBrush (Colours::transparentBlack);
  64194. int i = 0;
  64195. Colour colour (parseColour (fill, i, defaultColour));
  64196. colour = colour.withMultipliedAlpha (opacity);
  64197. return new SolidColourBrush (colour);
  64198. }
  64199. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  64200. {
  64201. const String width (getStyleAttribute (xml, T("stroke-width")));
  64202. const String cap (getStyleAttribute (xml, T("stroke-linecap")));
  64203. const String join (getStyleAttribute (xml, T("stroke-linejoin")));
  64204. //const String mitreLimit (getStyleAttribute (xml, T("stroke-miterlimit")));
  64205. //const String dashArray (getStyleAttribute (xml, T("stroke-dasharray")));
  64206. //const String dashOffset (getStyleAttribute (xml, T("stroke-dashoffset")));
  64207. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  64208. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  64209. if (join.equalsIgnoreCase (T("round")))
  64210. joinStyle = PathStrokeType::curved;
  64211. else if (join.equalsIgnoreCase (T("bevel")))
  64212. joinStyle = PathStrokeType::beveled;
  64213. if (cap.equalsIgnoreCase (T("round")))
  64214. capStyle = PathStrokeType::rounded;
  64215. else if (cap.equalsIgnoreCase (T("square")))
  64216. capStyle = PathStrokeType::square;
  64217. float ox = 0.0f, oy = 0.0f;
  64218. transform.transformPoint (ox, oy);
  64219. float x = getCoordLength (width, viewBoxW), y = 0.0f;
  64220. transform.transformPoint (x, y);
  64221. return PathStrokeType (width.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  64222. joinStyle, capStyle);
  64223. }
  64224. Drawable* parseText (const XmlElement& xml)
  64225. {
  64226. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  64227. getCoordList (xCoords, getInheritedAttribute (&xml, T("x")), true, true);
  64228. getCoordList (yCoords, getInheritedAttribute (&xml, T("y")), true, false);
  64229. getCoordList (dxCoords, getInheritedAttribute (&xml, T("dx")), true, true);
  64230. getCoordList (dyCoords, getInheritedAttribute (&xml, T("dy")), true, false);
  64231. //xxx not done text yet!
  64232. forEachXmlChildElement (xml, e)
  64233. {
  64234. if (e->isTextElement())
  64235. {
  64236. const String text (e->getText());
  64237. Path path;
  64238. Drawable* s = parseShape (*e, path);
  64239. delete s;
  64240. }
  64241. else if (e->hasTagName (T("tspan")))
  64242. {
  64243. Drawable* s = parseText (*e);
  64244. delete s;
  64245. }
  64246. }
  64247. return 0;
  64248. }
  64249. void addTransform (const XmlElement& xml)
  64250. {
  64251. transform = parseTransform (xml.getStringAttribute (T("transform")))
  64252. .followedBy (transform);
  64253. }
  64254. bool parseCoord (const String& s, float& value, int& index,
  64255. const bool allowUnits, const bool isX) const
  64256. {
  64257. String number;
  64258. if (! parseNextNumber (s, number, index, allowUnits))
  64259. {
  64260. value = 0;
  64261. return false;
  64262. }
  64263. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  64264. return true;
  64265. }
  64266. bool parseCoords (const String& s, float& x, float& y,
  64267. int& index, const bool allowUnits) const
  64268. {
  64269. return parseCoord (s, x, index, allowUnits, true)
  64270. && parseCoord (s, y, index, allowUnits, false);
  64271. }
  64272. float getCoordLength (const String& s, const float sizeForProportions) const
  64273. {
  64274. float n = s.getFloatValue();
  64275. const int len = s.length();
  64276. if (len > 2)
  64277. {
  64278. const float dpi = 96.0f;
  64279. const tchar n1 = s [len - 2];
  64280. const tchar n2 = s [len - 1];
  64281. if (n1 == T('i') && n2 == T('n'))
  64282. n *= dpi;
  64283. else if (n1 == T('m') && n2 == T('m'))
  64284. n *= dpi / 25.4f;
  64285. else if (n1 == T('c') && n2 == T('m'))
  64286. n *= dpi / 2.54f;
  64287. else if (n1 == T('p') && n2 == T('c'))
  64288. n *= 15.0f;
  64289. else if (n2 == T('%'))
  64290. n *= 0.01f * sizeForProportions;
  64291. }
  64292. return n;
  64293. }
  64294. void getCoordList (Array <float>& coords, const String& list,
  64295. const bool allowUnits, const bool isX) const
  64296. {
  64297. int index = 0;
  64298. float value;
  64299. while (parseCoord (list, value, index, allowUnits, isX))
  64300. coords.add (value);
  64301. }
  64302. void parseCSSStyle (const XmlElement& xml)
  64303. {
  64304. cssStyleText = xml.getAllSubText() + T("\n") + cssStyleText;
  64305. }
  64306. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  64307. const String& defaultValue = String::empty) const
  64308. {
  64309. if (xml->hasAttribute (attributeName))
  64310. return xml->getStringAttribute (attributeName, defaultValue);
  64311. const String styleAtt (xml->getStringAttribute (T("style")));
  64312. if (styleAtt.isNotEmpty())
  64313. {
  64314. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  64315. if (value.isNotEmpty())
  64316. return value;
  64317. }
  64318. else if (xml->hasAttribute (T("class")))
  64319. {
  64320. const String className (T(".") + xml->getStringAttribute (T("class")));
  64321. int index = cssStyleText.indexOfIgnoreCase (className + T(" "));
  64322. if (index < 0)
  64323. index = cssStyleText.indexOfIgnoreCase (className + T("{"));
  64324. if (index >= 0)
  64325. {
  64326. const int openBracket = cssStyleText.indexOfChar (index, T('{'));
  64327. if (openBracket > index)
  64328. {
  64329. const int closeBracket = cssStyleText.indexOfChar (openBracket, T('}'));
  64330. if (closeBracket > openBracket)
  64331. {
  64332. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  64333. if (value.isNotEmpty())
  64334. return value;
  64335. }
  64336. }
  64337. }
  64338. }
  64339. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  64340. if (xml != 0)
  64341. return getStyleAttribute (xml, attributeName, defaultValue);
  64342. return defaultValue;
  64343. }
  64344. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  64345. {
  64346. if (xml->hasAttribute (attributeName))
  64347. return xml->getStringAttribute (attributeName);
  64348. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  64349. if (xml != 0)
  64350. return getInheritedAttribute (xml, attributeName);
  64351. return String::empty;
  64352. }
  64353. static bool isIdentifierChar (const tchar c)
  64354. {
  64355. return CharacterFunctions::isLetter (c) || c == T('-');
  64356. }
  64357. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  64358. {
  64359. int i = 0;
  64360. for (;;)
  64361. {
  64362. i = list.indexOf (i, attributeName);
  64363. if (i < 0)
  64364. break;
  64365. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  64366. && ! isIdentifierChar (list [i + attributeName.length()]))
  64367. {
  64368. i = list.indexOfChar (i, T(':'));
  64369. if (i < 0)
  64370. break;
  64371. int end = list.indexOfChar (i, T(';'));
  64372. if (end < 0)
  64373. end = 0x7ffff;
  64374. return list.substring (i + 1, end).trim();
  64375. }
  64376. ++i;
  64377. }
  64378. return defaultValue;
  64379. }
  64380. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  64381. {
  64382. const tchar* const s = (const tchar*) source;
  64383. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  64384. ++index;
  64385. int start = index;
  64386. if (CharacterFunctions::isDigit (s[index]) || s[index] == T('.') || s[index] == T('-'))
  64387. ++index;
  64388. while (CharacterFunctions::isDigit (s[index]) || s[index] == T('.'))
  64389. ++index;
  64390. if ((s[index] == T('e') || s[index] == T('E'))
  64391. && (CharacterFunctions::isDigit (s[index + 1])
  64392. || s[index + 1] == T('-')
  64393. || s[index + 1] == T('+')))
  64394. {
  64395. index += 2;
  64396. while (CharacterFunctions::isDigit (s[index]))
  64397. ++index;
  64398. }
  64399. if (allowUnits)
  64400. {
  64401. while (CharacterFunctions::isLetter (s[index]))
  64402. ++index;
  64403. }
  64404. if (index == start)
  64405. return false;
  64406. value = String (s + start, index - start);
  64407. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  64408. ++index;
  64409. return true;
  64410. }
  64411. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  64412. {
  64413. if (s [index] == T('#'))
  64414. {
  64415. uint32 hex [6];
  64416. zeromem (hex, sizeof (hex));
  64417. int numChars = 0;
  64418. for (int i = 6; --i >= 0;)
  64419. {
  64420. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  64421. if (hexValue >= 0)
  64422. hex [numChars++] = hexValue;
  64423. else
  64424. break;
  64425. }
  64426. if (numChars <= 3)
  64427. return Colour ((uint8) (hex [0] * 0x11),
  64428. (uint8) (hex [1] * 0x11),
  64429. (uint8) (hex [2] * 0x11));
  64430. else
  64431. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  64432. (uint8) ((hex [2] << 4) + hex [3]),
  64433. (uint8) ((hex [4] << 4) + hex [5]));
  64434. }
  64435. else if (s [index] == T('r')
  64436. && s [index + 1] == T('g')
  64437. && s [index + 2] == T('b'))
  64438. {
  64439. const int openBracket = s.indexOfChar (index, T('('));
  64440. const int closeBracket = s.indexOfChar (openBracket, T(')'));
  64441. if (openBracket >= 3 && closeBracket > openBracket)
  64442. {
  64443. index = closeBracket;
  64444. StringArray tokens;
  64445. tokens.addTokens (s.substring (openBracket + 1, closeBracket), T(","), T(""));
  64446. tokens.trim();
  64447. tokens.removeEmptyStrings();
  64448. if (tokens[0].containsChar T('%'))
  64449. return Colour ((uint8) roundDoubleToInt (2.55 * tokens[0].getDoubleValue()),
  64450. (uint8) roundDoubleToInt (2.55 * tokens[1].getDoubleValue()),
  64451. (uint8) roundDoubleToInt (2.55 * tokens[2].getDoubleValue()));
  64452. else
  64453. return Colour ((uint8) tokens[0].getIntValue(),
  64454. (uint8) tokens[1].getIntValue(),
  64455. (uint8) tokens[2].getIntValue());
  64456. }
  64457. }
  64458. return Colours::findColourForName (s, defaultColour);
  64459. }
  64460. static const AffineTransform parseTransform (String t)
  64461. {
  64462. AffineTransform result;
  64463. while (t.isNotEmpty())
  64464. {
  64465. StringArray tokens;
  64466. tokens.addTokens (t.fromFirstOccurrenceOf (T("("), false, false)
  64467. .upToFirstOccurrenceOf (T(")"), false, false),
  64468. T(", "), 0);
  64469. tokens.removeEmptyStrings (true);
  64470. float numbers [6];
  64471. for (int i = 0; i < 6; ++i)
  64472. numbers[i] = tokens[i].getFloatValue();
  64473. AffineTransform trans;
  64474. if (t.startsWithIgnoreCase (T("matrix")))
  64475. {
  64476. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  64477. numbers[1], numbers[3], numbers[5]);
  64478. }
  64479. else if (t.startsWithIgnoreCase (T("translate")))
  64480. {
  64481. trans = trans.translated (numbers[0], numbers[1]);
  64482. }
  64483. else if (t.startsWithIgnoreCase (T("scale")))
  64484. {
  64485. if (tokens.size() == 1)
  64486. trans = trans.scaled (numbers[0], numbers[0]);
  64487. else
  64488. trans = trans.scaled (numbers[0], numbers[1]);
  64489. }
  64490. else if (t.startsWithIgnoreCase (T("rotate")))
  64491. {
  64492. if (tokens.size() != 3)
  64493. trans = trans.rotated (numbers[0] / (180.0f / float_Pi));
  64494. else
  64495. trans = trans.rotated (numbers[0] / (180.0f / float_Pi),
  64496. numbers[1], numbers[2]);
  64497. }
  64498. else if (t.startsWithIgnoreCase (T("skewX")))
  64499. {
  64500. trans = AffineTransform (1.0f, tanf (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  64501. 0.0f, 1.0f, 0.0f);
  64502. }
  64503. else if (t.startsWithIgnoreCase (T("skewY")))
  64504. {
  64505. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  64506. tanf (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  64507. }
  64508. result = trans.followedBy (result);
  64509. t = t.fromFirstOccurrenceOf (T(")"), false, false).trimStart();
  64510. }
  64511. return result;
  64512. }
  64513. static void endpointToCentreParameters (const double x1, const double y1,
  64514. const double x2, const double y2,
  64515. const double angle,
  64516. const bool largeArc, const bool sweep,
  64517. double& rx, double& ry,
  64518. double& centreX, double& centreY,
  64519. double& startAngle, double& deltaAngle)
  64520. {
  64521. const double midX = (x1 - x2) * 0.5;
  64522. const double midY = (y1 - y2) * 0.5;
  64523. const double cosAngle = cos (angle);
  64524. const double sinAngle = sin (angle);
  64525. const double xp = cosAngle * midX + sinAngle * midY;
  64526. const double yp = cosAngle * midY - sinAngle * midX;
  64527. const double xp2 = xp * xp;
  64528. const double yp2 = yp * yp;
  64529. double rx2 = rx * rx;
  64530. double ry2 = ry * ry;
  64531. const double s = (xp2 / rx2) + (yp2 / ry2);
  64532. double c;
  64533. if (s <= 1.0)
  64534. {
  64535. c = sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  64536. / (( rx2 * yp2) + (ry2 * xp2))));
  64537. if (largeArc == sweep)
  64538. c = -c;
  64539. }
  64540. else
  64541. {
  64542. const double s2 = sqrt (s);
  64543. rx *= s2;
  64544. ry *= s2;
  64545. rx2 = rx * rx;
  64546. ry2 = ry * ry;
  64547. c = 0;
  64548. }
  64549. const double cpx = ((rx * yp) / ry) * c;
  64550. const double cpy = ((-ry * xp) / rx) * c;
  64551. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  64552. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  64553. const double ux = (xp - cpx) / rx;
  64554. const double uy = (yp - cpy) / ry;
  64555. const double vx = (-xp - cpx) / rx;
  64556. const double vy = (-yp - cpy) / ry;
  64557. const double length = juce_hypot (ux, uy);
  64558. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  64559. if (uy < 0)
  64560. startAngle = -startAngle;
  64561. startAngle += double_Pi * 0.5;
  64562. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  64563. / (length * juce_hypot (vx, vy))));
  64564. if ((ux * vy) - (uy * vx) < 0)
  64565. deltaAngle = -deltaAngle;
  64566. if (sweep)
  64567. {
  64568. if (deltaAngle < 0)
  64569. deltaAngle += double_Pi * 2.0;
  64570. }
  64571. else
  64572. {
  64573. if (deltaAngle > 0)
  64574. deltaAngle -= double_Pi * 2.0;
  64575. }
  64576. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  64577. }
  64578. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  64579. {
  64580. forEachXmlChildElement (*parent, e)
  64581. {
  64582. if (e->compareAttribute (T("id"), id))
  64583. return e;
  64584. const XmlElement* const found = findElementForId (e, id);
  64585. if (found != 0)
  64586. return found;
  64587. }
  64588. return 0;
  64589. }
  64590. const SVGState& operator= (const SVGState&);
  64591. };
  64592. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  64593. {
  64594. SVGState state (&svgDocument);
  64595. return state.parseSVGElement (svgDocument);
  64596. }
  64597. END_JUCE_NAMESPACE
  64598. /********* End of inlined file: juce_SVGParser.cpp *********/
  64599. /********* Start of inlined file: juce_DropShadowEffect.cpp *********/
  64600. BEGIN_JUCE_NAMESPACE
  64601. #if JUCE_MSVC
  64602. #pragma optimize ("t", on) // try to avoid slowing everything down in debug builds
  64603. #endif
  64604. DropShadowEffect::DropShadowEffect()
  64605. : offsetX (0),
  64606. offsetY (0),
  64607. radius (4),
  64608. opacity (0.6f)
  64609. {
  64610. }
  64611. DropShadowEffect::~DropShadowEffect()
  64612. {
  64613. }
  64614. void DropShadowEffect::setShadowProperties (const float newRadius,
  64615. const float newOpacity,
  64616. const int newShadowOffsetX,
  64617. const int newShadowOffsetY)
  64618. {
  64619. radius = jmax (1.1f, newRadius);
  64620. offsetX = newShadowOffsetX;
  64621. offsetY = newShadowOffsetY;
  64622. opacity = newOpacity;
  64623. }
  64624. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  64625. {
  64626. const int w = image.getWidth();
  64627. const int h = image.getHeight();
  64628. int lineStride, pixelStride;
  64629. const PixelARGB* srcPixels = (const PixelARGB*) image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(), lineStride, pixelStride);
  64630. Image shadowImage (Image::SingleChannel, w, h, false);
  64631. int destStride, destPixelStride;
  64632. uint8* const shadowChannel = (uint8*) shadowImage.lockPixelDataReadWrite (0, 0, w, h, destStride, destPixelStride);
  64633. const int filter = roundFloatToInt (63.0f / radius);
  64634. const int radiusMinus1 = roundFloatToInt ((radius - 1.0f) * 63.0f);
  64635. for (int x = w; --x >= 0;)
  64636. {
  64637. int shadowAlpha = 0;
  64638. const PixelARGB* src = srcPixels + x;
  64639. uint8* shadowPix = shadowChannel + x;
  64640. for (int y = h; --y >= 0;)
  64641. {
  64642. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  64643. *shadowPix = (uint8) shadowAlpha;
  64644. src = (const PixelARGB*) (((const uint8*) src) + lineStride);
  64645. shadowPix += destStride;
  64646. }
  64647. }
  64648. for (int y = h; --y >= 0;)
  64649. {
  64650. int shadowAlpha = 0;
  64651. uint8* shadowPix = shadowChannel + y * destStride;
  64652. for (int x = w; --x >= 0;)
  64653. {
  64654. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  64655. *shadowPix++ = (uint8) shadowAlpha;
  64656. }
  64657. }
  64658. image.releasePixelDataReadOnly (srcPixels);
  64659. shadowImage.releasePixelDataReadWrite (shadowChannel);
  64660. g.setColour (Colours::black.withAlpha (opacity));
  64661. g.drawImageAt (&shadowImage, offsetX, offsetY, true);
  64662. g.setOpacity (1.0f);
  64663. g.drawImageAt (&image, 0, 0);
  64664. }
  64665. END_JUCE_NAMESPACE
  64666. /********* End of inlined file: juce_DropShadowEffect.cpp *********/
  64667. /********* Start of inlined file: juce_GlowEffect.cpp *********/
  64668. BEGIN_JUCE_NAMESPACE
  64669. GlowEffect::GlowEffect()
  64670. : radius (2.0f),
  64671. colour (Colours::white)
  64672. {
  64673. }
  64674. GlowEffect::~GlowEffect()
  64675. {
  64676. }
  64677. void GlowEffect::setGlowProperties (const float newRadius,
  64678. const Colour& newColour)
  64679. {
  64680. radius = newRadius;
  64681. colour = newColour;
  64682. }
  64683. void GlowEffect::applyEffect (Image& image, Graphics& g)
  64684. {
  64685. const int w = image.getWidth();
  64686. const int h = image.getHeight();
  64687. Image temp (image.getFormat(), w, h, true);
  64688. ImageConvolutionKernel blurKernel (roundFloatToInt (radius * 2.0f));
  64689. blurKernel.createGaussianBlur (radius);
  64690. blurKernel.rescaleAllValues (radius);
  64691. blurKernel.applyToImage (temp, &image, 0, 0, w, h);
  64692. g.setColour (colour);
  64693. g.drawImageAt (&temp, 0, 0, true);
  64694. g.setOpacity (1.0f);
  64695. g.drawImageAt (&image, 0, 0, false);
  64696. }
  64697. END_JUCE_NAMESPACE
  64698. /********* End of inlined file: juce_GlowEffect.cpp *********/
  64699. /********* Start of inlined file: juce_ReduceOpacityEffect.cpp *********/
  64700. BEGIN_JUCE_NAMESPACE
  64701. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  64702. : opacity (opacity_)
  64703. {
  64704. }
  64705. ReduceOpacityEffect::~ReduceOpacityEffect()
  64706. {
  64707. }
  64708. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  64709. {
  64710. opacity = jlimit (0.0f, 1.0f, newOpacity);
  64711. }
  64712. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  64713. {
  64714. g.setOpacity (opacity);
  64715. g.drawImageAt (&image, 0, 0);
  64716. }
  64717. END_JUCE_NAMESPACE
  64718. /********* End of inlined file: juce_ReduceOpacityEffect.cpp *********/
  64719. /********* Start of inlined file: juce_Font.cpp *********/
  64720. BEGIN_JUCE_NAMESPACE
  64721. static const float minFontHeight = 0.1f;
  64722. static const float maxFontHeight = 10000.0f;
  64723. static const float defaultFontHeight = 14.0f;
  64724. static String defaultSans, defaultSerif, defaultFixed, fallbackFont;
  64725. Font::Font() throw()
  64726. : typefaceName (defaultSans),
  64727. height (defaultFontHeight),
  64728. horizontalScale (1.0f),
  64729. kerning (0),
  64730. ascent (0),
  64731. styleFlags (Font::plain)
  64732. {
  64733. }
  64734. void Font::resetToDefaultState() throw()
  64735. {
  64736. typefaceName = defaultSans;
  64737. height = defaultFontHeight;
  64738. horizontalScale = 1.0f;
  64739. kerning = 0;
  64740. ascent = 0;
  64741. styleFlags = Font::plain;
  64742. typeface = 0;
  64743. }
  64744. Font::Font (const float fontHeight,
  64745. const int styleFlags_) throw()
  64746. : typefaceName (defaultSans),
  64747. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  64748. horizontalScale (1.0f),
  64749. kerning (0),
  64750. ascent (0),
  64751. styleFlags (styleFlags_)
  64752. {
  64753. }
  64754. Font::Font (const String& typefaceName_,
  64755. const float fontHeight,
  64756. const int styleFlags_) throw()
  64757. : typefaceName (typefaceName_),
  64758. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  64759. horizontalScale (1.0f),
  64760. kerning (0),
  64761. ascent (0),
  64762. styleFlags (styleFlags_)
  64763. {
  64764. }
  64765. Font::Font (const Font& other) throw()
  64766. : typefaceName (other.typefaceName),
  64767. height (other.height),
  64768. horizontalScale (other.horizontalScale),
  64769. kerning (other.kerning),
  64770. ascent (other.ascent),
  64771. styleFlags (other.styleFlags),
  64772. typeface (other.typeface)
  64773. {
  64774. }
  64775. const Font& Font::operator= (const Font& other) throw()
  64776. {
  64777. if (this != &other)
  64778. {
  64779. typefaceName = other.typefaceName;
  64780. height = other.height;
  64781. styleFlags = other.styleFlags;
  64782. horizontalScale = other.horizontalScale;
  64783. kerning = other.kerning;
  64784. ascent = other.ascent;
  64785. typeface = other.typeface;
  64786. }
  64787. return *this;
  64788. }
  64789. Font::~Font() throw()
  64790. {
  64791. }
  64792. Font::Font (const Typeface& face) throw()
  64793. : height (11.0f),
  64794. horizontalScale (1.0f),
  64795. kerning (0),
  64796. ascent (0),
  64797. styleFlags (plain)
  64798. {
  64799. typefaceName = face.getName();
  64800. setBold (face.isBold());
  64801. setItalic (face.isItalic());
  64802. typeface = new Typeface (face);
  64803. }
  64804. bool Font::operator== (const Font& other) const throw()
  64805. {
  64806. return height == other.height
  64807. && horizontalScale == other.horizontalScale
  64808. && kerning == other.kerning
  64809. && styleFlags == other.styleFlags
  64810. && typefaceName == other.typefaceName;
  64811. }
  64812. bool Font::operator!= (const Font& other) const throw()
  64813. {
  64814. return ! operator== (other);
  64815. }
  64816. void Font::setTypefaceName (const String& faceName) throw()
  64817. {
  64818. typefaceName = faceName;
  64819. typeface = 0;
  64820. ascent = 0;
  64821. }
  64822. void Font::initialiseDefaultFontNames() throw()
  64823. {
  64824. Font::getDefaultFontNames (defaultSans,
  64825. defaultSerif,
  64826. defaultFixed);
  64827. }
  64828. void clearUpDefaultFontNames() throw() // called at shutdown by code in Typface
  64829. {
  64830. defaultSans = String::empty;
  64831. defaultSerif = String::empty;
  64832. defaultFixed = String::empty;
  64833. fallbackFont = String::empty;
  64834. }
  64835. const String Font::getDefaultSansSerifFontName() throw()
  64836. {
  64837. return defaultSans;
  64838. }
  64839. const String Font::getDefaultSerifFontName() throw()
  64840. {
  64841. return defaultSerif;
  64842. }
  64843. const String Font::getDefaultMonospacedFontName() throw()
  64844. {
  64845. return defaultFixed;
  64846. }
  64847. void Font::setDefaultSansSerifFontName (const String& name) throw()
  64848. {
  64849. defaultSans = name;
  64850. }
  64851. const String Font::getFallbackFontName() throw()
  64852. {
  64853. return fallbackFont;
  64854. }
  64855. void Font::setFallbackFontName (const String& name) throw()
  64856. {
  64857. fallbackFont = name;
  64858. }
  64859. void Font::setHeight (float newHeight) throw()
  64860. {
  64861. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  64862. }
  64863. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  64864. {
  64865. newHeight = jlimit (minFontHeight, maxFontHeight, newHeight);
  64866. horizontalScale *= (height / newHeight);
  64867. height = newHeight;
  64868. }
  64869. void Font::setStyleFlags (const int newFlags) throw()
  64870. {
  64871. if (styleFlags != newFlags)
  64872. {
  64873. styleFlags = newFlags;
  64874. typeface = 0;
  64875. ascent = 0;
  64876. }
  64877. }
  64878. void Font::setSizeAndStyle (const float newHeight,
  64879. const int newStyleFlags,
  64880. const float newHorizontalScale,
  64881. const float newKerningAmount) throw()
  64882. {
  64883. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  64884. horizontalScale = newHorizontalScale;
  64885. kerning = newKerningAmount;
  64886. setStyleFlags (newStyleFlags);
  64887. }
  64888. void Font::setHorizontalScale (const float scaleFactor) throw()
  64889. {
  64890. horizontalScale = scaleFactor;
  64891. }
  64892. void Font::setExtraKerningFactor (const float extraKerning) throw()
  64893. {
  64894. kerning = extraKerning;
  64895. }
  64896. void Font::setBold (const bool shouldBeBold) throw()
  64897. {
  64898. setStyleFlags (shouldBeBold ? (styleFlags | bold)
  64899. : (styleFlags & ~bold));
  64900. }
  64901. bool Font::isBold() const throw()
  64902. {
  64903. return (styleFlags & bold) != 0;
  64904. }
  64905. void Font::setItalic (const bool shouldBeItalic) throw()
  64906. {
  64907. setStyleFlags (shouldBeItalic ? (styleFlags | italic)
  64908. : (styleFlags & ~italic));
  64909. }
  64910. bool Font::isItalic() const throw()
  64911. {
  64912. return (styleFlags & italic) != 0;
  64913. }
  64914. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  64915. {
  64916. setStyleFlags (shouldBeUnderlined ? (styleFlags | underlined)
  64917. : (styleFlags & ~underlined));
  64918. }
  64919. bool Font::isUnderlined() const throw()
  64920. {
  64921. return (styleFlags & underlined) != 0;
  64922. }
  64923. float Font::getAscent() const throw()
  64924. {
  64925. if (ascent == 0)
  64926. ascent = getTypeface()->getAscent();
  64927. return height * ascent;
  64928. }
  64929. float Font::getDescent() const throw()
  64930. {
  64931. return height - getAscent();
  64932. }
  64933. int Font::getStringWidth (const String& text) const throw()
  64934. {
  64935. return roundFloatToInt (getStringWidthFloat (text));
  64936. }
  64937. float Font::getStringWidthFloat (const String& text) const throw()
  64938. {
  64939. float x = 0.0f;
  64940. if (text.isNotEmpty())
  64941. {
  64942. Typeface* const typeface = getTypeface();
  64943. const juce_wchar* t = (const juce_wchar*) text;
  64944. do
  64945. {
  64946. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (*t++);
  64947. if (glyph != 0)
  64948. x += kerning + glyph->getHorizontalSpacing (*t);
  64949. }
  64950. while (*t != 0);
  64951. x *= height;
  64952. x *= horizontalScale;
  64953. }
  64954. return x;
  64955. }
  64956. Typeface* Font::getTypeface() const throw()
  64957. {
  64958. if (typeface == 0)
  64959. typeface = Typeface::getTypefaceFor (*this);
  64960. return typeface;
  64961. }
  64962. void Font::findFonts (OwnedArray<Font>& destArray) throw()
  64963. {
  64964. const StringArray names (findAllTypefaceNames());
  64965. for (int i = 0; i < names.size(); ++i)
  64966. destArray.add (new Font (names[i], defaultFontHeight, Font::plain));
  64967. }
  64968. END_JUCE_NAMESPACE
  64969. /********* End of inlined file: juce_Font.cpp *********/
  64970. /********* Start of inlined file: juce_GlyphArrangement.cpp *********/
  64971. BEGIN_JUCE_NAMESPACE
  64972. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  64973. class FontGlyphAlphaMap
  64974. {
  64975. public:
  64976. bool draw (const Graphics& g, float x, const float y) const throw()
  64977. {
  64978. if (bitmap1 == 0)
  64979. return false;
  64980. x += xOrigin;
  64981. const float xFloor = floorf (x);
  64982. const int intX = (int) xFloor;
  64983. g.drawImageAt (((x - xFloor) >= 0.5f && bitmap2 != 0) ? bitmap2 : bitmap1,
  64984. intX, (int) floorf (y + yOrigin), true);
  64985. return true;
  64986. }
  64987. juce_UseDebuggingNewOperator
  64988. private:
  64989. Image* bitmap1;
  64990. Image* bitmap2;
  64991. float xOrigin, yOrigin;
  64992. int lastAccessCount;
  64993. Typeface::Ptr typeface;
  64994. float height, horizontalScale;
  64995. juce_wchar character;
  64996. friend class GlyphCache;
  64997. FontGlyphAlphaMap() throw()
  64998. : bitmap1 (0),
  64999. bitmap2 (0),
  65000. lastAccessCount (0),
  65001. height (0),
  65002. horizontalScale (0),
  65003. character (0)
  65004. {
  65005. }
  65006. ~FontGlyphAlphaMap() throw()
  65007. {
  65008. delete bitmap1;
  65009. delete bitmap2;
  65010. }
  65011. class AlphaBitmapRenderer
  65012. {
  65013. uint8* const data;
  65014. const int stride;
  65015. uint8* lineStart;
  65016. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  65017. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  65018. public:
  65019. AlphaBitmapRenderer (uint8* const data_,
  65020. const int stride_) throw()
  65021. : data (data_),
  65022. stride (stride_)
  65023. {
  65024. }
  65025. forcedinline void setEdgeTableYPos (const int y) throw()
  65026. {
  65027. lineStart = data + (stride * y);
  65028. }
  65029. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  65030. {
  65031. lineStart [x] = (uint8) alphaLevel;
  65032. }
  65033. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  65034. {
  65035. uint8* d = lineStart + x;
  65036. while (--width >= 0)
  65037. *d++ = (uint8) alphaLevel;
  65038. }
  65039. };
  65040. Image* createAlphaMapFromPath (const Path& path,
  65041. float& topLeftX, float& topLeftY,
  65042. float xScale, float yScale,
  65043. const float subPixelOffsetX) throw()
  65044. {
  65045. Image* im = 0;
  65046. float px, py, pw, ph;
  65047. path.getBounds (px, py, pw, ph);
  65048. topLeftX = floorf (px * xScale);
  65049. topLeftY = floorf (py * yScale);
  65050. int bitmapWidth = roundFloatToInt (pw * xScale) + 2;
  65051. int bitmapHeight = roundFloatToInt (ph * yScale) + 2;
  65052. im = new Image (Image::SingleChannel, bitmapWidth, bitmapHeight, true);
  65053. EdgeTable edgeTable (0, bitmapHeight, EdgeTable::Oversampling_16times);
  65054. edgeTable.addPath (path, AffineTransform::scale (xScale, yScale)
  65055. .translated (subPixelOffsetX - topLeftX, -topLeftY));
  65056. int stride, pixelStride;
  65057. uint8* const pixels = (uint8*) im->lockPixelDataReadWrite (0, 0, bitmapWidth, bitmapHeight, stride, pixelStride);
  65058. jassert (pixelStride == 1);
  65059. AlphaBitmapRenderer renderer (pixels, stride);
  65060. edgeTable.iterate (renderer, 0, 0, bitmapWidth, bitmapHeight, 0);
  65061. im->releasePixelDataReadWrite (pixels);
  65062. return im;
  65063. }
  65064. void generate (Typeface* const face,
  65065. const juce_wchar character_,
  65066. const float fontHeight,
  65067. const float fontHorizontalScale) throw()
  65068. {
  65069. character = character_;
  65070. typeface = face;
  65071. height = fontHeight;
  65072. horizontalScale = fontHorizontalScale;
  65073. const Path* const glyphPath = face->getOutlineForGlyph (character_);
  65074. deleteAndZero (bitmap1);
  65075. deleteAndZero (bitmap2);
  65076. const float fontHScale = fontHeight * fontHorizontalScale;
  65077. if (glyphPath != 0 && ! glyphPath->isEmpty())
  65078. {
  65079. bitmap1 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.0f);
  65080. if (fontHScale < 24.0f)
  65081. bitmap2 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.5f);
  65082. }
  65083. else
  65084. {
  65085. xOrigin = yOrigin = 0;
  65086. }
  65087. }
  65088. };
  65089. static const int defaultNumGlyphsToCache = 120;
  65090. class GlyphCache;
  65091. static GlyphCache* cacheInstance = 0;
  65092. class GlyphCache : private DeletedAtShutdown
  65093. {
  65094. public:
  65095. static GlyphCache* getInstance() throw()
  65096. {
  65097. if (cacheInstance == 0)
  65098. cacheInstance = new GlyphCache();
  65099. return cacheInstance;
  65100. }
  65101. const FontGlyphAlphaMap& getGlyphFor (Typeface* const typeface,
  65102. const float fontHeight,
  65103. const float fontHorizontalScale,
  65104. const juce_wchar character) throw()
  65105. {
  65106. ++accessCounter;
  65107. int oldestCounter = INT_MAX;
  65108. int oldestIndex = 0;
  65109. for (int i = numGlyphs; --i >= 0;)
  65110. {
  65111. FontGlyphAlphaMap& g = glyphs[i];
  65112. if (g.character == character
  65113. && g.height == fontHeight
  65114. && g.typeface->hashCode() == typeface->hashCode()
  65115. && g.horizontalScale == fontHorizontalScale)
  65116. {
  65117. g.lastAccessCount = accessCounter;
  65118. ++hits;
  65119. return g;
  65120. }
  65121. if (oldestCounter > g.lastAccessCount)
  65122. {
  65123. oldestCounter = g.lastAccessCount;
  65124. oldestIndex = i;
  65125. }
  65126. }
  65127. ++misses;
  65128. if (hits + misses > (numGlyphs << 4))
  65129. {
  65130. if (misses * 2 > hits)
  65131. setCacheSize (numGlyphs + 32);
  65132. hits = 0;
  65133. misses = 0;
  65134. oldestIndex = 0;
  65135. }
  65136. FontGlyphAlphaMap& oldest = glyphs [oldestIndex];
  65137. oldest.lastAccessCount = accessCounter;
  65138. oldest.generate (typeface,
  65139. character,
  65140. fontHeight,
  65141. fontHorizontalScale);
  65142. return oldest;
  65143. }
  65144. void setCacheSize (const int num) throw()
  65145. {
  65146. if (numGlyphs != num)
  65147. {
  65148. numGlyphs = num;
  65149. if (glyphs != 0)
  65150. delete[] glyphs;
  65151. glyphs = new FontGlyphAlphaMap [numGlyphs];
  65152. hits = 0;
  65153. misses = 0;
  65154. }
  65155. }
  65156. juce_UseDebuggingNewOperator
  65157. private:
  65158. FontGlyphAlphaMap* glyphs;
  65159. int numGlyphs, accessCounter;
  65160. int hits, misses;
  65161. GlyphCache() throw()
  65162. : glyphs (0),
  65163. numGlyphs (0),
  65164. accessCounter (0)
  65165. {
  65166. setCacheSize (defaultNumGlyphsToCache);
  65167. }
  65168. ~GlyphCache() throw()
  65169. {
  65170. delete[] glyphs;
  65171. jassert (cacheInstance == this);
  65172. cacheInstance = 0;
  65173. }
  65174. GlyphCache (const GlyphCache&);
  65175. const GlyphCache& operator= (const GlyphCache&);
  65176. };
  65177. PositionedGlyph::PositionedGlyph() throw()
  65178. {
  65179. }
  65180. void PositionedGlyph::draw (const Graphics& g) const throw()
  65181. {
  65182. if (! glyphInfo->isWhitespace())
  65183. {
  65184. if (fontHeight < 100.0f && fontHeight > 0.1f && ! g.isVectorDevice())
  65185. {
  65186. const FontGlyphAlphaMap& alphaMap
  65187. = GlyphCache::getInstance()->getGlyphFor (glyphInfo->getTypeface(),
  65188. fontHeight,
  65189. fontHorizontalScale,
  65190. getCharacter());
  65191. alphaMap.draw (g, x, y);
  65192. }
  65193. else
  65194. {
  65195. // that's a bit of a dodgy size, isn't it??
  65196. jassert (fontHeight > 0.0f && fontHeight < 4000.0f);
  65197. draw (g, AffineTransform::identity);
  65198. }
  65199. }
  65200. }
  65201. void PositionedGlyph::draw (const Graphics& g,
  65202. const AffineTransform& transform) const throw()
  65203. {
  65204. if (! glyphInfo->isWhitespace())
  65205. {
  65206. g.fillPath (glyphInfo->getPath(),
  65207. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  65208. .translated (x, y)
  65209. .followedBy (transform));
  65210. }
  65211. }
  65212. void PositionedGlyph::createPath (Path& path) const throw()
  65213. {
  65214. if (! glyphInfo->isWhitespace())
  65215. {
  65216. path.addPath (glyphInfo->getPath(),
  65217. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  65218. .translated (x, y));
  65219. }
  65220. }
  65221. bool PositionedGlyph::hitTest (float px, float py) const throw()
  65222. {
  65223. if (px >= getLeft() && px < getRight()
  65224. && py >= getTop() && py < getBottom()
  65225. && fontHeight > 0.0f
  65226. && ! glyphInfo->isWhitespace())
  65227. {
  65228. AffineTransform::translation (-x, -y)
  65229. .scaled (1.0f / (fontHeight * fontHorizontalScale), 1.0f / fontHeight)
  65230. .transformPoint (px, py);
  65231. return glyphInfo->getPath().contains (px, py);
  65232. }
  65233. return false;
  65234. }
  65235. void PositionedGlyph::moveBy (const float deltaX,
  65236. const float deltaY) throw()
  65237. {
  65238. x += deltaX;
  65239. y += deltaY;
  65240. }
  65241. GlyphArrangement::GlyphArrangement() throw()
  65242. : numGlyphs (0),
  65243. numAllocated (0),
  65244. glyphs (0)
  65245. {
  65246. }
  65247. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other) throw()
  65248. : numGlyphs (0),
  65249. numAllocated (0),
  65250. glyphs (0)
  65251. {
  65252. addGlyphArrangement (other);
  65253. }
  65254. const GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other) throw()
  65255. {
  65256. if (this != &other)
  65257. {
  65258. clear();
  65259. addGlyphArrangement (other);
  65260. }
  65261. return *this;
  65262. }
  65263. GlyphArrangement::~GlyphArrangement() throw()
  65264. {
  65265. clear();
  65266. juce_free (glyphs);
  65267. }
  65268. void GlyphArrangement::ensureNumGlyphsAllocated (const int minGlyphs) throw()
  65269. {
  65270. if (numAllocated <= minGlyphs)
  65271. {
  65272. numAllocated = minGlyphs + 2;
  65273. if (glyphs == 0)
  65274. glyphs = (PositionedGlyph*) juce_malloc (numAllocated * sizeof (PositionedGlyph));
  65275. else
  65276. glyphs = (PositionedGlyph*) juce_realloc (glyphs, numAllocated * sizeof (PositionedGlyph));
  65277. }
  65278. }
  65279. void GlyphArrangement::incGlyphRefCount (const int i) const throw()
  65280. {
  65281. jassert (((unsigned int) i) < (unsigned int) numGlyphs);
  65282. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  65283. glyphs[i].glyphInfo->getTypeface()->incReferenceCount();
  65284. }
  65285. void GlyphArrangement::decGlyphRefCount (const int i) const throw()
  65286. {
  65287. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  65288. glyphs[i].glyphInfo->getTypeface()->decReferenceCount();
  65289. }
  65290. void GlyphArrangement::clear() throw()
  65291. {
  65292. for (int i = numGlyphs; --i >= 0;)
  65293. decGlyphRefCount (i);
  65294. numGlyphs = 0;
  65295. }
  65296. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const throw()
  65297. {
  65298. jassert (((unsigned int) index) < (unsigned int) numGlyphs);
  65299. return glyphs [index];
  65300. }
  65301. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other) throw()
  65302. {
  65303. ensureNumGlyphsAllocated (numGlyphs + other.numGlyphs);
  65304. memcpy (glyphs + numGlyphs, other.glyphs,
  65305. other.numGlyphs * sizeof (PositionedGlyph));
  65306. for (int i = other.numGlyphs; --i >= 0;)
  65307. incGlyphRefCount (numGlyphs++);
  65308. }
  65309. void GlyphArrangement::removeLast() throw()
  65310. {
  65311. if (numGlyphs > 0)
  65312. decGlyphRefCount (--numGlyphs);
  65313. }
  65314. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num) throw()
  65315. {
  65316. jassert (startIndex >= 0);
  65317. if (startIndex < 0)
  65318. startIndex = 0;
  65319. if (num < 0 || startIndex + num >= numGlyphs)
  65320. {
  65321. while (numGlyphs > startIndex)
  65322. removeLast();
  65323. }
  65324. else if (num > 0)
  65325. {
  65326. int i;
  65327. for (i = startIndex; i < startIndex + num; ++i)
  65328. decGlyphRefCount (i);
  65329. for (i = numGlyphs - (startIndex + num); --i >= 0;)
  65330. {
  65331. glyphs [startIndex] = glyphs [startIndex + num];
  65332. ++startIndex;
  65333. }
  65334. numGlyphs -= num;
  65335. }
  65336. }
  65337. void GlyphArrangement::addLineOfText (const Font& font,
  65338. const String& text,
  65339. const float xOffset,
  65340. const float yOffset) throw()
  65341. {
  65342. addCurtailedLineOfText (font, text,
  65343. xOffset, yOffset,
  65344. 1.0e10f, false);
  65345. }
  65346. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  65347. const String& text,
  65348. float xOffset,
  65349. const float yOffset,
  65350. const float maxWidthPixels,
  65351. const bool useEllipsis) throw()
  65352. {
  65353. const int textLen = text.length();
  65354. if (textLen > 0)
  65355. {
  65356. ensureNumGlyphsAllocated (numGlyphs + textLen + 3); // extra chars for ellipsis
  65357. Typeface* const typeface = font.getTypeface();
  65358. const float fontHeight = font.getHeight();
  65359. const float ascent = font.getAscent();
  65360. const float fontHorizontalScale = font.getHorizontalScale();
  65361. const float heightTimesScale = fontHorizontalScale * fontHeight;
  65362. const float kerningFactor = font.getExtraKerningFactor();
  65363. const float startX = xOffset;
  65364. const juce_wchar* const unicodeText = (const juce_wchar*) text;
  65365. for (int i = 0; i < textLen; ++i)
  65366. {
  65367. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (unicodeText[i]);
  65368. if (glyph != 0)
  65369. {
  65370. jassert (numAllocated > numGlyphs);
  65371. ensureNumGlyphsAllocated (numGlyphs);
  65372. PositionedGlyph& pg = glyphs [numGlyphs];
  65373. pg.glyphInfo = glyph;
  65374. pg.x = xOffset;
  65375. pg.y = yOffset;
  65376. pg.w = heightTimesScale * glyph->getHorizontalSpacing (0);
  65377. pg.fontHeight = fontHeight;
  65378. pg.fontAscent = ascent;
  65379. pg.fontHorizontalScale = fontHorizontalScale;
  65380. pg.isUnderlined = font.isUnderlined();
  65381. xOffset += heightTimesScale * (kerningFactor + glyph->getHorizontalSpacing (unicodeText [i + 1]));
  65382. if (xOffset - startX > maxWidthPixels + 1.0f)
  65383. {
  65384. // curtail the string if it's too wide..
  65385. if (useEllipsis && textLen > 3 && numGlyphs >= 3)
  65386. appendEllipsis (font, startX + maxWidthPixels);
  65387. break;
  65388. }
  65389. else
  65390. {
  65391. if (glyph->getTypeface() != 0)
  65392. glyph->getTypeface()->incReferenceCount();
  65393. ++numGlyphs;
  65394. }
  65395. }
  65396. }
  65397. }
  65398. }
  65399. void GlyphArrangement::appendEllipsis (const Font& font, const float maxXPixels) throw()
  65400. {
  65401. const TypefaceGlyphInfo* const dotGlyph = font.getTypeface()->getGlyph (T('.'));
  65402. if (dotGlyph != 0)
  65403. {
  65404. if (numGlyphs > 0)
  65405. {
  65406. PositionedGlyph& glyph = glyphs [numGlyphs - 1];
  65407. const float fontHeight = glyph.fontHeight;
  65408. const float fontHorizontalScale = glyph.fontHorizontalScale;
  65409. const float fontAscent = glyph.fontAscent;
  65410. const float dx = fontHeight * fontHorizontalScale
  65411. * (font.getExtraKerningFactor() + dotGlyph->getHorizontalSpacing (T('.')));
  65412. float xOffset = 0.0f, yOffset = 0.0f;
  65413. for (int dotPos = 3; --dotPos >= 0 && numGlyphs > 0;)
  65414. {
  65415. removeLast();
  65416. jassert (numAllocated > numGlyphs);
  65417. PositionedGlyph& pg = glyphs [numGlyphs];
  65418. xOffset = pg.x;
  65419. yOffset = pg.y;
  65420. if (numGlyphs == 0 || xOffset + dx * 3 <= maxXPixels)
  65421. break;
  65422. }
  65423. for (int i = 3; --i >= 0;)
  65424. {
  65425. jassert (numAllocated > numGlyphs);
  65426. ensureNumGlyphsAllocated (numGlyphs);
  65427. PositionedGlyph& pg = glyphs [numGlyphs];
  65428. pg.glyphInfo = dotGlyph;
  65429. pg.x = xOffset;
  65430. pg.y = yOffset;
  65431. pg.w = dx;
  65432. pg.fontHeight = fontHeight;
  65433. pg.fontAscent = fontAscent;
  65434. pg.fontHorizontalScale = fontHorizontalScale;
  65435. pg.isUnderlined = font.isUnderlined();
  65436. xOffset += dx;
  65437. if (dotGlyph->getTypeface() != 0)
  65438. dotGlyph->getTypeface()->incReferenceCount();
  65439. ++numGlyphs;
  65440. }
  65441. }
  65442. }
  65443. }
  65444. void GlyphArrangement::addJustifiedText (const Font& font,
  65445. const String& text,
  65446. float x, float y,
  65447. const float maxLineWidth,
  65448. const Justification& horizontalLayout) throw()
  65449. {
  65450. int lineStartIndex = numGlyphs;
  65451. addLineOfText (font, text, x, y);
  65452. const float originalY = y;
  65453. while (lineStartIndex < numGlyphs)
  65454. {
  65455. int i = lineStartIndex;
  65456. if (glyphs[i].getCharacter() != T('\n') && glyphs[i].getCharacter() != T('\r'))
  65457. ++i;
  65458. const float lineMaxX = glyphs [lineStartIndex].getLeft() + maxLineWidth;
  65459. int lastWordBreakIndex = -1;
  65460. while (i < numGlyphs)
  65461. {
  65462. PositionedGlyph& pg = glyphs[i];
  65463. const juce_wchar c = pg.getCharacter();
  65464. if (c == T('\r') || c == T('\n'))
  65465. {
  65466. ++i;
  65467. if (c == T('\r') && i < numGlyphs && glyphs [i].getCharacter() == T('\n'))
  65468. ++i;
  65469. break;
  65470. }
  65471. else if (pg.isWhitespace())
  65472. {
  65473. lastWordBreakIndex = i + 1;
  65474. }
  65475. else if (SHOULD_WRAP (pg.getRight(), lineMaxX))
  65476. {
  65477. if (lastWordBreakIndex >= 0)
  65478. i = lastWordBreakIndex;
  65479. break;
  65480. }
  65481. ++i;
  65482. }
  65483. const float currentLineStartX = glyphs [lineStartIndex].getLeft();
  65484. float currentLineEndX = currentLineStartX;
  65485. for (int j = i; --j >= lineStartIndex;)
  65486. {
  65487. if (! glyphs[j].isWhitespace())
  65488. {
  65489. currentLineEndX = glyphs[j].getRight();
  65490. break;
  65491. }
  65492. }
  65493. float deltaX = 0.0f;
  65494. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  65495. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  65496. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  65497. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  65498. else if (horizontalLayout.testFlags (Justification::right))
  65499. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  65500. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  65501. x + deltaX - currentLineStartX, y - originalY);
  65502. lineStartIndex = i;
  65503. y += font.getHeight();
  65504. }
  65505. }
  65506. void GlyphArrangement::addFittedText (const Font& f,
  65507. const String& text,
  65508. float x, float y,
  65509. float width, float height,
  65510. const Justification& layout,
  65511. int maximumLines,
  65512. const float minimumHorizontalScale) throw()
  65513. {
  65514. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  65515. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  65516. if (text.containsAnyOf (T("\r\n")))
  65517. {
  65518. GlyphArrangement ga;
  65519. ga.addJustifiedText (f, text, x, y, width, layout);
  65520. float l, t, r, b;
  65521. ga.getBoundingBox (0, -1, l, t, r, b, false);
  65522. float dy = y - t;
  65523. if (layout.testFlags (Justification::verticallyCentred))
  65524. dy += (height - (b - t)) * 0.5f;
  65525. else if (layout.testFlags (Justification::bottom))
  65526. dy += height - (b - t);
  65527. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  65528. addGlyphArrangement (ga);
  65529. return;
  65530. }
  65531. int startIndex = numGlyphs;
  65532. addLineOfText (f, text.trim(), x, y);
  65533. if (numGlyphs > startIndex)
  65534. {
  65535. float lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  65536. if (lineWidth <= 0)
  65537. return;
  65538. if (lineWidth * minimumHorizontalScale < width)
  65539. {
  65540. if (lineWidth > width)
  65541. {
  65542. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex,
  65543. width / lineWidth);
  65544. }
  65545. justifyGlyphs (startIndex, numGlyphs - startIndex,
  65546. x, y, width, height, layout);
  65547. }
  65548. else if (maximumLines <= 1)
  65549. {
  65550. const float ratio = jmax (minimumHorizontalScale, width / lineWidth);
  65551. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex, ratio);
  65552. while (numGlyphs > 0 && glyphs [numGlyphs - 1].x + glyphs [numGlyphs - 1].w >= x + width)
  65553. removeLast();
  65554. appendEllipsis (f, x + width);
  65555. justifyGlyphs (startIndex, numGlyphs - startIndex,
  65556. x, y, width, height, layout);
  65557. }
  65558. else
  65559. {
  65560. Font font (f);
  65561. String txt (text.trim());
  65562. const int length = txt.length();
  65563. int numLines = 1;
  65564. const int originalStartIndex = startIndex;
  65565. if (length <= 12 && ! txt.containsAnyOf (T(" -\t\r\n")))
  65566. maximumLines = 1;
  65567. maximumLines = jmin (maximumLines, length);
  65568. while (numLines < maximumLines)
  65569. {
  65570. ++numLines;
  65571. const float newFontHeight = height / (float)numLines;
  65572. if (newFontHeight < 8.0f)
  65573. break;
  65574. if (newFontHeight < font.getHeight())
  65575. {
  65576. font.setHeight (newFontHeight);
  65577. while (numGlyphs > startIndex)
  65578. removeLast();
  65579. addLineOfText (font, txt, x, y);
  65580. lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  65581. }
  65582. if (numLines > lineWidth / width)
  65583. break;
  65584. }
  65585. if (numLines < 1)
  65586. numLines = 1;
  65587. float lineY = y;
  65588. float widthPerLine = lineWidth / numLines;
  65589. int lastLineStartIndex = 0;
  65590. for (int line = 0; line < numLines; ++line)
  65591. {
  65592. int i = startIndex;
  65593. lastLineStartIndex = i;
  65594. float lineStartX = glyphs[startIndex].getLeft();
  65595. while (i < numGlyphs)
  65596. {
  65597. lineWidth = (glyphs[i].getRight() - lineStartX);
  65598. if (lineWidth > widthPerLine)
  65599. {
  65600. // got to a point where the line's too long, so skip forward to find a
  65601. // good place to break it..
  65602. const int searchStartIndex = i;
  65603. while (i < numGlyphs)
  65604. {
  65605. if ((glyphs[i].getRight() - lineStartX) * minimumHorizontalScale < width)
  65606. {
  65607. if (glyphs[i].isWhitespace()
  65608. || glyphs[i].getCharacter() == T('-'))
  65609. {
  65610. ++i;
  65611. break;
  65612. }
  65613. }
  65614. else
  65615. {
  65616. // can't find a suitable break, so try looking backwards..
  65617. i = searchStartIndex;
  65618. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  65619. {
  65620. if (glyphs[i - back].isWhitespace()
  65621. || glyphs[i - back].getCharacter() == T('-'))
  65622. {
  65623. i -= back - 1;
  65624. break;
  65625. }
  65626. }
  65627. break;
  65628. }
  65629. ++i;
  65630. }
  65631. break;
  65632. }
  65633. ++i;
  65634. }
  65635. int wsStart = i;
  65636. while (wsStart > 0 && glyphs[wsStart - 1].isWhitespace())
  65637. --wsStart;
  65638. int wsEnd = i;
  65639. while (wsEnd < numGlyphs && glyphs[wsEnd].isWhitespace())
  65640. ++wsEnd;
  65641. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  65642. i = jmax (wsStart, startIndex + 1);
  65643. lineWidth = glyphs[i - 1].getRight() - lineStartX;
  65644. if (lineWidth > width)
  65645. {
  65646. stretchRangeOfGlyphs (startIndex, i - startIndex,
  65647. width / lineWidth);
  65648. }
  65649. justifyGlyphs (startIndex, i - startIndex,
  65650. x, lineY, width, font.getHeight(),
  65651. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  65652. startIndex = i;
  65653. lineY += font.getHeight();
  65654. if (startIndex >= numGlyphs)
  65655. break;
  65656. }
  65657. if (startIndex < numGlyphs)
  65658. {
  65659. while (numGlyphs > startIndex)
  65660. removeLast();
  65661. if (startIndex - originalStartIndex > 4)
  65662. {
  65663. const float lineStartX = glyphs[lastLineStartIndex].getLeft();
  65664. appendEllipsis (font, lineStartX + width);
  65665. lineWidth = glyphs[startIndex - 1].getRight() - lineStartX;
  65666. if (lineWidth > width)
  65667. {
  65668. stretchRangeOfGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  65669. width / lineWidth);
  65670. }
  65671. justifyGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  65672. x, lineY - font.getHeight(), width, font.getHeight(),
  65673. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  65674. }
  65675. startIndex = numGlyphs;
  65676. }
  65677. justifyGlyphs (originalStartIndex, startIndex - originalStartIndex,
  65678. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  65679. }
  65680. }
  65681. }
  65682. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  65683. const float dx, const float dy) throw()
  65684. {
  65685. jassert (startIndex >= 0);
  65686. if (dx != 0.0f || dy != 0.0f)
  65687. {
  65688. if (num < 0 || startIndex + num > numGlyphs)
  65689. num = numGlyphs - startIndex;
  65690. while (--num >= 0)
  65691. {
  65692. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  65693. glyphs [startIndex++].moveBy (dx, dy);
  65694. }
  65695. }
  65696. }
  65697. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  65698. const float horizontalScaleFactor) throw()
  65699. {
  65700. jassert (startIndex >= 0);
  65701. if (num < 0 || startIndex + num > numGlyphs)
  65702. num = numGlyphs - startIndex;
  65703. if (num > 0)
  65704. {
  65705. const float xAnchor = glyphs[startIndex].getLeft();
  65706. while (--num >= 0)
  65707. {
  65708. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  65709. PositionedGlyph& pg = glyphs[startIndex++];
  65710. pg.x = xAnchor + (pg.x - xAnchor) * horizontalScaleFactor;
  65711. pg.fontHorizontalScale *= horizontalScaleFactor;
  65712. pg.w *= horizontalScaleFactor;
  65713. }
  65714. }
  65715. }
  65716. void GlyphArrangement::getBoundingBox (int startIndex, int num,
  65717. float& left,
  65718. float& top,
  65719. float& right,
  65720. float& bottom,
  65721. const bool includeWhitespace) const throw()
  65722. {
  65723. jassert (startIndex >= 0);
  65724. if (num < 0 || startIndex + num > numGlyphs)
  65725. num = numGlyphs - startIndex;
  65726. left = 0.0f;
  65727. top = 0.0f;
  65728. right = 0.0f;
  65729. bottom = 0.0f;
  65730. bool isFirst = true;
  65731. while (--num >= 0)
  65732. {
  65733. const PositionedGlyph& pg = glyphs [startIndex++];
  65734. if (includeWhitespace || ! pg.isWhitespace())
  65735. {
  65736. if (isFirst)
  65737. {
  65738. isFirst = false;
  65739. left = pg.getLeft();
  65740. top = pg.getTop();
  65741. right = pg.getRight();
  65742. bottom = pg.getBottom();
  65743. }
  65744. else
  65745. {
  65746. left = jmin (left, pg.getLeft());
  65747. top = jmin (top, pg.getTop());
  65748. right = jmax (right, pg.getRight());
  65749. bottom = jmax (bottom, pg.getBottom());
  65750. }
  65751. }
  65752. }
  65753. }
  65754. void GlyphArrangement::justifyGlyphs (const int startIndex,
  65755. const int num,
  65756. const float x, const float y,
  65757. const float width, const float height,
  65758. const Justification& justification) throw()
  65759. {
  65760. jassert (num >= 0 && startIndex >= 0);
  65761. if (numGlyphs > 0 && num > 0)
  65762. {
  65763. float left, top, right, bottom;
  65764. getBoundingBox (startIndex, num, left, top, right, bottom,
  65765. ! justification.testFlags (Justification::horizontallyJustified
  65766. | Justification::horizontallyCentred));
  65767. float deltaX = 0.0f;
  65768. if (justification.testFlags (Justification::horizontallyJustified))
  65769. deltaX = x - left;
  65770. else if (justification.testFlags (Justification::horizontallyCentred))
  65771. deltaX = x + (width - (right - left)) * 0.5f - left;
  65772. else if (justification.testFlags (Justification::right))
  65773. deltaX = (x + width) - right;
  65774. else
  65775. deltaX = x - left;
  65776. float deltaY = 0.0f;
  65777. if (justification.testFlags (Justification::top))
  65778. deltaY = y - top;
  65779. else if (justification.testFlags (Justification::bottom))
  65780. deltaY = (y + height) - bottom;
  65781. else
  65782. deltaY = y + (height - (bottom - top)) * 0.5f - top;
  65783. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  65784. if (justification.testFlags (Justification::horizontallyJustified))
  65785. {
  65786. int lineStart = 0;
  65787. float baseY = glyphs [startIndex].getBaselineY();
  65788. int i;
  65789. for (i = 0; i < num; ++i)
  65790. {
  65791. const float glyphY = glyphs [startIndex + i].getBaselineY();
  65792. if (glyphY != baseY)
  65793. {
  65794. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  65795. lineStart = i;
  65796. baseY = glyphY;
  65797. }
  65798. }
  65799. if (i > lineStart)
  65800. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  65801. }
  65802. }
  65803. }
  65804. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth) throw()
  65805. {
  65806. if (start + num < numGlyphs
  65807. && glyphs [start + num - 1].getCharacter() != T('\r')
  65808. && glyphs [start + num - 1].getCharacter() != T('\n'))
  65809. {
  65810. int numSpaces = 0;
  65811. int spacesAtEnd = 0;
  65812. for (int i = 0; i < num; ++i)
  65813. {
  65814. if (glyphs [start + i].isWhitespace())
  65815. {
  65816. ++spacesAtEnd;
  65817. ++numSpaces;
  65818. }
  65819. else
  65820. {
  65821. spacesAtEnd = 0;
  65822. }
  65823. }
  65824. numSpaces -= spacesAtEnd;
  65825. if (numSpaces > 0)
  65826. {
  65827. const float startX = glyphs [start].getLeft();
  65828. const float endX = glyphs [start + num - 1 - spacesAtEnd].getRight();
  65829. const float extraPaddingBetweenWords
  65830. = (targetWidth - (endX - startX)) / (float) numSpaces;
  65831. float deltaX = 0.0f;
  65832. for (int i = 0; i < num; ++i)
  65833. {
  65834. glyphs [start + i].moveBy (deltaX, 0.0);
  65835. if (glyphs [start + i].isWhitespace())
  65836. deltaX += extraPaddingBetweenWords;
  65837. }
  65838. }
  65839. }
  65840. }
  65841. void GlyphArrangement::draw (const Graphics& g) const throw()
  65842. {
  65843. for (int i = 0; i < numGlyphs; ++i)
  65844. {
  65845. glyphs[i].draw (g);
  65846. if (glyphs[i].isUnderlined)
  65847. {
  65848. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  65849. juce_wchar nextChar = 0;
  65850. if (i < numGlyphs - 1
  65851. && glyphs[i + 1].y == glyphs[i].y)
  65852. {
  65853. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  65854. }
  65855. g.fillRect (glyphs[i].x,
  65856. glyphs[i].y + lineThickness * 2.0f,
  65857. glyphs[i].fontHeight
  65858. * glyphs[i].fontHorizontalScale
  65859. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  65860. lineThickness);
  65861. }
  65862. }
  65863. }
  65864. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const throw()
  65865. {
  65866. for (int i = 0; i < numGlyphs; ++i)
  65867. {
  65868. glyphs[i].draw (g, transform);
  65869. if (glyphs[i].isUnderlined)
  65870. {
  65871. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  65872. juce_wchar nextChar = 0;
  65873. if (i < numGlyphs - 1
  65874. && glyphs[i + 1].y == glyphs[i].y)
  65875. {
  65876. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  65877. }
  65878. Path p;
  65879. p.addLineSegment (glyphs[i].x,
  65880. glyphs[i].y + lineThickness * 2.5f,
  65881. glyphs[i].x + glyphs[i].fontHeight
  65882. * glyphs[i].fontHorizontalScale
  65883. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  65884. glyphs[i].y + lineThickness * 2.5f,
  65885. lineThickness);
  65886. g.fillPath (p, transform);
  65887. }
  65888. }
  65889. }
  65890. void GlyphArrangement::createPath (Path& path) const throw()
  65891. {
  65892. for (int i = 0; i < numGlyphs; ++i)
  65893. glyphs[i].createPath (path);
  65894. }
  65895. int GlyphArrangement::findGlyphIndexAt (float x, float y) const throw()
  65896. {
  65897. for (int i = 0; i < numGlyphs; ++i)
  65898. if (glyphs[i].hitTest (x, y))
  65899. return i;
  65900. return -1;
  65901. }
  65902. END_JUCE_NAMESPACE
  65903. /********* End of inlined file: juce_GlyphArrangement.cpp *********/
  65904. /********* Start of inlined file: juce_TextLayout.cpp *********/
  65905. BEGIN_JUCE_NAMESPACE
  65906. class TextLayoutToken
  65907. {
  65908. public:
  65909. String text;
  65910. Font font;
  65911. int x, y, w, h;
  65912. int line, lineHeight;
  65913. bool isWhitespace, isNewLine;
  65914. TextLayoutToken (const String& t,
  65915. const Font& f,
  65916. const bool isWhitespace_) throw()
  65917. : text (t),
  65918. font (f),
  65919. x(0),
  65920. y(0),
  65921. isWhitespace (isWhitespace_)
  65922. {
  65923. w = font.getStringWidth (t);
  65924. h = roundFloatToInt (f.getHeight());
  65925. isNewLine = t.containsAnyOf (T("\r\n"));
  65926. }
  65927. TextLayoutToken (const TextLayoutToken& other) throw()
  65928. : text (other.text),
  65929. font (other.font),
  65930. x (other.x),
  65931. y (other.y),
  65932. w (other.w),
  65933. h (other.h),
  65934. line (other.line),
  65935. lineHeight (other.lineHeight),
  65936. isWhitespace (other.isWhitespace),
  65937. isNewLine (other.isNewLine)
  65938. {
  65939. }
  65940. ~TextLayoutToken() throw()
  65941. {
  65942. }
  65943. void draw (Graphics& g,
  65944. const int xOffset,
  65945. const int yOffset) throw()
  65946. {
  65947. if (! isWhitespace)
  65948. {
  65949. g.setFont (font);
  65950. g.drawSingleLineText (text.trimEnd(),
  65951. xOffset + x,
  65952. yOffset + y + (lineHeight - h)
  65953. + roundFloatToInt (font.getAscent()));
  65954. }
  65955. }
  65956. juce_UseDebuggingNewOperator
  65957. };
  65958. TextLayout::TextLayout() throw()
  65959. : tokens (64),
  65960. totalLines (0)
  65961. {
  65962. }
  65963. TextLayout::TextLayout (const String& text,
  65964. const Font& font) throw()
  65965. : tokens (64),
  65966. totalLines (0)
  65967. {
  65968. appendText (text, font);
  65969. }
  65970. TextLayout::TextLayout (const TextLayout& other) throw()
  65971. : tokens (64),
  65972. totalLines (0)
  65973. {
  65974. *this = other;
  65975. }
  65976. const TextLayout& TextLayout::operator= (const TextLayout& other) throw()
  65977. {
  65978. if (this != &other)
  65979. {
  65980. clear();
  65981. totalLines = other.totalLines;
  65982. for (int i = 0; i < other.tokens.size(); ++i)
  65983. tokens.add (new TextLayoutToken (*(const TextLayoutToken*)(other.tokens.getUnchecked(i))));
  65984. }
  65985. return *this;
  65986. }
  65987. TextLayout::~TextLayout() throw()
  65988. {
  65989. clear();
  65990. }
  65991. void TextLayout::clear() throw()
  65992. {
  65993. for (int i = tokens.size(); --i >= 0;)
  65994. {
  65995. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  65996. delete t;
  65997. }
  65998. tokens.clear();
  65999. totalLines = 0;
  66000. }
  66001. void TextLayout::appendText (const String& text,
  66002. const Font& font) throw()
  66003. {
  66004. const tchar* t = text;
  66005. String currentString;
  66006. int lastCharType = 0;
  66007. for (;;)
  66008. {
  66009. const tchar c = *t++;
  66010. if (c == 0)
  66011. break;
  66012. int charType;
  66013. if (c == T('\r') || c == T('\n'))
  66014. {
  66015. charType = 0;
  66016. }
  66017. else if (CharacterFunctions::isWhitespace (c))
  66018. {
  66019. charType = 2;
  66020. }
  66021. else
  66022. {
  66023. charType = 1;
  66024. }
  66025. if (charType == 0 || charType != lastCharType)
  66026. {
  66027. if (currentString.isNotEmpty())
  66028. {
  66029. tokens.add (new TextLayoutToken (currentString, font,
  66030. lastCharType == 2 || lastCharType == 0));
  66031. }
  66032. currentString = String::charToString (c);
  66033. if (c == T('\r') && *t == T('\n'))
  66034. currentString += *t++;
  66035. }
  66036. else
  66037. {
  66038. currentString += c;
  66039. }
  66040. lastCharType = charType;
  66041. }
  66042. if (currentString.isNotEmpty())
  66043. tokens.add (new TextLayoutToken (currentString,
  66044. font,
  66045. lastCharType == 2));
  66046. }
  66047. void TextLayout::setText (const String& text, const Font& font) throw()
  66048. {
  66049. clear();
  66050. appendText (text, font);
  66051. }
  66052. void TextLayout::layout (int maxWidth,
  66053. const Justification& justification,
  66054. const bool attemptToBalanceLineLengths) throw()
  66055. {
  66056. if (attemptToBalanceLineLengths)
  66057. {
  66058. const int originalW = maxWidth;
  66059. int bestWidth = maxWidth;
  66060. float bestLineProportion = 0.0f;
  66061. while (maxWidth > originalW / 2)
  66062. {
  66063. layout (maxWidth, justification, false);
  66064. if (getNumLines() <= 1)
  66065. return;
  66066. const int lastLineW = getLineWidth (getNumLines() - 1);
  66067. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  66068. const float prop = lastLineW / (float) lastButOneLineW;
  66069. if (prop > 0.9f)
  66070. return;
  66071. if (prop > bestLineProportion)
  66072. {
  66073. bestLineProportion = prop;
  66074. bestWidth = maxWidth;
  66075. }
  66076. maxWidth -= 10;
  66077. }
  66078. layout (bestWidth, justification, false);
  66079. }
  66080. else
  66081. {
  66082. int x = 0;
  66083. int y = 0;
  66084. int h = 0;
  66085. totalLines = 0;
  66086. int i;
  66087. for (i = 0; i < tokens.size(); ++i)
  66088. {
  66089. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  66090. t->x = x;
  66091. t->y = y;
  66092. t->line = totalLines;
  66093. x += t->w;
  66094. h = jmax (h, t->h);
  66095. const TextLayoutToken* nextTok = (TextLayoutToken*) tokens [i + 1];
  66096. if (nextTok == 0)
  66097. break;
  66098. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  66099. {
  66100. // finished a line, so go back and update the heights of the things on it
  66101. for (int j = i; j >= 0; --j)
  66102. {
  66103. TextLayoutToken* const tok = (TextLayoutToken*)tokens.getUnchecked(j);
  66104. if (tok->line == totalLines)
  66105. tok->lineHeight = h;
  66106. else
  66107. break;
  66108. }
  66109. x = 0;
  66110. y += h;
  66111. h = 0;
  66112. ++totalLines;
  66113. }
  66114. }
  66115. // finished a line, so go back and update the heights of the things on it
  66116. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  66117. {
  66118. TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(j);
  66119. if (t->line == totalLines)
  66120. t->lineHeight = h;
  66121. else
  66122. break;
  66123. }
  66124. ++totalLines;
  66125. if (! justification.testFlags (Justification::left))
  66126. {
  66127. int totalW = getWidth();
  66128. for (i = totalLines; --i >= 0;)
  66129. {
  66130. const int lineW = getLineWidth (i);
  66131. int dx = 0;
  66132. if (justification.testFlags (Justification::horizontallyCentred))
  66133. dx = (totalW - lineW) / 2;
  66134. else if (justification.testFlags (Justification::right))
  66135. dx = totalW - lineW;
  66136. for (int j = tokens.size(); --j >= 0;)
  66137. {
  66138. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(j);
  66139. if (t->line == i)
  66140. t->x += dx;
  66141. }
  66142. }
  66143. }
  66144. }
  66145. }
  66146. int TextLayout::getLineWidth (const int lineNumber) const throw()
  66147. {
  66148. int maxW = 0;
  66149. for (int i = tokens.size(); --i >= 0;)
  66150. {
  66151. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  66152. if (t->line == lineNumber && ! t->isWhitespace)
  66153. maxW = jmax (maxW, t->x + t->w);
  66154. }
  66155. return maxW;
  66156. }
  66157. int TextLayout::getWidth() const throw()
  66158. {
  66159. int maxW = 0;
  66160. for (int i = tokens.size(); --i >= 0;)
  66161. {
  66162. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  66163. if (! t->isWhitespace)
  66164. maxW = jmax (maxW, t->x + t->w);
  66165. }
  66166. return maxW;
  66167. }
  66168. int TextLayout::getHeight() const throw()
  66169. {
  66170. int maxH = 0;
  66171. for (int i = tokens.size(); --i >= 0;)
  66172. {
  66173. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  66174. if (! t->isWhitespace)
  66175. maxH = jmax (maxH, t->y + t->h);
  66176. }
  66177. return maxH;
  66178. }
  66179. void TextLayout::draw (Graphics& g,
  66180. const int xOffset,
  66181. const int yOffset) const throw()
  66182. {
  66183. for (int i = tokens.size(); --i >= 0;)
  66184. ((TextLayoutToken*) tokens.getUnchecked(i))->draw (g, xOffset, yOffset);
  66185. }
  66186. void TextLayout::drawWithin (Graphics& g,
  66187. int x, int y, int w, int h,
  66188. const Justification& justification) const throw()
  66189. {
  66190. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  66191. x, y, w, h);
  66192. draw (g, x, y);
  66193. }
  66194. END_JUCE_NAMESPACE
  66195. /********* End of inlined file: juce_TextLayout.cpp *********/
  66196. /********* Start of inlined file: juce_Typeface.cpp *********/
  66197. BEGIN_JUCE_NAMESPACE
  66198. TypefaceGlyphInfo::TypefaceGlyphInfo (const juce_wchar character_,
  66199. const Path& shape,
  66200. const float horizontalSeparation,
  66201. Typeface* const typeface_) throw()
  66202. : character (character_),
  66203. path (shape),
  66204. width (horizontalSeparation),
  66205. typeface (typeface_)
  66206. {
  66207. }
  66208. TypefaceGlyphInfo::~TypefaceGlyphInfo() throw()
  66209. {
  66210. }
  66211. float TypefaceGlyphInfo::getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  66212. {
  66213. if (subsequentCharacter != 0)
  66214. {
  66215. const KerningPair* const pairs = (const KerningPair*) kerningPairs.getData();
  66216. const int numPairs = getNumKerningPairs();
  66217. for (int i = 0; i < numPairs; ++i)
  66218. if (pairs [i].character2 == subsequentCharacter)
  66219. return width + pairs [i].kerningAmount;
  66220. }
  66221. return width;
  66222. }
  66223. void TypefaceGlyphInfo::addKerningPair (const juce_wchar subsequentCharacter,
  66224. const float extraKerningAmount) throw()
  66225. {
  66226. const int numPairs = getNumKerningPairs();
  66227. kerningPairs.setSize ((numPairs + 1) * sizeof (KerningPair));
  66228. KerningPair& p = getKerningPair (numPairs);
  66229. p.character2 = subsequentCharacter;
  66230. p.kerningAmount = extraKerningAmount;
  66231. }
  66232. TypefaceGlyphInfo::KerningPair& TypefaceGlyphInfo::getKerningPair (const int index) const throw()
  66233. {
  66234. return ((KerningPair*) kerningPairs.getData()) [index];
  66235. }
  66236. int TypefaceGlyphInfo::getNumKerningPairs() const throw()
  66237. {
  66238. return kerningPairs.getSize() / sizeof (KerningPair);
  66239. }
  66240. Typeface::Typeface() throw()
  66241. : hash (0),
  66242. isFullyPopulated (false)
  66243. {
  66244. zeromem (lookupTable, sizeof (lookupTable));
  66245. }
  66246. Typeface::Typeface (const Typeface& other)
  66247. : typefaceName (other.typefaceName),
  66248. ascent (other.ascent),
  66249. bold (other.bold),
  66250. italic (other.italic),
  66251. isFullyPopulated (other.isFullyPopulated),
  66252. defaultCharacter (other.defaultCharacter)
  66253. {
  66254. zeromem (lookupTable, sizeof (lookupTable));
  66255. for (int i = 0; i < other.glyphs.size(); ++i)
  66256. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  66257. updateHashCode();
  66258. }
  66259. Typeface::Typeface (const String& faceName,
  66260. const bool bold,
  66261. const bool italic)
  66262. : isFullyPopulated (false)
  66263. {
  66264. zeromem (lookupTable, sizeof (lookupTable));
  66265. initialiseTypefaceCharacteristics (faceName, bold, italic, false);
  66266. updateHashCode();
  66267. }
  66268. Typeface::~Typeface()
  66269. {
  66270. clear();
  66271. }
  66272. const Typeface& Typeface::operator= (const Typeface& other) throw()
  66273. {
  66274. if (this != &other)
  66275. {
  66276. clear();
  66277. typefaceName = other.typefaceName;
  66278. ascent = other.ascent;
  66279. bold = other.bold;
  66280. italic = other.italic;
  66281. isFullyPopulated = other.isFullyPopulated;
  66282. defaultCharacter = other.defaultCharacter;
  66283. for (int i = 0; i < other.glyphs.size(); ++i)
  66284. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  66285. updateHashCode();
  66286. }
  66287. return *this;
  66288. }
  66289. void Typeface::updateHashCode() throw()
  66290. {
  66291. hash = typefaceName.hashCode();
  66292. if (bold)
  66293. hash ^= 0xffff;
  66294. if (italic)
  66295. hash ^= 0xffff0000;
  66296. }
  66297. void Typeface::clear() throw()
  66298. {
  66299. zeromem (lookupTable, sizeof (lookupTable));
  66300. typefaceName = String::empty;
  66301. bold = false;
  66302. italic = false;
  66303. for (int i = glyphs.size(); --i >= 0;)
  66304. {
  66305. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) (glyphs.getUnchecked(i));
  66306. delete g;
  66307. }
  66308. glyphs.clear();
  66309. updateHashCode();
  66310. }
  66311. Typeface::Typeface (InputStream& serialisedTypefaceStream)
  66312. {
  66313. zeromem (lookupTable, sizeof (lookupTable));
  66314. isFullyPopulated = true;
  66315. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  66316. BufferedInputStream in (&gzin, 32768, false);
  66317. typefaceName = in.readString();
  66318. bold = in.readBool();
  66319. italic = in.readBool();
  66320. ascent = in.readFloat();
  66321. defaultCharacter = (juce_wchar) in.readShort();
  66322. int i, numChars = in.readInt();
  66323. for (i = 0; i < numChars; ++i)
  66324. {
  66325. const juce_wchar c = (juce_wchar) in.readShort();
  66326. const float width = in.readFloat();
  66327. Path p;
  66328. p.loadPathFromStream (in);
  66329. addGlyph (c, p, width);
  66330. }
  66331. const int numKerningPairs = in.readInt();
  66332. for (i = 0; i < numKerningPairs; ++i)
  66333. {
  66334. const juce_wchar char1 = (juce_wchar) in.readShort();
  66335. const juce_wchar char2 = (juce_wchar) in.readShort();
  66336. addKerningPair (char1, char2, in.readFloat());
  66337. }
  66338. updateHashCode();
  66339. }
  66340. void Typeface::serialise (OutputStream& outputStream)
  66341. {
  66342. GZIPCompressorOutputStream out (&outputStream);
  66343. out.writeString (typefaceName);
  66344. out.writeBool (bold);
  66345. out.writeBool (italic);
  66346. out.writeFloat (ascent);
  66347. out.writeShort ((short) (unsigned short) defaultCharacter);
  66348. out.writeInt (glyphs.size());
  66349. int i, numKerningPairs = 0;
  66350. for (i = 0; i < glyphs.size(); ++i)
  66351. {
  66352. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  66353. out.writeShort ((short) (unsigned short) g.character);
  66354. out.writeFloat (g.width);
  66355. g.path.writePathToStream (out);
  66356. numKerningPairs += g.getNumKerningPairs();
  66357. }
  66358. out.writeInt (numKerningPairs);
  66359. for (i = 0; i < glyphs.size(); ++i)
  66360. {
  66361. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  66362. for (int j = 0; j < g.getNumKerningPairs(); ++j)
  66363. {
  66364. const TypefaceGlyphInfo::KerningPair& p = g.getKerningPair (j);
  66365. out.writeShort ((short) (unsigned short) g.character);
  66366. out.writeShort ((short) (unsigned short) p.character2);
  66367. out.writeFloat (p.kerningAmount);
  66368. }
  66369. }
  66370. }
  66371. const Path* Typeface::getOutlineForGlyph (const juce_wchar character) throw()
  66372. {
  66373. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) getGlyph (character);
  66374. if (g != 0)
  66375. return &(g->path);
  66376. else
  66377. return 0;
  66378. }
  66379. const TypefaceGlyphInfo* Typeface::getGlyph (const juce_wchar character) throw()
  66380. {
  66381. if (((unsigned int) character) < 128 && lookupTable [character] > 0)
  66382. return (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  66383. for (int i = 0; i < glyphs.size(); ++i)
  66384. {
  66385. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  66386. if (g->character == character)
  66387. return g;
  66388. }
  66389. if ((! isFullyPopulated)
  66390. && findAndAddSystemGlyph (character))
  66391. {
  66392. for (int i = 0; i < glyphs.size(); ++i)
  66393. {
  66394. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  66395. if (g->character == character)
  66396. return g;
  66397. }
  66398. }
  66399. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  66400. {
  66401. const TypefaceGlyphInfo* spaceGlyph = getGlyph (L' ');
  66402. if (spaceGlyph != 0)
  66403. {
  66404. // Add a copy of the empty glyph, mapped onto this character
  66405. addGlyph (character, spaceGlyph->getPath(), spaceGlyph->getHorizontalSpacing (0));
  66406. spaceGlyph = (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  66407. }
  66408. return spaceGlyph;
  66409. }
  66410. else if (character != defaultCharacter)
  66411. {
  66412. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  66413. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  66414. if (fallbackTypeface != 0 && fallbackTypeface != this)
  66415. return fallbackTypeface->getGlyph (character);
  66416. return getGlyph (defaultCharacter);
  66417. }
  66418. return 0;
  66419. }
  66420. void Typeface::addGlyph (const juce_wchar character,
  66421. const Path& path,
  66422. const float horizontalSpacing) throw()
  66423. {
  66424. #ifdef JUCE_DEBUG
  66425. for (int i = 0; i < glyphs.size(); ++i)
  66426. {
  66427. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  66428. if (g->character == character)
  66429. jassertfalse;
  66430. }
  66431. #endif
  66432. if (((unsigned int) character) < 128)
  66433. lookupTable [character] = (short) glyphs.size();
  66434. glyphs.add (new TypefaceGlyphInfo (character,
  66435. path,
  66436. horizontalSpacing,
  66437. this));
  66438. }
  66439. void Typeface::addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw()
  66440. {
  66441. if (glyphInfoToCopy != 0)
  66442. {
  66443. if (glyphInfoToCopy->character > 0 && glyphInfoToCopy->character < 128)
  66444. lookupTable [glyphInfoToCopy->character] = (short) glyphs.size();
  66445. TypefaceGlyphInfo* const newOne
  66446. = new TypefaceGlyphInfo (glyphInfoToCopy->character,
  66447. glyphInfoToCopy->path,
  66448. glyphInfoToCopy->width,
  66449. this);
  66450. newOne->kerningPairs = glyphInfoToCopy->kerningPairs;
  66451. glyphs.add (newOne);
  66452. }
  66453. }
  66454. void Typeface::addKerningPair (const juce_wchar char1,
  66455. const juce_wchar char2,
  66456. const float extraAmount) throw()
  66457. {
  66458. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) getGlyph (char1);
  66459. if (g != 0)
  66460. g->addKerningPair (char2, extraAmount);
  66461. }
  66462. void Typeface::setName (const String& name) throw()
  66463. {
  66464. typefaceName = name;
  66465. updateHashCode();
  66466. }
  66467. void Typeface::setAscent (const float newAscent) throw()
  66468. {
  66469. ascent = newAscent;
  66470. }
  66471. void Typeface::setDefaultCharacter (const juce_wchar newDefaultCharacter) throw()
  66472. {
  66473. defaultCharacter = newDefaultCharacter;
  66474. }
  66475. void Typeface::setBold (const bool shouldBeBold) throw()
  66476. {
  66477. bold = shouldBeBold;
  66478. updateHashCode();
  66479. }
  66480. void Typeface::setItalic (const bool shouldBeItalic) throw()
  66481. {
  66482. italic = shouldBeItalic;
  66483. updateHashCode();
  66484. }
  66485. class TypefaceCache;
  66486. static TypefaceCache* typefaceCacheInstance = 0;
  66487. void clearUpDefaultFontNames() throw(); // in juce_Font.cpp
  66488. class TypefaceCache : private DeletedAtShutdown
  66489. {
  66490. private:
  66491. struct CachedFace
  66492. {
  66493. CachedFace() throw()
  66494. : lastUsageCount (0),
  66495. flags (0)
  66496. {
  66497. }
  66498. String typefaceName;
  66499. int lastUsageCount;
  66500. int flags;
  66501. Typeface::Ptr typeFace;
  66502. };
  66503. int counter;
  66504. OwnedArray <CachedFace> faces;
  66505. TypefaceCache (const TypefaceCache&);
  66506. const TypefaceCache& operator= (const TypefaceCache&);
  66507. public:
  66508. TypefaceCache (int numToCache = 10)
  66509. : counter (1),
  66510. faces (2)
  66511. {
  66512. while (--numToCache >= 0)
  66513. {
  66514. CachedFace* const face = new CachedFace();
  66515. face->typeFace = new Typeface();
  66516. faces.add (face);
  66517. }
  66518. }
  66519. ~TypefaceCache()
  66520. {
  66521. faces.clear();
  66522. jassert (typefaceCacheInstance == this);
  66523. typefaceCacheInstance = 0;
  66524. // just a courtesy call to get avoid leaking these strings at shutdown
  66525. clearUpDefaultFontNames();
  66526. }
  66527. static TypefaceCache* getInstance() throw()
  66528. {
  66529. if (typefaceCacheInstance == 0)
  66530. typefaceCacheInstance = new TypefaceCache();
  66531. return typefaceCacheInstance;
  66532. }
  66533. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  66534. {
  66535. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  66536. int i;
  66537. for (i = faces.size(); --i >= 0;)
  66538. {
  66539. CachedFace* const face = faces.getUnchecked(i);
  66540. if (face->flags == flags
  66541. && face->typefaceName == font.getTypefaceName())
  66542. {
  66543. face->lastUsageCount = ++counter;
  66544. return face->typeFace;
  66545. }
  66546. }
  66547. int replaceIndex = 0;
  66548. int bestLastUsageCount = INT_MAX;
  66549. for (i = faces.size(); --i >= 0;)
  66550. {
  66551. const int lu = faces.getUnchecked(i)->lastUsageCount;
  66552. if (bestLastUsageCount > lu)
  66553. {
  66554. bestLastUsageCount = lu;
  66555. replaceIndex = i;
  66556. }
  66557. }
  66558. CachedFace* const face = faces.getUnchecked (replaceIndex);
  66559. face->typefaceName = font.getTypefaceName();
  66560. face->flags = flags;
  66561. face->lastUsageCount = ++counter;
  66562. face->typeFace = new Typeface (font.getTypefaceName(),
  66563. font.isBold(),
  66564. font.isItalic());
  66565. return face->typeFace;
  66566. }
  66567. };
  66568. const Typeface::Ptr Typeface::getTypefaceFor (const Font& font) throw()
  66569. {
  66570. return TypefaceCache::getInstance()->findTypefaceFor (font);
  66571. }
  66572. END_JUCE_NAMESPACE
  66573. /********* End of inlined file: juce_Typeface.cpp *********/
  66574. /********* Start of inlined file: juce_AffineTransform.cpp *********/
  66575. BEGIN_JUCE_NAMESPACE
  66576. AffineTransform::AffineTransform() throw()
  66577. : mat00 (1.0f),
  66578. mat01 (0),
  66579. mat02 (0),
  66580. mat10 (0),
  66581. mat11 (1.0f),
  66582. mat12 (0)
  66583. {
  66584. }
  66585. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  66586. : mat00 (other.mat00),
  66587. mat01 (other.mat01),
  66588. mat02 (other.mat02),
  66589. mat10 (other.mat10),
  66590. mat11 (other.mat11),
  66591. mat12 (other.mat12)
  66592. {
  66593. }
  66594. AffineTransform::AffineTransform (const float mat00_,
  66595. const float mat01_,
  66596. const float mat02_,
  66597. const float mat10_,
  66598. const float mat11_,
  66599. const float mat12_) throw()
  66600. : mat00 (mat00_),
  66601. mat01 (mat01_),
  66602. mat02 (mat02_),
  66603. mat10 (mat10_),
  66604. mat11 (mat11_),
  66605. mat12 (mat12_)
  66606. {
  66607. }
  66608. const AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  66609. {
  66610. mat00 = other.mat00;
  66611. mat01 = other.mat01;
  66612. mat02 = other.mat02;
  66613. mat10 = other.mat10;
  66614. mat11 = other.mat11;
  66615. mat12 = other.mat12;
  66616. return *this;
  66617. }
  66618. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  66619. {
  66620. return mat00 == other.mat00
  66621. && mat01 == other.mat01
  66622. && mat02 == other.mat02
  66623. && mat10 == other.mat10
  66624. && mat11 == other.mat11
  66625. && mat12 == other.mat12;
  66626. }
  66627. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  66628. {
  66629. return ! operator== (other);
  66630. }
  66631. bool AffineTransform::isIdentity() const throw()
  66632. {
  66633. return (mat01 == 0)
  66634. && (mat02 == 0)
  66635. && (mat10 == 0)
  66636. && (mat12 == 0)
  66637. && (mat00 == 1.0f)
  66638. && (mat11 == 1.0f);
  66639. }
  66640. const AffineTransform AffineTransform::identity;
  66641. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  66642. {
  66643. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  66644. other.mat00 * mat01 + other.mat01 * mat11,
  66645. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  66646. other.mat10 * mat00 + other.mat11 * mat10,
  66647. other.mat10 * mat01 + other.mat11 * mat11,
  66648. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  66649. }
  66650. const AffineTransform AffineTransform::followedBy (const float omat00,
  66651. const float omat01,
  66652. const float omat02,
  66653. const float omat10,
  66654. const float omat11,
  66655. const float omat12) const throw()
  66656. {
  66657. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  66658. omat00 * mat01 + omat01 * mat11,
  66659. omat00 * mat02 + omat01 * mat12 + omat02,
  66660. omat10 * mat00 + omat11 * mat10,
  66661. omat10 * mat01 + omat11 * mat11,
  66662. omat10 * mat02 + omat11 * mat12 + omat12);
  66663. }
  66664. const AffineTransform AffineTransform::translated (const float dx,
  66665. const float dy) const throw()
  66666. {
  66667. return followedBy (1.0f, 0, dx,
  66668. 0, 1.0f, dy);
  66669. }
  66670. const AffineTransform AffineTransform::translation (const float dx,
  66671. const float dy) throw()
  66672. {
  66673. return AffineTransform (1.0f, 0, dx,
  66674. 0, 1.0f, dy);
  66675. }
  66676. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  66677. {
  66678. const float cosRad = cosf (rad);
  66679. const float sinRad = sinf (rad);
  66680. return followedBy (cosRad, -sinRad, 0,
  66681. sinRad, cosRad, 0);
  66682. }
  66683. const AffineTransform AffineTransform::rotation (const float rad) throw()
  66684. {
  66685. const float cosRad = cosf (rad);
  66686. const float sinRad = sinf (rad);
  66687. return AffineTransform (cosRad, -sinRad, 0,
  66688. sinRad, cosRad, 0);
  66689. }
  66690. const AffineTransform AffineTransform::rotated (const float angle,
  66691. const float pivotX,
  66692. const float pivotY) const throw()
  66693. {
  66694. return translated (-pivotX, -pivotY)
  66695. .rotated (angle)
  66696. .translated (pivotX, pivotY);
  66697. }
  66698. const AffineTransform AffineTransform::rotation (const float angle,
  66699. const float pivotX,
  66700. const float pivotY) throw()
  66701. {
  66702. return translation (-pivotX, -pivotY)
  66703. .rotated (angle)
  66704. .translated (pivotX, pivotY);
  66705. }
  66706. const AffineTransform AffineTransform::scaled (const float factorX,
  66707. const float factorY) const throw()
  66708. {
  66709. return followedBy (factorX, 0, 0,
  66710. 0, factorY, 0);
  66711. }
  66712. const AffineTransform AffineTransform::scale (const float factorX,
  66713. const float factorY) throw()
  66714. {
  66715. return AffineTransform (factorX, 0, 0,
  66716. 0, factorY, 0);
  66717. }
  66718. const AffineTransform AffineTransform::sheared (const float shearX,
  66719. const float shearY) const throw()
  66720. {
  66721. return followedBy (1.0f, shearX, 0,
  66722. shearY, 1.0f, 0);
  66723. }
  66724. const AffineTransform AffineTransform::inverted() const throw()
  66725. {
  66726. double determinant = (mat00 * mat11 - mat10 * mat01);
  66727. if (determinant != 0.0)
  66728. {
  66729. determinant = 1.0 / determinant;
  66730. const float dst00 = (float) (mat11 * determinant);
  66731. const float dst10 = (float) (-mat10 * determinant);
  66732. const float dst01 = (float) (-mat01 * determinant);
  66733. const float dst11 = (float) (mat00 * determinant);
  66734. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  66735. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  66736. }
  66737. else
  66738. {
  66739. // singularity..
  66740. return *this;
  66741. }
  66742. }
  66743. bool AffineTransform::isSingularity() const throw()
  66744. {
  66745. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  66746. }
  66747. void AffineTransform::transformPoint (float& x,
  66748. float& y) const throw()
  66749. {
  66750. const float oldX = x;
  66751. x = mat00 * oldX + mat01 * y + mat02;
  66752. y = mat10 * oldX + mat11 * y + mat12;
  66753. }
  66754. void AffineTransform::transformPoint (double& x,
  66755. double& y) const throw()
  66756. {
  66757. const double oldX = x;
  66758. x = mat00 * oldX + mat01 * y + mat02;
  66759. y = mat10 * oldX + mat11 * y + mat12;
  66760. }
  66761. END_JUCE_NAMESPACE
  66762. /********* End of inlined file: juce_AffineTransform.cpp *********/
  66763. /********* Start of inlined file: juce_BorderSize.cpp *********/
  66764. BEGIN_JUCE_NAMESPACE
  66765. BorderSize::BorderSize() throw()
  66766. : top (0),
  66767. left (0),
  66768. bottom (0),
  66769. right (0)
  66770. {
  66771. }
  66772. BorderSize::BorderSize (const BorderSize& other) throw()
  66773. : top (other.top),
  66774. left (other.left),
  66775. bottom (other.bottom),
  66776. right (other.right)
  66777. {
  66778. }
  66779. BorderSize::BorderSize (const int topGap,
  66780. const int leftGap,
  66781. const int bottomGap,
  66782. const int rightGap) throw()
  66783. : top (topGap),
  66784. left (leftGap),
  66785. bottom (bottomGap),
  66786. right (rightGap)
  66787. {
  66788. }
  66789. BorderSize::BorderSize (const int allGaps) throw()
  66790. : top (allGaps),
  66791. left (allGaps),
  66792. bottom (allGaps),
  66793. right (allGaps)
  66794. {
  66795. }
  66796. BorderSize::~BorderSize() throw()
  66797. {
  66798. }
  66799. void BorderSize::setTop (const int newTopGap) throw()
  66800. {
  66801. top = newTopGap;
  66802. }
  66803. void BorderSize::setLeft (const int newLeftGap) throw()
  66804. {
  66805. left = newLeftGap;
  66806. }
  66807. void BorderSize::setBottom (const int newBottomGap) throw()
  66808. {
  66809. bottom = newBottomGap;
  66810. }
  66811. void BorderSize::setRight (const int newRightGap) throw()
  66812. {
  66813. right = newRightGap;
  66814. }
  66815. const Rectangle BorderSize::subtractedFrom (const Rectangle& r) const throw()
  66816. {
  66817. return Rectangle (r.getX() + left,
  66818. r.getY() + top,
  66819. r.getWidth() - (left + right),
  66820. r.getHeight() - (top + bottom));
  66821. }
  66822. void BorderSize::subtractFrom (Rectangle& r) const throw()
  66823. {
  66824. r.setBounds (r.getX() + left,
  66825. r.getY() + top,
  66826. r.getWidth() - (left + right),
  66827. r.getHeight() - (top + bottom));
  66828. }
  66829. const Rectangle BorderSize::addedTo (const Rectangle& r) const throw()
  66830. {
  66831. return Rectangle (r.getX() - left,
  66832. r.getY() - top,
  66833. r.getWidth() + (left + right),
  66834. r.getHeight() + (top + bottom));
  66835. }
  66836. void BorderSize::addTo (Rectangle& r) const throw()
  66837. {
  66838. r.setBounds (r.getX() - left,
  66839. r.getY() - top,
  66840. r.getWidth() + (left + right),
  66841. r.getHeight() + (top + bottom));
  66842. }
  66843. bool BorderSize::operator== (const BorderSize& other) const throw()
  66844. {
  66845. return top == other.top
  66846. && left == other.left
  66847. && bottom == other.bottom
  66848. && right == other.right;
  66849. }
  66850. bool BorderSize::operator!= (const BorderSize& other) const throw()
  66851. {
  66852. return ! operator== (other);
  66853. }
  66854. END_JUCE_NAMESPACE
  66855. /********* End of inlined file: juce_BorderSize.cpp *********/
  66856. /********* Start of inlined file: juce_Line.cpp *********/
  66857. BEGIN_JUCE_NAMESPACE
  66858. static bool juce_lineIntersection (const float x1, const float y1,
  66859. const float x2, const float y2,
  66860. const float x3, const float y3,
  66861. const float x4, const float y4,
  66862. float& intersectionX,
  66863. float& intersectionY) throw()
  66864. {
  66865. if (x2 != x3 || y2 != y3)
  66866. {
  66867. const float dx1 = x2 - x1;
  66868. const float dy1 = y2 - y1;
  66869. const float dx2 = x4 - x3;
  66870. const float dy2 = y4 - y3;
  66871. const float divisor = dx1 * dy2 - dx2 * dy1;
  66872. if (divisor == 0)
  66873. {
  66874. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  66875. {
  66876. if (dy1 == 0 && dy2 != 0)
  66877. {
  66878. const float along = (y1 - y3) / dy2;
  66879. intersectionX = x3 + along * dx2;
  66880. intersectionY = y1;
  66881. return along >= 0 && along <= 1.0f;
  66882. }
  66883. else if (dy2 == 0 && dy1 != 0)
  66884. {
  66885. const float along = (y3 - y1) / dy1;
  66886. intersectionX = x1 + along * dx1;
  66887. intersectionY = y3;
  66888. return along >= 0 && along <= 1.0f;
  66889. }
  66890. else if (dx1 == 0 && dx2 != 0)
  66891. {
  66892. const float along = (x1 - x3) / dx2;
  66893. intersectionX = x1;
  66894. intersectionY = y3 + along * dy2;
  66895. return along >= 0 && along <= 1.0f;
  66896. }
  66897. else if (dx2 == 0 && dx1 != 0)
  66898. {
  66899. const float along = (x3 - x1) / dx1;
  66900. intersectionX = x3;
  66901. intersectionY = y1 + along * dy1;
  66902. return along >= 0 && along <= 1.0f;
  66903. }
  66904. }
  66905. intersectionX = 0.5f * (x2 + x3);
  66906. intersectionY = 0.5f * (y2 + y3);
  66907. return false;
  66908. }
  66909. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  66910. intersectionX = x1 + along1 * dx1;
  66911. intersectionY = y1 + along1 * dy1;
  66912. if (along1 < 0 || along1 > 1.0f)
  66913. return false;
  66914. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1) / divisor;
  66915. return along2 >= 0 && along2 <= 1.0f;
  66916. }
  66917. intersectionX = x2;
  66918. intersectionY = y2;
  66919. return true;
  66920. }
  66921. Line::Line() throw()
  66922. : startX (0.0f),
  66923. startY (0.0f),
  66924. endX (0.0f),
  66925. endY (0.0f)
  66926. {
  66927. }
  66928. Line::Line (const Line& other) throw()
  66929. : startX (other.startX),
  66930. startY (other.startY),
  66931. endX (other.endX),
  66932. endY (other.endY)
  66933. {
  66934. }
  66935. Line::Line (const float startX_, const float startY_,
  66936. const float endX_, const float endY_) throw()
  66937. : startX (startX_),
  66938. startY (startY_),
  66939. endX (endX_),
  66940. endY (endY_)
  66941. {
  66942. }
  66943. Line::Line (const Point& start,
  66944. const Point& end) throw()
  66945. : startX (start.getX()),
  66946. startY (start.getY()),
  66947. endX (end.getX()),
  66948. endY (end.getY())
  66949. {
  66950. }
  66951. const Line& Line::operator= (const Line& other) throw()
  66952. {
  66953. startX = other.startX;
  66954. startY = other.startY;
  66955. endX = other.endX;
  66956. endY = other.endY;
  66957. return *this;
  66958. }
  66959. Line::~Line() throw()
  66960. {
  66961. }
  66962. const Point Line::getStart() const throw()
  66963. {
  66964. return Point (startX, startY);
  66965. }
  66966. const Point Line::getEnd() const throw()
  66967. {
  66968. return Point (endX, endY);
  66969. }
  66970. void Line::setStart (const float newStartX,
  66971. const float newStartY) throw()
  66972. {
  66973. startX = newStartX;
  66974. startY = newStartY;
  66975. }
  66976. void Line::setStart (const Point& newStart) throw()
  66977. {
  66978. startX = newStart.getX();
  66979. startY = newStart.getY();
  66980. }
  66981. void Line::setEnd (const float newEndX,
  66982. const float newEndY) throw()
  66983. {
  66984. endX = newEndX;
  66985. endY = newEndY;
  66986. }
  66987. void Line::setEnd (const Point& newEnd) throw()
  66988. {
  66989. endX = newEnd.getX();
  66990. endY = newEnd.getY();
  66991. }
  66992. bool Line::operator== (const Line& other) const throw()
  66993. {
  66994. return startX == other.startX
  66995. && startY == other.startY
  66996. && endX == other.endX
  66997. && endY == other.endY;
  66998. }
  66999. bool Line::operator!= (const Line& other) const throw()
  67000. {
  67001. return startX != other.startX
  67002. || startY != other.startY
  67003. || endX != other.endX
  67004. || endY != other.endY;
  67005. }
  67006. void Line::applyTransform (const AffineTransform& transform) throw()
  67007. {
  67008. transform.transformPoint (startX, startY);
  67009. transform.transformPoint (endX, endY);
  67010. }
  67011. float Line::getLength() const throw()
  67012. {
  67013. return (float) juce_hypot (startX - endX,
  67014. startY - endY);
  67015. }
  67016. float Line::getAngle() const throw()
  67017. {
  67018. return atan2f (endX - startX,
  67019. endY - startY);
  67020. }
  67021. const Point Line::getPointAlongLine (const float distanceFromStart) const throw()
  67022. {
  67023. const float alpha = distanceFromStart / getLength();
  67024. return Point (startX + (endX - startX) * alpha,
  67025. startY + (endY - startY) * alpha);
  67026. }
  67027. const Point Line::getPointAlongLine (const float offsetX,
  67028. const float offsetY) const throw()
  67029. {
  67030. const float dx = endX - startX;
  67031. const float dy = endY - startY;
  67032. const double length = juce_hypot (dx, dy);
  67033. if (length == 0)
  67034. return Point (startX, startY);
  67035. else
  67036. return Point (startX + (float) (((dx * offsetX) - (dy * offsetY)) / length),
  67037. startY + (float) (((dy * offsetX) + (dx * offsetY)) / length));
  67038. }
  67039. const Point Line::getPointAlongLineProportionally (const float alpha) const throw()
  67040. {
  67041. return Point (startX + (endX - startX) * alpha,
  67042. startY + (endY - startY) * alpha);
  67043. }
  67044. float Line::getDistanceFromLine (const float x,
  67045. const float y) const throw()
  67046. {
  67047. const double dx = endX - startX;
  67048. const double dy = endY - startY;
  67049. const double length = dx * dx + dy * dy;
  67050. if (length > 0)
  67051. {
  67052. const double prop = ((x - startX) * dx + (y - startY) * dy) / length;
  67053. if (prop >= 0.0f && prop < 1.0f)
  67054. {
  67055. return (float) juce_hypot (x - (startX + prop * dx),
  67056. y - (startY + prop * dy));
  67057. }
  67058. }
  67059. return (float) jmin (juce_hypot (x - startX, y - startY),
  67060. juce_hypot (x - endX, y - endY));
  67061. }
  67062. float Line::findNearestPointTo (const float x,
  67063. const float y) const throw()
  67064. {
  67065. const double dx = endX - startX;
  67066. const double dy = endY - startY;
  67067. const double length = dx * dx + dy * dy;
  67068. if (length <= 0.0)
  67069. return 0.0f;
  67070. return jlimit (0.0f, 1.0f,
  67071. (float) (((x - startX) * dx + (y - startY) * dy) / length));
  67072. }
  67073. const Line Line::withShortenedStart (const float distanceToShortenBy) const throw()
  67074. {
  67075. const float length = getLength();
  67076. return Line (getPointAlongLine (jmin (distanceToShortenBy, length)),
  67077. getEnd());
  67078. }
  67079. const Line Line::withShortenedEnd (const float distanceToShortenBy) const throw()
  67080. {
  67081. const float length = getLength();
  67082. return Line (getStart(),
  67083. getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  67084. }
  67085. bool Line::clipToPath (const Path& path,
  67086. const bool keepSectionOutsidePath) throw()
  67087. {
  67088. const bool startInside = path.contains (startX, startY);
  67089. const bool endInside = path.contains (endX, endY);
  67090. if (startInside == endInside)
  67091. {
  67092. if (keepSectionOutsidePath != startInside)
  67093. {
  67094. // entirely outside the path
  67095. return false;
  67096. }
  67097. else
  67098. {
  67099. // entirely inside the path
  67100. startX = 0.0f;
  67101. startY = 0.0f;
  67102. endX = 0.0f;
  67103. endY = 0.0f;
  67104. return true;
  67105. }
  67106. }
  67107. else
  67108. {
  67109. bool changed = false;
  67110. PathFlatteningIterator iter (path, AffineTransform::identity);
  67111. while (iter.next())
  67112. {
  67113. float ix, iy;
  67114. if (intersects (Line (iter.x1, iter.y1,
  67115. iter.x2, iter.y2),
  67116. ix, iy))
  67117. {
  67118. if ((startInside && keepSectionOutsidePath)
  67119. || (endInside && ! keepSectionOutsidePath))
  67120. {
  67121. setStart (ix, iy);
  67122. }
  67123. else
  67124. {
  67125. setEnd (ix, iy);
  67126. }
  67127. changed = true;
  67128. }
  67129. }
  67130. return changed;
  67131. }
  67132. }
  67133. bool Line::intersects (const Line& line,
  67134. float& intersectionX,
  67135. float& intersectionY) const throw()
  67136. {
  67137. return juce_lineIntersection (startX, startY,
  67138. endX, endY,
  67139. line.startX, line.startY,
  67140. line.endX, line.endY,
  67141. intersectionX,
  67142. intersectionY);
  67143. }
  67144. bool Line::isVertical() const throw()
  67145. {
  67146. return startX == endX;
  67147. }
  67148. bool Line::isHorizontal() const throw()
  67149. {
  67150. return startY == endY;
  67151. }
  67152. bool Line::isPointAbove (const float x, const float y) const throw()
  67153. {
  67154. return startX != endX
  67155. && y < ((endY - startY) * (x - startX)) / (endX - startX) + startY;
  67156. }
  67157. END_JUCE_NAMESPACE
  67158. /********* End of inlined file: juce_Line.cpp *********/
  67159. /********* Start of inlined file: juce_Path.cpp *********/
  67160. BEGIN_JUCE_NAMESPACE
  67161. // tests that some co-ords aren't NaNs
  67162. #define CHECK_COORDS_ARE_VALID(x, y) \
  67163. jassert (x == x && y == y);
  67164. const float Path::lineMarker = 100001.0f;
  67165. const float Path::moveMarker = 100002.0f;
  67166. const float Path::quadMarker = 100003.0f;
  67167. const float Path::cubicMarker = 100004.0f;
  67168. const float Path::closeSubPathMarker = 100005.0f;
  67169. static const int defaultGranularity = 32;
  67170. Path::Path() throw()
  67171. : ArrayAllocationBase <float> (defaultGranularity),
  67172. numElements (0),
  67173. pathXMin (0),
  67174. pathXMax (0),
  67175. pathYMin (0),
  67176. pathYMax (0),
  67177. useNonZeroWinding (true)
  67178. {
  67179. }
  67180. Path::~Path() throw()
  67181. {
  67182. }
  67183. Path::Path (const Path& other) throw()
  67184. : ArrayAllocationBase <float> (defaultGranularity),
  67185. numElements (other.numElements),
  67186. pathXMin (other.pathXMin),
  67187. pathXMax (other.pathXMax),
  67188. pathYMin (other.pathYMin),
  67189. pathYMax (other.pathYMax),
  67190. useNonZeroWinding (other.useNonZeroWinding)
  67191. {
  67192. if (numElements > 0)
  67193. {
  67194. setAllocatedSize (numElements);
  67195. memcpy (elements, other.elements, numElements * sizeof (float));
  67196. }
  67197. }
  67198. const Path& Path::operator= (const Path& other) throw()
  67199. {
  67200. if (this != &other)
  67201. {
  67202. ensureAllocatedSize (other.numElements);
  67203. numElements = other.numElements;
  67204. pathXMin = other.pathXMin;
  67205. pathXMax = other.pathXMax;
  67206. pathYMin = other.pathYMin;
  67207. pathYMax = other.pathYMax;
  67208. useNonZeroWinding = other.useNonZeroWinding;
  67209. if (numElements > 0)
  67210. memcpy (elements, other.elements, numElements * sizeof (float));
  67211. }
  67212. return *this;
  67213. }
  67214. void Path::clear() throw()
  67215. {
  67216. numElements = 0;
  67217. pathXMin = 0;
  67218. pathYMin = 0;
  67219. pathYMax = 0;
  67220. pathXMax = 0;
  67221. }
  67222. void Path::swapWithPath (Path& other)
  67223. {
  67224. swapVariables <int> (this->numAllocated, other.numAllocated);
  67225. swapVariables <float*> (this->elements, other.elements);
  67226. swapVariables <int> (this->numElements, other.numElements);
  67227. swapVariables <float> (this->pathXMin, other.pathXMin);
  67228. swapVariables <float> (this->pathXMax, other.pathXMax);
  67229. swapVariables <float> (this->pathYMin, other.pathYMin);
  67230. swapVariables <float> (this->pathYMax, other.pathYMax);
  67231. swapVariables <bool> (this->useNonZeroWinding, other.useNonZeroWinding);
  67232. }
  67233. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  67234. {
  67235. useNonZeroWinding = isNonZero;
  67236. }
  67237. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  67238. const bool preserveProportions) throw()
  67239. {
  67240. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  67241. }
  67242. bool Path::isEmpty() const throw()
  67243. {
  67244. int i = 0;
  67245. while (i < numElements)
  67246. {
  67247. const float type = elements [i++];
  67248. if (type == moveMarker)
  67249. {
  67250. i += 2;
  67251. }
  67252. else if (type == lineMarker
  67253. || type == quadMarker
  67254. || type == cubicMarker)
  67255. {
  67256. return false;
  67257. }
  67258. }
  67259. return true;
  67260. }
  67261. void Path::getBounds (float& x, float& y,
  67262. float& w, float& h) const throw()
  67263. {
  67264. x = pathXMin;
  67265. y = pathYMin;
  67266. w = pathXMax - pathXMin;
  67267. h = pathYMax - pathYMin;
  67268. }
  67269. void Path::getBoundsTransformed (const AffineTransform& transform,
  67270. float& x, float& y,
  67271. float& w, float& h) const throw()
  67272. {
  67273. float x1 = pathXMin;
  67274. float y1 = pathYMin;
  67275. transform.transformPoint (x1, y1);
  67276. float x2 = pathXMax;
  67277. float y2 = pathYMin;
  67278. transform.transformPoint (x2, y2);
  67279. float x3 = pathXMin;
  67280. float y3 = pathYMax;
  67281. transform.transformPoint (x3, y3);
  67282. float x4 = pathXMax;
  67283. float y4 = pathYMax;
  67284. transform.transformPoint (x4, y4);
  67285. x = jmin (x1, x2, x3, x4);
  67286. y = jmin (y1, y2, y3, y4);
  67287. w = jmax (x1, x2, x3, x4) - x;
  67288. h = jmax (y1, y2, y3, y4) - y;
  67289. }
  67290. void Path::startNewSubPath (const float x,
  67291. const float y) throw()
  67292. {
  67293. CHECK_COORDS_ARE_VALID (x, y);
  67294. if (numElements == 0)
  67295. {
  67296. pathXMin = pathXMax = x;
  67297. pathYMin = pathYMax = y;
  67298. }
  67299. else
  67300. {
  67301. pathXMin = jmin (pathXMin, x);
  67302. pathXMax = jmax (pathXMax, x);
  67303. pathYMin = jmin (pathYMin, y);
  67304. pathYMax = jmax (pathYMax, y);
  67305. }
  67306. ensureAllocatedSize (numElements + 3);
  67307. elements [numElements++] = moveMarker;
  67308. elements [numElements++] = x;
  67309. elements [numElements++] = y;
  67310. }
  67311. void Path::lineTo (const float x, const float y) throw()
  67312. {
  67313. CHECK_COORDS_ARE_VALID (x, y);
  67314. if (numElements == 0)
  67315. startNewSubPath (0, 0);
  67316. ensureAllocatedSize (numElements + 3);
  67317. elements [numElements++] = lineMarker;
  67318. elements [numElements++] = x;
  67319. elements [numElements++] = y;
  67320. pathXMin = jmin (pathXMin, x);
  67321. pathXMax = jmax (pathXMax, x);
  67322. pathYMin = jmin (pathYMin, y);
  67323. pathYMax = jmax (pathYMax, y);
  67324. }
  67325. void Path::quadraticTo (const float x1, const float y1,
  67326. const float x2, const float y2) throw()
  67327. {
  67328. CHECK_COORDS_ARE_VALID (x1, y1);
  67329. CHECK_COORDS_ARE_VALID (x2, y2);
  67330. if (numElements == 0)
  67331. startNewSubPath (0, 0);
  67332. ensureAllocatedSize (numElements + 5);
  67333. elements [numElements++] = quadMarker;
  67334. elements [numElements++] = x1;
  67335. elements [numElements++] = y1;
  67336. elements [numElements++] = x2;
  67337. elements [numElements++] = y2;
  67338. pathXMin = jmin (pathXMin, x1, x2);
  67339. pathXMax = jmax (pathXMax, x1, x2);
  67340. pathYMin = jmin (pathYMin, y1, y2);
  67341. pathYMax = jmax (pathYMax, y1, y2);
  67342. }
  67343. void Path::cubicTo (const float x1, const float y1,
  67344. const float x2, const float y2,
  67345. const float x3, const float y3) throw()
  67346. {
  67347. CHECK_COORDS_ARE_VALID (x1, y1);
  67348. CHECK_COORDS_ARE_VALID (x2, y2);
  67349. CHECK_COORDS_ARE_VALID (x3, y3);
  67350. if (numElements == 0)
  67351. startNewSubPath (0, 0);
  67352. ensureAllocatedSize (numElements + 7);
  67353. elements [numElements++] = cubicMarker;
  67354. elements [numElements++] = x1;
  67355. elements [numElements++] = y1;
  67356. elements [numElements++] = x2;
  67357. elements [numElements++] = y2;
  67358. elements [numElements++] = x3;
  67359. elements [numElements++] = y3;
  67360. pathXMin = jmin (pathXMin, x1, x2, x3);
  67361. pathXMax = jmax (pathXMax, x1, x2, x3);
  67362. pathYMin = jmin (pathYMin, y1, y2, y3);
  67363. pathYMax = jmax (pathYMax, y1, y2, y3);
  67364. }
  67365. void Path::closeSubPath() throw()
  67366. {
  67367. if (numElements > 0
  67368. && elements [numElements - 1] != closeSubPathMarker)
  67369. {
  67370. ensureAllocatedSize (numElements + 1);
  67371. elements [numElements++] = closeSubPathMarker;
  67372. }
  67373. }
  67374. const Point Path::getCurrentPosition() const
  67375. {
  67376. int i = numElements - 1;
  67377. if (i > 0 && elements[i] == closeSubPathMarker)
  67378. {
  67379. while (i >= 0)
  67380. {
  67381. if (elements[i] == moveMarker)
  67382. {
  67383. i += 2;
  67384. break;
  67385. }
  67386. --i;
  67387. }
  67388. }
  67389. if (i > 0)
  67390. return Point (elements [i - 1], elements [i]);
  67391. return Point (0.0f, 0.0f);
  67392. }
  67393. void Path::addRectangle (const float x, const float y,
  67394. const float w, const float h) throw()
  67395. {
  67396. startNewSubPath (x, y + h);
  67397. lineTo (x, y);
  67398. lineTo (x + w, y);
  67399. lineTo (x + w, y + h);
  67400. closeSubPath();
  67401. }
  67402. void Path::addRoundedRectangle (const float x, const float y,
  67403. const float w, const float h,
  67404. float csx,
  67405. float csy) throw()
  67406. {
  67407. csx = jmin (csx, w * 0.5f);
  67408. csy = jmin (csy, h * 0.5f);
  67409. const float cs45x = csx * 0.45f;
  67410. const float cs45y = csy * 0.45f;
  67411. const float x2 = x + w;
  67412. const float y2 = y + h;
  67413. startNewSubPath (x + csx, y);
  67414. lineTo (x2 - csx, y);
  67415. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  67416. lineTo (x2, y2 - csy);
  67417. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  67418. lineTo (x + csx, y2);
  67419. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  67420. lineTo (x, y + csy);
  67421. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  67422. closeSubPath();
  67423. }
  67424. void Path::addRoundedRectangle (const float x, const float y,
  67425. const float w, const float h,
  67426. float cs) throw()
  67427. {
  67428. addRoundedRectangle (x, y, w, h, cs, cs);
  67429. }
  67430. void Path::addTriangle (const float x1, const float y1,
  67431. const float x2, const float y2,
  67432. const float x3, const float y3) throw()
  67433. {
  67434. startNewSubPath (x1, y1);
  67435. lineTo (x2, y2);
  67436. lineTo (x3, y3);
  67437. closeSubPath();
  67438. }
  67439. void Path::addQuadrilateral (const float x1, const float y1,
  67440. const float x2, const float y2,
  67441. const float x3, const float y3,
  67442. const float x4, const float y4) throw()
  67443. {
  67444. startNewSubPath (x1, y1);
  67445. lineTo (x2, y2);
  67446. lineTo (x3, y3);
  67447. lineTo (x4, y4);
  67448. closeSubPath();
  67449. }
  67450. void Path::addEllipse (const float x, const float y,
  67451. const float w, const float h) throw()
  67452. {
  67453. const float hw = w * 0.5f;
  67454. const float hw55 = hw * 0.55f;
  67455. const float hh = h * 0.5f;
  67456. const float hh45 = hh * 0.55f;
  67457. const float cx = x + hw;
  67458. const float cy = y + hh;
  67459. startNewSubPath (cx, cy - hh);
  67460. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  67461. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  67462. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  67463. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  67464. closeSubPath();
  67465. }
  67466. void Path::addArc (const float x, const float y,
  67467. const float w, const float h,
  67468. const float fromRadians,
  67469. const float toRadians,
  67470. const bool startAsNewSubPath) throw()
  67471. {
  67472. const float radiusX = w / 2.0f;
  67473. const float radiusY = h / 2.0f;
  67474. addCentredArc (x + radiusX,
  67475. y + radiusY,
  67476. radiusX, radiusY,
  67477. 0.0f,
  67478. fromRadians, toRadians,
  67479. startAsNewSubPath);
  67480. }
  67481. static const float ellipseAngularIncrement = 0.05f;
  67482. void Path::addCentredArc (const float centreX, const float centreY,
  67483. const float radiusX, const float radiusY,
  67484. const float rotationOfEllipse,
  67485. const float fromRadians,
  67486. const float toRadians,
  67487. const bool startAsNewSubPath) throw()
  67488. {
  67489. if (radiusX > 0.0f && radiusY > 0.0f)
  67490. {
  67491. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  67492. float angle = fromRadians;
  67493. if (startAsNewSubPath)
  67494. {
  67495. float x = centreX + radiusX * sinf (angle);
  67496. float y = centreY - radiusY * cosf (angle);
  67497. if (rotationOfEllipse != 0)
  67498. rotation.transformPoint (x, y);
  67499. startNewSubPath (x, y);
  67500. }
  67501. if (fromRadians < toRadians)
  67502. {
  67503. if (startAsNewSubPath)
  67504. angle += ellipseAngularIncrement;
  67505. while (angle < toRadians)
  67506. {
  67507. float x = centreX + radiusX * sinf (angle);
  67508. float y = centreY - radiusY * cosf (angle);
  67509. if (rotationOfEllipse != 0)
  67510. rotation.transformPoint (x, y);
  67511. lineTo (x, y);
  67512. angle += ellipseAngularIncrement;
  67513. }
  67514. }
  67515. else
  67516. {
  67517. if (startAsNewSubPath)
  67518. angle -= ellipseAngularIncrement;
  67519. while (angle > toRadians)
  67520. {
  67521. float x = centreX + radiusX * sinf (angle);
  67522. float y = centreY - radiusY * cosf (angle);
  67523. if (rotationOfEllipse != 0)
  67524. rotation.transformPoint (x, y);
  67525. lineTo (x, y);
  67526. angle -= ellipseAngularIncrement;
  67527. }
  67528. }
  67529. float x = centreX + radiusX * sinf (toRadians);
  67530. float y = centreY - radiusY * cosf (toRadians);
  67531. if (rotationOfEllipse != 0)
  67532. rotation.transformPoint (x, y);
  67533. lineTo (x, y);
  67534. }
  67535. }
  67536. void Path::addPieSegment (const float x, const float y,
  67537. const float width, const float height,
  67538. const float fromRadians,
  67539. const float toRadians,
  67540. const float innerCircleProportionalSize)
  67541. {
  67542. float hw = width * 0.5f;
  67543. float hh = height * 0.5f;
  67544. const float centreX = x + hw;
  67545. const float centreY = y + hh;
  67546. startNewSubPath (centreX + hw * sinf (fromRadians),
  67547. centreY - hh * cosf (fromRadians));
  67548. addArc (x, y, width, height, fromRadians, toRadians);
  67549. if (fabs (fromRadians - toRadians) > float_Pi * 1.999f)
  67550. {
  67551. closeSubPath();
  67552. if (innerCircleProportionalSize > 0)
  67553. {
  67554. hw *= innerCircleProportionalSize;
  67555. hh *= innerCircleProportionalSize;
  67556. startNewSubPath (centreX + hw * sinf (toRadians),
  67557. centreY - hh * cosf (toRadians));
  67558. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  67559. toRadians, fromRadians);
  67560. }
  67561. }
  67562. else
  67563. {
  67564. if (innerCircleProportionalSize > 0)
  67565. {
  67566. hw *= innerCircleProportionalSize;
  67567. hh *= innerCircleProportionalSize;
  67568. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  67569. toRadians, fromRadians);
  67570. }
  67571. else
  67572. {
  67573. lineTo (centreX, centreY);
  67574. }
  67575. }
  67576. closeSubPath();
  67577. }
  67578. static void perpendicularOffset (const float x1, const float y1,
  67579. const float x2, const float y2,
  67580. const float offsetX, const float offsetY,
  67581. float& resultX, float& resultY) throw()
  67582. {
  67583. const float dx = x2 - x1;
  67584. const float dy = y2 - y1;
  67585. const float len = juce_hypotf (dx, dy);
  67586. if (len == 0)
  67587. {
  67588. resultX = x1;
  67589. resultY = y1;
  67590. }
  67591. else
  67592. {
  67593. resultX = x1 + ((dx * offsetX) - (dy * offsetY)) / len;
  67594. resultY = y1 + ((dy * offsetX) + (dx * offsetY)) / len;
  67595. }
  67596. }
  67597. void Path::addLineSegment (const float startX, const float startY,
  67598. const float endX, const float endY,
  67599. float lineThickness) throw()
  67600. {
  67601. lineThickness *= 0.5f;
  67602. float x, y;
  67603. perpendicularOffset (startX, startY, endX, endY,
  67604. 0, lineThickness, x, y);
  67605. startNewSubPath (x, y);
  67606. perpendicularOffset (startX, startY, endX, endY,
  67607. 0, -lineThickness, x, y);
  67608. lineTo (x, y);
  67609. perpendicularOffset (endX, endY, startX, startY,
  67610. 0, lineThickness, x, y);
  67611. lineTo (x, y);
  67612. perpendicularOffset (endX, endY, startX, startY,
  67613. 0, -lineThickness, x, y);
  67614. lineTo (x, y);
  67615. closeSubPath();
  67616. }
  67617. void Path::addArrow (const float startX, const float startY,
  67618. const float endX, const float endY,
  67619. float lineThickness,
  67620. float arrowheadWidth,
  67621. float arrowheadLength) throw()
  67622. {
  67623. lineThickness *= 0.5f;
  67624. arrowheadWidth *= 0.5f;
  67625. arrowheadLength = jmin (arrowheadLength, 0.8f * juce_hypotf (startX - endX,
  67626. startY - endY));
  67627. float x, y;
  67628. perpendicularOffset (startX, startY, endX, endY,
  67629. 0, lineThickness, x, y);
  67630. startNewSubPath (x, y);
  67631. perpendicularOffset (startX, startY, endX, endY,
  67632. 0, -lineThickness, x, y);
  67633. lineTo (x, y);
  67634. perpendicularOffset (endX, endY, startX, startY,
  67635. arrowheadLength, lineThickness, x, y);
  67636. lineTo (x, y);
  67637. perpendicularOffset (endX, endY, startX, startY,
  67638. arrowheadLength, arrowheadWidth, x, y);
  67639. lineTo (x, y);
  67640. perpendicularOffset (endX, endY, startX, startY,
  67641. 0, 0, x, y);
  67642. lineTo (x, y);
  67643. perpendicularOffset (endX, endY, startX, startY,
  67644. arrowheadLength, -arrowheadWidth, x, y);
  67645. lineTo (x, y);
  67646. perpendicularOffset (endX, endY, startX, startY,
  67647. arrowheadLength, -lineThickness, x, y);
  67648. lineTo (x, y);
  67649. closeSubPath();
  67650. }
  67651. void Path::addStar (const float centreX,
  67652. const float centreY,
  67653. const int numberOfPoints,
  67654. const float innerRadius,
  67655. const float outerRadius,
  67656. const float startAngle)
  67657. {
  67658. jassert (numberOfPoints > 1); // this would be silly.
  67659. if (numberOfPoints > 1)
  67660. {
  67661. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  67662. for (int i = 0; i < numberOfPoints; ++i)
  67663. {
  67664. float angle = startAngle + i * angleBetweenPoints;
  67665. const float x = centreX + outerRadius * sinf (angle);
  67666. const float y = centreY - outerRadius * cosf (angle);
  67667. if (i == 0)
  67668. startNewSubPath (x, y);
  67669. else
  67670. lineTo (x, y);
  67671. angle += angleBetweenPoints * 0.5f;
  67672. lineTo (centreX + innerRadius * sinf (angle),
  67673. centreY - innerRadius * cosf (angle));
  67674. }
  67675. closeSubPath();
  67676. }
  67677. }
  67678. void Path::addBubble (float x, float y,
  67679. float w, float h,
  67680. float cs,
  67681. float tipX,
  67682. float tipY,
  67683. int whichSide,
  67684. float arrowPos,
  67685. float arrowWidth)
  67686. {
  67687. if (w > 1.0f && h > 1.0f)
  67688. {
  67689. cs = jmin (cs, w * 0.5f, h * 0.5f);
  67690. const float cs2 = 2.0f * cs;
  67691. startNewSubPath (x + cs, y);
  67692. if (whichSide == 0)
  67693. {
  67694. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  67695. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  67696. lineTo (arrowX1, y);
  67697. lineTo (tipX, tipY);
  67698. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  67699. }
  67700. lineTo (x + w - cs, y);
  67701. if (cs > 0.0f)
  67702. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  67703. if (whichSide == 3)
  67704. {
  67705. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  67706. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  67707. lineTo (x + w, arrowY1);
  67708. lineTo (tipX, tipY);
  67709. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  67710. }
  67711. lineTo (x + w, y + h - cs);
  67712. if (cs > 0.0f)
  67713. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  67714. if (whichSide == 2)
  67715. {
  67716. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  67717. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  67718. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  67719. lineTo (tipX, tipY);
  67720. lineTo (arrowX1, y + h);
  67721. }
  67722. lineTo (x + cs, y + h);
  67723. if (cs > 0.0f)
  67724. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  67725. if (whichSide == 1)
  67726. {
  67727. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  67728. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  67729. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  67730. lineTo (tipX, tipY);
  67731. lineTo (x, arrowY1);
  67732. }
  67733. lineTo (x, y + cs);
  67734. if (cs > 0.0f)
  67735. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - ellipseAngularIncrement);
  67736. closeSubPath();
  67737. }
  67738. }
  67739. void Path::addPath (const Path& other) throw()
  67740. {
  67741. int i = 0;
  67742. while (i < other.numElements)
  67743. {
  67744. const float type = other.elements [i++];
  67745. if (type == moveMarker)
  67746. {
  67747. startNewSubPath (other.elements [i],
  67748. other.elements [i + 1]);
  67749. i += 2;
  67750. }
  67751. else if (type == lineMarker)
  67752. {
  67753. lineTo (other.elements [i],
  67754. other.elements [i + 1]);
  67755. i += 2;
  67756. }
  67757. else if (type == quadMarker)
  67758. {
  67759. quadraticTo (other.elements [i],
  67760. other.elements [i + 1],
  67761. other.elements [i + 2],
  67762. other.elements [i + 3]);
  67763. i += 4;
  67764. }
  67765. else if (type == cubicMarker)
  67766. {
  67767. cubicTo (other.elements [i],
  67768. other.elements [i + 1],
  67769. other.elements [i + 2],
  67770. other.elements [i + 3],
  67771. other.elements [i + 4],
  67772. other.elements [i + 5]);
  67773. i += 6;
  67774. }
  67775. else if (type == closeSubPathMarker)
  67776. {
  67777. closeSubPath();
  67778. }
  67779. else
  67780. {
  67781. // something's gone wrong with the element list!
  67782. jassertfalse
  67783. }
  67784. }
  67785. }
  67786. void Path::addPath (const Path& other,
  67787. const AffineTransform& transformToApply) throw()
  67788. {
  67789. int i = 0;
  67790. while (i < other.numElements)
  67791. {
  67792. const float type = other.elements [i++];
  67793. if (type == closeSubPathMarker)
  67794. {
  67795. closeSubPath();
  67796. }
  67797. else
  67798. {
  67799. float x = other.elements [i++];
  67800. float y = other.elements [i++];
  67801. transformToApply.transformPoint (x, y);
  67802. if (type == moveMarker)
  67803. {
  67804. startNewSubPath (x, y);
  67805. }
  67806. else if (type == lineMarker)
  67807. {
  67808. lineTo (x, y);
  67809. }
  67810. else if (type == quadMarker)
  67811. {
  67812. float x2 = other.elements [i++];
  67813. float y2 = other.elements [i++];
  67814. transformToApply.transformPoint (x2, y2);
  67815. quadraticTo (x, y, x2, y2);
  67816. }
  67817. else if (type == cubicMarker)
  67818. {
  67819. float x2 = other.elements [i++];
  67820. float y2 = other.elements [i++];
  67821. float x3 = other.elements [i++];
  67822. float y3 = other.elements [i++];
  67823. transformToApply.transformPoint (x2, y2);
  67824. transformToApply.transformPoint (x3, y3);
  67825. cubicTo (x, y, x2, y2, x3, y3);
  67826. }
  67827. else
  67828. {
  67829. // something's gone wrong with the element list!
  67830. jassertfalse
  67831. }
  67832. }
  67833. }
  67834. }
  67835. void Path::applyTransform (const AffineTransform& transform) throw()
  67836. {
  67837. int i = 0;
  67838. pathYMin = pathXMin = 0;
  67839. pathYMax = pathXMax = 0;
  67840. bool setMaxMin = false;
  67841. while (i < numElements)
  67842. {
  67843. const float type = elements [i++];
  67844. if (type == moveMarker)
  67845. {
  67846. transform.transformPoint (elements [i],
  67847. elements [i + 1]);
  67848. if (setMaxMin)
  67849. {
  67850. pathXMin = jmin (pathXMin, elements [i]);
  67851. pathXMax = jmax (pathXMax, elements [i]);
  67852. pathYMin = jmin (pathYMin, elements [i + 1]);
  67853. pathYMax = jmax (pathYMax, elements [i + 1]);
  67854. }
  67855. else
  67856. {
  67857. pathXMin = pathXMax = elements [i];
  67858. pathYMin = pathYMax = elements [i + 1];
  67859. setMaxMin = true;
  67860. }
  67861. i += 2;
  67862. }
  67863. else if (type == lineMarker)
  67864. {
  67865. transform.transformPoint (elements [i],
  67866. elements [i + 1]);
  67867. pathXMin = jmin (pathXMin, elements [i]);
  67868. pathXMax = jmax (pathXMax, elements [i]);
  67869. pathYMin = jmin (pathYMin, elements [i + 1]);
  67870. pathYMax = jmax (pathYMax, elements [i + 1]);
  67871. i += 2;
  67872. }
  67873. else if (type == quadMarker)
  67874. {
  67875. transform.transformPoint (elements [i],
  67876. elements [i + 1]);
  67877. transform.transformPoint (elements [i + 2],
  67878. elements [i + 3]);
  67879. pathXMin = jmin (pathXMin, elements [i], elements [i + 2]);
  67880. pathXMax = jmax (pathXMax, elements [i], elements [i + 2]);
  67881. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3]);
  67882. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3]);
  67883. i += 4;
  67884. }
  67885. else if (type == cubicMarker)
  67886. {
  67887. transform.transformPoint (elements [i],
  67888. elements [i + 1]);
  67889. transform.transformPoint (elements [i + 2],
  67890. elements [i + 3]);
  67891. transform.transformPoint (elements [i + 4],
  67892. elements [i + 5]);
  67893. pathXMin = jmin (pathXMin, elements [i], elements [i + 2], elements [i + 4]);
  67894. pathXMax = jmax (pathXMax, elements [i], elements [i + 2], elements [i + 4]);
  67895. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3], elements [i + 5]);
  67896. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3], elements [i + 5]);
  67897. i += 6;
  67898. }
  67899. }
  67900. }
  67901. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  67902. const float w, const float h,
  67903. const bool preserveProportions,
  67904. const Justification& justification) const throw()
  67905. {
  67906. float sx, sy, sw, sh;
  67907. getBounds (sx, sy, sw, sh);
  67908. if (preserveProportions)
  67909. {
  67910. if (w <= 0 || h <= 0 || sw <= 0 || sh <= 0)
  67911. return AffineTransform::identity;
  67912. float newW, newH;
  67913. const float srcRatio = sh / sw;
  67914. if (srcRatio > h / w)
  67915. {
  67916. newW = h / srcRatio;
  67917. newH = h;
  67918. }
  67919. else
  67920. {
  67921. newW = w;
  67922. newH = w * srcRatio;
  67923. }
  67924. float newXCentre = x;
  67925. float newYCentre = y;
  67926. if (justification.testFlags (Justification::left))
  67927. newXCentre += newW * 0.5f;
  67928. else if (justification.testFlags (Justification::right))
  67929. newXCentre += w - newW * 0.5f;
  67930. else
  67931. newXCentre += w * 0.5f;
  67932. if (justification.testFlags (Justification::top))
  67933. newYCentre += newH * 0.5f;
  67934. else if (justification.testFlags (Justification::bottom))
  67935. newYCentre += h - newH * 0.5f;
  67936. else
  67937. newYCentre += h * 0.5f;
  67938. return AffineTransform::translation (sw * -0.5f - sx, sh * -0.5f - sy)
  67939. .scaled (newW / sw, newH / sh)
  67940. .translated (newXCentre, newYCentre);
  67941. }
  67942. else
  67943. {
  67944. return AffineTransform::translation (-sx, -sy)
  67945. .scaled (w / sw, h / sh)
  67946. .translated (x, y);
  67947. }
  67948. }
  67949. static const float collisionDetectionTolerence = 20.0f;
  67950. bool Path::contains (const float x, const float y) const throw()
  67951. {
  67952. if (x <= pathXMin || x >= pathXMax
  67953. || y <= pathYMin || y >= pathYMax)
  67954. return false;
  67955. PathFlatteningIterator i (*this, AffineTransform::identity, collisionDetectionTolerence);
  67956. int positiveCrossings = 0;
  67957. int negativeCrossings = 0;
  67958. while (i.next())
  67959. {
  67960. if ((i.y1 <= y && i.y2 > y)
  67961. || (i.y2 <= y && i.y1 > y))
  67962. {
  67963. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  67964. if (intersectX <= x)
  67965. {
  67966. if (i.y1 < i.y2)
  67967. ++positiveCrossings;
  67968. else
  67969. ++negativeCrossings;
  67970. }
  67971. }
  67972. }
  67973. return (useNonZeroWinding) ? (negativeCrossings != positiveCrossings)
  67974. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  67975. }
  67976. bool Path::intersectsLine (const float x1, const float y1,
  67977. const float x2, const float y2) throw()
  67978. {
  67979. PathFlatteningIterator i (*this, AffineTransform::identity, collisionDetectionTolerence);
  67980. const Line line1 (x1, y1, x2, y2);
  67981. while (i.next())
  67982. {
  67983. const Line line2 (i.x1, i.y1, i.x2, i.y2);
  67984. float ix, iy;
  67985. if (line1.intersects (line2, ix, iy))
  67986. return true;
  67987. }
  67988. return false;
  67989. }
  67990. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const throw()
  67991. {
  67992. if (cornerRadius <= 0.01f)
  67993. return *this;
  67994. int indexOfPathStart = 0, indexOfPathStartThis = 0;
  67995. int n = 0;
  67996. bool lastWasLine = false, firstWasLine = false;
  67997. Path p;
  67998. while (n < numElements)
  67999. {
  68000. const float type = elements [n++];
  68001. if (type == moveMarker)
  68002. {
  68003. indexOfPathStart = p.numElements;
  68004. indexOfPathStartThis = n - 1;
  68005. const float x = elements [n++];
  68006. const float y = elements [n++];
  68007. p.startNewSubPath (x, y);
  68008. lastWasLine = false;
  68009. firstWasLine = (elements [n] == lineMarker);
  68010. }
  68011. else if (type == lineMarker || type == closeSubPathMarker)
  68012. {
  68013. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  68014. if (type == lineMarker)
  68015. {
  68016. endX = elements [n++];
  68017. endY = elements [n++];
  68018. if (n > 8)
  68019. {
  68020. startX = elements [n - 8];
  68021. startY = elements [n - 7];
  68022. joinX = elements [n - 5];
  68023. joinY = elements [n - 4];
  68024. }
  68025. }
  68026. else
  68027. {
  68028. endX = elements [indexOfPathStartThis + 1];
  68029. endY = elements [indexOfPathStartThis + 2];
  68030. if (n > 6)
  68031. {
  68032. startX = elements [n - 6];
  68033. startY = elements [n - 5];
  68034. joinX = elements [n - 3];
  68035. joinY = elements [n - 2];
  68036. }
  68037. }
  68038. if (lastWasLine)
  68039. {
  68040. const double len1 = juce_hypot (startX - joinX,
  68041. startY - joinY);
  68042. if (len1 > 0)
  68043. {
  68044. const double propNeeded = jmin (0.5, cornerRadius / len1);
  68045. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  68046. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  68047. }
  68048. const double len2 = juce_hypot (endX - joinX,
  68049. endY - joinY);
  68050. if (len2 > 0)
  68051. {
  68052. const double propNeeded = jmin (0.5, cornerRadius / len2);
  68053. p.quadraticTo (joinX, joinY,
  68054. (float) (joinX + (endX - joinX) * propNeeded),
  68055. (float) (joinY + (endY - joinY) * propNeeded));
  68056. }
  68057. p.lineTo (endX, endY);
  68058. }
  68059. else if (type == lineMarker)
  68060. {
  68061. p.lineTo (endX, endY);
  68062. lastWasLine = true;
  68063. }
  68064. if (type == closeSubPathMarker)
  68065. {
  68066. if (firstWasLine)
  68067. {
  68068. startX = elements [n - 3];
  68069. startY = elements [n - 2];
  68070. joinX = endX;
  68071. joinY = endY;
  68072. endX = elements [indexOfPathStartThis + 4];
  68073. endY = elements [indexOfPathStartThis + 5];
  68074. const double len1 = juce_hypot (startX - joinX,
  68075. startY - joinY);
  68076. if (len1 > 0)
  68077. {
  68078. const double propNeeded = jmin (0.5, cornerRadius / len1);
  68079. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  68080. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  68081. }
  68082. const double len2 = juce_hypot (endX - joinX,
  68083. endY - joinY);
  68084. if (len2 > 0)
  68085. {
  68086. const double propNeeded = jmin (0.5, cornerRadius / len2);
  68087. endX = (float) (joinX + (endX - joinX) * propNeeded);
  68088. endY = (float) (joinY + (endY - joinY) * propNeeded);
  68089. p.quadraticTo (joinX, joinY, endX, endY);
  68090. p.elements [indexOfPathStart + 1] = endX;
  68091. p.elements [indexOfPathStart + 2] = endY;
  68092. }
  68093. }
  68094. p.closeSubPath();
  68095. }
  68096. }
  68097. else if (type == quadMarker)
  68098. {
  68099. lastWasLine = false;
  68100. const float x1 = elements [n++];
  68101. const float y1 = elements [n++];
  68102. const float x2 = elements [n++];
  68103. const float y2 = elements [n++];
  68104. p.quadraticTo (x1, y1, x2, y2);
  68105. }
  68106. else if (type == cubicMarker)
  68107. {
  68108. lastWasLine = false;
  68109. const float x1 = elements [n++];
  68110. const float y1 = elements [n++];
  68111. const float x2 = elements [n++];
  68112. const float y2 = elements [n++];
  68113. const float x3 = elements [n++];
  68114. const float y3 = elements [n++];
  68115. p.cubicTo (x1, y1, x2, y2, x3, y3);
  68116. }
  68117. }
  68118. return p;
  68119. }
  68120. void Path::loadPathFromStream (InputStream& source)
  68121. {
  68122. while (! source.isExhausted())
  68123. {
  68124. switch (source.readByte())
  68125. {
  68126. case 'm':
  68127. {
  68128. const float x = source.readFloat();
  68129. const float y = source.readFloat();
  68130. startNewSubPath (x, y);
  68131. break;
  68132. }
  68133. case 'l':
  68134. {
  68135. const float x = source.readFloat();
  68136. const float y = source.readFloat();
  68137. lineTo (x, y);
  68138. break;
  68139. }
  68140. case 'q':
  68141. {
  68142. const float x1 = source.readFloat();
  68143. const float y1 = source.readFloat();
  68144. const float x2 = source.readFloat();
  68145. const float y2 = source.readFloat();
  68146. quadraticTo (x1, y1, x2, y2);
  68147. break;
  68148. }
  68149. case 'b':
  68150. {
  68151. const float x1 = source.readFloat();
  68152. const float y1 = source.readFloat();
  68153. const float x2 = source.readFloat();
  68154. const float y2 = source.readFloat();
  68155. const float x3 = source.readFloat();
  68156. const float y3 = source.readFloat();
  68157. cubicTo (x1, y1, x2, y2, x3, y3);
  68158. break;
  68159. }
  68160. case 'c':
  68161. closeSubPath();
  68162. break;
  68163. case 'n':
  68164. useNonZeroWinding = true;
  68165. break;
  68166. case 'z':
  68167. useNonZeroWinding = false;
  68168. break;
  68169. case 'e':
  68170. return; // end of path marker
  68171. default:
  68172. jassertfalse // illegal char in the stream
  68173. break;
  68174. }
  68175. }
  68176. }
  68177. void Path::loadPathFromData (const unsigned char* const data,
  68178. const int numberOfBytes) throw()
  68179. {
  68180. MemoryInputStream in ((const char*) data, numberOfBytes, false);
  68181. loadPathFromStream (in);
  68182. }
  68183. void Path::writePathToStream (OutputStream& dest) const
  68184. {
  68185. dest.writeByte ((useNonZeroWinding) ? 'n' : 'z');
  68186. int i = 0;
  68187. while (i < numElements)
  68188. {
  68189. const float type = elements [i++];
  68190. if (type == moveMarker)
  68191. {
  68192. dest.writeByte ('m');
  68193. dest.writeFloat (elements [i++]);
  68194. dest.writeFloat (elements [i++]);
  68195. }
  68196. else if (type == lineMarker)
  68197. {
  68198. dest.writeByte ('l');
  68199. dest.writeFloat (elements [i++]);
  68200. dest.writeFloat (elements [i++]);
  68201. }
  68202. else if (type == quadMarker)
  68203. {
  68204. dest.writeByte ('q');
  68205. dest.writeFloat (elements [i++]);
  68206. dest.writeFloat (elements [i++]);
  68207. dest.writeFloat (elements [i++]);
  68208. dest.writeFloat (elements [i++]);
  68209. }
  68210. else if (type == cubicMarker)
  68211. {
  68212. dest.writeByte ('b');
  68213. dest.writeFloat (elements [i++]);
  68214. dest.writeFloat (elements [i++]);
  68215. dest.writeFloat (elements [i++]);
  68216. dest.writeFloat (elements [i++]);
  68217. dest.writeFloat (elements [i++]);
  68218. dest.writeFloat (elements [i++]);
  68219. }
  68220. else if (type == closeSubPathMarker)
  68221. {
  68222. dest.writeByte ('c');
  68223. }
  68224. }
  68225. dest.writeByte ('e'); // marks the end-of-path
  68226. }
  68227. const String Path::toString() const
  68228. {
  68229. String s;
  68230. s.preallocateStorage (numElements * 4);
  68231. if (! useNonZeroWinding)
  68232. s << T("a ");
  68233. int i = 0;
  68234. float lastMarker = 0.0f;
  68235. while (i < numElements)
  68236. {
  68237. const float marker = elements [i++];
  68238. tchar markerChar = 0;
  68239. int numCoords = 0;
  68240. if (marker == moveMarker)
  68241. {
  68242. markerChar = T('m');
  68243. numCoords = 2;
  68244. }
  68245. else if (marker == lineMarker)
  68246. {
  68247. markerChar = T('l');
  68248. numCoords = 2;
  68249. }
  68250. else if (marker == quadMarker)
  68251. {
  68252. markerChar = T('q');
  68253. numCoords = 4;
  68254. }
  68255. else if (marker == cubicMarker)
  68256. {
  68257. markerChar = T('c');
  68258. numCoords = 6;
  68259. }
  68260. else
  68261. {
  68262. jassert (marker == closeSubPathMarker);
  68263. markerChar = T('z');
  68264. }
  68265. if (marker != lastMarker)
  68266. {
  68267. s << markerChar << T(' ');
  68268. lastMarker = marker;
  68269. }
  68270. while (--numCoords >= 0 && i < numElements)
  68271. {
  68272. String n (elements [i++], 3);
  68273. while (n.endsWithChar (T('0')))
  68274. n = n.dropLastCharacters (1);
  68275. if (n.endsWithChar (T('.')))
  68276. n = n.dropLastCharacters (1);
  68277. s << n << T(' ');
  68278. }
  68279. }
  68280. return s.trimEnd();
  68281. }
  68282. static const String nextToken (const tchar*& t)
  68283. {
  68284. while (*t == T(' '))
  68285. ++t;
  68286. const tchar* const start = t;
  68287. while (*t != 0 && *t != T(' '))
  68288. ++t;
  68289. const int length = (int) (t - start);
  68290. while (*t == T(' '))
  68291. ++t;
  68292. return String (start, length);
  68293. }
  68294. void Path::restoreFromString (const String& stringVersion)
  68295. {
  68296. clear();
  68297. setUsingNonZeroWinding (true);
  68298. const tchar* t = stringVersion;
  68299. tchar marker = T('m');
  68300. int numValues = 2;
  68301. float values [6];
  68302. while (*t != 0)
  68303. {
  68304. const String token (nextToken (t));
  68305. const tchar firstChar = token[0];
  68306. int startNum = 0;
  68307. if (firstChar == T('m') || firstChar == T('l'))
  68308. {
  68309. marker = firstChar;
  68310. numValues = 2;
  68311. }
  68312. else if (firstChar == T('q'))
  68313. {
  68314. marker = firstChar;
  68315. numValues = 4;
  68316. }
  68317. else if (firstChar == T('c'))
  68318. {
  68319. marker = firstChar;
  68320. numValues = 6;
  68321. }
  68322. else if (firstChar == T('z'))
  68323. {
  68324. marker = firstChar;
  68325. numValues = 0;
  68326. }
  68327. else if (firstChar == T('a'))
  68328. {
  68329. setUsingNonZeroWinding (false);
  68330. continue;
  68331. }
  68332. else
  68333. {
  68334. ++startNum;
  68335. values [0] = token.getFloatValue();
  68336. }
  68337. for (int i = startNum; i < numValues; ++i)
  68338. values [i] = nextToken (t).getFloatValue();
  68339. switch (marker)
  68340. {
  68341. case T('m'):
  68342. startNewSubPath (values[0], values[1]);
  68343. break;
  68344. case T('l'):
  68345. lineTo (values[0], values[1]);
  68346. break;
  68347. case T('q'):
  68348. quadraticTo (values[0], values[1],
  68349. values[2], values[3]);
  68350. break;
  68351. case T('c'):
  68352. cubicTo (values[0], values[1],
  68353. values[2], values[3],
  68354. values[4], values[5]);
  68355. break;
  68356. case T('z'):
  68357. closeSubPath();
  68358. break;
  68359. default:
  68360. jassertfalse // illegal string format?
  68361. break;
  68362. }
  68363. }
  68364. }
  68365. Path::Iterator::Iterator (const Path& path_)
  68366. : path (path_),
  68367. index (0)
  68368. {
  68369. }
  68370. Path::Iterator::~Iterator()
  68371. {
  68372. }
  68373. bool Path::Iterator::next()
  68374. {
  68375. const float* const elements = path.elements;
  68376. if (index < path.numElements)
  68377. {
  68378. const float type = elements [index++];
  68379. if (type == moveMarker)
  68380. {
  68381. elementType = startNewSubPath;
  68382. x1 = elements [index++];
  68383. y1 = elements [index++];
  68384. }
  68385. else if (type == lineMarker)
  68386. {
  68387. elementType = lineTo;
  68388. x1 = elements [index++];
  68389. y1 = elements [index++];
  68390. }
  68391. else if (type == quadMarker)
  68392. {
  68393. elementType = quadraticTo;
  68394. x1 = elements [index++];
  68395. y1 = elements [index++];
  68396. x2 = elements [index++];
  68397. y2 = elements [index++];
  68398. }
  68399. else if (type == cubicMarker)
  68400. {
  68401. elementType = cubicTo;
  68402. x1 = elements [index++];
  68403. y1 = elements [index++];
  68404. x2 = elements [index++];
  68405. y2 = elements [index++];
  68406. x3 = elements [index++];
  68407. y3 = elements [index++];
  68408. }
  68409. else if (type == closeSubPathMarker)
  68410. {
  68411. elementType = closePath;
  68412. }
  68413. return true;
  68414. }
  68415. return false;
  68416. }
  68417. END_JUCE_NAMESPACE
  68418. /********* End of inlined file: juce_Path.cpp *********/
  68419. /********* Start of inlined file: juce_PathIterator.cpp *********/
  68420. BEGIN_JUCE_NAMESPACE
  68421. #if JUCE_MSVC
  68422. #pragma optimize ("t", on)
  68423. #endif
  68424. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  68425. const AffineTransform& transform_,
  68426. float tolerence_) throw()
  68427. : x2 (0),
  68428. y2 (0),
  68429. closesSubPath (false),
  68430. subPathIndex (-1),
  68431. path (path_),
  68432. transform (transform_),
  68433. points (path_.elements),
  68434. tolerence (tolerence_ * tolerence_),
  68435. subPathCloseX (0),
  68436. subPathCloseY (0),
  68437. index (0),
  68438. stackSize (32)
  68439. {
  68440. stackBase = (float*) juce_malloc (stackSize * sizeof (float));
  68441. isIdentityTransform = transform.isIdentity();
  68442. stackPos = stackBase;
  68443. }
  68444. PathFlatteningIterator::~PathFlatteningIterator() throw()
  68445. {
  68446. juce_free (stackBase);
  68447. }
  68448. bool PathFlatteningIterator::next() throw()
  68449. {
  68450. x1 = x2;
  68451. y1 = y2;
  68452. float x3 = 0;
  68453. float y3 = 0;
  68454. float x4 = 0;
  68455. float y4 = 0;
  68456. float type;
  68457. for (;;)
  68458. {
  68459. if (stackPos == stackBase)
  68460. {
  68461. if (index >= path.numElements)
  68462. {
  68463. return false;
  68464. }
  68465. else
  68466. {
  68467. type = points [index++];
  68468. if (type != Path::closeSubPathMarker)
  68469. {
  68470. x2 = points [index++];
  68471. y2 = points [index++];
  68472. if (! isIdentityTransform)
  68473. transform.transformPoint (x2, y2);
  68474. if (type == Path::quadMarker)
  68475. {
  68476. x3 = points [index++];
  68477. y3 = points [index++];
  68478. if (! isIdentityTransform)
  68479. transform.transformPoint (x3, y3);
  68480. }
  68481. else if (type == Path::cubicMarker)
  68482. {
  68483. x3 = points [index++];
  68484. y3 = points [index++];
  68485. x4 = points [index++];
  68486. y4 = points [index++];
  68487. if (! isIdentityTransform)
  68488. {
  68489. transform.transformPoint (x3, y3);
  68490. transform.transformPoint (x4, y4);
  68491. }
  68492. }
  68493. }
  68494. }
  68495. }
  68496. else
  68497. {
  68498. type = *--stackPos;
  68499. if (type != Path::closeSubPathMarker)
  68500. {
  68501. x2 = *--stackPos;
  68502. y2 = *--stackPos;
  68503. if (type == Path::quadMarker)
  68504. {
  68505. x3 = *--stackPos;
  68506. y3 = *--stackPos;
  68507. }
  68508. else if (type == Path::cubicMarker)
  68509. {
  68510. x3 = *--stackPos;
  68511. y3 = *--stackPos;
  68512. x4 = *--stackPos;
  68513. y4 = *--stackPos;
  68514. }
  68515. }
  68516. }
  68517. if (type == Path::lineMarker)
  68518. {
  68519. ++subPathIndex;
  68520. closesSubPath = (stackPos == stackBase)
  68521. && (index < path.numElements)
  68522. && (points [index] == Path::closeSubPathMarker)
  68523. && x2 == subPathCloseX
  68524. && y2 == subPathCloseY;
  68525. return true;
  68526. }
  68527. else if (type == Path::quadMarker)
  68528. {
  68529. const int offset = (int) (stackPos - stackBase);
  68530. if (offset >= stackSize - 10)
  68531. {
  68532. stackSize <<= 1;
  68533. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  68534. stackPos = stackBase + offset;
  68535. }
  68536. const float dx1 = x1 - x2;
  68537. const float dy1 = y1 - y2;
  68538. const float dx2 = x2 - x3;
  68539. const float dy2 = y2 - y3;
  68540. const float m1x = (x1 + x2) * 0.5f;
  68541. const float m1y = (y1 + y2) * 0.5f;
  68542. const float m2x = (x2 + x3) * 0.5f;
  68543. const float m2y = (y2 + y3) * 0.5f;
  68544. const float m3x = (m1x + m2x) * 0.5f;
  68545. const float m3y = (m1y + m2y) * 0.5f;
  68546. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  68547. {
  68548. *stackPos++ = y3;
  68549. *stackPos++ = x3;
  68550. *stackPos++ = m2y;
  68551. *stackPos++ = m2x;
  68552. *stackPos++ = Path::quadMarker;
  68553. *stackPos++ = m3y;
  68554. *stackPos++ = m3x;
  68555. *stackPos++ = m1y;
  68556. *stackPos++ = m1x;
  68557. *stackPos++ = Path::quadMarker;
  68558. }
  68559. else
  68560. {
  68561. *stackPos++ = y3;
  68562. *stackPos++ = x3;
  68563. *stackPos++ = Path::lineMarker;
  68564. *stackPos++ = m3y;
  68565. *stackPos++ = m3x;
  68566. *stackPos++ = Path::lineMarker;
  68567. }
  68568. jassert (stackPos < stackBase + stackSize);
  68569. }
  68570. else if (type == Path::cubicMarker)
  68571. {
  68572. const int offset = (int) (stackPos - stackBase);
  68573. if (offset >= stackSize - 16)
  68574. {
  68575. stackSize <<= 1;
  68576. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  68577. stackPos = stackBase + offset;
  68578. }
  68579. const float dx1 = x1 - x2;
  68580. const float dy1 = y1 - y2;
  68581. const float dx2 = x2 - x3;
  68582. const float dy2 = y2 - y3;
  68583. const float dx3 = x3 - x4;
  68584. const float dy3 = y3 - y4;
  68585. const float m1x = (x1 + x2) * 0.5f;
  68586. const float m1y = (y1 + y2) * 0.5f;
  68587. const float m2x = (x3 + x2) * 0.5f;
  68588. const float m2y = (y3 + y2) * 0.5f;
  68589. const float m3x = (x3 + x4) * 0.5f;
  68590. const float m3y = (y3 + y4) * 0.5f;
  68591. const float m4x = (m1x + m2x) * 0.5f;
  68592. const float m4y = (m1y + m2y) * 0.5f;
  68593. const float m5x = (m3x + m2x) * 0.5f;
  68594. const float m5y = (m3y + m2y) * 0.5f;
  68595. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  68596. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  68597. {
  68598. *stackPos++ = y4;
  68599. *stackPos++ = x4;
  68600. *stackPos++ = m3y;
  68601. *stackPos++ = m3x;
  68602. *stackPos++ = m5y;
  68603. *stackPos++ = m5x;
  68604. *stackPos++ = Path::cubicMarker;
  68605. *stackPos++ = (m4y + m5y) * 0.5f;
  68606. *stackPos++ = (m4x + m5x) * 0.5f;
  68607. *stackPos++ = m4y;
  68608. *stackPos++ = m4x;
  68609. *stackPos++ = m1y;
  68610. *stackPos++ = m1x;
  68611. *stackPos++ = Path::cubicMarker;
  68612. }
  68613. else
  68614. {
  68615. *stackPos++ = y4;
  68616. *stackPos++ = x4;
  68617. *stackPos++ = Path::lineMarker;
  68618. *stackPos++ = m5y;
  68619. *stackPos++ = m5x;
  68620. *stackPos++ = Path::lineMarker;
  68621. *stackPos++ = m4y;
  68622. *stackPos++ = m4x;
  68623. *stackPos++ = Path::lineMarker;
  68624. }
  68625. }
  68626. else if (type == Path::closeSubPathMarker)
  68627. {
  68628. if (x2 != subPathCloseX || y2 != subPathCloseY)
  68629. {
  68630. x1 = x2;
  68631. y1 = y2;
  68632. x2 = subPathCloseX;
  68633. y2 = subPathCloseY;
  68634. closesSubPath = true;
  68635. return true;
  68636. }
  68637. }
  68638. else
  68639. {
  68640. subPathIndex = -1;
  68641. subPathCloseX = x1 = x2;
  68642. subPathCloseY = y1 = y2;
  68643. }
  68644. }
  68645. }
  68646. END_JUCE_NAMESPACE
  68647. /********* End of inlined file: juce_PathIterator.cpp *********/
  68648. /********* Start of inlined file: juce_PathStrokeType.cpp *********/
  68649. BEGIN_JUCE_NAMESPACE
  68650. PathStrokeType::PathStrokeType (const float strokeThickness,
  68651. const JointStyle jointStyle_,
  68652. const EndCapStyle endStyle_) throw()
  68653. : thickness (strokeThickness),
  68654. jointStyle (jointStyle_),
  68655. endStyle (endStyle_)
  68656. {
  68657. }
  68658. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  68659. : thickness (other.thickness),
  68660. jointStyle (other.jointStyle),
  68661. endStyle (other.endStyle)
  68662. {
  68663. }
  68664. const PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  68665. {
  68666. thickness = other.thickness;
  68667. jointStyle = other.jointStyle;
  68668. endStyle = other.endStyle;
  68669. return *this;
  68670. }
  68671. PathStrokeType::~PathStrokeType() throw()
  68672. {
  68673. }
  68674. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  68675. {
  68676. return thickness == other.thickness
  68677. && jointStyle == other.jointStyle
  68678. && endStyle == other.endStyle;
  68679. }
  68680. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  68681. {
  68682. return ! operator== (other);
  68683. }
  68684. static bool lineIntersection (const float x1, const float y1,
  68685. const float x2, const float y2,
  68686. const float x3, const float y3,
  68687. const float x4, const float y4,
  68688. float& intersectionX,
  68689. float& intersectionY,
  68690. float& distanceBeyondLine1EndSquared) throw()
  68691. {
  68692. if (x2 != x3 || y2 != y3)
  68693. {
  68694. const float dx1 = x2 - x1;
  68695. const float dy1 = y2 - y1;
  68696. const float dx2 = x4 - x3;
  68697. const float dy2 = y4 - y3;
  68698. const float divisor = dx1 * dy2 - dx2 * dy1;
  68699. if (divisor == 0)
  68700. {
  68701. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  68702. {
  68703. if (dy1 == 0 && dy2 != 0)
  68704. {
  68705. const float along = (y1 - y3) / dy2;
  68706. intersectionX = x3 + along * dx2;
  68707. intersectionY = y1;
  68708. distanceBeyondLine1EndSquared = intersectionX - x2;
  68709. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68710. if ((x2 > x1) == (intersectionX < x2))
  68711. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68712. return along >= 0 && along <= 1.0f;
  68713. }
  68714. else if (dy2 == 0 && dy1 != 0)
  68715. {
  68716. const float along = (y3 - y1) / dy1;
  68717. intersectionX = x1 + along * dx1;
  68718. intersectionY = y3;
  68719. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  68720. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68721. if (along < 1.0f)
  68722. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68723. return along >= 0 && along <= 1.0f;
  68724. }
  68725. else if (dx1 == 0 && dx2 != 0)
  68726. {
  68727. const float along = (x1 - x3) / dx2;
  68728. intersectionX = x1;
  68729. intersectionY = y3 + along * dy2;
  68730. distanceBeyondLine1EndSquared = intersectionY - y2;
  68731. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68732. if ((y2 > y1) == (intersectionY < y2))
  68733. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68734. return along >= 0 && along <= 1.0f;
  68735. }
  68736. else if (dx2 == 0 && dx1 != 0)
  68737. {
  68738. const float along = (x3 - x1) / dx1;
  68739. intersectionX = x3;
  68740. intersectionY = y1 + along * dy1;
  68741. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  68742. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68743. if (along < 1.0f)
  68744. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68745. return along >= 0 && along <= 1.0f;
  68746. }
  68747. }
  68748. intersectionX = 0.5f * (x2 + x3);
  68749. intersectionY = 0.5f * (y2 + y3);
  68750. distanceBeyondLine1EndSquared = 0.0f;
  68751. return false;
  68752. }
  68753. else
  68754. {
  68755. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  68756. intersectionX = x1 + along1 * dx1;
  68757. intersectionY = y1 + along1 * dy1;
  68758. if (along1 >= 0 && along1 <= 1.0f)
  68759. {
  68760. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  68761. if (along2 >= 0 && along2 <= divisor)
  68762. {
  68763. distanceBeyondLine1EndSquared = 0.0f;
  68764. return true;
  68765. }
  68766. }
  68767. distanceBeyondLine1EndSquared = along1 - 1.0f;
  68768. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68769. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  68770. if (along1 < 1.0f)
  68771. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68772. return false;
  68773. }
  68774. }
  68775. intersectionX = x2;
  68776. intersectionY = y2;
  68777. distanceBeyondLine1EndSquared = 0.0f;
  68778. return true;
  68779. }
  68780. // part of stroke drawing stuff
  68781. static void addEdgeAndJoint (Path& destPath,
  68782. const PathStrokeType::JointStyle style,
  68783. const float maxMiterExtensionSquared, const float width,
  68784. const float x1, const float y1,
  68785. const float x2, const float y2,
  68786. const float x3, const float y3,
  68787. const float x4, const float y4,
  68788. const float midX, const float midY) throw()
  68789. {
  68790. if (style == PathStrokeType::beveled
  68791. || (x3 == x4 && y3 == y4)
  68792. || (x1 == x2 && y1 == y2))
  68793. {
  68794. destPath.lineTo (x2, y2);
  68795. destPath.lineTo (x3, y3);
  68796. }
  68797. else
  68798. {
  68799. float jx, jy, distanceBeyondLine1EndSquared;
  68800. // if they intersect, use this point..
  68801. if (lineIntersection (x1, y1, x2, y2,
  68802. x3, y3, x4, y4,
  68803. jx, jy, distanceBeyondLine1EndSquared))
  68804. {
  68805. destPath.lineTo (jx, jy);
  68806. }
  68807. else
  68808. {
  68809. if (style == PathStrokeType::mitered)
  68810. {
  68811. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  68812. && distanceBeyondLine1EndSquared > 0.0f)
  68813. {
  68814. destPath.lineTo (jx, jy);
  68815. }
  68816. else
  68817. {
  68818. // the end sticks out too far, so just use a blunt joint
  68819. destPath.lineTo (x2, y2);
  68820. destPath.lineTo (x3, y3);
  68821. }
  68822. }
  68823. else
  68824. {
  68825. // curved joints
  68826. float angle = atan2f (x2 - midX, y2 - midY);
  68827. float angle2 = atan2f (x3 - midX, y3 - midY);
  68828. while (angle < angle2 - 0.01f)
  68829. angle2 -= float_Pi * 2.0f;
  68830. destPath.lineTo (x2, y2);
  68831. while (angle > angle2)
  68832. {
  68833. destPath.lineTo (midX + width * sinf (angle),
  68834. midY + width * cosf (angle));
  68835. angle -= 0.1f;
  68836. }
  68837. destPath.lineTo (x3, y3);
  68838. }
  68839. }
  68840. }
  68841. }
  68842. static inline void addLineEnd (Path& destPath,
  68843. const PathStrokeType::EndCapStyle style,
  68844. const float x1, const float y1,
  68845. const float x2, const float y2,
  68846. const float width) throw()
  68847. {
  68848. if (style == PathStrokeType::butt)
  68849. {
  68850. destPath.lineTo (x2, y2);
  68851. }
  68852. else
  68853. {
  68854. float offx1, offy1, offx2, offy2;
  68855. float dx = x2 - x1;
  68856. float dy = y2 - y1;
  68857. const float len = juce_hypotf (dx, dy);
  68858. if (len == 0)
  68859. {
  68860. offx1 = offx2 = x1;
  68861. offy1 = offy2 = y1;
  68862. }
  68863. else
  68864. {
  68865. const float offset = width / len;
  68866. dx *= offset;
  68867. dy *= offset;
  68868. offx1 = x1 + dy;
  68869. offy1 = y1 - dx;
  68870. offx2 = x2 + dy;
  68871. offy2 = y2 - dx;
  68872. }
  68873. if (style == PathStrokeType::square)
  68874. {
  68875. // sqaure ends
  68876. destPath.lineTo (offx1, offy1);
  68877. destPath.lineTo (offx2, offy2);
  68878. destPath.lineTo (x2, y2);
  68879. }
  68880. else
  68881. {
  68882. // rounded ends
  68883. const float midx = (offx1 + offx2) * 0.5f;
  68884. const float midy = (offy1 + offy2) * 0.5f;
  68885. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  68886. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  68887. midx, midy);
  68888. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  68889. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  68890. x2, y2);
  68891. }
  68892. }
  68893. }
  68894. struct LineSection
  68895. {
  68896. LineSection() throw() {}
  68897. LineSection (int) throw() {}
  68898. float x1, y1, x2, y2; // original line
  68899. float lx1, ly1, lx2, ly2; // the left-hand stroke
  68900. float rx1, ry1, rx2, ry2; // the right-hand stroke
  68901. };
  68902. static void addSubPath (Path& destPath, const Array <LineSection>& subPath,
  68903. const bool isClosed,
  68904. const float width, const float maxMiterExtensionSquared,
  68905. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle) throw()
  68906. {
  68907. jassert (subPath.size() > 0);
  68908. const LineSection& firstLine = subPath.getReference (0);
  68909. float lastX1 = firstLine.lx1;
  68910. float lastY1 = firstLine.ly1;
  68911. float lastX2 = firstLine.lx2;
  68912. float lastY2 = firstLine.ly2;
  68913. if (isClosed)
  68914. {
  68915. destPath.startNewSubPath (lastX1, lastY1);
  68916. }
  68917. else
  68918. {
  68919. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  68920. addLineEnd (destPath, endStyle,
  68921. firstLine.rx2, firstLine.ry2,
  68922. lastX1, lastY1,
  68923. width);
  68924. }
  68925. int i;
  68926. for (i = 1; i < subPath.size(); ++i)
  68927. {
  68928. const LineSection& l = subPath.getReference (i);
  68929. addEdgeAndJoint (destPath, jointStyle,
  68930. maxMiterExtensionSquared, width,
  68931. lastX1, lastY1, lastX2, lastY2,
  68932. l.lx1, l.ly1, l.lx2, l.ly2,
  68933. l.x1, l.y1);
  68934. lastX1 = l.lx1;
  68935. lastY1 = l.ly1;
  68936. lastX2 = l.lx2;
  68937. lastY2 = l.ly2;
  68938. }
  68939. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  68940. if (isClosed)
  68941. {
  68942. const LineSection& l = subPath.getReference (0);
  68943. addEdgeAndJoint (destPath, jointStyle,
  68944. maxMiterExtensionSquared, width,
  68945. lastX1, lastY1, lastX2, lastY2,
  68946. l.lx1, l.ly1, l.lx2, l.ly2,
  68947. l.x1, l.y1);
  68948. destPath.closeSubPath();
  68949. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  68950. }
  68951. else
  68952. {
  68953. destPath.lineTo (lastX2, lastY2);
  68954. addLineEnd (destPath, endStyle,
  68955. lastX2, lastY2,
  68956. lastLine.rx1, lastLine.ry1,
  68957. width);
  68958. }
  68959. lastX1 = lastLine.rx1;
  68960. lastY1 = lastLine.ry1;
  68961. lastX2 = lastLine.rx2;
  68962. lastY2 = lastLine.ry2;
  68963. for (i = subPath.size() - 1; --i >= 0;)
  68964. {
  68965. const LineSection& l = subPath.getReference (i);
  68966. addEdgeAndJoint (destPath, jointStyle,
  68967. maxMiterExtensionSquared, width,
  68968. lastX1, lastY1, lastX2, lastY2,
  68969. l.rx1, l.ry1, l.rx2, l.ry2,
  68970. l.x2, l.y2);
  68971. lastX1 = l.rx1;
  68972. lastY1 = l.ry1;
  68973. lastX2 = l.rx2;
  68974. lastY2 = l.ry2;
  68975. }
  68976. if (isClosed)
  68977. {
  68978. addEdgeAndJoint (destPath, jointStyle,
  68979. maxMiterExtensionSquared, width,
  68980. lastX1, lastY1, lastX2, lastY2,
  68981. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  68982. lastLine.x2, lastLine.y2);
  68983. }
  68984. else
  68985. {
  68986. // do the last line
  68987. destPath.lineTo (lastX2, lastY2);
  68988. }
  68989. destPath.closeSubPath();
  68990. }
  68991. void PathStrokeType::createStrokedPath (Path& destPath,
  68992. const Path& source,
  68993. const AffineTransform& transform,
  68994. const float extraAccuracy) const throw()
  68995. {
  68996. if (thickness <= 0)
  68997. {
  68998. destPath.clear();
  68999. return;
  69000. }
  69001. const Path* sourcePath = &source;
  69002. Path temp;
  69003. if (sourcePath == &destPath)
  69004. {
  69005. destPath.swapWithPath (temp);
  69006. sourcePath = &temp;
  69007. }
  69008. else
  69009. {
  69010. destPath.clear();
  69011. }
  69012. destPath.setUsingNonZeroWinding (true);
  69013. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  69014. const float width = 0.5f * thickness;
  69015. // Iterate the path, creating a list of the
  69016. // left/right-hand lines along either side of it...
  69017. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  69018. Array <LineSection> subPath;
  69019. LineSection l;
  69020. l.x1 = 0;
  69021. l.y1 = 0;
  69022. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  69023. while (it.next())
  69024. {
  69025. if (it.subPathIndex == 0)
  69026. {
  69027. if (subPath.size() > 0)
  69028. {
  69029. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  69030. subPath.clearQuick();
  69031. }
  69032. l.x1 = it.x1;
  69033. l.y1 = it.y1;
  69034. }
  69035. l.x2 = it.x2;
  69036. l.y2 = it.y2;
  69037. float dx = l.x2 - l.x1;
  69038. float dy = l.y2 - l.y1;
  69039. const float hypotSquared = dx*dx + dy*dy;
  69040. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  69041. {
  69042. const float len = sqrtf (hypotSquared);
  69043. if (len == 0)
  69044. {
  69045. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  69046. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  69047. }
  69048. else
  69049. {
  69050. const float offset = width / len;
  69051. dx *= offset;
  69052. dy *= offset;
  69053. l.rx2 = l.x1 - dy;
  69054. l.ry2 = l.y1 + dx;
  69055. l.lx1 = l.x1 + dy;
  69056. l.ly1 = l.y1 - dx;
  69057. l.lx2 = l.x2 + dy;
  69058. l.ly2 = l.y2 - dx;
  69059. l.rx1 = l.x2 - dy;
  69060. l.ry1 = l.y2 + dx;
  69061. }
  69062. subPath.add (l);
  69063. if (it.closesSubPath)
  69064. {
  69065. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle);
  69066. subPath.clearQuick();
  69067. }
  69068. else
  69069. {
  69070. l.x1 = it.x2;
  69071. l.y1 = it.y2;
  69072. }
  69073. }
  69074. }
  69075. if (subPath.size() > 0)
  69076. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  69077. }
  69078. void PathStrokeType::createDashedStroke (Path& destPath,
  69079. const Path& sourcePath,
  69080. const float* dashLengths,
  69081. int numDashLengths,
  69082. const AffineTransform& transform,
  69083. const float extraAccuracy) const throw()
  69084. {
  69085. if (thickness <= 0)
  69086. return;
  69087. // this should really be an even number..
  69088. jassert ((numDashLengths & 1) == 0);
  69089. Path newDestPath;
  69090. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  69091. bool first = true;
  69092. int dashNum = 0;
  69093. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  69094. float dx = 0.0f, dy = 0.0f;
  69095. for (;;)
  69096. {
  69097. const bool isSolid = ((dashNum & 1) == 0);
  69098. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  69099. jassert (dashLen > 0); // must be a positive increment!
  69100. if (dashLen <= 0)
  69101. break;
  69102. pos += dashLen;
  69103. while (pos > lineEndPos)
  69104. {
  69105. if (! it.next())
  69106. {
  69107. if (isSolid && ! first)
  69108. newDestPath.lineTo (it.x2, it.y2);
  69109. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  69110. return;
  69111. }
  69112. if (isSolid && ! first)
  69113. {
  69114. newDestPath.lineTo (it.x1, it.y1);
  69115. }
  69116. else
  69117. {
  69118. newDestPath.startNewSubPath (it.x1, it.y1);
  69119. first = false;
  69120. }
  69121. dx = it.x2 - it.x1;
  69122. dy = it.y2 - it.y1;
  69123. lineLen = juce_hypotf (dx, dy);
  69124. lineEndPos += lineLen;
  69125. }
  69126. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  69127. if (isSolid)
  69128. newDestPath.lineTo (it.x1 + dx * alpha,
  69129. it.y1 + dy * alpha);
  69130. else
  69131. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  69132. it.y1 + dy * alpha);
  69133. }
  69134. }
  69135. END_JUCE_NAMESPACE
  69136. /********* End of inlined file: juce_PathStrokeType.cpp *********/
  69137. /********* Start of inlined file: juce_Point.cpp *********/
  69138. BEGIN_JUCE_NAMESPACE
  69139. Point::Point() throw()
  69140. : x (0.0f),
  69141. y (0.0f)
  69142. {
  69143. }
  69144. Point::Point (const Point& other) throw()
  69145. : x (other.x),
  69146. y (other.y)
  69147. {
  69148. }
  69149. const Point& Point::operator= (const Point& other) throw()
  69150. {
  69151. x = other.x;
  69152. y = other.y;
  69153. return *this;
  69154. }
  69155. Point::Point (const float x_,
  69156. const float y_) throw()
  69157. : x (x_),
  69158. y (y_)
  69159. {
  69160. }
  69161. Point::~Point() throw()
  69162. {
  69163. }
  69164. void Point::setXY (const float x_,
  69165. const float y_) throw()
  69166. {
  69167. x = x_;
  69168. y = y_;
  69169. }
  69170. void Point::applyTransform (const AffineTransform& transform) throw()
  69171. {
  69172. transform.transformPoint (x, y);
  69173. }
  69174. END_JUCE_NAMESPACE
  69175. /********* End of inlined file: juce_Point.cpp *********/
  69176. /********* Start of inlined file: juce_PositionedRectangle.cpp *********/
  69177. BEGIN_JUCE_NAMESPACE
  69178. PositionedRectangle::PositionedRectangle() throw()
  69179. : x (0.0),
  69180. y (0.0),
  69181. w (0.0),
  69182. h (0.0),
  69183. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  69184. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  69185. wMode (absoluteSize),
  69186. hMode (absoluteSize)
  69187. {
  69188. }
  69189. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  69190. : x (other.x),
  69191. y (other.y),
  69192. w (other.w),
  69193. h (other.h),
  69194. xMode (other.xMode),
  69195. yMode (other.yMode),
  69196. wMode (other.wMode),
  69197. hMode (other.hMode)
  69198. {
  69199. }
  69200. const PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  69201. {
  69202. if (this != &other)
  69203. {
  69204. x = other.x;
  69205. y = other.y;
  69206. w = other.w;
  69207. h = other.h;
  69208. xMode = other.xMode;
  69209. yMode = other.yMode;
  69210. wMode = other.wMode;
  69211. hMode = other.hMode;
  69212. }
  69213. return *this;
  69214. }
  69215. PositionedRectangle::~PositionedRectangle() throw()
  69216. {
  69217. }
  69218. const bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  69219. {
  69220. return x == other.x
  69221. && y == other.y
  69222. && w == other.w
  69223. && h == other.h
  69224. && xMode == other.xMode
  69225. && yMode == other.yMode
  69226. && wMode == other.wMode
  69227. && hMode == other.hMode;
  69228. }
  69229. const bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  69230. {
  69231. return ! operator== (other);
  69232. }
  69233. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  69234. {
  69235. StringArray tokens;
  69236. tokens.addTokens (stringVersion, false);
  69237. decodePosString (tokens [0], xMode, x);
  69238. decodePosString (tokens [1], yMode, y);
  69239. decodeSizeString (tokens [2], wMode, w);
  69240. decodeSizeString (tokens [3], hMode, h);
  69241. }
  69242. const String PositionedRectangle::toString() const throw()
  69243. {
  69244. String s;
  69245. s.preallocateStorage (12);
  69246. addPosDescription (s, xMode, x);
  69247. s << T(' ');
  69248. addPosDescription (s, yMode, y);
  69249. s << T(' ');
  69250. addSizeDescription (s, wMode, w);
  69251. s << T(' ');
  69252. addSizeDescription (s, hMode, h);
  69253. return s;
  69254. }
  69255. const Rectangle PositionedRectangle::getRectangle (const Rectangle& target) const throw()
  69256. {
  69257. jassert (! target.isEmpty());
  69258. double x_, y_, w_, h_;
  69259. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  69260. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  69261. return Rectangle (roundDoubleToInt (x_), roundDoubleToInt (y_),
  69262. roundDoubleToInt (w_), roundDoubleToInt (h_));
  69263. }
  69264. void PositionedRectangle::getRectangleDouble (const Rectangle& target,
  69265. double& x_, double& y_,
  69266. double& w_, double& h_) const throw()
  69267. {
  69268. jassert (! target.isEmpty());
  69269. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  69270. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  69271. }
  69272. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  69273. {
  69274. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  69275. }
  69276. void PositionedRectangle::updateFrom (const Rectangle& rectangle,
  69277. const Rectangle& target) throw()
  69278. {
  69279. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  69280. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  69281. }
  69282. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  69283. const double newW, const double newH,
  69284. const Rectangle& target) throw()
  69285. {
  69286. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  69287. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  69288. }
  69289. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  69290. {
  69291. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  69292. updateFrom (comp.getBounds(), Rectangle());
  69293. else
  69294. updateFrom (comp.getBounds(), Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  69295. }
  69296. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  69297. {
  69298. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  69299. }
  69300. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  69301. {
  69302. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  69303. | absoluteFromParentBottomRight
  69304. | absoluteFromParentCentre
  69305. | proportionOfParentSize));
  69306. }
  69307. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  69308. {
  69309. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  69310. }
  69311. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  69312. {
  69313. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  69314. | absoluteFromParentBottomRight
  69315. | absoluteFromParentCentre
  69316. | proportionOfParentSize));
  69317. }
  69318. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  69319. {
  69320. return (SizeMode) wMode;
  69321. }
  69322. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  69323. {
  69324. return (SizeMode) hMode;
  69325. }
  69326. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  69327. const PositionMode xMode_,
  69328. const AnchorPoint yAnchor,
  69329. const PositionMode yMode_,
  69330. const SizeMode widthMode,
  69331. const SizeMode heightMode,
  69332. const Rectangle& target) throw()
  69333. {
  69334. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  69335. {
  69336. double tx, tw;
  69337. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  69338. xMode = (uint8) (xAnchor | xMode_);
  69339. wMode = (uint8) widthMode;
  69340. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  69341. }
  69342. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  69343. {
  69344. double ty, th;
  69345. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  69346. yMode = (uint8) (yAnchor | yMode_);
  69347. hMode = (uint8) heightMode;
  69348. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  69349. }
  69350. }
  69351. bool PositionedRectangle::isPositionAbsolute() const throw()
  69352. {
  69353. return xMode == absoluteFromParentTopLeft
  69354. && yMode == absoluteFromParentTopLeft
  69355. && wMode == absoluteSize
  69356. && hMode == absoluteSize;
  69357. }
  69358. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  69359. {
  69360. if ((mode & proportionOfParentSize) != 0)
  69361. {
  69362. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  69363. }
  69364. else
  69365. {
  69366. s << (roundDoubleToInt (value * 100.0) / 100.0);
  69367. if ((mode & absoluteFromParentBottomRight) != 0)
  69368. s << T('R');
  69369. else if ((mode & absoluteFromParentCentre) != 0)
  69370. s << T('C');
  69371. }
  69372. if ((mode & anchorAtRightOrBottom) != 0)
  69373. s << T('r');
  69374. else if ((mode & anchorAtCentre) != 0)
  69375. s << T('c');
  69376. }
  69377. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  69378. {
  69379. if (mode == proportionalSize)
  69380. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  69381. else if (mode == parentSizeMinusAbsolute)
  69382. s << (roundDoubleToInt (value * 100.0) / 100.0) << T('M');
  69383. else
  69384. s << (roundDoubleToInt (value * 100.0) / 100.0);
  69385. }
  69386. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  69387. {
  69388. if (s.containsChar (T('r')))
  69389. mode = anchorAtRightOrBottom;
  69390. else if (s.containsChar (T('c')))
  69391. mode = anchorAtCentre;
  69392. else
  69393. mode = anchorAtLeftOrTop;
  69394. if (s.containsChar (T('%')))
  69395. {
  69396. mode |= proportionOfParentSize;
  69397. value = s.removeCharacters (T("%rcRC")).getDoubleValue() / 100.0;
  69398. }
  69399. else
  69400. {
  69401. if (s.containsChar (T('R')))
  69402. mode |= absoluteFromParentBottomRight;
  69403. else if (s.containsChar (T('C')))
  69404. mode |= absoluteFromParentCentre;
  69405. else
  69406. mode |= absoluteFromParentTopLeft;
  69407. value = s.removeCharacters (T("rcRC")).getDoubleValue();
  69408. }
  69409. }
  69410. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  69411. {
  69412. if (s.containsChar (T('%')))
  69413. {
  69414. mode = proportionalSize;
  69415. value = s.upToFirstOccurrenceOf (T("%"), false, false).getDoubleValue() / 100.0;
  69416. }
  69417. else if (s.containsChar (T('M')))
  69418. {
  69419. mode = parentSizeMinusAbsolute;
  69420. value = s.getDoubleValue();
  69421. }
  69422. else
  69423. {
  69424. mode = absoluteSize;
  69425. value = s.getDoubleValue();
  69426. }
  69427. }
  69428. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  69429. const double x, const double w,
  69430. const uint8 xMode, const uint8 wMode,
  69431. const int parentPos,
  69432. const int parentSize) const throw()
  69433. {
  69434. if (wMode == proportionalSize)
  69435. wOut = roundDoubleToInt (w * parentSize);
  69436. else if (wMode == parentSizeMinusAbsolute)
  69437. wOut = jmax (0, parentSize - roundDoubleToInt (w));
  69438. else
  69439. wOut = roundDoubleToInt (w);
  69440. if ((xMode & proportionOfParentSize) != 0)
  69441. xOut = parentPos + x * parentSize;
  69442. else if ((xMode & absoluteFromParentBottomRight) != 0)
  69443. xOut = (parentPos + parentSize) - x;
  69444. else if ((xMode & absoluteFromParentCentre) != 0)
  69445. xOut = x + (parentPos + parentSize / 2);
  69446. else
  69447. xOut = x + parentPos;
  69448. if ((xMode & anchorAtRightOrBottom) != 0)
  69449. xOut -= wOut;
  69450. else if ((xMode & anchorAtCentre) != 0)
  69451. xOut -= wOut / 2;
  69452. }
  69453. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  69454. double x, const double w,
  69455. const uint8 xMode, const uint8 wMode,
  69456. const int parentPos,
  69457. const int parentSize) const throw()
  69458. {
  69459. if (wMode == proportionalSize)
  69460. {
  69461. if (parentSize > 0)
  69462. wOut = w / parentSize;
  69463. }
  69464. else if (wMode == parentSizeMinusAbsolute)
  69465. wOut = parentSize - w;
  69466. else
  69467. wOut = w;
  69468. if ((xMode & anchorAtRightOrBottom) != 0)
  69469. x += w;
  69470. else if ((xMode & anchorAtCentre) != 0)
  69471. x += w / 2;
  69472. if ((xMode & proportionOfParentSize) != 0)
  69473. {
  69474. if (parentSize > 0)
  69475. xOut = (x - parentPos) / parentSize;
  69476. }
  69477. else if ((xMode & absoluteFromParentBottomRight) != 0)
  69478. xOut = (parentPos + parentSize) - x;
  69479. else if ((xMode & absoluteFromParentCentre) != 0)
  69480. xOut = x - (parentPos + parentSize / 2);
  69481. else
  69482. xOut = x - parentPos;
  69483. }
  69484. END_JUCE_NAMESPACE
  69485. /********* End of inlined file: juce_PositionedRectangle.cpp *********/
  69486. /********* Start of inlined file: juce_Rectangle.cpp *********/
  69487. BEGIN_JUCE_NAMESPACE
  69488. Rectangle::Rectangle() throw()
  69489. : x (0),
  69490. y (0),
  69491. w (0),
  69492. h (0)
  69493. {
  69494. }
  69495. Rectangle::Rectangle (const int x_, const int y_,
  69496. const int w_, const int h_) throw()
  69497. : x (x_),
  69498. y (y_),
  69499. w (w_),
  69500. h (h_)
  69501. {
  69502. }
  69503. Rectangle::Rectangle (const int w_, const int h_) throw()
  69504. : x (0),
  69505. y (0),
  69506. w (w_),
  69507. h (h_)
  69508. {
  69509. }
  69510. Rectangle::Rectangle (const Rectangle& other) throw()
  69511. : x (other.x),
  69512. y (other.y),
  69513. w (other.w),
  69514. h (other.h)
  69515. {
  69516. }
  69517. Rectangle::~Rectangle() throw()
  69518. {
  69519. }
  69520. bool Rectangle::isEmpty() const throw()
  69521. {
  69522. return w <= 0 || h <= 0;
  69523. }
  69524. void Rectangle::setBounds (const int x_,
  69525. const int y_,
  69526. const int w_,
  69527. const int h_) throw()
  69528. {
  69529. x = x_;
  69530. y = y_;
  69531. w = w_;
  69532. h = h_;
  69533. }
  69534. void Rectangle::setPosition (const int x_,
  69535. const int y_) throw()
  69536. {
  69537. x = x_;
  69538. y = y_;
  69539. }
  69540. void Rectangle::setSize (const int w_,
  69541. const int h_) throw()
  69542. {
  69543. w = w_;
  69544. h = h_;
  69545. }
  69546. void Rectangle::translate (const int dx,
  69547. const int dy) throw()
  69548. {
  69549. x += dx;
  69550. y += dy;
  69551. }
  69552. const Rectangle Rectangle::translated (const int dx,
  69553. const int dy) const throw()
  69554. {
  69555. return Rectangle (x + dx, y + dy, w, h);
  69556. }
  69557. void Rectangle::expand (const int deltaX,
  69558. const int deltaY) throw()
  69559. {
  69560. const int nw = jmax (0, w + deltaX + deltaX);
  69561. const int nh = jmax (0, h + deltaY + deltaY);
  69562. setBounds (x - deltaX,
  69563. y - deltaY,
  69564. nw, nh);
  69565. }
  69566. const Rectangle Rectangle::expanded (const int deltaX,
  69567. const int deltaY) const throw()
  69568. {
  69569. const int nw = jmax (0, w + deltaX + deltaX);
  69570. const int nh = jmax (0, h + deltaY + deltaY);
  69571. return Rectangle (x - deltaX,
  69572. y - deltaY,
  69573. nw, nh);
  69574. }
  69575. void Rectangle::reduce (const int deltaX,
  69576. const int deltaY) throw()
  69577. {
  69578. expand (-deltaX, -deltaY);
  69579. }
  69580. const Rectangle Rectangle::reduced (const int deltaX,
  69581. const int deltaY) const throw()
  69582. {
  69583. return expanded (-deltaX, -deltaY);
  69584. }
  69585. bool Rectangle::operator== (const Rectangle& other) const throw()
  69586. {
  69587. return x == other.x
  69588. && y == other.y
  69589. && w == other.w
  69590. && h == other.h;
  69591. }
  69592. bool Rectangle::operator!= (const Rectangle& other) const throw()
  69593. {
  69594. return x != other.x
  69595. || y != other.y
  69596. || w != other.w
  69597. || h != other.h;
  69598. }
  69599. bool Rectangle::contains (const int px,
  69600. const int py) const throw()
  69601. {
  69602. return px >= x
  69603. && py >= y
  69604. && px < x + w
  69605. && py < y + h;
  69606. }
  69607. bool Rectangle::contains (const Rectangle& other) const throw()
  69608. {
  69609. return x <= other.x
  69610. && y <= other.y
  69611. && x + w >= other.x + other.w
  69612. && y + h >= other.y + other.h;
  69613. }
  69614. bool Rectangle::intersects (const Rectangle& other) const throw()
  69615. {
  69616. return x + w > other.x
  69617. && y + h > other.y
  69618. && x < other.x + other.w
  69619. && y < other.y + other.h
  69620. && w > 0
  69621. && h > 0;
  69622. }
  69623. const Rectangle Rectangle::getIntersection (const Rectangle& other) const throw()
  69624. {
  69625. const int nx = jmax (x, other.x);
  69626. const int ny = jmax (y, other.y);
  69627. const int nw = jmin (x + w, other.x + other.w) - nx;
  69628. const int nh = jmin (y + h, other.y + other.h) - ny;
  69629. if (nw >= 0 && nh >= 0)
  69630. return Rectangle (nx, ny, nw, nh);
  69631. else
  69632. return Rectangle();
  69633. }
  69634. bool Rectangle::intersectRectangle (int& x1, int& y1, int& w1, int& h1) const throw()
  69635. {
  69636. const int maxX = jmax (x1, x);
  69637. w1 = jmin (x1 + w1, x + w) - maxX;
  69638. if (w1 > 0)
  69639. {
  69640. const int maxY = jmax (y1, y);
  69641. h1 = jmin (y1 + h1, y + h) - maxY;
  69642. if (h1 > 0)
  69643. {
  69644. x1 = maxX;
  69645. y1 = maxY;
  69646. return true;
  69647. }
  69648. }
  69649. return false;
  69650. }
  69651. bool Rectangle::intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  69652. int x2, int y2, int w2, int h2) throw()
  69653. {
  69654. const int x = jmax (x1, x2);
  69655. w1 = jmin (x1 + w1, x2 + w2) - x;
  69656. if (w1 > 0)
  69657. {
  69658. const int y = jmax (y1, y2);
  69659. h1 = jmin (y1 + h1, y2 + h2) - y;
  69660. if (h1 > 0)
  69661. {
  69662. x1 = x;
  69663. y1 = y;
  69664. return true;
  69665. }
  69666. }
  69667. return false;
  69668. }
  69669. const Rectangle Rectangle::getUnion (const Rectangle& other) const throw()
  69670. {
  69671. const int newX = jmin (x, other.x);
  69672. const int newY = jmin (y, other.y);
  69673. return Rectangle (newX, newY,
  69674. jmax (x + w, other.x + other.w) - newX,
  69675. jmax (y + h, other.y + other.h) - newY);
  69676. }
  69677. bool Rectangle::enlargeIfAdjacent (const Rectangle& other) throw()
  69678. {
  69679. if (x == other.x && getRight() == other.getRight()
  69680. && (other.getBottom() >= y && other.y <= getBottom()))
  69681. {
  69682. const int newY = jmin (y, other.y);
  69683. h = jmax (getBottom(), other.getBottom()) - newY;
  69684. y = newY;
  69685. return true;
  69686. }
  69687. else if (y == other.y && getBottom() == other.getBottom()
  69688. && (other.getRight() >= x && other.x <= getRight()))
  69689. {
  69690. const int newX = jmin (x, other.x);
  69691. w = jmax (getRight(), other.getRight()) - newX;
  69692. x = newX;
  69693. return true;
  69694. }
  69695. return false;
  69696. }
  69697. bool Rectangle::reduceIfPartlyContainedIn (const Rectangle& other) throw()
  69698. {
  69699. int inside = 0;
  69700. const int otherR = other.getRight();
  69701. if (x >= other.x && x < otherR)
  69702. inside = 1;
  69703. const int otherB = other.getBottom();
  69704. if (y >= other.y && y < otherB)
  69705. inside |= 2;
  69706. const int r = x + w;
  69707. if (r >= other.x && r < otherR)
  69708. inside |= 4;
  69709. const int b = y + h;
  69710. if (b >= other.y && b < otherB)
  69711. inside |= 8;
  69712. switch (inside)
  69713. {
  69714. case 1 + 2 + 8:
  69715. w = r - otherR;
  69716. x = otherR;
  69717. return true;
  69718. case 1 + 2 + 4:
  69719. h = b - otherB;
  69720. y = otherB;
  69721. return true;
  69722. case 2 + 4 + 8:
  69723. w = other.x - x;
  69724. return true;
  69725. case 1 + 4 + 8:
  69726. h = other.y - y;
  69727. return true;
  69728. }
  69729. return false;
  69730. }
  69731. const String Rectangle::toString() const throw()
  69732. {
  69733. String s;
  69734. s.preallocateStorage (16);
  69735. s << x << T(' ')
  69736. << y << T(' ')
  69737. << w << T(' ')
  69738. << h;
  69739. return s;
  69740. }
  69741. const Rectangle Rectangle::fromString (const String& stringVersion)
  69742. {
  69743. StringArray toks;
  69744. toks.addTokens (stringVersion.trim(), T(",; \t\r\n"), 0);
  69745. return Rectangle (toks[0].trim().getIntValue(),
  69746. toks[1].trim().getIntValue(),
  69747. toks[2].trim().getIntValue(),
  69748. toks[3].trim().getIntValue());
  69749. }
  69750. END_JUCE_NAMESPACE
  69751. /********* End of inlined file: juce_Rectangle.cpp *********/
  69752. /********* Start of inlined file: juce_RectangleList.cpp *********/
  69753. BEGIN_JUCE_NAMESPACE
  69754. RectangleList::RectangleList() throw()
  69755. {
  69756. }
  69757. RectangleList::RectangleList (const Rectangle& rect) throw()
  69758. {
  69759. if (! rect.isEmpty())
  69760. rects.add (rect);
  69761. }
  69762. RectangleList::RectangleList (const RectangleList& other) throw()
  69763. : rects (other.rects)
  69764. {
  69765. }
  69766. const RectangleList& RectangleList::operator= (const RectangleList& other) throw()
  69767. {
  69768. if (this != &other)
  69769. rects = other.rects;
  69770. return *this;
  69771. }
  69772. RectangleList::~RectangleList() throw()
  69773. {
  69774. }
  69775. void RectangleList::clear() throw()
  69776. {
  69777. rects.clearQuick();
  69778. }
  69779. const Rectangle RectangleList::getRectangle (const int index) const throw()
  69780. {
  69781. if (((unsigned int) index) < (unsigned int) rects.size())
  69782. return rects.getReference (index);
  69783. return Rectangle();
  69784. }
  69785. bool RectangleList::isEmpty() const throw()
  69786. {
  69787. return rects.size() == 0;
  69788. }
  69789. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  69790. : current (0),
  69791. owner (list),
  69792. index (list.rects.size())
  69793. {
  69794. }
  69795. RectangleList::Iterator::~Iterator() throw()
  69796. {
  69797. }
  69798. bool RectangleList::Iterator::next() throw()
  69799. {
  69800. if (--index >= 0)
  69801. {
  69802. current = & (owner.rects.getReference (index));
  69803. return true;
  69804. }
  69805. return false;
  69806. }
  69807. void RectangleList::add (const Rectangle& rect) throw()
  69808. {
  69809. if (! rect.isEmpty())
  69810. {
  69811. if (rects.size() == 0)
  69812. {
  69813. rects.add (rect);
  69814. }
  69815. else
  69816. {
  69817. bool anyOverlaps = false;
  69818. int i;
  69819. for (i = rects.size(); --i >= 0;)
  69820. {
  69821. Rectangle& ourRect = rects.getReference (i);
  69822. if (rect.intersects (ourRect))
  69823. {
  69824. if (rect.contains (ourRect))
  69825. rects.remove (i);
  69826. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  69827. anyOverlaps = true;
  69828. }
  69829. }
  69830. if (anyOverlaps && rects.size() > 0)
  69831. {
  69832. RectangleList r (rect);
  69833. for (i = rects.size(); --i >= 0;)
  69834. {
  69835. const Rectangle& ourRect = rects.getReference (i);
  69836. if (rect.intersects (ourRect))
  69837. {
  69838. r.subtract (ourRect);
  69839. if (r.rects.size() == 0)
  69840. return;
  69841. }
  69842. }
  69843. for (i = r.getNumRectangles(); --i >= 0;)
  69844. rects.add (r.rects.getReference (i));
  69845. }
  69846. else
  69847. {
  69848. rects.add (rect);
  69849. }
  69850. }
  69851. }
  69852. }
  69853. void RectangleList::addWithoutMerging (const Rectangle& rect) throw()
  69854. {
  69855. rects.add (rect);
  69856. }
  69857. void RectangleList::add (const int x, const int y, const int w, const int h) throw()
  69858. {
  69859. if (rects.size() == 0)
  69860. {
  69861. if (w > 0 && h > 0)
  69862. rects.add (Rectangle (x, y, w, h));
  69863. }
  69864. else
  69865. {
  69866. add (Rectangle (x, y, w, h));
  69867. }
  69868. }
  69869. void RectangleList::add (const RectangleList& other) throw()
  69870. {
  69871. for (int i = 0; i < other.rects.size(); ++i)
  69872. add (other.rects.getReference (i));
  69873. }
  69874. void RectangleList::subtract (const Rectangle& rect) throw()
  69875. {
  69876. const int originalNumRects = rects.size();
  69877. if (originalNumRects > 0)
  69878. {
  69879. const int x1 = rect.x;
  69880. const int y1 = rect.y;
  69881. const int x2 = x1 + rect.w;
  69882. const int y2 = y1 + rect.h;
  69883. for (int i = getNumRectangles(); --i >= 0;)
  69884. {
  69885. Rectangle& r = rects.getReference (i);
  69886. const int rx1 = r.x;
  69887. const int ry1 = r.y;
  69888. const int rx2 = rx1 + r.w;
  69889. const int ry2 = ry1 + r.h;
  69890. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  69891. {
  69892. if (x1 > rx1 && x1 < rx2)
  69893. {
  69894. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  69895. {
  69896. r.w = x1 - rx1;
  69897. }
  69898. else
  69899. {
  69900. r.x = x1;
  69901. r.w = rx2 - x1;
  69902. rects.insert (i + 1, Rectangle (rx1, ry1, x1 - rx1, ry2 - ry1));
  69903. i += 2;
  69904. }
  69905. }
  69906. else if (x2 > rx1 && x2 < rx2)
  69907. {
  69908. r.x = x2;
  69909. r.w = rx2 - x2;
  69910. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  69911. {
  69912. rects.insert (i + 1, Rectangle (rx1, ry1, x2 - rx1, ry2 - ry1));
  69913. i += 2;
  69914. }
  69915. }
  69916. else if (y1 > ry1 && y1 < ry2)
  69917. {
  69918. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  69919. {
  69920. r.h = y1 - ry1;
  69921. }
  69922. else
  69923. {
  69924. r.y = y1;
  69925. r.h = ry2 - y1;
  69926. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y1 - ry1));
  69927. i += 2;
  69928. }
  69929. }
  69930. else if (y2 > ry1 && y2 < ry2)
  69931. {
  69932. r.y = y2;
  69933. r.h = ry2 - y2;
  69934. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  69935. {
  69936. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y2 - ry1));
  69937. i += 2;
  69938. }
  69939. }
  69940. else
  69941. {
  69942. rects.remove (i);
  69943. }
  69944. }
  69945. }
  69946. if (rects.size() > originalNumRects + 10)
  69947. consolidate();
  69948. }
  69949. }
  69950. void RectangleList::subtract (const RectangleList& otherList) throw()
  69951. {
  69952. for (int i = otherList.rects.size(); --i >= 0;)
  69953. subtract (otherList.rects.getReference (i));
  69954. }
  69955. bool RectangleList::clipTo (const Rectangle& rect) throw()
  69956. {
  69957. bool notEmpty = false;
  69958. if (rect.isEmpty())
  69959. {
  69960. clear();
  69961. }
  69962. else
  69963. {
  69964. for (int i = rects.size(); --i >= 0;)
  69965. {
  69966. Rectangle& r = rects.getReference (i);
  69967. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  69968. rects.remove (i);
  69969. else
  69970. notEmpty = true;
  69971. }
  69972. }
  69973. return notEmpty;
  69974. }
  69975. bool RectangleList::clipTo (const RectangleList& other) throw()
  69976. {
  69977. if (rects.size() == 0)
  69978. return false;
  69979. RectangleList result;
  69980. for (int j = 0; j < rects.size(); ++j)
  69981. {
  69982. const Rectangle& rect = rects.getReference (j);
  69983. for (int i = other.rects.size(); --i >= 0;)
  69984. {
  69985. Rectangle r (other.rects.getReference (i));
  69986. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  69987. result.rects.add (r);
  69988. }
  69989. }
  69990. swapWith (result);
  69991. return ! isEmpty();
  69992. }
  69993. bool RectangleList::getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw()
  69994. {
  69995. destRegion.clear();
  69996. if (! rect.isEmpty())
  69997. {
  69998. for (int i = rects.size(); --i >= 0;)
  69999. {
  70000. Rectangle r (rects.getReference (i));
  70001. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  70002. destRegion.rects.add (r);
  70003. }
  70004. }
  70005. return destRegion.rects.size() > 0;
  70006. }
  70007. void RectangleList::swapWith (RectangleList& otherList) throw()
  70008. {
  70009. rects.swapWithArray (otherList.rects);
  70010. }
  70011. void RectangleList::consolidate() throw()
  70012. {
  70013. int i;
  70014. for (i = 0; i < getNumRectangles() - 1; ++i)
  70015. {
  70016. Rectangle& r = rects.getReference (i);
  70017. const int rx1 = r.x;
  70018. const int ry1 = r.y;
  70019. const int rx2 = rx1 + r.w;
  70020. const int ry2 = ry1 + r.h;
  70021. for (int j = rects.size(); --j > i;)
  70022. {
  70023. Rectangle& r2 = rects.getReference (j);
  70024. const int jrx1 = r2.x;
  70025. const int jry1 = r2.y;
  70026. const int jrx2 = jrx1 + r2.w;
  70027. const int jry2 = jry1 + r2.h;
  70028. // if the vertical edges of any blocks are touching and their horizontals don't
  70029. // line up, split them horizontally..
  70030. if (jrx1 == rx2 || jrx2 == rx1)
  70031. {
  70032. if (jry1 > ry1 && jry1 < ry2)
  70033. {
  70034. r.h = jry1 - ry1;
  70035. rects.add (Rectangle (rx1, jry1, rx2 - rx1, ry2 - jry1));
  70036. i = -1;
  70037. break;
  70038. }
  70039. if (jry2 > ry1 && jry2 < ry2)
  70040. {
  70041. r.h = jry2 - ry1;
  70042. rects.add (Rectangle (rx1, jry2, rx2 - rx1, ry2 - jry2));
  70043. i = -1;
  70044. break;
  70045. }
  70046. else if (ry1 > jry1 && ry1 < jry2)
  70047. {
  70048. r2.h = ry1 - jry1;
  70049. rects.add (Rectangle (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  70050. i = -1;
  70051. break;
  70052. }
  70053. else if (ry2 > jry1 && ry2 < jry2)
  70054. {
  70055. r2.h = ry2 - jry1;
  70056. rects.add (Rectangle (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  70057. i = -1;
  70058. break;
  70059. }
  70060. }
  70061. }
  70062. }
  70063. for (i = 0; i < rects.size() - 1; ++i)
  70064. {
  70065. Rectangle& r = rects.getReference (i);
  70066. for (int j = rects.size(); --j > i;)
  70067. {
  70068. if (r.enlargeIfAdjacent (rects.getReference (j)))
  70069. {
  70070. rects.remove (j);
  70071. i = -1;
  70072. break;
  70073. }
  70074. }
  70075. }
  70076. }
  70077. bool RectangleList::containsPoint (const int x, const int y) const throw()
  70078. {
  70079. for (int i = getNumRectangles(); --i >= 0;)
  70080. if (rects.getReference (i).contains (x, y))
  70081. return true;
  70082. return false;
  70083. }
  70084. bool RectangleList::containsRectangle (const Rectangle& rectangleToCheck) const throw()
  70085. {
  70086. if (rects.size() > 1)
  70087. {
  70088. RectangleList r (rectangleToCheck);
  70089. for (int i = rects.size(); --i >= 0;)
  70090. {
  70091. r.subtract (rects.getReference (i));
  70092. if (r.rects.size() == 0)
  70093. return true;
  70094. }
  70095. }
  70096. else if (rects.size() > 0)
  70097. {
  70098. return rects.getReference (0).contains (rectangleToCheck);
  70099. }
  70100. return false;
  70101. }
  70102. bool RectangleList::intersectsRectangle (const Rectangle& rectangleToCheck) const throw()
  70103. {
  70104. for (int i = rects.size(); --i >= 0;)
  70105. if (rects.getReference (i).intersects (rectangleToCheck))
  70106. return true;
  70107. return false;
  70108. }
  70109. bool RectangleList::intersects (const RectangleList& other) const throw()
  70110. {
  70111. for (int i = rects.size(); --i >= 0;)
  70112. if (other.intersectsRectangle (rects.getReference (i)))
  70113. return true;
  70114. return false;
  70115. }
  70116. const Rectangle RectangleList::getBounds() const throw()
  70117. {
  70118. if (rects.size() <= 1)
  70119. {
  70120. if (rects.size() == 0)
  70121. return Rectangle();
  70122. else
  70123. return rects.getReference (0);
  70124. }
  70125. else
  70126. {
  70127. const Rectangle& r = rects.getReference (0);
  70128. int minX = r.x;
  70129. int minY = r.y;
  70130. int maxX = minX + r.w;
  70131. int maxY = minY + r.h;
  70132. for (int i = rects.size(); --i > 0;)
  70133. {
  70134. const Rectangle& r2 = rects.getReference (i);
  70135. minX = jmin (minX, r2.x);
  70136. minY = jmin (minY, r2.y);
  70137. maxX = jmax (maxX, r2.getRight());
  70138. maxY = jmax (maxY, r2.getBottom());
  70139. }
  70140. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  70141. }
  70142. }
  70143. void RectangleList::offsetAll (const int dx, const int dy) throw()
  70144. {
  70145. for (int i = rects.size(); --i >= 0;)
  70146. {
  70147. Rectangle& r = rects.getReference (i);
  70148. r.x += dx;
  70149. r.y += dy;
  70150. }
  70151. }
  70152. const Path RectangleList::toPath() const throw()
  70153. {
  70154. Path p;
  70155. for (int i = rects.size(); --i >= 0;)
  70156. {
  70157. const Rectangle& r = rects.getReference (i);
  70158. p.addRectangle ((float) r.x,
  70159. (float) r.y,
  70160. (float) r.w,
  70161. (float) r.h);
  70162. }
  70163. return p;
  70164. }
  70165. END_JUCE_NAMESPACE
  70166. /********* End of inlined file: juce_RectangleList.cpp *********/
  70167. /********* Start of inlined file: juce_Image.cpp *********/
  70168. BEGIN_JUCE_NAMESPACE
  70169. static const int fullAlphaThreshold = 253;
  70170. Image::Image (const PixelFormat format_,
  70171. const int imageWidth_,
  70172. const int imageHeight_)
  70173. : format (format_),
  70174. imageWidth (imageWidth_),
  70175. imageHeight (imageHeight_),
  70176. imageData (0)
  70177. {
  70178. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  70179. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  70180. // actual image will be at least 1x1.
  70181. }
  70182. Image::Image (const PixelFormat format_,
  70183. const int imageWidth_,
  70184. const int imageHeight_,
  70185. const bool clearImage)
  70186. : format (format_),
  70187. imageWidth (imageWidth_),
  70188. imageHeight (imageHeight_)
  70189. {
  70190. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  70191. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  70192. // actual image will be at least 1x1.
  70193. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  70194. lineStride = (pixelStride * jmax (1, imageWidth_) + 3) & ~3;
  70195. const int dataSize = lineStride * jmax (1, imageHeight_);
  70196. imageData = (uint8*) (clearImage ? juce_calloc (dataSize)
  70197. : juce_malloc (dataSize));
  70198. }
  70199. Image::Image (const Image& other)
  70200. : format (other.format),
  70201. imageWidth (other.imageWidth),
  70202. imageHeight (other.imageHeight)
  70203. {
  70204. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  70205. lineStride = (pixelStride * jmax (1, imageWidth) + 3) & ~3;
  70206. const int dataSize = lineStride * jmax (1, imageHeight);
  70207. imageData = (uint8*) juce_malloc (dataSize);
  70208. int ls, ps;
  70209. const uint8* srcData = other.lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  70210. setPixelData (0, 0, imageWidth, imageHeight, srcData, ls);
  70211. other.releasePixelDataReadOnly (srcData);
  70212. }
  70213. Image::~Image()
  70214. {
  70215. juce_free (imageData);
  70216. }
  70217. LowLevelGraphicsContext* Image::createLowLevelContext()
  70218. {
  70219. return new LowLevelGraphicsSoftwareRenderer (*this);
  70220. }
  70221. uint8* Image::lockPixelDataReadWrite (int x, int y, int w, int h, int& ls, int& ps)
  70222. {
  70223. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  70224. w = w;
  70225. h = h;
  70226. ls = lineStride;
  70227. ps = pixelStride;
  70228. return imageData + x * pixelStride + y * lineStride;
  70229. }
  70230. void Image::releasePixelDataReadWrite (void*)
  70231. {
  70232. }
  70233. const uint8* Image::lockPixelDataReadOnly (int x, int y, int w, int h, int& ls, int& ps) const
  70234. {
  70235. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  70236. w = w;
  70237. h = h;
  70238. ls = lineStride;
  70239. ps = pixelStride;
  70240. return imageData + x * pixelStride + y * lineStride;
  70241. }
  70242. void Image::releasePixelDataReadOnly (const void*) const
  70243. {
  70244. }
  70245. void Image::setPixelData (int x, int y, int w, int h,
  70246. const uint8* sourcePixelData, int sourceLineStride)
  70247. {
  70248. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  70249. if (Rectangle::intersectRectangles (x, y, w, h, 0, 0, imageWidth, imageHeight))
  70250. {
  70251. int ls, ps;
  70252. uint8* dest = lockPixelDataReadWrite (x, y, w, h, ls, ps);
  70253. for (int i = 0; i < h; ++i)
  70254. {
  70255. memcpy (dest + ls * i,
  70256. sourcePixelData + sourceLineStride * i,
  70257. w * pixelStride);
  70258. }
  70259. releasePixelDataReadWrite (dest);
  70260. }
  70261. }
  70262. void Image::clear (int dx, int dy, int dw, int dh,
  70263. const Colour& colourToClearTo)
  70264. {
  70265. const PixelARGB col (colourToClearTo.getPixelARGB());
  70266. int ls, ps;
  70267. uint8* dstData = lockPixelDataReadWrite (dx, dy, dw, dh, ls, ps);
  70268. uint8* dest = dstData;
  70269. while (--dh >= 0)
  70270. {
  70271. uint8* line = dest;
  70272. dest += ls;
  70273. if (isARGB())
  70274. {
  70275. for (int x = dw; --x >= 0;)
  70276. {
  70277. ((PixelARGB*) line)->set (col);
  70278. line += ps;
  70279. }
  70280. }
  70281. else if (isRGB())
  70282. {
  70283. for (int x = dw; --x >= 0;)
  70284. {
  70285. ((PixelRGB*) line)->set (col);
  70286. line += ps;
  70287. }
  70288. }
  70289. else
  70290. {
  70291. for (int x = dw; --x >= 0;)
  70292. {
  70293. *line = col.getAlpha();
  70294. line += ps;
  70295. }
  70296. }
  70297. }
  70298. releasePixelDataReadWrite (dstData);
  70299. }
  70300. Image* Image::createCopy (int newWidth, int newHeight,
  70301. const Graphics::ResamplingQuality quality) const
  70302. {
  70303. if (newWidth < 0)
  70304. newWidth = imageWidth;
  70305. if (newHeight < 0)
  70306. newHeight = imageHeight;
  70307. Image* const newImage = new Image (format, newWidth, newHeight, true);
  70308. Graphics g (*newImage);
  70309. g.setImageResamplingQuality (quality);
  70310. g.drawImage (this,
  70311. 0, 0, newWidth, newHeight,
  70312. 0, 0, imageWidth, imageHeight,
  70313. false);
  70314. return newImage;
  70315. }
  70316. const Colour Image::getPixelAt (const int x, const int y) const
  70317. {
  70318. Colour c;
  70319. if (((unsigned int) x) < (unsigned int) imageWidth
  70320. && ((unsigned int) y) < (unsigned int) imageHeight)
  70321. {
  70322. int ls, ps;
  70323. const uint8* const pixels = lockPixelDataReadOnly (x, y, 1, 1, ls, ps);
  70324. if (isARGB())
  70325. {
  70326. PixelARGB p (*(const PixelARGB*) pixels);
  70327. p.unpremultiply();
  70328. c = Colour (p.getARGB());
  70329. }
  70330. else if (isRGB())
  70331. c = Colour (((const PixelRGB*) pixels)->getARGB());
  70332. else
  70333. c = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixels);
  70334. releasePixelDataReadOnly (pixels);
  70335. }
  70336. return c;
  70337. }
  70338. void Image::setPixelAt (const int x, const int y,
  70339. const Colour& colour)
  70340. {
  70341. if (((unsigned int) x) < (unsigned int) imageWidth
  70342. && ((unsigned int) y) < (unsigned int) imageHeight)
  70343. {
  70344. int ls, ps;
  70345. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  70346. const PixelARGB col (colour.getPixelARGB());
  70347. if (isARGB())
  70348. ((PixelARGB*) pixels)->set (col);
  70349. else if (isRGB())
  70350. ((PixelRGB*) pixels)->set (col);
  70351. else
  70352. *pixels = col.getAlpha();
  70353. releasePixelDataReadWrite (pixels);
  70354. }
  70355. }
  70356. void Image::multiplyAlphaAt (const int x, const int y,
  70357. const float multiplier)
  70358. {
  70359. if (((unsigned int) x) < (unsigned int) imageWidth
  70360. && ((unsigned int) y) < (unsigned int) imageHeight
  70361. && hasAlphaChannel())
  70362. {
  70363. int ls, ps;
  70364. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  70365. if (isARGB())
  70366. ((PixelARGB*) pixels)->multiplyAlpha (multiplier);
  70367. else
  70368. *pixels = (uint8) (*pixels * multiplier);
  70369. releasePixelDataReadWrite (pixels);
  70370. }
  70371. }
  70372. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  70373. {
  70374. if (hasAlphaChannel())
  70375. {
  70376. int ls, ps;
  70377. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  70378. if (isARGB())
  70379. {
  70380. for (int y = 0; y < imageHeight; ++y)
  70381. {
  70382. uint8* p = pixels + y * ls;
  70383. for (int x = 0; x < imageWidth; ++x)
  70384. {
  70385. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  70386. p += ps;
  70387. }
  70388. }
  70389. }
  70390. else
  70391. {
  70392. for (int y = 0; y < imageHeight; ++y)
  70393. {
  70394. uint8* p = pixels + y * ls;
  70395. for (int x = 0; x < imageWidth; ++x)
  70396. {
  70397. *p = (uint8) (*p * amountToMultiplyBy);
  70398. p += ps;
  70399. }
  70400. }
  70401. }
  70402. releasePixelDataReadWrite (pixels);
  70403. }
  70404. else
  70405. {
  70406. jassertfalse // can't do this without an alpha-channel!
  70407. }
  70408. }
  70409. void Image::desaturate()
  70410. {
  70411. if (isARGB() || isRGB())
  70412. {
  70413. int ls, ps;
  70414. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  70415. if (isARGB())
  70416. {
  70417. for (int y = 0; y < imageHeight; ++y)
  70418. {
  70419. uint8* p = pixels + y * ls;
  70420. for (int x = 0; x < imageWidth; ++x)
  70421. {
  70422. ((PixelARGB*) p)->desaturate();
  70423. p += ps;
  70424. }
  70425. }
  70426. }
  70427. else
  70428. {
  70429. for (int y = 0; y < imageHeight; ++y)
  70430. {
  70431. uint8* p = pixels + y * ls;
  70432. for (int x = 0; x < imageWidth; ++x)
  70433. {
  70434. ((PixelRGB*) p)->desaturate();
  70435. p += ps;
  70436. }
  70437. }
  70438. }
  70439. releasePixelDataReadWrite (pixels);
  70440. }
  70441. }
  70442. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  70443. {
  70444. if (hasAlphaChannel())
  70445. {
  70446. const uint8 threshold = (uint8) jlimit (0, 255, roundFloatToInt (alphaThreshold * 255.0f));
  70447. SparseSet <int> pixelsOnRow;
  70448. int ls, ps;
  70449. const uint8* const pixels = lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  70450. for (int y = 0; y < imageHeight; ++y)
  70451. {
  70452. pixelsOnRow.clear();
  70453. const uint8* lineData = pixels + ls * y;
  70454. if (isARGB())
  70455. {
  70456. for (int x = 0; x < imageWidth; ++x)
  70457. {
  70458. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  70459. pixelsOnRow.addRange (x, 1);
  70460. lineData += ps;
  70461. }
  70462. }
  70463. else
  70464. {
  70465. for (int x = 0; x < imageWidth; ++x)
  70466. {
  70467. if (*lineData >= threshold)
  70468. pixelsOnRow.addRange (x, 1);
  70469. lineData += ps;
  70470. }
  70471. }
  70472. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  70473. {
  70474. int x, w;
  70475. if (pixelsOnRow.getRange (i, x, w))
  70476. result.add (Rectangle (x, y, w, 1));
  70477. }
  70478. result.consolidate();
  70479. }
  70480. releasePixelDataReadOnly (pixels);
  70481. }
  70482. else
  70483. {
  70484. result.add (0, 0, imageWidth, imageHeight);
  70485. }
  70486. }
  70487. void Image::moveImageSection (int dx, int dy,
  70488. int sx, int sy,
  70489. int w, int h)
  70490. {
  70491. if (dx < 0)
  70492. {
  70493. w += dx;
  70494. sx -= dx;
  70495. dx = 0;
  70496. }
  70497. if (dy < 0)
  70498. {
  70499. h += dy;
  70500. sy -= dy;
  70501. dy = 0;
  70502. }
  70503. if (sx < 0)
  70504. {
  70505. w += sx;
  70506. dx -= sx;
  70507. sx = 0;
  70508. }
  70509. if (sy < 0)
  70510. {
  70511. h += sy;
  70512. dy -= sy;
  70513. sy = 0;
  70514. }
  70515. const int minX = jmin (dx, sx);
  70516. const int minY = jmin (dy, sy);
  70517. w = jmin (w, getWidth() - jmax (sx, dx));
  70518. h = jmin (h, getHeight() - jmax (sy, dy));
  70519. if (w > 0 && h > 0)
  70520. {
  70521. const int maxX = jmax (dx, sx) + w;
  70522. const int maxY = jmax (dy, sy) + h;
  70523. int ls, ps;
  70524. uint8* const pixels = lockPixelDataReadWrite (minX, minY, maxX - minX, maxY - minY, ls, ps);
  70525. uint8* dst = pixels + ls * (dy - minY) + ps * (dx - minX);
  70526. const uint8* src = pixels + ls * (sy - minY) + ps * (sx - minX);
  70527. const int lineSize = ps * w;
  70528. if (dy > sy)
  70529. {
  70530. while (--h >= 0)
  70531. {
  70532. const int offset = h * ls;
  70533. memmove (dst + offset, src + offset, lineSize);
  70534. }
  70535. }
  70536. else if (dst != src)
  70537. {
  70538. while (--h >= 0)
  70539. {
  70540. memmove (dst, src, lineSize);
  70541. dst += ls;
  70542. src += ls;
  70543. }
  70544. }
  70545. releasePixelDataReadWrite (pixels);
  70546. }
  70547. }
  70548. END_JUCE_NAMESPACE
  70549. /********* End of inlined file: juce_Image.cpp *********/
  70550. /********* Start of inlined file: juce_ImageCache.cpp *********/
  70551. BEGIN_JUCE_NAMESPACE
  70552. struct CachedImageInfo
  70553. {
  70554. Image* image;
  70555. int64 hashCode;
  70556. int refCount;
  70557. unsigned int releaseTime;
  70558. juce_UseDebuggingNewOperator
  70559. };
  70560. static ImageCache* instance = 0;
  70561. static int cacheTimeout = 5000;
  70562. ImageCache::ImageCache() throw()
  70563. : images (4)
  70564. {
  70565. }
  70566. ImageCache::~ImageCache()
  70567. {
  70568. const ScopedLock sl (lock);
  70569. for (int i = images.size(); --i >= 0;)
  70570. {
  70571. CachedImageInfo* const ci = (CachedImageInfo*)(images.getUnchecked(i));
  70572. delete ci->image;
  70573. delete ci;
  70574. }
  70575. images.clear();
  70576. jassert (instance == this);
  70577. instance = 0;
  70578. }
  70579. Image* ImageCache::getFromHashCode (const int64 hashCode)
  70580. {
  70581. if (instance != 0)
  70582. {
  70583. const ScopedLock sl (instance->lock);
  70584. for (int i = instance->images.size(); --i >= 0;)
  70585. {
  70586. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  70587. if (ci->hashCode == hashCode)
  70588. {
  70589. atomicIncrement (ci->refCount);
  70590. return ci->image;
  70591. }
  70592. }
  70593. }
  70594. return 0;
  70595. }
  70596. void ImageCache::addImageToCache (Image* const image,
  70597. const int64 hashCode)
  70598. {
  70599. if (image != 0)
  70600. {
  70601. if (instance == 0)
  70602. instance = new ImageCache();
  70603. CachedImageInfo* const newC = new CachedImageInfo();
  70604. newC->hashCode = hashCode;
  70605. newC->image = image;
  70606. newC->refCount = 1;
  70607. newC->releaseTime = 0;
  70608. const ScopedLock sl (instance->lock);
  70609. instance->images.add (newC);
  70610. }
  70611. }
  70612. void ImageCache::release (Image* const imageToRelease)
  70613. {
  70614. if (imageToRelease != 0 && instance != 0)
  70615. {
  70616. const ScopedLock sl (instance->lock);
  70617. for (int i = instance->images.size(); --i >= 0;)
  70618. {
  70619. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  70620. if (ci->image == imageToRelease)
  70621. {
  70622. if (--(ci->refCount) == 0)
  70623. ci->releaseTime = Time::getApproximateMillisecondCounter();
  70624. if (! instance->isTimerRunning())
  70625. instance->startTimer (999);
  70626. break;
  70627. }
  70628. }
  70629. }
  70630. }
  70631. bool ImageCache::isImageInCache (Image* const imageToLookFor)
  70632. {
  70633. if (instance != 0)
  70634. {
  70635. const ScopedLock sl (instance->lock);
  70636. for (int i = instance->images.size(); --i >= 0;)
  70637. if (((const CachedImageInfo*) instance->images.getUnchecked(i))->image == imageToLookFor)
  70638. return true;
  70639. }
  70640. return false;
  70641. }
  70642. void ImageCache::incReferenceCount (Image* const image)
  70643. {
  70644. if (instance != 0)
  70645. {
  70646. const ScopedLock sl (instance->lock);
  70647. for (int i = instance->images.size(); --i >= 0;)
  70648. {
  70649. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  70650. if (ci->image == image)
  70651. {
  70652. ci->refCount++;
  70653. return;
  70654. }
  70655. }
  70656. }
  70657. jassertfalse // (trying to inc the ref count of an image that's not in the cache)
  70658. }
  70659. void ImageCache::timerCallback()
  70660. {
  70661. int numberStillNeedingReleasing = 0;
  70662. const unsigned int now = Time::getApproximateMillisecondCounter();
  70663. const ScopedLock sl (lock);
  70664. for (int i = images.size(); --i >= 0;)
  70665. {
  70666. CachedImageInfo* const ci = (CachedImageInfo*) images.getUnchecked(i);
  70667. if (ci->refCount <= 0)
  70668. {
  70669. if (now > ci->releaseTime + cacheTimeout
  70670. || now < ci->releaseTime - 1000)
  70671. {
  70672. images.remove (i);
  70673. delete ci->image;
  70674. delete ci;
  70675. }
  70676. else
  70677. {
  70678. ++numberStillNeedingReleasing;
  70679. }
  70680. }
  70681. }
  70682. if (numberStillNeedingReleasing == 0)
  70683. stopTimer();
  70684. }
  70685. Image* ImageCache::getFromFile (const File& file)
  70686. {
  70687. const int64 hashCode = file.getFullPathName().hashCode64();
  70688. Image* image = getFromHashCode (hashCode);
  70689. if (image == 0)
  70690. {
  70691. image = ImageFileFormat::loadFrom (file);
  70692. addImageToCache (image, hashCode);
  70693. }
  70694. return image;
  70695. }
  70696. Image* ImageCache::getFromMemory (const void* imageData,
  70697. const int dataSize)
  70698. {
  70699. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  70700. Image* image = getFromHashCode (hashCode);
  70701. if (image == 0)
  70702. {
  70703. image = ImageFileFormat::loadFrom (imageData, dataSize);
  70704. addImageToCache (image, hashCode);
  70705. }
  70706. return image;
  70707. }
  70708. void ImageCache::setCacheTimeout (const int millisecs)
  70709. {
  70710. cacheTimeout = millisecs;
  70711. }
  70712. END_JUCE_NAMESPACE
  70713. /********* End of inlined file: juce_ImageCache.cpp *********/
  70714. /********* Start of inlined file: juce_ImageConvolutionKernel.cpp *********/
  70715. BEGIN_JUCE_NAMESPACE
  70716. ImageConvolutionKernel::ImageConvolutionKernel (const int size_) throw()
  70717. : size (size_)
  70718. {
  70719. values = new float* [size];
  70720. for (int i = size; --i >= 0;)
  70721. values[i] = new float [size];
  70722. clear();
  70723. }
  70724. ImageConvolutionKernel::~ImageConvolutionKernel() throw()
  70725. {
  70726. for (int i = size; --i >= 0;)
  70727. delete[] values[i];
  70728. delete[] values;
  70729. }
  70730. void ImageConvolutionKernel::setKernelValue (const int x,
  70731. const int y,
  70732. const float value) throw()
  70733. {
  70734. if (((unsigned int) x) < (unsigned int) size
  70735. && ((unsigned int) y) < (unsigned int) size)
  70736. {
  70737. values[x][y] = value;
  70738. }
  70739. else
  70740. {
  70741. jassertfalse
  70742. }
  70743. }
  70744. void ImageConvolutionKernel::clear() throw()
  70745. {
  70746. for (int y = size; --y >= 0;)
  70747. for (int x = size; --x >= 0;)
  70748. values[x][y] = 0;
  70749. }
  70750. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum) throw()
  70751. {
  70752. double currentTotal = 0.0;
  70753. for (int y = size; --y >= 0;)
  70754. for (int x = size; --x >= 0;)
  70755. currentTotal += values[x][y];
  70756. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  70757. }
  70758. void ImageConvolutionKernel::rescaleAllValues (const float multiplier) throw()
  70759. {
  70760. for (int y = size; --y >= 0;)
  70761. for (int x = size; --x >= 0;)
  70762. values[x][y] *= multiplier;
  70763. }
  70764. void ImageConvolutionKernel::createGaussianBlur (const float radius) throw()
  70765. {
  70766. const double radiusFactor = -1.0 / (radius * radius * 2);
  70767. const int centre = size >> 1;
  70768. for (int y = size; --y >= 0;)
  70769. {
  70770. for (int x = size; --x >= 0;)
  70771. {
  70772. const int cx = x - centre;
  70773. const int cy = y - centre;
  70774. values[x][y] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  70775. }
  70776. }
  70777. setOverallSum (1.0f);
  70778. }
  70779. void ImageConvolutionKernel::applyToImage (Image& destImage,
  70780. const Image* sourceImage,
  70781. int dx,
  70782. int dy,
  70783. int dw,
  70784. int dh) const
  70785. {
  70786. Image* imageCreated = 0;
  70787. if (sourceImage == 0)
  70788. {
  70789. sourceImage = imageCreated = destImage.createCopy();
  70790. }
  70791. else
  70792. {
  70793. jassert (sourceImage->getWidth() == destImage.getWidth()
  70794. && sourceImage->getHeight() == destImage.getHeight()
  70795. && sourceImage->getFormat() == destImage.getFormat());
  70796. if (sourceImage->getWidth() != destImage.getWidth()
  70797. || sourceImage->getHeight() != destImage.getHeight()
  70798. || sourceImage->getFormat() != destImage.getFormat())
  70799. return;
  70800. }
  70801. const int imageWidth = destImage.getWidth();
  70802. const int imageHeight = destImage.getHeight();
  70803. if (dx >= imageWidth || dy >= imageHeight)
  70804. return;
  70805. if (dx + dw > imageWidth)
  70806. dw = imageWidth - dx;
  70807. if (dy + dh > imageHeight)
  70808. dh = imageHeight - dy;
  70809. const int dx2 = dx + dw;
  70810. const int dy2 = dy + dh;
  70811. int lineStride, pixelStride;
  70812. uint8* pixels = destImage.lockPixelDataReadWrite (dx, dy, dw, dh, lineStride, pixelStride);
  70813. uint8* line = pixels;
  70814. int srcLineStride, srcPixelStride;
  70815. const uint8* srcPixels = sourceImage->lockPixelDataReadOnly (0, 0, sourceImage->getWidth(), sourceImage->getHeight(), srcLineStride, srcPixelStride);
  70816. if (pixelStride == 4)
  70817. {
  70818. for (int y = dy; y < dy2; ++y)
  70819. {
  70820. uint8* dest = line;
  70821. line += lineStride;
  70822. for (int x = dx; x < dx2; ++x)
  70823. {
  70824. float c1 = 0;
  70825. float c2 = 0;
  70826. float c3 = 0;
  70827. float c4 = 0;
  70828. for (int yy = 0; yy < size; ++yy)
  70829. {
  70830. const int sy = y + yy - (size >> 1);
  70831. if (sy >= imageHeight)
  70832. break;
  70833. if (sy >= 0)
  70834. {
  70835. int sx = x - (size >> 1);
  70836. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  70837. for (int xx = 0; xx < size; ++xx)
  70838. {
  70839. if (sx >= imageWidth)
  70840. break;
  70841. if (sx >= 0)
  70842. {
  70843. const float kernelMult = values[xx][yy];
  70844. c1 += kernelMult * *src++;
  70845. c2 += kernelMult * *src++;
  70846. c3 += kernelMult * *src++;
  70847. c4 += kernelMult * *src++;
  70848. }
  70849. else
  70850. {
  70851. src += 4;
  70852. }
  70853. ++sx;
  70854. }
  70855. }
  70856. }
  70857. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c1));
  70858. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c2));
  70859. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c3));
  70860. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c4));
  70861. }
  70862. }
  70863. }
  70864. else if (pixelStride == 3)
  70865. {
  70866. for (int y = dy; y < dy2; ++y)
  70867. {
  70868. uint8* dest = line;
  70869. line += lineStride;
  70870. for (int x = dx; x < dx2; ++x)
  70871. {
  70872. float c1 = 0;
  70873. float c2 = 0;
  70874. float c3 = 0;
  70875. for (int yy = 0; yy < size; ++yy)
  70876. {
  70877. const int sy = y + yy - (size >> 1);
  70878. if (sy >= imageHeight)
  70879. break;
  70880. if (sy >= 0)
  70881. {
  70882. int sx = x - (size >> 1);
  70883. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  70884. for (int xx = 0; xx < size; ++xx)
  70885. {
  70886. if (sx >= imageWidth)
  70887. break;
  70888. if (sx >= 0)
  70889. {
  70890. const float kernelMult = values[xx][yy];
  70891. c1 += kernelMult * *src++;
  70892. c2 += kernelMult * *src++;
  70893. c3 += kernelMult * *src++;
  70894. }
  70895. else
  70896. {
  70897. src += 3;
  70898. }
  70899. ++sx;
  70900. }
  70901. }
  70902. }
  70903. *dest++ = (uint8) roundFloatToInt (c1);
  70904. *dest++ = (uint8) roundFloatToInt (c2);
  70905. *dest++ = (uint8) roundFloatToInt (c3);
  70906. }
  70907. }
  70908. }
  70909. sourceImage->releasePixelDataReadOnly (srcPixels);
  70910. destImage.releasePixelDataReadWrite (pixels);
  70911. if (imageCreated != 0)
  70912. delete imageCreated;
  70913. }
  70914. END_JUCE_NAMESPACE
  70915. /********* End of inlined file: juce_ImageConvolutionKernel.cpp *********/
  70916. /********* Start of inlined file: juce_ImageFileFormat.cpp *********/
  70917. BEGIN_JUCE_NAMESPACE
  70918. /********* Start of inlined file: juce_GIFLoader.h *********/
  70919. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  70920. #define __JUCE_GIFLOADER_JUCEHEADER__
  70921. #ifndef DOXYGEN
  70922. static const int maxGifCode = 1 << 12;
  70923. /**
  70924. Used internally by ImageFileFormat - don't use this class directly in your
  70925. application.
  70926. @see ImageFileFormat
  70927. */
  70928. class GIFLoader
  70929. {
  70930. public:
  70931. GIFLoader (InputStream& in);
  70932. ~GIFLoader() throw();
  70933. Image* getImage() const throw() { return image; }
  70934. private:
  70935. Image* image;
  70936. InputStream& input;
  70937. uint8 buffer [300];
  70938. uint8 palette [256][4];
  70939. bool dataBlockIsZero, fresh, finished;
  70940. int currentBit, lastBit, lastByteIndex;
  70941. int codeSize, setCodeSize;
  70942. int maxCode, maxCodeSize;
  70943. int firstcode, oldcode;
  70944. int clearCode, end_code;
  70945. int table [2] [maxGifCode];
  70946. int stack [2 * maxGifCode];
  70947. int *sp;
  70948. bool getSizeFromHeader (int& width, int& height);
  70949. bool readPalette (const int numCols);
  70950. int readDataBlock (unsigned char* dest);
  70951. int processExtension (int type, int& transparent);
  70952. int readLZWByte (bool initialise, int input_code_size);
  70953. int getCode (int code_size, bool initialise);
  70954. bool readImage (int width, int height,
  70955. int interlace, int transparent);
  70956. GIFLoader (const GIFLoader&);
  70957. const GIFLoader& operator= (const GIFLoader&);
  70958. };
  70959. #endif // DOXYGEN
  70960. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  70961. /********* End of inlined file: juce_GIFLoader.h *********/
  70962. Image* juce_loadPNGImageFromStream (InputStream& inputStream) throw();
  70963. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw();
  70964. PNGImageFormat::PNGImageFormat() throw() {}
  70965. PNGImageFormat::~PNGImageFormat() throw() {}
  70966. const String PNGImageFormat::getFormatName()
  70967. {
  70968. return T("PNG");
  70969. }
  70970. bool PNGImageFormat::canUnderstand (InputStream& in)
  70971. {
  70972. const int bytesNeeded = 4;
  70973. char header [bytesNeeded];
  70974. return in.read (header, bytesNeeded) == bytesNeeded
  70975. && header[1] == 'P'
  70976. && header[2] == 'N'
  70977. && header[3] == 'G';
  70978. }
  70979. Image* PNGImageFormat::decodeImage (InputStream& in)
  70980. {
  70981. return juce_loadPNGImageFromStream (in);
  70982. }
  70983. bool PNGImageFormat::writeImageToStream (const Image& sourceImage,
  70984. OutputStream& destStream)
  70985. {
  70986. return juce_writePNGImageToStream (sourceImage, destStream);
  70987. }
  70988. Image* juce_loadJPEGImageFromStream (InputStream& inputStream) throw();
  70989. bool juce_writeJPEGImageToStream (const Image& image, OutputStream& out, float quality) throw();
  70990. JPEGImageFormat::JPEGImageFormat() throw()
  70991. : quality (-1.0f)
  70992. {
  70993. }
  70994. JPEGImageFormat::~JPEGImageFormat() throw() {}
  70995. void JPEGImageFormat::setQuality (const float newQuality)
  70996. {
  70997. quality = newQuality;
  70998. }
  70999. const String JPEGImageFormat::getFormatName()
  71000. {
  71001. return T("JPEG");
  71002. }
  71003. bool JPEGImageFormat::canUnderstand (InputStream& in)
  71004. {
  71005. const int bytesNeeded = 10;
  71006. uint8 header [bytesNeeded];
  71007. if (in.read (header, bytesNeeded) == bytesNeeded)
  71008. {
  71009. return header[0] == 0xff
  71010. && header[1] == 0xd8
  71011. && header[2] == 0xff
  71012. && (header[3] == 0xe0 || header[3] == 0xe1);
  71013. }
  71014. return false;
  71015. }
  71016. Image* JPEGImageFormat::decodeImage (InputStream& in)
  71017. {
  71018. return juce_loadJPEGImageFromStream (in);
  71019. }
  71020. bool JPEGImageFormat::writeImageToStream (const Image& sourceImage,
  71021. OutputStream& destStream)
  71022. {
  71023. return juce_writeJPEGImageToStream (sourceImage, destStream, quality);
  71024. }
  71025. class GIFImageFormat : public ImageFileFormat
  71026. {
  71027. public:
  71028. GIFImageFormat() throw() {}
  71029. ~GIFImageFormat() throw() {}
  71030. const String getFormatName()
  71031. {
  71032. return T("GIF");
  71033. }
  71034. bool canUnderstand (InputStream& in)
  71035. {
  71036. const int bytesNeeded = 4;
  71037. char header [bytesNeeded];
  71038. return (in.read (header, bytesNeeded) == bytesNeeded)
  71039. && header[0] == 'G'
  71040. && header[1] == 'I'
  71041. && header[2] == 'F';
  71042. }
  71043. Image* decodeImage (InputStream& in)
  71044. {
  71045. GIFLoader* const loader = new GIFLoader (in);
  71046. Image* const im = loader->getImage();
  71047. delete loader;
  71048. return im;
  71049. }
  71050. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  71051. {
  71052. return false;
  71053. }
  71054. };
  71055. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  71056. {
  71057. static PNGImageFormat png;
  71058. static JPEGImageFormat jpg;
  71059. static GIFImageFormat gif;
  71060. ImageFileFormat* formats[4];
  71061. int numFormats = 0;
  71062. formats [numFormats++] = &png;
  71063. formats [numFormats++] = &jpg;
  71064. formats [numFormats++] = &gif;
  71065. const int64 streamPos = input.getPosition();
  71066. for (int i = 0; i < numFormats; ++i)
  71067. {
  71068. const bool found = formats[i]->canUnderstand (input);
  71069. input.setPosition (streamPos);
  71070. if (found)
  71071. return formats[i];
  71072. }
  71073. return 0;
  71074. }
  71075. Image* ImageFileFormat::loadFrom (InputStream& input)
  71076. {
  71077. ImageFileFormat* const format = findImageFormatForStream (input);
  71078. if (format != 0)
  71079. return format->decodeImage (input);
  71080. return 0;
  71081. }
  71082. Image* ImageFileFormat::loadFrom (const File& file)
  71083. {
  71084. InputStream* const in = file.createInputStream();
  71085. if (in != 0)
  71086. {
  71087. BufferedInputStream b (in, 8192, true);
  71088. return loadFrom (b);
  71089. }
  71090. return 0;
  71091. }
  71092. Image* ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  71093. {
  71094. if (rawData != 0 && numBytes > 4)
  71095. {
  71096. MemoryInputStream stream (rawData, numBytes, false);
  71097. return loadFrom (stream);
  71098. }
  71099. return 0;
  71100. }
  71101. END_JUCE_NAMESPACE
  71102. /********* End of inlined file: juce_ImageFileFormat.cpp *********/
  71103. /********* Start of inlined file: juce_GIFLoader.cpp *********/
  71104. BEGIN_JUCE_NAMESPACE
  71105. static inline int makeWord (const unsigned char a, const unsigned char b) throw()
  71106. {
  71107. return (b << 8) | a;
  71108. }
  71109. GIFLoader::GIFLoader (InputStream& in)
  71110. : image (0),
  71111. input (in),
  71112. dataBlockIsZero (false),
  71113. fresh (false),
  71114. finished (false)
  71115. {
  71116. currentBit = lastBit = lastByteIndex = 0;
  71117. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  71118. firstcode = oldcode = 0;
  71119. clearCode = end_code = 0;
  71120. int imageWidth, imageHeight;
  71121. int transparent = -1;
  71122. if (! getSizeFromHeader (imageWidth, imageHeight))
  71123. return;
  71124. if ((imageWidth <= 0) || (imageHeight <= 0))
  71125. return;
  71126. unsigned char buf [16];
  71127. if (in.read (buf, 3) != 3)
  71128. return;
  71129. int numColours = 2 << (buf[0] & 7);
  71130. if ((buf[0] & 0x80) != 0)
  71131. readPalette (numColours);
  71132. for (;;)
  71133. {
  71134. if (input.read (buf, 1) != 1)
  71135. break;
  71136. if (buf[0] == ';')
  71137. break;
  71138. if (buf[0] == '!')
  71139. {
  71140. if (input.read (buf, 1) != 1)
  71141. break;
  71142. if (processExtension (buf[0], transparent) < 0)
  71143. break;
  71144. continue;
  71145. }
  71146. if (buf[0] != ',')
  71147. continue;
  71148. if (input.read (buf, 9) != 9)
  71149. break;
  71150. imageWidth = makeWord (buf[4], buf[5]);
  71151. imageHeight = makeWord (buf[6], buf[7]);
  71152. numColours = 2 << (buf[8] & 7);
  71153. if ((buf[8] & 0x80) != 0)
  71154. if (! readPalette (numColours))
  71155. break;
  71156. image = new Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  71157. imageWidth, imageHeight, (transparent >= 0));
  71158. readImage (imageWidth, imageHeight,
  71159. (buf[8] & 0x40) != 0,
  71160. transparent);
  71161. break;
  71162. }
  71163. }
  71164. GIFLoader::~GIFLoader() throw()
  71165. {
  71166. }
  71167. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  71168. {
  71169. unsigned char b [8];
  71170. if (input.read (b, 6) == 6)
  71171. {
  71172. if ((strncmp ("GIF87a", (char*) b, 6) == 0)
  71173. || (strncmp ("GIF89a", (char*) b, 6) == 0))
  71174. {
  71175. if (input.read (b, 4) == 4)
  71176. {
  71177. w = makeWord (b[0], b[1]);
  71178. h = makeWord (b[2], b[3]);
  71179. return true;
  71180. }
  71181. }
  71182. }
  71183. return false;
  71184. }
  71185. bool GIFLoader::readPalette (const int numCols)
  71186. {
  71187. unsigned char rgb[4];
  71188. for (int i = 0; i < numCols; ++i)
  71189. {
  71190. input.read (rgb, 3);
  71191. palette [i][0] = rgb[0];
  71192. palette [i][1] = rgb[1];
  71193. palette [i][2] = rgb[2];
  71194. palette [i][3] = 0xff;
  71195. }
  71196. return true;
  71197. }
  71198. int GIFLoader::readDataBlock (unsigned char* const dest)
  71199. {
  71200. unsigned char n;
  71201. if (input.read (&n, 1) == 1)
  71202. {
  71203. dataBlockIsZero = (n == 0);
  71204. if (dataBlockIsZero || (input.read (dest, n) == n))
  71205. return n;
  71206. }
  71207. return -1;
  71208. }
  71209. int GIFLoader::processExtension (const int type, int& transparent)
  71210. {
  71211. unsigned char b [300];
  71212. int n = 0;
  71213. if (type == 0xf9)
  71214. {
  71215. n = readDataBlock (b);
  71216. if (n < 0)
  71217. return 1;
  71218. if ((b[0] & 0x1) != 0)
  71219. transparent = b[3];
  71220. }
  71221. do
  71222. {
  71223. n = readDataBlock (b);
  71224. }
  71225. while (n > 0);
  71226. return n;
  71227. }
  71228. int GIFLoader::getCode (const int codeSize, const bool initialise)
  71229. {
  71230. if (initialise)
  71231. {
  71232. currentBit = 0;
  71233. lastBit = 0;
  71234. finished = false;
  71235. return 0;
  71236. }
  71237. if ((currentBit + codeSize) >= lastBit)
  71238. {
  71239. if (finished)
  71240. return -1;
  71241. buffer[0] = buffer [lastByteIndex - 2];
  71242. buffer[1] = buffer [lastByteIndex - 1];
  71243. const int n = readDataBlock (&buffer[2]);
  71244. if (n == 0)
  71245. finished = true;
  71246. lastByteIndex = 2 + n;
  71247. currentBit = (currentBit - lastBit) + 16;
  71248. lastBit = (2 + n) * 8 ;
  71249. }
  71250. int result = 0;
  71251. int i = currentBit;
  71252. for (int j = 0; j < codeSize; ++j)
  71253. {
  71254. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  71255. ++i;
  71256. }
  71257. currentBit += codeSize;
  71258. return result;
  71259. }
  71260. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  71261. {
  71262. int code, incode, i;
  71263. if (initialise)
  71264. {
  71265. setCodeSize = inputCodeSize;
  71266. codeSize = setCodeSize + 1;
  71267. clearCode = 1 << setCodeSize;
  71268. end_code = clearCode + 1;
  71269. maxCodeSize = 2 * clearCode;
  71270. maxCode = clearCode + 2;
  71271. getCode (0, true);
  71272. fresh = true;
  71273. for (i = 0; i < clearCode; ++i)
  71274. {
  71275. table[0][i] = 0;
  71276. table[1][i] = i;
  71277. }
  71278. for (; i < maxGifCode; ++i)
  71279. {
  71280. table[0][i] = 0;
  71281. table[1][i] = 0;
  71282. }
  71283. sp = stack;
  71284. return 0;
  71285. }
  71286. else if (fresh)
  71287. {
  71288. fresh = false;
  71289. do
  71290. {
  71291. firstcode = oldcode
  71292. = getCode (codeSize, false);
  71293. }
  71294. while (firstcode == clearCode);
  71295. return firstcode;
  71296. }
  71297. if (sp > stack)
  71298. return *--sp;
  71299. while ((code = getCode (codeSize, false)) >= 0)
  71300. {
  71301. if (code == clearCode)
  71302. {
  71303. for (i = 0; i < clearCode; ++i)
  71304. {
  71305. table[0][i] = 0;
  71306. table[1][i] = i;
  71307. }
  71308. for (; i < maxGifCode; ++i)
  71309. {
  71310. table[0][i] = 0;
  71311. table[1][i] = 0;
  71312. }
  71313. codeSize = setCodeSize + 1;
  71314. maxCodeSize = 2 * clearCode;
  71315. maxCode = clearCode + 2;
  71316. sp = stack;
  71317. firstcode = oldcode = getCode (codeSize, false);
  71318. return firstcode;
  71319. }
  71320. else if (code == end_code)
  71321. {
  71322. if (dataBlockIsZero)
  71323. return -2;
  71324. unsigned char buf [260];
  71325. int n;
  71326. while ((n = readDataBlock (buf)) > 0)
  71327. {}
  71328. if (n != 0)
  71329. return -2;
  71330. }
  71331. incode = code;
  71332. if (code >= maxCode)
  71333. {
  71334. *sp++ = firstcode;
  71335. code = oldcode;
  71336. }
  71337. while (code >= clearCode)
  71338. {
  71339. *sp++ = table[1][code];
  71340. if (code == table[0][code])
  71341. return -2;
  71342. code = table[0][code];
  71343. }
  71344. *sp++ = firstcode = table[1][code];
  71345. if ((code = maxCode) < maxGifCode)
  71346. {
  71347. table[0][code] = oldcode;
  71348. table[1][code] = firstcode;
  71349. ++maxCode;
  71350. if ((maxCode >= maxCodeSize)
  71351. && (maxCodeSize < maxGifCode))
  71352. {
  71353. maxCodeSize <<= 1;
  71354. ++codeSize;
  71355. }
  71356. }
  71357. oldcode = incode;
  71358. if (sp > stack)
  71359. return *--sp;
  71360. }
  71361. return code;
  71362. }
  71363. bool GIFLoader::readImage (const int width, const int height,
  71364. const int interlace, const int transparent)
  71365. {
  71366. unsigned char c;
  71367. if (input.read (&c, 1) != 1
  71368. || readLZWByte (true, c) < 0)
  71369. return false;
  71370. if (transparent >= 0)
  71371. {
  71372. palette [transparent][0] = 0;
  71373. palette [transparent][1] = 0;
  71374. palette [transparent][2] = 0;
  71375. palette [transparent][3] = 0;
  71376. }
  71377. int index;
  71378. int xpos = 0, ypos = 0, pass = 0;
  71379. int stride, pixelStride;
  71380. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  71381. uint8* p = pixels;
  71382. const bool hasAlpha = image->hasAlphaChannel();
  71383. while ((index = readLZWByte (false, c)) >= 0)
  71384. {
  71385. const uint8* const paletteEntry = palette [index];
  71386. if (hasAlpha)
  71387. {
  71388. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  71389. paletteEntry[0],
  71390. paletteEntry[1],
  71391. paletteEntry[2]);
  71392. ((PixelARGB*) p)->premultiply();
  71393. p += pixelStride;
  71394. }
  71395. else
  71396. {
  71397. ((PixelRGB*) p)->setARGB (0,
  71398. paletteEntry[0],
  71399. paletteEntry[1],
  71400. paletteEntry[2]);
  71401. p += pixelStride;
  71402. }
  71403. ++xpos;
  71404. if (xpos == width)
  71405. {
  71406. xpos = 0;
  71407. if (interlace)
  71408. {
  71409. switch (pass)
  71410. {
  71411. case 0:
  71412. case 1:
  71413. ypos += 8;
  71414. break;
  71415. case 2:
  71416. ypos += 4;
  71417. break;
  71418. case 3:
  71419. ypos += 2;
  71420. break;
  71421. }
  71422. while (ypos >= height)
  71423. {
  71424. ++pass;
  71425. switch (pass)
  71426. {
  71427. case 1:
  71428. ypos = 4;
  71429. break;
  71430. case 2:
  71431. ypos = 2;
  71432. break;
  71433. case 3:
  71434. ypos = 1;
  71435. break;
  71436. default:
  71437. return true;
  71438. }
  71439. }
  71440. }
  71441. else
  71442. {
  71443. ++ypos;
  71444. }
  71445. p = pixels + xpos * pixelStride + ypos * stride;
  71446. }
  71447. if (ypos >= height)
  71448. break;
  71449. }
  71450. image->releasePixelDataReadWrite (pixels);
  71451. return true;
  71452. }
  71453. END_JUCE_NAMESPACE
  71454. /********* End of inlined file: juce_GIFLoader.cpp *********/
  71455. #endif
  71456. //==============================================================================
  71457. // some files include lots of library code, so leave them to the end to avoid cluttering
  71458. // up the build for the clean files.
  71459. /********* Start of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  71460. namespace zlibNamespace
  71461. {
  71462. #undef OS_CODE
  71463. #undef fdopen
  71464. /********* Start of inlined file: zlib.h *********/
  71465. #ifndef ZLIB_H
  71466. #define ZLIB_H
  71467. /********* Start of inlined file: zconf.h *********/
  71468. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  71469. #ifndef ZCONF_H
  71470. #define ZCONF_H
  71471. // *** Just a few hacks here to make it compile nicely with Juce..
  71472. #define Z_PREFIX 1
  71473. #undef __MACTYPES__
  71474. #ifdef _MSC_VER
  71475. #pragma warning (disable : 4131 4127 4244 4267)
  71476. #endif
  71477. /*
  71478. * If you *really* need a unique prefix for all types and library functions,
  71479. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  71480. */
  71481. #ifdef Z_PREFIX
  71482. # define deflateInit_ z_deflateInit_
  71483. # define deflate z_deflate
  71484. # define deflateEnd z_deflateEnd
  71485. # define inflateInit_ z_inflateInit_
  71486. # define inflate z_inflate
  71487. # define inflateEnd z_inflateEnd
  71488. # define deflateInit2_ z_deflateInit2_
  71489. # define deflateSetDictionary z_deflateSetDictionary
  71490. # define deflateCopy z_deflateCopy
  71491. # define deflateReset z_deflateReset
  71492. # define deflateParams z_deflateParams
  71493. # define deflateBound z_deflateBound
  71494. # define deflatePrime z_deflatePrime
  71495. # define inflateInit2_ z_inflateInit2_
  71496. # define inflateSetDictionary z_inflateSetDictionary
  71497. # define inflateSync z_inflateSync
  71498. # define inflateSyncPoint z_inflateSyncPoint
  71499. # define inflateCopy z_inflateCopy
  71500. # define inflateReset z_inflateReset
  71501. # define inflateBack z_inflateBack
  71502. # define inflateBackEnd z_inflateBackEnd
  71503. # define compress z_compress
  71504. # define compress2 z_compress2
  71505. # define compressBound z_compressBound
  71506. # define uncompress z_uncompress
  71507. # define adler32 z_adler32
  71508. # define crc32 z_crc32
  71509. # define get_crc_table z_get_crc_table
  71510. # define zError z_zError
  71511. # define alloc_func z_alloc_func
  71512. # define free_func z_free_func
  71513. # define in_func z_in_func
  71514. # define out_func z_out_func
  71515. # define Byte z_Byte
  71516. # define uInt z_uInt
  71517. # define uLong z_uLong
  71518. # define Bytef z_Bytef
  71519. # define charf z_charf
  71520. # define intf z_intf
  71521. # define uIntf z_uIntf
  71522. # define uLongf z_uLongf
  71523. # define voidpf z_voidpf
  71524. # define voidp z_voidp
  71525. #endif
  71526. #if defined(__MSDOS__) && !defined(MSDOS)
  71527. # define MSDOS
  71528. #endif
  71529. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  71530. # define OS2
  71531. #endif
  71532. #if defined(_WINDOWS) && !defined(WINDOWS)
  71533. # define WINDOWS
  71534. #endif
  71535. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  71536. # ifndef WIN32
  71537. # define WIN32
  71538. # endif
  71539. #endif
  71540. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  71541. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  71542. # ifndef SYS16BIT
  71543. # define SYS16BIT
  71544. # endif
  71545. # endif
  71546. #endif
  71547. /*
  71548. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  71549. * than 64k bytes at a time (needed on systems with 16-bit int).
  71550. */
  71551. #ifdef SYS16BIT
  71552. # define MAXSEG_64K
  71553. #endif
  71554. #ifdef MSDOS
  71555. # define UNALIGNED_OK
  71556. #endif
  71557. #ifdef __STDC_VERSION__
  71558. # ifndef STDC
  71559. # define STDC
  71560. # endif
  71561. # if __STDC_VERSION__ >= 199901L
  71562. # ifndef STDC99
  71563. # define STDC99
  71564. # endif
  71565. # endif
  71566. #endif
  71567. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  71568. # define STDC
  71569. #endif
  71570. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  71571. # define STDC
  71572. #endif
  71573. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  71574. # define STDC
  71575. #endif
  71576. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  71577. # define STDC
  71578. #endif
  71579. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  71580. # define STDC
  71581. #endif
  71582. #ifndef STDC
  71583. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  71584. # define const /* note: need a more gentle solution here */
  71585. # endif
  71586. #endif
  71587. /* Some Mac compilers merge all .h files incorrectly: */
  71588. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  71589. # define NO_DUMMY_DECL
  71590. #endif
  71591. /* Maximum value for memLevel in deflateInit2 */
  71592. #ifndef MAX_MEM_LEVEL
  71593. # ifdef MAXSEG_64K
  71594. # define MAX_MEM_LEVEL 8
  71595. # else
  71596. # define MAX_MEM_LEVEL 9
  71597. # endif
  71598. #endif
  71599. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  71600. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  71601. * created by gzip. (Files created by minigzip can still be extracted by
  71602. * gzip.)
  71603. */
  71604. #ifndef MAX_WBITS
  71605. # define MAX_WBITS 15 /* 32K LZ77 window */
  71606. #endif
  71607. /* The memory requirements for deflate are (in bytes):
  71608. (1 << (windowBits+2)) + (1 << (memLevel+9))
  71609. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  71610. plus a few kilobytes for small objects. For example, if you want to reduce
  71611. the default memory requirements from 256K to 128K, compile with
  71612. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  71613. Of course this will generally degrade compression (there's no free lunch).
  71614. The memory requirements for inflate are (in bytes) 1 << windowBits
  71615. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  71616. for small objects.
  71617. */
  71618. /* Type declarations */
  71619. #ifndef OF /* function prototypes */
  71620. # ifdef STDC
  71621. # define OF(args) args
  71622. # else
  71623. # define OF(args) ()
  71624. # endif
  71625. #endif
  71626. /* The following definitions for FAR are needed only for MSDOS mixed
  71627. * model programming (small or medium model with some far allocations).
  71628. * This was tested only with MSC; for other MSDOS compilers you may have
  71629. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  71630. * just define FAR to be empty.
  71631. */
  71632. #ifdef SYS16BIT
  71633. # if defined(M_I86SM) || defined(M_I86MM)
  71634. /* MSC small or medium model */
  71635. # define SMALL_MEDIUM
  71636. # ifdef _MSC_VER
  71637. # define FAR _far
  71638. # else
  71639. # define FAR far
  71640. # endif
  71641. # endif
  71642. # if (defined(__SMALL__) || defined(__MEDIUM__))
  71643. /* Turbo C small or medium model */
  71644. # define SMALL_MEDIUM
  71645. # ifdef __BORLANDC__
  71646. # define FAR _far
  71647. # else
  71648. # define FAR far
  71649. # endif
  71650. # endif
  71651. #endif
  71652. #if defined(WINDOWS) || defined(WIN32)
  71653. /* If building or using zlib as a DLL, define ZLIB_DLL.
  71654. * This is not mandatory, but it offers a little performance increase.
  71655. */
  71656. # ifdef ZLIB_DLL
  71657. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  71658. # ifdef ZLIB_INTERNAL
  71659. # define ZEXTERN extern __declspec(dllexport)
  71660. # else
  71661. # define ZEXTERN extern __declspec(dllimport)
  71662. # endif
  71663. # endif
  71664. # endif /* ZLIB_DLL */
  71665. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  71666. * define ZLIB_WINAPI.
  71667. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  71668. */
  71669. # ifdef ZLIB_WINAPI
  71670. # ifdef FAR
  71671. # undef FAR
  71672. # endif
  71673. # include <windows.h>
  71674. /* No need for _export, use ZLIB.DEF instead. */
  71675. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  71676. # define ZEXPORT WINAPI
  71677. # ifdef WIN32
  71678. # define ZEXPORTVA WINAPIV
  71679. # else
  71680. # define ZEXPORTVA FAR CDECL
  71681. # endif
  71682. # endif
  71683. #endif
  71684. #if defined (__BEOS__)
  71685. # ifdef ZLIB_DLL
  71686. # ifdef ZLIB_INTERNAL
  71687. # define ZEXPORT __declspec(dllexport)
  71688. # define ZEXPORTVA __declspec(dllexport)
  71689. # else
  71690. # define ZEXPORT __declspec(dllimport)
  71691. # define ZEXPORTVA __declspec(dllimport)
  71692. # endif
  71693. # endif
  71694. #endif
  71695. #ifndef ZEXTERN
  71696. # define ZEXTERN extern
  71697. #endif
  71698. #ifndef ZEXPORT
  71699. # define ZEXPORT
  71700. #endif
  71701. #ifndef ZEXPORTVA
  71702. # define ZEXPORTVA
  71703. #endif
  71704. #ifndef FAR
  71705. # define FAR
  71706. #endif
  71707. #if !defined(__MACTYPES__)
  71708. typedef unsigned char Byte; /* 8 bits */
  71709. #endif
  71710. typedef unsigned int uInt; /* 16 bits or more */
  71711. typedef unsigned long uLong; /* 32 bits or more */
  71712. #ifdef SMALL_MEDIUM
  71713. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  71714. # define Bytef Byte FAR
  71715. #else
  71716. typedef Byte FAR Bytef;
  71717. #endif
  71718. typedef char FAR charf;
  71719. typedef int FAR intf;
  71720. typedef uInt FAR uIntf;
  71721. typedef uLong FAR uLongf;
  71722. #ifdef STDC
  71723. typedef void const *voidpc;
  71724. typedef void FAR *voidpf;
  71725. typedef void *voidp;
  71726. #else
  71727. typedef Byte const *voidpc;
  71728. typedef Byte FAR *voidpf;
  71729. typedef Byte *voidp;
  71730. #endif
  71731. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  71732. # include <sys/types.h> /* for off_t */
  71733. # include <unistd.h> /* for SEEK_* and off_t */
  71734. # ifdef VMS
  71735. # include <unixio.h> /* for off_t */
  71736. # endif
  71737. # define z_off_t off_t
  71738. #endif
  71739. #ifndef SEEK_SET
  71740. # define SEEK_SET 0 /* Seek from beginning of file. */
  71741. # define SEEK_CUR 1 /* Seek from current position. */
  71742. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  71743. #endif
  71744. #ifndef z_off_t
  71745. # define z_off_t long
  71746. #endif
  71747. #if defined(__OS400__)
  71748. # define NO_vsnprintf
  71749. #endif
  71750. #if defined(__MVS__)
  71751. # define NO_vsnprintf
  71752. # ifdef FAR
  71753. # undef FAR
  71754. # endif
  71755. #endif
  71756. /* MVS linker does not support external names larger than 8 bytes */
  71757. #if defined(__MVS__)
  71758. # pragma map(deflateInit_,"DEIN")
  71759. # pragma map(deflateInit2_,"DEIN2")
  71760. # pragma map(deflateEnd,"DEEND")
  71761. # pragma map(deflateBound,"DEBND")
  71762. # pragma map(inflateInit_,"ININ")
  71763. # pragma map(inflateInit2_,"ININ2")
  71764. # pragma map(inflateEnd,"INEND")
  71765. # pragma map(inflateSync,"INSY")
  71766. # pragma map(inflateSetDictionary,"INSEDI")
  71767. # pragma map(compressBound,"CMBND")
  71768. # pragma map(inflate_table,"INTABL")
  71769. # pragma map(inflate_fast,"INFA")
  71770. # pragma map(inflate_copyright,"INCOPY")
  71771. #endif
  71772. #endif /* ZCONF_H */
  71773. /********* End of inlined file: zconf.h *********/
  71774. #ifdef __cplusplus
  71775. extern "C" {
  71776. #endif
  71777. #define ZLIB_VERSION "1.2.3"
  71778. #define ZLIB_VERNUM 0x1230
  71779. /*
  71780. The 'zlib' compression library provides in-memory compression and
  71781. decompression functions, including integrity checks of the uncompressed
  71782. data. This version of the library supports only one compression method
  71783. (deflation) but other algorithms will be added later and will have the same
  71784. stream interface.
  71785. Compression can be done in a single step if the buffers are large
  71786. enough (for example if an input file is mmap'ed), or can be done by
  71787. repeated calls of the compression function. In the latter case, the
  71788. application must provide more input and/or consume the output
  71789. (providing more output space) before each call.
  71790. The compressed data format used by default by the in-memory functions is
  71791. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  71792. around a deflate stream, which is itself documented in RFC 1951.
  71793. The library also supports reading and writing files in gzip (.gz) format
  71794. with an interface similar to that of stdio using the functions that start
  71795. with "gz". The gzip format is different from the zlib format. gzip is a
  71796. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  71797. This library can optionally read and write gzip streams in memory as well.
  71798. The zlib format was designed to be compact and fast for use in memory
  71799. and on communications channels. The gzip format was designed for single-
  71800. file compression on file systems, has a larger header than zlib to maintain
  71801. directory information, and uses a different, slower check method than zlib.
  71802. The library does not install any signal handler. The decoder checks
  71803. the consistency of the compressed data, so the library should never
  71804. crash even in case of corrupted input.
  71805. */
  71806. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  71807. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  71808. struct internal_state;
  71809. typedef struct z_stream_s {
  71810. Bytef *next_in; /* next input byte */
  71811. uInt avail_in; /* number of bytes available at next_in */
  71812. uLong total_in; /* total nb of input bytes read so far */
  71813. Bytef *next_out; /* next output byte should be put there */
  71814. uInt avail_out; /* remaining free space at next_out */
  71815. uLong total_out; /* total nb of bytes output so far */
  71816. char *msg; /* last error message, NULL if no error */
  71817. struct internal_state FAR *state; /* not visible by applications */
  71818. alloc_func zalloc; /* used to allocate the internal state */
  71819. free_func zfree; /* used to free the internal state */
  71820. voidpf opaque; /* private data object passed to zalloc and zfree */
  71821. int data_type; /* best guess about the data type: binary or text */
  71822. uLong adler; /* adler32 value of the uncompressed data */
  71823. uLong reserved; /* reserved for future use */
  71824. } z_stream;
  71825. typedef z_stream FAR *z_streamp;
  71826. /*
  71827. gzip header information passed to and from zlib routines. See RFC 1952
  71828. for more details on the meanings of these fields.
  71829. */
  71830. typedef struct gz_header_s {
  71831. int text; /* true if compressed data believed to be text */
  71832. uLong time; /* modification time */
  71833. int xflags; /* extra flags (not used when writing a gzip file) */
  71834. int os; /* operating system */
  71835. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  71836. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  71837. uInt extra_max; /* space at extra (only when reading header) */
  71838. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  71839. uInt name_max; /* space at name (only when reading header) */
  71840. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  71841. uInt comm_max; /* space at comment (only when reading header) */
  71842. int hcrc; /* true if there was or will be a header crc */
  71843. int done; /* true when done reading gzip header (not used
  71844. when writing a gzip file) */
  71845. } gz_header;
  71846. typedef gz_header FAR *gz_headerp;
  71847. /*
  71848. The application must update next_in and avail_in when avail_in has
  71849. dropped to zero. It must update next_out and avail_out when avail_out
  71850. has dropped to zero. The application must initialize zalloc, zfree and
  71851. opaque before calling the init function. All other fields are set by the
  71852. compression library and must not be updated by the application.
  71853. The opaque value provided by the application will be passed as the first
  71854. parameter for calls of zalloc and zfree. This can be useful for custom
  71855. memory management. The compression library attaches no meaning to the
  71856. opaque value.
  71857. zalloc must return Z_NULL if there is not enough memory for the object.
  71858. If zlib is used in a multi-threaded application, zalloc and zfree must be
  71859. thread safe.
  71860. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  71861. exactly 65536 bytes, but will not be required to allocate more than this
  71862. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  71863. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  71864. have their offset normalized to zero. The default allocation function
  71865. provided by this library ensures this (see zutil.c). To reduce memory
  71866. requirements and avoid any allocation of 64K objects, at the expense of
  71867. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  71868. The fields total_in and total_out can be used for statistics or
  71869. progress reports. After compression, total_in holds the total size of
  71870. the uncompressed data and may be saved for use in the decompressor
  71871. (particularly if the decompressor wants to decompress everything in
  71872. a single step).
  71873. */
  71874. /* constants */
  71875. #define Z_NO_FLUSH 0
  71876. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  71877. #define Z_SYNC_FLUSH 2
  71878. #define Z_FULL_FLUSH 3
  71879. #define Z_FINISH 4
  71880. #define Z_BLOCK 5
  71881. /* Allowed flush values; see deflate() and inflate() below for details */
  71882. #define Z_OK 0
  71883. #define Z_STREAM_END 1
  71884. #define Z_NEED_DICT 2
  71885. #define Z_ERRNO (-1)
  71886. #define Z_STREAM_ERROR (-2)
  71887. #define Z_DATA_ERROR (-3)
  71888. #define Z_MEM_ERROR (-4)
  71889. #define Z_BUF_ERROR (-5)
  71890. #define Z_VERSION_ERROR (-6)
  71891. /* Return codes for the compression/decompression functions. Negative
  71892. * values are errors, positive values are used for special but normal events.
  71893. */
  71894. #define Z_NO_COMPRESSION 0
  71895. #define Z_BEST_SPEED 1
  71896. #define Z_BEST_COMPRESSION 9
  71897. #define Z_DEFAULT_COMPRESSION (-1)
  71898. /* compression levels */
  71899. #define Z_FILTERED 1
  71900. #define Z_HUFFMAN_ONLY 2
  71901. #define Z_RLE 3
  71902. #define Z_FIXED 4
  71903. #define Z_DEFAULT_STRATEGY 0
  71904. /* compression strategy; see deflateInit2() below for details */
  71905. #define Z_BINARY 0
  71906. #define Z_TEXT 1
  71907. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  71908. #define Z_UNKNOWN 2
  71909. /* Possible values of the data_type field (though see inflate()) */
  71910. #define Z_DEFLATED 8
  71911. /* The deflate compression method (the only one supported in this version) */
  71912. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  71913. #define zlib_version zlibVersion()
  71914. /* for compatibility with versions < 1.0.2 */
  71915. /* basic functions */
  71916. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  71917. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  71918. If the first character differs, the library code actually used is
  71919. not compatible with the zlib.h header file used by the application.
  71920. This check is automatically made by deflateInit and inflateInit.
  71921. */
  71922. /*
  71923. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  71924. Initializes the internal stream state for compression. The fields
  71925. zalloc, zfree and opaque must be initialized before by the caller.
  71926. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  71927. use default allocation functions.
  71928. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  71929. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  71930. all (the input data is simply copied a block at a time).
  71931. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  71932. compression (currently equivalent to level 6).
  71933. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  71934. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  71935. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  71936. with the version assumed by the caller (ZLIB_VERSION).
  71937. msg is set to null if there is no error message. deflateInit does not
  71938. perform any compression: this will be done by deflate().
  71939. */
  71940. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  71941. /*
  71942. deflate compresses as much data as possible, and stops when the input
  71943. buffer becomes empty or the output buffer becomes full. It may introduce some
  71944. output latency (reading input without producing any output) except when
  71945. forced to flush.
  71946. The detailed semantics are as follows. deflate performs one or both of the
  71947. following actions:
  71948. - Compress more input starting at next_in and update next_in and avail_in
  71949. accordingly. If not all input can be processed (because there is not
  71950. enough room in the output buffer), next_in and avail_in are updated and
  71951. processing will resume at this point for the next call of deflate().
  71952. - Provide more output starting at next_out and update next_out and avail_out
  71953. accordingly. This action is forced if the parameter flush is non zero.
  71954. Forcing flush frequently degrades the compression ratio, so this parameter
  71955. should be set only when necessary (in interactive applications).
  71956. Some output may be provided even if flush is not set.
  71957. Before the call of deflate(), the application should ensure that at least
  71958. one of the actions is possible, by providing more input and/or consuming
  71959. more output, and updating avail_in or avail_out accordingly; avail_out
  71960. should never be zero before the call. The application can consume the
  71961. compressed output when it wants, for example when the output buffer is full
  71962. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  71963. and with zero avail_out, it must be called again after making room in the
  71964. output buffer because there might be more output pending.
  71965. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  71966. decide how much data to accumualte before producing output, in order to
  71967. maximize compression.
  71968. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  71969. flushed to the output buffer and the output is aligned on a byte boundary, so
  71970. that the decompressor can get all input data available so far. (In particular
  71971. avail_in is zero after the call if enough output space has been provided
  71972. before the call.) Flushing may degrade compression for some compression
  71973. algorithms and so it should be used only when necessary.
  71974. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  71975. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  71976. restart from this point if previous compressed data has been damaged or if
  71977. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  71978. compression.
  71979. If deflate returns with avail_out == 0, this function must be called again
  71980. with the same value of the flush parameter and more output space (updated
  71981. avail_out), until the flush is complete (deflate returns with non-zero
  71982. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  71983. avail_out is greater than six to avoid repeated flush markers due to
  71984. avail_out == 0 on return.
  71985. If the parameter flush is set to Z_FINISH, pending input is processed,
  71986. pending output is flushed and deflate returns with Z_STREAM_END if there
  71987. was enough output space; if deflate returns with Z_OK, this function must be
  71988. called again with Z_FINISH and more output space (updated avail_out) but no
  71989. more input data, until it returns with Z_STREAM_END or an error. After
  71990. deflate has returned Z_STREAM_END, the only possible operations on the
  71991. stream are deflateReset or deflateEnd.
  71992. Z_FINISH can be used immediately after deflateInit if all the compression
  71993. is to be done in a single step. In this case, avail_out must be at least
  71994. the value returned by deflateBound (see below). If deflate does not return
  71995. Z_STREAM_END, then it must be called again as described above.
  71996. deflate() sets strm->adler to the adler32 checksum of all input read
  71997. so far (that is, total_in bytes).
  71998. deflate() may update strm->data_type if it can make a good guess about
  71999. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  72000. binary. This field is only for information purposes and does not affect
  72001. the compression algorithm in any manner.
  72002. deflate() returns Z_OK if some progress has been made (more input
  72003. processed or more output produced), Z_STREAM_END if all input has been
  72004. consumed and all output has been produced (only when flush is set to
  72005. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  72006. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  72007. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  72008. fatal, and deflate() can be called again with more input and more output
  72009. space to continue compressing.
  72010. */
  72011. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  72012. /*
  72013. All dynamically allocated data structures for this stream are freed.
  72014. This function discards any unprocessed input and does not flush any
  72015. pending output.
  72016. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  72017. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  72018. prematurely (some input or output was discarded). In the error case,
  72019. msg may be set but then points to a static string (which must not be
  72020. deallocated).
  72021. */
  72022. /*
  72023. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  72024. Initializes the internal stream state for decompression. The fields
  72025. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  72026. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  72027. value depends on the compression method), inflateInit determines the
  72028. compression method from the zlib header and allocates all data structures
  72029. accordingly; otherwise the allocation will be deferred to the first call of
  72030. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  72031. use default allocation functions.
  72032. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  72033. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  72034. version assumed by the caller. msg is set to null if there is no error
  72035. message. inflateInit does not perform any decompression apart from reading
  72036. the zlib header if present: this will be done by inflate(). (So next_in and
  72037. avail_in may be modified, but next_out and avail_out are unchanged.)
  72038. */
  72039. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  72040. /*
  72041. inflate decompresses as much data as possible, and stops when the input
  72042. buffer becomes empty or the output buffer becomes full. It may introduce
  72043. some output latency (reading input without producing any output) except when
  72044. forced to flush.
  72045. The detailed semantics are as follows. inflate performs one or both of the
  72046. following actions:
  72047. - Decompress more input starting at next_in and update next_in and avail_in
  72048. accordingly. If not all input can be processed (because there is not
  72049. enough room in the output buffer), next_in is updated and processing
  72050. will resume at this point for the next call of inflate().
  72051. - Provide more output starting at next_out and update next_out and avail_out
  72052. accordingly. inflate() provides as much output as possible, until there
  72053. is no more input data or no more space in the output buffer (see below
  72054. about the flush parameter).
  72055. Before the call of inflate(), the application should ensure that at least
  72056. one of the actions is possible, by providing more input and/or consuming
  72057. more output, and updating the next_* and avail_* values accordingly.
  72058. The application can consume the uncompressed output when it wants, for
  72059. example when the output buffer is full (avail_out == 0), or after each
  72060. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  72061. must be called again after making room in the output buffer because there
  72062. might be more output pending.
  72063. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  72064. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  72065. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  72066. if and when it gets to the next deflate block boundary. When decoding the
  72067. zlib or gzip format, this will cause inflate() to return immediately after
  72068. the header and before the first block. When doing a raw inflate, inflate()
  72069. will go ahead and process the first block, and will return when it gets to
  72070. the end of that block, or when it runs out of data.
  72071. The Z_BLOCK option assists in appending to or combining deflate streams.
  72072. Also to assist in this, on return inflate() will set strm->data_type to the
  72073. number of unused bits in the last byte taken from strm->next_in, plus 64
  72074. if inflate() is currently decoding the last block in the deflate stream,
  72075. plus 128 if inflate() returned immediately after decoding an end-of-block
  72076. code or decoding the complete header up to just before the first byte of the
  72077. deflate stream. The end-of-block will not be indicated until all of the
  72078. uncompressed data from that block has been written to strm->next_out. The
  72079. number of unused bits may in general be greater than seven, except when
  72080. bit 7 of data_type is set, in which case the number of unused bits will be
  72081. less than eight.
  72082. inflate() should normally be called until it returns Z_STREAM_END or an
  72083. error. However if all decompression is to be performed in a single step
  72084. (a single call of inflate), the parameter flush should be set to
  72085. Z_FINISH. In this case all pending input is processed and all pending
  72086. output is flushed; avail_out must be large enough to hold all the
  72087. uncompressed data. (The size of the uncompressed data may have been saved
  72088. by the compressor for this purpose.) The next operation on this stream must
  72089. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  72090. is never required, but can be used to inform inflate that a faster approach
  72091. may be used for the single inflate() call.
  72092. In this implementation, inflate() always flushes as much output as
  72093. possible to the output buffer, and always uses the faster approach on the
  72094. first call. So the only effect of the flush parameter in this implementation
  72095. is on the return value of inflate(), as noted below, or when it returns early
  72096. because Z_BLOCK is used.
  72097. If a preset dictionary is needed after this call (see inflateSetDictionary
  72098. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  72099. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  72100. strm->adler to the adler32 checksum of all output produced so far (that is,
  72101. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  72102. below. At the end of the stream, inflate() checks that its computed adler32
  72103. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  72104. only if the checksum is correct.
  72105. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  72106. deflate data. The header type is detected automatically. Any information
  72107. contained in the gzip header is not retained, so applications that need that
  72108. information should instead use raw inflate, see inflateInit2() below, or
  72109. inflateBack() and perform their own processing of the gzip header and
  72110. trailer.
  72111. inflate() returns Z_OK if some progress has been made (more input processed
  72112. or more output produced), Z_STREAM_END if the end of the compressed data has
  72113. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  72114. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  72115. corrupted (input stream not conforming to the zlib format or incorrect check
  72116. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  72117. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  72118. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  72119. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  72120. inflate() can be called again with more input and more output space to
  72121. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  72122. call inflateSync() to look for a good compression block if a partial recovery
  72123. of the data is desired.
  72124. */
  72125. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  72126. /*
  72127. All dynamically allocated data structures for this stream are freed.
  72128. This function discards any unprocessed input and does not flush any
  72129. pending output.
  72130. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  72131. was inconsistent. In the error case, msg may be set but then points to a
  72132. static string (which must not be deallocated).
  72133. */
  72134. /* Advanced functions */
  72135. /*
  72136. The following functions are needed only in some special applications.
  72137. */
  72138. /*
  72139. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  72140. int level,
  72141. int method,
  72142. int windowBits,
  72143. int memLevel,
  72144. int strategy));
  72145. This is another version of deflateInit with more compression options. The
  72146. fields next_in, zalloc, zfree and opaque must be initialized before by
  72147. the caller.
  72148. The method parameter is the compression method. It must be Z_DEFLATED in
  72149. this version of the library.
  72150. The windowBits parameter is the base two logarithm of the window size
  72151. (the size of the history buffer). It should be in the range 8..15 for this
  72152. version of the library. Larger values of this parameter result in better
  72153. compression at the expense of memory usage. The default value is 15 if
  72154. deflateInit is used instead.
  72155. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  72156. determines the window size. deflate() will then generate raw deflate data
  72157. with no zlib header or trailer, and will not compute an adler32 check value.
  72158. windowBits can also be greater than 15 for optional gzip encoding. Add
  72159. 16 to windowBits to write a simple gzip header and trailer around the
  72160. compressed data instead of a zlib wrapper. The gzip header will have no
  72161. file name, no extra data, no comment, no modification time (set to zero),
  72162. no header crc, and the operating system will be set to 255 (unknown). If a
  72163. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  72164. The memLevel parameter specifies how much memory should be allocated
  72165. for the internal compression state. memLevel=1 uses minimum memory but
  72166. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  72167. for optimal speed. The default value is 8. See zconf.h for total memory
  72168. usage as a function of windowBits and memLevel.
  72169. The strategy parameter is used to tune the compression algorithm. Use the
  72170. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  72171. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  72172. string match), or Z_RLE to limit match distances to one (run-length
  72173. encoding). Filtered data consists mostly of small values with a somewhat
  72174. random distribution. In this case, the compression algorithm is tuned to
  72175. compress them better. The effect of Z_FILTERED is to force more Huffman
  72176. coding and less string matching; it is somewhat intermediate between
  72177. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  72178. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  72179. parameter only affects the compression ratio but not the correctness of the
  72180. compressed output even if it is not set appropriately. Z_FIXED prevents the
  72181. use of dynamic Huffman codes, allowing for a simpler decoder for special
  72182. applications.
  72183. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  72184. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  72185. method). msg is set to null if there is no error message. deflateInit2 does
  72186. not perform any compression: this will be done by deflate().
  72187. */
  72188. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  72189. const Bytef *dictionary,
  72190. uInt dictLength));
  72191. /*
  72192. Initializes the compression dictionary from the given byte sequence
  72193. without producing any compressed output. This function must be called
  72194. immediately after deflateInit, deflateInit2 or deflateReset, before any
  72195. call of deflate. The compressor and decompressor must use exactly the same
  72196. dictionary (see inflateSetDictionary).
  72197. The dictionary should consist of strings (byte sequences) that are likely
  72198. to be encountered later in the data to be compressed, with the most commonly
  72199. used strings preferably put towards the end of the dictionary. Using a
  72200. dictionary is most useful when the data to be compressed is short and can be
  72201. predicted with good accuracy; the data can then be compressed better than
  72202. with the default empty dictionary.
  72203. Depending on the size of the compression data structures selected by
  72204. deflateInit or deflateInit2, a part of the dictionary may in effect be
  72205. discarded, for example if the dictionary is larger than the window size in
  72206. deflate or deflate2. Thus the strings most likely to be useful should be
  72207. put at the end of the dictionary, not at the front. In addition, the
  72208. current implementation of deflate will use at most the window size minus
  72209. 262 bytes of the provided dictionary.
  72210. Upon return of this function, strm->adler is set to the adler32 value
  72211. of the dictionary; the decompressor may later use this value to determine
  72212. which dictionary has been used by the compressor. (The adler32 value
  72213. applies to the whole dictionary even if only a subset of the dictionary is
  72214. actually used by the compressor.) If a raw deflate was requested, then the
  72215. adler32 value is not computed and strm->adler is not set.
  72216. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  72217. parameter is invalid (such as NULL dictionary) or the stream state is
  72218. inconsistent (for example if deflate has already been called for this stream
  72219. or if the compression method is bsort). deflateSetDictionary does not
  72220. perform any compression: this will be done by deflate().
  72221. */
  72222. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  72223. z_streamp source));
  72224. /*
  72225. Sets the destination stream as a complete copy of the source stream.
  72226. This function can be useful when several compression strategies will be
  72227. tried, for example when there are several ways of pre-processing the input
  72228. data with a filter. The streams that will be discarded should then be freed
  72229. by calling deflateEnd. Note that deflateCopy duplicates the internal
  72230. compression state which can be quite large, so this strategy is slow and
  72231. can consume lots of memory.
  72232. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  72233. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  72234. (such as zalloc being NULL). msg is left unchanged in both source and
  72235. destination.
  72236. */
  72237. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  72238. /*
  72239. This function is equivalent to deflateEnd followed by deflateInit,
  72240. but does not free and reallocate all the internal compression state.
  72241. The stream will keep the same compression level and any other attributes
  72242. that may have been set by deflateInit2.
  72243. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  72244. stream state was inconsistent (such as zalloc or state being NULL).
  72245. */
  72246. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  72247. int level,
  72248. int strategy));
  72249. /*
  72250. Dynamically update the compression level and compression strategy. The
  72251. interpretation of level and strategy is as in deflateInit2. This can be
  72252. used to switch between compression and straight copy of the input data, or
  72253. to switch to a different kind of input data requiring a different
  72254. strategy. If the compression level is changed, the input available so far
  72255. is compressed with the old level (and may be flushed); the new level will
  72256. take effect only at the next call of deflate().
  72257. Before the call of deflateParams, the stream state must be set as for
  72258. a call of deflate(), since the currently available input may have to
  72259. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  72260. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  72261. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  72262. if strm->avail_out was zero.
  72263. */
  72264. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  72265. int good_length,
  72266. int max_lazy,
  72267. int nice_length,
  72268. int max_chain));
  72269. /*
  72270. Fine tune deflate's internal compression parameters. This should only be
  72271. used by someone who understands the algorithm used by zlib's deflate for
  72272. searching for the best matching string, and even then only by the most
  72273. fanatic optimizer trying to squeeze out the last compressed bit for their
  72274. specific input data. Read the deflate.c source code for the meaning of the
  72275. max_lazy, good_length, nice_length, and max_chain parameters.
  72276. deflateTune() can be called after deflateInit() or deflateInit2(), and
  72277. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  72278. */
  72279. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  72280. uLong sourceLen));
  72281. /*
  72282. deflateBound() returns an upper bound on the compressed size after
  72283. deflation of sourceLen bytes. It must be called after deflateInit()
  72284. or deflateInit2(). This would be used to allocate an output buffer
  72285. for deflation in a single pass, and so would be called before deflate().
  72286. */
  72287. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  72288. int bits,
  72289. int value));
  72290. /*
  72291. deflatePrime() inserts bits in the deflate output stream. The intent
  72292. is that this function is used to start off the deflate output with the
  72293. bits leftover from a previous deflate stream when appending to it. As such,
  72294. this function can only be used for raw deflate, and must be used before the
  72295. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  72296. less than or equal to 16, and that many of the least significant bits of
  72297. value will be inserted in the output.
  72298. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  72299. stream state was inconsistent.
  72300. */
  72301. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  72302. gz_headerp head));
  72303. /*
  72304. deflateSetHeader() provides gzip header information for when a gzip
  72305. stream is requested by deflateInit2(). deflateSetHeader() may be called
  72306. after deflateInit2() or deflateReset() and before the first call of
  72307. deflate(). The text, time, os, extra field, name, and comment information
  72308. in the provided gz_header structure are written to the gzip header (xflag is
  72309. ignored -- the extra flags are set according to the compression level). The
  72310. caller must assure that, if not Z_NULL, name and comment are terminated with
  72311. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  72312. available there. If hcrc is true, a gzip header crc is included. Note that
  72313. the current versions of the command-line version of gzip (up through version
  72314. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  72315. gzip file" and give up.
  72316. If deflateSetHeader is not used, the default gzip header has text false,
  72317. the time set to zero, and os set to 255, with no extra, name, or comment
  72318. fields. The gzip header is returned to the default state by deflateReset().
  72319. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  72320. stream state was inconsistent.
  72321. */
  72322. /*
  72323. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  72324. int windowBits));
  72325. This is another version of inflateInit with an extra parameter. The
  72326. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  72327. before by the caller.
  72328. The windowBits parameter is the base two logarithm of the maximum window
  72329. size (the size of the history buffer). It should be in the range 8..15 for
  72330. this version of the library. The default value is 15 if inflateInit is used
  72331. instead. windowBits must be greater than or equal to the windowBits value
  72332. provided to deflateInit2() while compressing, or it must be equal to 15 if
  72333. deflateInit2() was not used. If a compressed stream with a larger window
  72334. size is given as input, inflate() will return with the error code
  72335. Z_DATA_ERROR instead of trying to allocate a larger window.
  72336. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  72337. determines the window size. inflate() will then process raw deflate data,
  72338. not looking for a zlib or gzip header, not generating a check value, and not
  72339. looking for any check values for comparison at the end of the stream. This
  72340. is for use with other formats that use the deflate compressed data format
  72341. such as zip. Those formats provide their own check values. If a custom
  72342. format is developed using the raw deflate format for compressed data, it is
  72343. recommended that a check value such as an adler32 or a crc32 be applied to
  72344. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  72345. most applications, the zlib format should be used as is. Note that comments
  72346. above on the use in deflateInit2() applies to the magnitude of windowBits.
  72347. windowBits can also be greater than 15 for optional gzip decoding. Add
  72348. 32 to windowBits to enable zlib and gzip decoding with automatic header
  72349. detection, or add 16 to decode only the gzip format (the zlib format will
  72350. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  72351. a crc32 instead of an adler32.
  72352. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  72353. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  72354. is set to null if there is no error message. inflateInit2 does not perform
  72355. any decompression apart from reading the zlib header if present: this will
  72356. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  72357. and avail_out are unchanged.)
  72358. */
  72359. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  72360. const Bytef *dictionary,
  72361. uInt dictLength));
  72362. /*
  72363. Initializes the decompression dictionary from the given uncompressed byte
  72364. sequence. This function must be called immediately after a call of inflate,
  72365. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  72366. can be determined from the adler32 value returned by that call of inflate.
  72367. The compressor and decompressor must use exactly the same dictionary (see
  72368. deflateSetDictionary). For raw inflate, this function can be called
  72369. immediately after inflateInit2() or inflateReset() and before any call of
  72370. inflate() to set the dictionary. The application must insure that the
  72371. dictionary that was used for compression is provided.
  72372. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  72373. parameter is invalid (such as NULL dictionary) or the stream state is
  72374. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  72375. expected one (incorrect adler32 value). inflateSetDictionary does not
  72376. perform any decompression: this will be done by subsequent calls of
  72377. inflate().
  72378. */
  72379. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  72380. /*
  72381. Skips invalid compressed data until a full flush point (see above the
  72382. description of deflate with Z_FULL_FLUSH) can be found, or until all
  72383. available input is skipped. No output is provided.
  72384. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  72385. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  72386. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  72387. case, the application may save the current current value of total_in which
  72388. indicates where valid compressed data was found. In the error case, the
  72389. application may repeatedly call inflateSync, providing more input each time,
  72390. until success or end of the input data.
  72391. */
  72392. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  72393. z_streamp source));
  72394. /*
  72395. Sets the destination stream as a complete copy of the source stream.
  72396. This function can be useful when randomly accessing a large stream. The
  72397. first pass through the stream can periodically record the inflate state,
  72398. allowing restarting inflate at those points when randomly accessing the
  72399. stream.
  72400. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  72401. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  72402. (such as zalloc being NULL). msg is left unchanged in both source and
  72403. destination.
  72404. */
  72405. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  72406. /*
  72407. This function is equivalent to inflateEnd followed by inflateInit,
  72408. but does not free and reallocate all the internal decompression state.
  72409. The stream will keep attributes that may have been set by inflateInit2.
  72410. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  72411. stream state was inconsistent (such as zalloc or state being NULL).
  72412. */
  72413. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  72414. int bits,
  72415. int value));
  72416. /*
  72417. This function inserts bits in the inflate input stream. The intent is
  72418. that this function is used to start inflating at a bit position in the
  72419. middle of a byte. The provided bits will be used before any bytes are used
  72420. from next_in. This function should only be used with raw inflate, and
  72421. should be used before the first inflate() call after inflateInit2() or
  72422. inflateReset(). bits must be less than or equal to 16, and that many of the
  72423. least significant bits of value will be inserted in the input.
  72424. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  72425. stream state was inconsistent.
  72426. */
  72427. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  72428. gz_headerp head));
  72429. /*
  72430. inflateGetHeader() requests that gzip header information be stored in the
  72431. provided gz_header structure. inflateGetHeader() may be called after
  72432. inflateInit2() or inflateReset(), and before the first call of inflate().
  72433. As inflate() processes the gzip stream, head->done is zero until the header
  72434. is completed, at which time head->done is set to one. If a zlib stream is
  72435. being decoded, then head->done is set to -1 to indicate that there will be
  72436. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  72437. force inflate() to return immediately after header processing is complete
  72438. and before any actual data is decompressed.
  72439. The text, time, xflags, and os fields are filled in with the gzip header
  72440. contents. hcrc is set to true if there is a header CRC. (The header CRC
  72441. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  72442. contains the maximum number of bytes to write to extra. Once done is true,
  72443. extra_len contains the actual extra field length, and extra contains the
  72444. extra field, or that field truncated if extra_max is less than extra_len.
  72445. If name is not Z_NULL, then up to name_max characters are written there,
  72446. terminated with a zero unless the length is greater than name_max. If
  72447. comment is not Z_NULL, then up to comm_max characters are written there,
  72448. terminated with a zero unless the length is greater than comm_max. When
  72449. any of extra, name, or comment are not Z_NULL and the respective field is
  72450. not present in the header, then that field is set to Z_NULL to signal its
  72451. absence. This allows the use of deflateSetHeader() with the returned
  72452. structure to duplicate the header. However if those fields are set to
  72453. allocated memory, then the application will need to save those pointers
  72454. elsewhere so that they can be eventually freed.
  72455. If inflateGetHeader is not used, then the header information is simply
  72456. discarded. The header is always checked for validity, including the header
  72457. CRC if present. inflateReset() will reset the process to discard the header
  72458. information. The application would need to call inflateGetHeader() again to
  72459. retrieve the header from the next gzip stream.
  72460. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  72461. stream state was inconsistent.
  72462. */
  72463. /*
  72464. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  72465. unsigned char FAR *window));
  72466. Initialize the internal stream state for decompression using inflateBack()
  72467. calls. The fields zalloc, zfree and opaque in strm must be initialized
  72468. before the call. If zalloc and zfree are Z_NULL, then the default library-
  72469. derived memory allocation routines are used. windowBits is the base two
  72470. logarithm of the window size, in the range 8..15. window is a caller
  72471. supplied buffer of that size. Except for special applications where it is
  72472. assured that deflate was used with small window sizes, windowBits must be 15
  72473. and a 32K byte window must be supplied to be able to decompress general
  72474. deflate streams.
  72475. See inflateBack() for the usage of these routines.
  72476. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  72477. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  72478. be allocated, or Z_VERSION_ERROR if the version of the library does not
  72479. match the version of the header file.
  72480. */
  72481. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  72482. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  72483. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  72484. in_func in, void FAR *in_desc,
  72485. out_func out, void FAR *out_desc));
  72486. /*
  72487. inflateBack() does a raw inflate with a single call using a call-back
  72488. interface for input and output. This is more efficient than inflate() for
  72489. file i/o applications in that it avoids copying between the output and the
  72490. sliding window by simply making the window itself the output buffer. This
  72491. function trusts the application to not change the output buffer passed by
  72492. the output function, at least until inflateBack() returns.
  72493. inflateBackInit() must be called first to allocate the internal state
  72494. and to initialize the state with the user-provided window buffer.
  72495. inflateBack() may then be used multiple times to inflate a complete, raw
  72496. deflate stream with each call. inflateBackEnd() is then called to free
  72497. the allocated state.
  72498. A raw deflate stream is one with no zlib or gzip header or trailer.
  72499. This routine would normally be used in a utility that reads zip or gzip
  72500. files and writes out uncompressed files. The utility would decode the
  72501. header and process the trailer on its own, hence this routine expects
  72502. only the raw deflate stream to decompress. This is different from the
  72503. normal behavior of inflate(), which expects either a zlib or gzip header and
  72504. trailer around the deflate stream.
  72505. inflateBack() uses two subroutines supplied by the caller that are then
  72506. called by inflateBack() for input and output. inflateBack() calls those
  72507. routines until it reads a complete deflate stream and writes out all of the
  72508. uncompressed data, or until it encounters an error. The function's
  72509. parameters and return types are defined above in the in_func and out_func
  72510. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  72511. number of bytes of provided input, and a pointer to that input in buf. If
  72512. there is no input available, in() must return zero--buf is ignored in that
  72513. case--and inflateBack() will return a buffer error. inflateBack() will call
  72514. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  72515. should return zero on success, or non-zero on failure. If out() returns
  72516. non-zero, inflateBack() will return with an error. Neither in() nor out()
  72517. are permitted to change the contents of the window provided to
  72518. inflateBackInit(), which is also the buffer that out() uses to write from.
  72519. The length written by out() will be at most the window size. Any non-zero
  72520. amount of input may be provided by in().
  72521. For convenience, inflateBack() can be provided input on the first call by
  72522. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  72523. in() will be called. Therefore strm->next_in must be initialized before
  72524. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  72525. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  72526. must also be initialized, and then if strm->avail_in is not zero, input will
  72527. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  72528. The in_desc and out_desc parameters of inflateBack() is passed as the
  72529. first parameter of in() and out() respectively when they are called. These
  72530. descriptors can be optionally used to pass any information that the caller-
  72531. supplied in() and out() functions need to do their job.
  72532. On return, inflateBack() will set strm->next_in and strm->avail_in to
  72533. pass back any unused input that was provided by the last in() call. The
  72534. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  72535. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  72536. error in the deflate stream (in which case strm->msg is set to indicate the
  72537. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  72538. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  72539. distinguished using strm->next_in which will be Z_NULL only if in() returned
  72540. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  72541. out() returning non-zero. (in() will always be called before out(), so
  72542. strm->next_in is assured to be defined if out() returns non-zero.) Note
  72543. that inflateBack() cannot return Z_OK.
  72544. */
  72545. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  72546. /*
  72547. All memory allocated by inflateBackInit() is freed.
  72548. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  72549. state was inconsistent.
  72550. */
  72551. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  72552. /* Return flags indicating compile-time options.
  72553. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  72554. 1.0: size of uInt
  72555. 3.2: size of uLong
  72556. 5.4: size of voidpf (pointer)
  72557. 7.6: size of z_off_t
  72558. Compiler, assembler, and debug options:
  72559. 8: DEBUG
  72560. 9: ASMV or ASMINF -- use ASM code
  72561. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  72562. 11: 0 (reserved)
  72563. One-time table building (smaller code, but not thread-safe if true):
  72564. 12: BUILDFIXED -- build static block decoding tables when needed
  72565. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  72566. 14,15: 0 (reserved)
  72567. Library content (indicates missing functionality):
  72568. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  72569. deflate code when not needed)
  72570. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  72571. and decode gzip streams (to avoid linking crc code)
  72572. 18-19: 0 (reserved)
  72573. Operation variations (changes in library functionality):
  72574. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  72575. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  72576. 22,23: 0 (reserved)
  72577. The sprintf variant used by gzprintf (zero is best):
  72578. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  72579. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  72580. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  72581. Remainder:
  72582. 27-31: 0 (reserved)
  72583. */
  72584. /* utility functions */
  72585. /*
  72586. The following utility functions are implemented on top of the
  72587. basic stream-oriented functions. To simplify the interface, some
  72588. default options are assumed (compression level and memory usage,
  72589. standard memory allocation functions). The source code of these
  72590. utility functions can easily be modified if you need special options.
  72591. */
  72592. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  72593. const Bytef *source, uLong sourceLen));
  72594. /*
  72595. Compresses the source buffer into the destination buffer. sourceLen is
  72596. the byte length of the source buffer. Upon entry, destLen is the total
  72597. size of the destination buffer, which must be at least the value returned
  72598. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  72599. compressed buffer.
  72600. This function can be used to compress a whole file at once if the
  72601. input file is mmap'ed.
  72602. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  72603. enough memory, Z_BUF_ERROR if there was not enough room in the output
  72604. buffer.
  72605. */
  72606. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  72607. const Bytef *source, uLong sourceLen,
  72608. int level));
  72609. /*
  72610. Compresses the source buffer into the destination buffer. The level
  72611. parameter has the same meaning as in deflateInit. sourceLen is the byte
  72612. length of the source buffer. Upon entry, destLen is the total size of the
  72613. destination buffer, which must be at least the value returned by
  72614. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  72615. compressed buffer.
  72616. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  72617. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  72618. Z_STREAM_ERROR if the level parameter is invalid.
  72619. */
  72620. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  72621. /*
  72622. compressBound() returns an upper bound on the compressed size after
  72623. compress() or compress2() on sourceLen bytes. It would be used before
  72624. a compress() or compress2() call to allocate the destination buffer.
  72625. */
  72626. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  72627. const Bytef *source, uLong sourceLen));
  72628. /*
  72629. Decompresses the source buffer into the destination buffer. sourceLen is
  72630. the byte length of the source buffer. Upon entry, destLen is the total
  72631. size of the destination buffer, which must be large enough to hold the
  72632. entire uncompressed data. (The size of the uncompressed data must have
  72633. been saved previously by the compressor and transmitted to the decompressor
  72634. by some mechanism outside the scope of this compression library.)
  72635. Upon exit, destLen is the actual size of the compressed buffer.
  72636. This function can be used to decompress a whole file at once if the
  72637. input file is mmap'ed.
  72638. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  72639. enough memory, Z_BUF_ERROR if there was not enough room in the output
  72640. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  72641. */
  72642. typedef voidp gzFile;
  72643. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  72644. /*
  72645. Opens a gzip (.gz) file for reading or writing. The mode parameter
  72646. is as in fopen ("rb" or "wb") but can also include a compression level
  72647. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  72648. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  72649. as in "wb1R". (See the description of deflateInit2 for more information
  72650. about the strategy parameter.)
  72651. gzopen can be used to read a file which is not in gzip format; in this
  72652. case gzread will directly read from the file without decompression.
  72653. gzopen returns NULL if the file could not be opened or if there was
  72654. insufficient memory to allocate the (de)compression state; errno
  72655. can be checked to distinguish the two cases (if errno is zero, the
  72656. zlib error is Z_MEM_ERROR). */
  72657. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  72658. /*
  72659. gzdopen() associates a gzFile with the file descriptor fd. File
  72660. descriptors are obtained from calls like open, dup, creat, pipe or
  72661. fileno (in the file has been previously opened with fopen).
  72662. The mode parameter is as in gzopen.
  72663. The next call of gzclose on the returned gzFile will also close the
  72664. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  72665. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  72666. gzdopen returns NULL if there was insufficient memory to allocate
  72667. the (de)compression state.
  72668. */
  72669. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  72670. /*
  72671. Dynamically update the compression level or strategy. See the description
  72672. of deflateInit2 for the meaning of these parameters.
  72673. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  72674. opened for writing.
  72675. */
  72676. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  72677. /*
  72678. Reads the given number of uncompressed bytes from the compressed file.
  72679. If the input file was not in gzip format, gzread copies the given number
  72680. of bytes into the buffer.
  72681. gzread returns the number of uncompressed bytes actually read (0 for
  72682. end of file, -1 for error). */
  72683. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  72684. voidpc buf, unsigned len));
  72685. /*
  72686. Writes the given number of uncompressed bytes into the compressed file.
  72687. gzwrite returns the number of uncompressed bytes actually written
  72688. (0 in case of error).
  72689. */
  72690. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  72691. /*
  72692. Converts, formats, and writes the args to the compressed file under
  72693. control of the format string, as in fprintf. gzprintf returns the number of
  72694. uncompressed bytes actually written (0 in case of error). The number of
  72695. uncompressed bytes written is limited to 4095. The caller should assure that
  72696. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  72697. return an error (0) with nothing written. In this case, there may also be a
  72698. buffer overflow with unpredictable consequences, which is possible only if
  72699. zlib was compiled with the insecure functions sprintf() or vsprintf()
  72700. because the secure snprintf() or vsnprintf() functions were not available.
  72701. */
  72702. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  72703. /*
  72704. Writes the given null-terminated string to the compressed file, excluding
  72705. the terminating null character.
  72706. gzputs returns the number of characters written, or -1 in case of error.
  72707. */
  72708. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  72709. /*
  72710. Reads bytes from the compressed file until len-1 characters are read, or
  72711. a newline character is read and transferred to buf, or an end-of-file
  72712. condition is encountered. The string is then terminated with a null
  72713. character.
  72714. gzgets returns buf, or Z_NULL in case of error.
  72715. */
  72716. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  72717. /*
  72718. Writes c, converted to an unsigned char, into the compressed file.
  72719. gzputc returns the value that was written, or -1 in case of error.
  72720. */
  72721. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  72722. /*
  72723. Reads one byte from the compressed file. gzgetc returns this byte
  72724. or -1 in case of end of file or error.
  72725. */
  72726. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  72727. /*
  72728. Push one character back onto the stream to be read again later.
  72729. Only one character of push-back is allowed. gzungetc() returns the
  72730. character pushed, or -1 on failure. gzungetc() will fail if a
  72731. character has been pushed but not read yet, or if c is -1. The pushed
  72732. character will be discarded if the stream is repositioned with gzseek()
  72733. or gzrewind().
  72734. */
  72735. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  72736. /*
  72737. Flushes all pending output into the compressed file. The parameter
  72738. flush is as in the deflate() function. The return value is the zlib
  72739. error number (see function gzerror below). gzflush returns Z_OK if
  72740. the flush parameter is Z_FINISH and all output could be flushed.
  72741. gzflush should be called only when strictly necessary because it can
  72742. degrade compression.
  72743. */
  72744. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  72745. z_off_t offset, int whence));
  72746. /*
  72747. Sets the starting position for the next gzread or gzwrite on the
  72748. given compressed file. The offset represents a number of bytes in the
  72749. uncompressed data stream. The whence parameter is defined as in lseek(2);
  72750. the value SEEK_END is not supported.
  72751. If the file is opened for reading, this function is emulated but can be
  72752. extremely slow. If the file is opened for writing, only forward seeks are
  72753. supported; gzseek then compresses a sequence of zeroes up to the new
  72754. starting position.
  72755. gzseek returns the resulting offset location as measured in bytes from
  72756. the beginning of the uncompressed stream, or -1 in case of error, in
  72757. particular if the file is opened for writing and the new starting position
  72758. would be before the current position.
  72759. */
  72760. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  72761. /*
  72762. Rewinds the given file. This function is supported only for reading.
  72763. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  72764. */
  72765. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  72766. /*
  72767. Returns the starting position for the next gzread or gzwrite on the
  72768. given compressed file. This position represents a number of bytes in the
  72769. uncompressed data stream.
  72770. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  72771. */
  72772. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  72773. /*
  72774. Returns 1 when EOF has previously been detected reading the given
  72775. input stream, otherwise zero.
  72776. */
  72777. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  72778. /*
  72779. Returns 1 if file is being read directly without decompression, otherwise
  72780. zero.
  72781. */
  72782. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  72783. /*
  72784. Flushes all pending output if necessary, closes the compressed file
  72785. and deallocates all the (de)compression state. The return value is the zlib
  72786. error number (see function gzerror below).
  72787. */
  72788. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  72789. /*
  72790. Returns the error message for the last error which occurred on the
  72791. given compressed file. errnum is set to zlib error number. If an
  72792. error occurred in the file system and not in the compression library,
  72793. errnum is set to Z_ERRNO and the application may consult errno
  72794. to get the exact error code.
  72795. */
  72796. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  72797. /*
  72798. Clears the error and end-of-file flags for file. This is analogous to the
  72799. clearerr() function in stdio. This is useful for continuing to read a gzip
  72800. file that is being written concurrently.
  72801. */
  72802. /* checksum functions */
  72803. /*
  72804. These functions are not related to compression but are exported
  72805. anyway because they might be useful in applications using the
  72806. compression library.
  72807. */
  72808. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  72809. /*
  72810. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  72811. return the updated checksum. If buf is NULL, this function returns
  72812. the required initial value for the checksum.
  72813. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  72814. much faster. Usage example:
  72815. uLong adler = adler32(0L, Z_NULL, 0);
  72816. while (read_buffer(buffer, length) != EOF) {
  72817. adler = adler32(adler, buffer, length);
  72818. }
  72819. if (adler != original_adler) error();
  72820. */
  72821. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  72822. z_off_t len2));
  72823. /*
  72824. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  72825. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  72826. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  72827. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  72828. */
  72829. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  72830. /*
  72831. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  72832. updated CRC-32. If buf is NULL, this function returns the required initial
  72833. value for the for the crc. Pre- and post-conditioning (one's complement) is
  72834. performed within this function so it shouldn't be done by the application.
  72835. Usage example:
  72836. uLong crc = crc32(0L, Z_NULL, 0);
  72837. while (read_buffer(buffer, length) != EOF) {
  72838. crc = crc32(crc, buffer, length);
  72839. }
  72840. if (crc != original_crc) error();
  72841. */
  72842. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  72843. /*
  72844. Combine two CRC-32 check values into one. For two sequences of bytes,
  72845. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  72846. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  72847. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  72848. len2.
  72849. */
  72850. /* various hacks, don't look :) */
  72851. /* deflateInit and inflateInit are macros to allow checking the zlib version
  72852. * and the compiler's view of z_stream:
  72853. */
  72854. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  72855. const char *version, int stream_size));
  72856. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  72857. const char *version, int stream_size));
  72858. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  72859. int windowBits, int memLevel,
  72860. int strategy, const char *version,
  72861. int stream_size));
  72862. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  72863. const char *version, int stream_size));
  72864. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  72865. unsigned char FAR *window,
  72866. const char *version,
  72867. int stream_size));
  72868. #define deflateInit(strm, level) \
  72869. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  72870. #define inflateInit(strm) \
  72871. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  72872. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  72873. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  72874. (strategy), ZLIB_VERSION, sizeof(z_stream))
  72875. #define inflateInit2(strm, windowBits) \
  72876. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  72877. #define inflateBackInit(strm, windowBits, window) \
  72878. inflateBackInit_((strm), (windowBits), (window), \
  72879. ZLIB_VERSION, sizeof(z_stream))
  72880. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  72881. struct internal_state {int dummy;}; /* hack for buggy compilers */
  72882. #endif
  72883. ZEXTERN const char * ZEXPORT zError OF((int));
  72884. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  72885. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  72886. #ifdef __cplusplus
  72887. }
  72888. #endif
  72889. #endif /* ZLIB_H */
  72890. /********* End of inlined file: zlib.h *********/
  72891. #undef OS_CODE
  72892. }
  72893. BEGIN_JUCE_NAMESPACE
  72894. using namespace zlibNamespace;
  72895. // internal helper object that holds the zlib structures so they don't have to be
  72896. // included publicly.
  72897. class GZIPCompressorHelper
  72898. {
  72899. private:
  72900. z_stream* stream;
  72901. uint8* data;
  72902. int dataSize, compLevel, strategy;
  72903. bool setParams;
  72904. public:
  72905. bool finished, shouldFinish;
  72906. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  72907. : data (0),
  72908. dataSize (0),
  72909. compLevel (compressionLevel),
  72910. strategy (0),
  72911. setParams (true),
  72912. finished (false),
  72913. shouldFinish (false)
  72914. {
  72915. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  72916. if (deflateInit2 (stream,
  72917. compLevel,
  72918. Z_DEFLATED,
  72919. nowrap ? -MAX_WBITS : MAX_WBITS,
  72920. 8,
  72921. strategy) != Z_OK)
  72922. {
  72923. juce_free (stream);
  72924. stream = 0;
  72925. }
  72926. }
  72927. ~GZIPCompressorHelper()
  72928. {
  72929. if (stream != 0)
  72930. {
  72931. deflateEnd (stream);
  72932. juce_free (stream);
  72933. }
  72934. }
  72935. bool needsInput() const throw()
  72936. {
  72937. return dataSize <= 0;
  72938. }
  72939. void setInput (uint8* const newData, const int size) throw()
  72940. {
  72941. data = newData;
  72942. dataSize = size;
  72943. }
  72944. int doNextBlock (uint8* const dest, const int destSize) throw()
  72945. {
  72946. if (stream != 0)
  72947. {
  72948. stream->next_in = data;
  72949. stream->next_out = dest;
  72950. stream->avail_in = dataSize;
  72951. stream->avail_out = destSize;
  72952. const int result = setParams ? deflateParams (stream, compLevel, strategy)
  72953. : deflate (stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  72954. setParams = false;
  72955. switch (result)
  72956. {
  72957. case Z_STREAM_END:
  72958. finished = true;
  72959. case Z_OK:
  72960. data += dataSize - stream->avail_in;
  72961. dataSize = stream->avail_in;
  72962. return destSize - stream->avail_out;
  72963. default:
  72964. break;
  72965. }
  72966. }
  72967. return 0;
  72968. }
  72969. };
  72970. const int gzipCompBufferSize = 32768;
  72971. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  72972. int compressionLevel,
  72973. const bool deleteDestStream_,
  72974. const bool noWrap)
  72975. : destStream (destStream_),
  72976. deleteDestStream (deleteDestStream_)
  72977. {
  72978. if (compressionLevel < 1 || compressionLevel > 9)
  72979. compressionLevel = -1;
  72980. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  72981. buffer = (uint8*) juce_malloc (gzipCompBufferSize);
  72982. }
  72983. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  72984. {
  72985. flush();
  72986. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72987. delete h;
  72988. juce_free (buffer);
  72989. if (deleteDestStream)
  72990. delete destStream;
  72991. }
  72992. void GZIPCompressorOutputStream::flush()
  72993. {
  72994. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72995. if (! h->finished)
  72996. {
  72997. h->shouldFinish = true;
  72998. while (! h->finished)
  72999. doNextBlock();
  73000. }
  73001. destStream->flush();
  73002. }
  73003. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  73004. {
  73005. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  73006. if (! h->finished)
  73007. {
  73008. h->setInput ((uint8*) destBuffer, howMany);
  73009. while (! h->needsInput())
  73010. {
  73011. if (! doNextBlock())
  73012. return false;
  73013. }
  73014. }
  73015. return true;
  73016. }
  73017. bool GZIPCompressorOutputStream::doNextBlock()
  73018. {
  73019. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  73020. const int len = h->doNextBlock (buffer, gzipCompBufferSize);
  73021. if (len > 0)
  73022. return destStream->write (buffer, len);
  73023. else
  73024. return true;
  73025. }
  73026. int64 GZIPCompressorOutputStream::getPosition()
  73027. {
  73028. return destStream->getPosition();
  73029. }
  73030. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  73031. {
  73032. jassertfalse // can't do it!
  73033. return false;
  73034. }
  73035. END_JUCE_NAMESPACE
  73036. /********* End of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  73037. /********* Start of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  73038. #if JUCE_MSVC
  73039. #pragma warning (push)
  73040. #pragma warning (disable: 4309 4305)
  73041. #endif
  73042. namespace zlibNamespace
  73043. {
  73044. extern "C"
  73045. {
  73046. #undef OS_CODE
  73047. #undef fdopen
  73048. #define ZLIB_INTERNAL
  73049. #define NO_DUMMY_DECL
  73050. /********* Start of inlined file: adler32.c *********/
  73051. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73052. #define ZLIB_INTERNAL
  73053. #define BASE 65521UL /* largest prime smaller than 65536 */
  73054. #define NMAX 5552
  73055. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  73056. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  73057. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  73058. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  73059. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  73060. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  73061. /* use NO_DIVIDE if your processor does not do division in hardware */
  73062. #ifdef NO_DIVIDE
  73063. # define MOD(a) \
  73064. do { \
  73065. if (a >= (BASE << 16)) a -= (BASE << 16); \
  73066. if (a >= (BASE << 15)) a -= (BASE << 15); \
  73067. if (a >= (BASE << 14)) a -= (BASE << 14); \
  73068. if (a >= (BASE << 13)) a -= (BASE << 13); \
  73069. if (a >= (BASE << 12)) a -= (BASE << 12); \
  73070. if (a >= (BASE << 11)) a -= (BASE << 11); \
  73071. if (a >= (BASE << 10)) a -= (BASE << 10); \
  73072. if (a >= (BASE << 9)) a -= (BASE << 9); \
  73073. if (a >= (BASE << 8)) a -= (BASE << 8); \
  73074. if (a >= (BASE << 7)) a -= (BASE << 7); \
  73075. if (a >= (BASE << 6)) a -= (BASE << 6); \
  73076. if (a >= (BASE << 5)) a -= (BASE << 5); \
  73077. if (a >= (BASE << 4)) a -= (BASE << 4); \
  73078. if (a >= (BASE << 3)) a -= (BASE << 3); \
  73079. if (a >= (BASE << 2)) a -= (BASE << 2); \
  73080. if (a >= (BASE << 1)) a -= (BASE << 1); \
  73081. if (a >= BASE) a -= BASE; \
  73082. } while (0)
  73083. # define MOD4(a) \
  73084. do { \
  73085. if (a >= (BASE << 4)) a -= (BASE << 4); \
  73086. if (a >= (BASE << 3)) a -= (BASE << 3); \
  73087. if (a >= (BASE << 2)) a -= (BASE << 2); \
  73088. if (a >= (BASE << 1)) a -= (BASE << 1); \
  73089. if (a >= BASE) a -= BASE; \
  73090. } while (0)
  73091. #else
  73092. # define MOD(a) a %= BASE
  73093. # define MOD4(a) a %= BASE
  73094. #endif
  73095. /* ========================================================================= */
  73096. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  73097. {
  73098. unsigned long sum2;
  73099. unsigned n;
  73100. /* split Adler-32 into component sums */
  73101. sum2 = (adler >> 16) & 0xffff;
  73102. adler &= 0xffff;
  73103. /* in case user likes doing a byte at a time, keep it fast */
  73104. if (len == 1) {
  73105. adler += buf[0];
  73106. if (adler >= BASE)
  73107. adler -= BASE;
  73108. sum2 += adler;
  73109. if (sum2 >= BASE)
  73110. sum2 -= BASE;
  73111. return adler | (sum2 << 16);
  73112. }
  73113. /* initial Adler-32 value (deferred check for len == 1 speed) */
  73114. if (buf == Z_NULL)
  73115. return 1L;
  73116. /* in case short lengths are provided, keep it somewhat fast */
  73117. if (len < 16) {
  73118. while (len--) {
  73119. adler += *buf++;
  73120. sum2 += adler;
  73121. }
  73122. if (adler >= BASE)
  73123. adler -= BASE;
  73124. MOD4(sum2); /* only added so many BASE's */
  73125. return adler | (sum2 << 16);
  73126. }
  73127. /* do length NMAX blocks -- requires just one modulo operation */
  73128. while (len >= NMAX) {
  73129. len -= NMAX;
  73130. n = NMAX / 16; /* NMAX is divisible by 16 */
  73131. do {
  73132. DO16(buf); /* 16 sums unrolled */
  73133. buf += 16;
  73134. } while (--n);
  73135. MOD(adler);
  73136. MOD(sum2);
  73137. }
  73138. /* do remaining bytes (less than NMAX, still just one modulo) */
  73139. if (len) { /* avoid modulos if none remaining */
  73140. while (len >= 16) {
  73141. len -= 16;
  73142. DO16(buf);
  73143. buf += 16;
  73144. }
  73145. while (len--) {
  73146. adler += *buf++;
  73147. sum2 += adler;
  73148. }
  73149. MOD(adler);
  73150. MOD(sum2);
  73151. }
  73152. /* return recombined sums */
  73153. return adler | (sum2 << 16);
  73154. }
  73155. /* ========================================================================= */
  73156. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  73157. {
  73158. unsigned long sum1;
  73159. unsigned long sum2;
  73160. unsigned rem;
  73161. /* the derivation of this formula is left as an exercise for the reader */
  73162. rem = (unsigned)(len2 % BASE);
  73163. sum1 = adler1 & 0xffff;
  73164. sum2 = rem * sum1;
  73165. MOD(sum2);
  73166. sum1 += (adler2 & 0xffff) + BASE - 1;
  73167. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  73168. if (sum1 > BASE) sum1 -= BASE;
  73169. if (sum1 > BASE) sum1 -= BASE;
  73170. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  73171. if (sum2 > BASE) sum2 -= BASE;
  73172. return sum1 | (sum2 << 16);
  73173. }
  73174. /********* End of inlined file: adler32.c *********/
  73175. /********* Start of inlined file: compress.c *********/
  73176. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73177. #define ZLIB_INTERNAL
  73178. /* ===========================================================================
  73179. Compresses the source buffer into the destination buffer. The level
  73180. parameter has the same meaning as in deflateInit. sourceLen is the byte
  73181. length of the source buffer. Upon entry, destLen is the total size of the
  73182. destination buffer, which must be at least 0.1% larger than sourceLen plus
  73183. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  73184. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  73185. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  73186. Z_STREAM_ERROR if the level parameter is invalid.
  73187. */
  73188. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  73189. uLong sourceLen, int level)
  73190. {
  73191. z_stream stream;
  73192. int err;
  73193. stream.next_in = (Bytef*)source;
  73194. stream.avail_in = (uInt)sourceLen;
  73195. #ifdef MAXSEG_64K
  73196. /* Check for source > 64K on 16-bit machine: */
  73197. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  73198. #endif
  73199. stream.next_out = dest;
  73200. stream.avail_out = (uInt)*destLen;
  73201. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  73202. stream.zalloc = (alloc_func)0;
  73203. stream.zfree = (free_func)0;
  73204. stream.opaque = (voidpf)0;
  73205. err = deflateInit(&stream, level);
  73206. if (err != Z_OK) return err;
  73207. err = deflate(&stream, Z_FINISH);
  73208. if (err != Z_STREAM_END) {
  73209. deflateEnd(&stream);
  73210. return err == Z_OK ? Z_BUF_ERROR : err;
  73211. }
  73212. *destLen = stream.total_out;
  73213. err = deflateEnd(&stream);
  73214. return err;
  73215. }
  73216. /* ===========================================================================
  73217. */
  73218. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  73219. {
  73220. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  73221. }
  73222. /* ===========================================================================
  73223. If the default memLevel or windowBits for deflateInit() is changed, then
  73224. this function needs to be updated.
  73225. */
  73226. uLong ZEXPORT compressBound (uLong sourceLen)
  73227. {
  73228. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  73229. }
  73230. /********* End of inlined file: compress.c *********/
  73231. #undef DO1
  73232. #undef DO8
  73233. /********* Start of inlined file: crc32.c *********/
  73234. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73235. /*
  73236. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  73237. protection on the static variables used to control the first-use generation
  73238. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  73239. first call get_crc_table() to initialize the tables before allowing more than
  73240. one thread to use crc32().
  73241. */
  73242. #ifdef MAKECRCH
  73243. # include <stdio.h>
  73244. # ifndef DYNAMIC_CRC_TABLE
  73245. # define DYNAMIC_CRC_TABLE
  73246. # endif /* !DYNAMIC_CRC_TABLE */
  73247. #endif /* MAKECRCH */
  73248. /********* Start of inlined file: zutil.h *********/
  73249. /* WARNING: this file should *not* be used by applications. It is
  73250. part of the implementation of the compression library and is
  73251. subject to change. Applications should only use zlib.h.
  73252. */
  73253. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73254. #ifndef ZUTIL_H
  73255. #define ZUTIL_H
  73256. #define ZLIB_INTERNAL
  73257. #ifdef STDC
  73258. # ifndef _WIN32_WCE
  73259. # include <stddef.h>
  73260. # endif
  73261. # include <string.h>
  73262. # include <stdlib.h>
  73263. #endif
  73264. #ifdef NO_ERRNO_H
  73265. # ifdef _WIN32_WCE
  73266. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  73267. * errno. We define it as a global variable to simplify porting.
  73268. * Its value is always 0 and should not be used. We rename it to
  73269. * avoid conflict with other libraries that use the same workaround.
  73270. */
  73271. # define errno z_errno
  73272. # endif
  73273. extern int errno;
  73274. #else
  73275. # ifndef _WIN32_WCE
  73276. # include <errno.h>
  73277. # endif
  73278. #endif
  73279. #ifndef local
  73280. # define local static
  73281. #endif
  73282. /* compile with -Dlocal if your debugger can't find static symbols */
  73283. typedef unsigned char uch;
  73284. typedef uch FAR uchf;
  73285. typedef unsigned short ush;
  73286. typedef ush FAR ushf;
  73287. typedef unsigned long ulg;
  73288. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  73289. /* (size given to avoid silly warnings with Visual C++) */
  73290. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  73291. #define ERR_RETURN(strm,err) \
  73292. return (strm->msg = (char*)ERR_MSG(err), (err))
  73293. /* To be used only when the state is known to be valid */
  73294. /* common constants */
  73295. #ifndef DEF_WBITS
  73296. # define DEF_WBITS MAX_WBITS
  73297. #endif
  73298. /* default windowBits for decompression. MAX_WBITS is for compression only */
  73299. #if MAX_MEM_LEVEL >= 8
  73300. # define DEF_MEM_LEVEL 8
  73301. #else
  73302. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  73303. #endif
  73304. /* default memLevel */
  73305. #define STORED_BLOCK 0
  73306. #define STATIC_TREES 1
  73307. #define DYN_TREES 2
  73308. /* The three kinds of block type */
  73309. #define MIN_MATCH 3
  73310. #define MAX_MATCH 258
  73311. /* The minimum and maximum match lengths */
  73312. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  73313. /* target dependencies */
  73314. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  73315. # define OS_CODE 0x00
  73316. # if defined(__TURBOC__) || defined(__BORLANDC__)
  73317. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  73318. /* Allow compilation with ANSI keywords only enabled */
  73319. void _Cdecl farfree( void *block );
  73320. void *_Cdecl farmalloc( unsigned long nbytes );
  73321. # else
  73322. # include <alloc.h>
  73323. # endif
  73324. # else /* MSC or DJGPP */
  73325. # include <malloc.h>
  73326. # endif
  73327. #endif
  73328. #ifdef AMIGA
  73329. # define OS_CODE 0x01
  73330. #endif
  73331. #if defined(VAXC) || defined(VMS)
  73332. # define OS_CODE 0x02
  73333. # define F_OPEN(name, mode) \
  73334. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  73335. #endif
  73336. #if defined(ATARI) || defined(atarist)
  73337. # define OS_CODE 0x05
  73338. #endif
  73339. #ifdef OS2
  73340. # define OS_CODE 0x06
  73341. # ifdef M_I86
  73342. #include <malloc.h>
  73343. # endif
  73344. #endif
  73345. #if defined(MACOS) || TARGET_OS_MAC
  73346. # define OS_CODE 0x07
  73347. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  73348. # include <unix.h> /* for fdopen */
  73349. # else
  73350. # ifndef fdopen
  73351. # define fdopen(fd,mode) NULL /* No fdopen() */
  73352. # endif
  73353. # endif
  73354. #endif
  73355. #ifdef TOPS20
  73356. # define OS_CODE 0x0a
  73357. #endif
  73358. #ifdef WIN32
  73359. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  73360. # define OS_CODE 0x0b
  73361. # endif
  73362. #endif
  73363. #ifdef __50SERIES /* Prime/PRIMOS */
  73364. # define OS_CODE 0x0f
  73365. #endif
  73366. #if defined(_BEOS_) || defined(RISCOS)
  73367. # define fdopen(fd,mode) NULL /* No fdopen() */
  73368. #endif
  73369. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  73370. # if defined(_WIN32_WCE)
  73371. # define fdopen(fd,mode) NULL /* No fdopen() */
  73372. # ifndef _PTRDIFF_T_DEFINED
  73373. typedef int ptrdiff_t;
  73374. # define _PTRDIFF_T_DEFINED
  73375. # endif
  73376. # else
  73377. # define fdopen(fd,type) _fdopen(fd,type)
  73378. # endif
  73379. #endif
  73380. /* common defaults */
  73381. #ifndef OS_CODE
  73382. # define OS_CODE 0x03 /* assume Unix */
  73383. #endif
  73384. #ifndef F_OPEN
  73385. # define F_OPEN(name, mode) fopen((name), (mode))
  73386. #endif
  73387. /* functions */
  73388. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  73389. # ifndef HAVE_VSNPRINTF
  73390. # define HAVE_VSNPRINTF
  73391. # endif
  73392. #endif
  73393. #if defined(__CYGWIN__)
  73394. # ifndef HAVE_VSNPRINTF
  73395. # define HAVE_VSNPRINTF
  73396. # endif
  73397. #endif
  73398. #ifndef HAVE_VSNPRINTF
  73399. # ifdef MSDOS
  73400. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  73401. but for now we just assume it doesn't. */
  73402. # define NO_vsnprintf
  73403. # endif
  73404. # ifdef __TURBOC__
  73405. # define NO_vsnprintf
  73406. # endif
  73407. # ifdef WIN32
  73408. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  73409. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  73410. # define vsnprintf _vsnprintf
  73411. # endif
  73412. # endif
  73413. # ifdef __SASC
  73414. # define NO_vsnprintf
  73415. # endif
  73416. #endif
  73417. #ifdef VMS
  73418. # define NO_vsnprintf
  73419. #endif
  73420. #if defined(pyr)
  73421. # define NO_MEMCPY
  73422. #endif
  73423. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  73424. /* Use our own functions for small and medium model with MSC <= 5.0.
  73425. * You may have to use the same strategy for Borland C (untested).
  73426. * The __SC__ check is for Symantec.
  73427. */
  73428. # define NO_MEMCPY
  73429. #endif
  73430. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  73431. # define HAVE_MEMCPY
  73432. #endif
  73433. #ifdef HAVE_MEMCPY
  73434. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  73435. # define zmemcpy _fmemcpy
  73436. # define zmemcmp _fmemcmp
  73437. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  73438. # else
  73439. # define zmemcpy memcpy
  73440. # define zmemcmp memcmp
  73441. # define zmemzero(dest, len) memset(dest, 0, len)
  73442. # endif
  73443. #else
  73444. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  73445. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  73446. extern void zmemzero OF((Bytef* dest, uInt len));
  73447. #endif
  73448. /* Diagnostic functions */
  73449. #ifdef DEBUG
  73450. # include <stdio.h>
  73451. extern int z_verbose;
  73452. extern void z_error OF((char *m));
  73453. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  73454. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  73455. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  73456. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  73457. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  73458. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  73459. #else
  73460. # define Assert(cond,msg)
  73461. # define Trace(x)
  73462. # define Tracev(x)
  73463. # define Tracevv(x)
  73464. # define Tracec(c,x)
  73465. # define Tracecv(c,x)
  73466. #endif
  73467. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  73468. void zcfree OF((voidpf opaque, voidpf ptr));
  73469. #define ZALLOC(strm, items, size) \
  73470. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  73471. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  73472. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  73473. #endif /* ZUTIL_H */
  73474. /********* End of inlined file: zutil.h *********/
  73475. /* for STDC and FAR definitions */
  73476. #define local static
  73477. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  73478. #ifndef NOBYFOUR
  73479. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  73480. # include <limits.h>
  73481. # define BYFOUR
  73482. # if (UINT_MAX == 0xffffffffUL)
  73483. typedef unsigned int u4;
  73484. # else
  73485. # if (ULONG_MAX == 0xffffffffUL)
  73486. typedef unsigned long u4;
  73487. # else
  73488. # if (USHRT_MAX == 0xffffffffUL)
  73489. typedef unsigned short u4;
  73490. # else
  73491. # undef BYFOUR /* can't find a four-byte integer type! */
  73492. # endif
  73493. # endif
  73494. # endif
  73495. # endif /* STDC */
  73496. #endif /* !NOBYFOUR */
  73497. /* Definitions for doing the crc four data bytes at a time. */
  73498. #ifdef BYFOUR
  73499. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  73500. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  73501. local unsigned long crc32_little OF((unsigned long,
  73502. const unsigned char FAR *, unsigned));
  73503. local unsigned long crc32_big OF((unsigned long,
  73504. const unsigned char FAR *, unsigned));
  73505. # define TBLS 8
  73506. #else
  73507. # define TBLS 1
  73508. #endif /* BYFOUR */
  73509. /* Local functions for crc concatenation */
  73510. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  73511. unsigned long vec));
  73512. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  73513. #ifdef DYNAMIC_CRC_TABLE
  73514. local volatile int crc_table_empty = 1;
  73515. local unsigned long FAR crc_table[TBLS][256];
  73516. local void make_crc_table OF((void));
  73517. #ifdef MAKECRCH
  73518. local void write_table OF((FILE *, const unsigned long FAR *));
  73519. #endif /* MAKECRCH */
  73520. /*
  73521. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  73522. 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.
  73523. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  73524. with the lowest powers in the most significant bit. Then adding polynomials
  73525. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  73526. one. If we call the above polynomial p, and represent a byte as the
  73527. polynomial q, also with the lowest power in the most significant bit (so the
  73528. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  73529. where a mod b means the remainder after dividing a by b.
  73530. This calculation is done using the shift-register method of multiplying and
  73531. taking the remainder. The register is initialized to zero, and for each
  73532. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  73533. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  73534. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  73535. out is a one). We start with the highest power (least significant bit) of
  73536. q and repeat for all eight bits of q.
  73537. The first table is simply the CRC of all possible eight bit values. This is
  73538. all the information needed to generate CRCs on data a byte at a time for all
  73539. combinations of CRC register values and incoming bytes. The remaining tables
  73540. allow for word-at-a-time CRC calculation for both big-endian and little-
  73541. endian machines, where a word is four bytes.
  73542. */
  73543. local void make_crc_table()
  73544. {
  73545. unsigned long c;
  73546. int n, k;
  73547. unsigned long poly; /* polynomial exclusive-or pattern */
  73548. /* terms of polynomial defining this crc (except x^32): */
  73549. static volatile int first = 1; /* flag to limit concurrent making */
  73550. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  73551. /* See if another task is already doing this (not thread-safe, but better
  73552. than nothing -- significantly reduces duration of vulnerability in
  73553. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  73554. if (first) {
  73555. first = 0;
  73556. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  73557. poly = 0UL;
  73558. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  73559. poly |= 1UL << (31 - p[n]);
  73560. /* generate a crc for every 8-bit value */
  73561. for (n = 0; n < 256; n++) {
  73562. c = (unsigned long)n;
  73563. for (k = 0; k < 8; k++)
  73564. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  73565. crc_table[0][n] = c;
  73566. }
  73567. #ifdef BYFOUR
  73568. /* generate crc for each value followed by one, two, and three zeros,
  73569. and then the byte reversal of those as well as the first table */
  73570. for (n = 0; n < 256; n++) {
  73571. c = crc_table[0][n];
  73572. crc_table[4][n] = REV(c);
  73573. for (k = 1; k < 4; k++) {
  73574. c = crc_table[0][c & 0xff] ^ (c >> 8);
  73575. crc_table[k][n] = c;
  73576. crc_table[k + 4][n] = REV(c);
  73577. }
  73578. }
  73579. #endif /* BYFOUR */
  73580. crc_table_empty = 0;
  73581. }
  73582. else { /* not first */
  73583. /* wait for the other guy to finish (not efficient, but rare) */
  73584. while (crc_table_empty)
  73585. ;
  73586. }
  73587. #ifdef MAKECRCH
  73588. /* write out CRC tables to crc32.h */
  73589. {
  73590. FILE *out;
  73591. out = fopen("crc32.h", "w");
  73592. if (out == NULL) return;
  73593. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  73594. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  73595. fprintf(out, "local const unsigned long FAR ");
  73596. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  73597. write_table(out, crc_table[0]);
  73598. # ifdef BYFOUR
  73599. fprintf(out, "#ifdef BYFOUR\n");
  73600. for (k = 1; k < 8; k++) {
  73601. fprintf(out, " },\n {\n");
  73602. write_table(out, crc_table[k]);
  73603. }
  73604. fprintf(out, "#endif\n");
  73605. # endif /* BYFOUR */
  73606. fprintf(out, " }\n};\n");
  73607. fclose(out);
  73608. }
  73609. #endif /* MAKECRCH */
  73610. }
  73611. #ifdef MAKECRCH
  73612. local void write_table(out, table)
  73613. FILE *out;
  73614. const unsigned long FAR *table;
  73615. {
  73616. int n;
  73617. for (n = 0; n < 256; n++)
  73618. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  73619. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  73620. }
  73621. #endif /* MAKECRCH */
  73622. #else /* !DYNAMIC_CRC_TABLE */
  73623. /* ========================================================================
  73624. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  73625. */
  73626. /********* Start of inlined file: crc32.h *********/
  73627. local const unsigned long FAR crc_table[TBLS][256] =
  73628. {
  73629. {
  73630. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  73631. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  73632. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  73633. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  73634. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  73635. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  73636. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  73637. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  73638. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  73639. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  73640. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  73641. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  73642. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  73643. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  73644. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  73645. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  73646. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  73647. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  73648. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  73649. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  73650. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  73651. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  73652. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  73653. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  73654. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  73655. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  73656. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  73657. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  73658. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  73659. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  73660. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  73661. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  73662. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  73663. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  73664. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  73665. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  73666. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  73667. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  73668. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  73669. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  73670. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  73671. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  73672. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  73673. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  73674. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  73675. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  73676. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  73677. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  73678. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  73679. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  73680. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  73681. 0x2d02ef8dUL
  73682. #ifdef BYFOUR
  73683. },
  73684. {
  73685. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  73686. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  73687. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  73688. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  73689. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  73690. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  73691. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  73692. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  73693. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  73694. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  73695. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  73696. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  73697. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  73698. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  73699. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  73700. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  73701. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  73702. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  73703. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  73704. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  73705. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  73706. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  73707. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  73708. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  73709. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  73710. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  73711. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  73712. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  73713. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  73714. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  73715. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  73716. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  73717. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  73718. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  73719. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  73720. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  73721. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  73722. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  73723. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  73724. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  73725. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  73726. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  73727. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  73728. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  73729. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  73730. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  73731. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  73732. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  73733. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  73734. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  73735. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  73736. 0x9324fd72UL
  73737. },
  73738. {
  73739. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  73740. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  73741. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  73742. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  73743. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  73744. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  73745. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  73746. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  73747. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  73748. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  73749. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  73750. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  73751. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  73752. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  73753. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  73754. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  73755. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  73756. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  73757. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  73758. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  73759. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  73760. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  73761. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  73762. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  73763. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  73764. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  73765. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  73766. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  73767. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  73768. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  73769. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  73770. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  73771. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  73772. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  73773. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  73774. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  73775. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  73776. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  73777. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  73778. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  73779. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  73780. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  73781. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  73782. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  73783. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  73784. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  73785. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  73786. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  73787. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  73788. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  73789. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  73790. 0xbe9834edUL
  73791. },
  73792. {
  73793. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  73794. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  73795. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  73796. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  73797. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  73798. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  73799. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  73800. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  73801. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  73802. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  73803. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  73804. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  73805. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  73806. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  73807. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  73808. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  73809. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  73810. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  73811. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  73812. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  73813. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  73814. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  73815. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  73816. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  73817. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  73818. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  73819. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  73820. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  73821. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  73822. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  73823. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  73824. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  73825. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  73826. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  73827. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  73828. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  73829. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  73830. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  73831. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  73832. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  73833. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  73834. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  73835. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  73836. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  73837. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  73838. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  73839. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  73840. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  73841. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  73842. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  73843. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  73844. 0xde0506f1UL
  73845. },
  73846. {
  73847. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  73848. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  73849. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  73850. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  73851. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  73852. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  73853. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  73854. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  73855. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  73856. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  73857. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  73858. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  73859. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  73860. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  73861. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  73862. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  73863. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  73864. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  73865. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  73866. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  73867. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  73868. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  73869. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  73870. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  73871. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  73872. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  73873. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  73874. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  73875. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  73876. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  73877. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  73878. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  73879. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  73880. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  73881. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  73882. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  73883. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  73884. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  73885. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  73886. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  73887. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  73888. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  73889. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  73890. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  73891. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  73892. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  73893. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  73894. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  73895. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  73896. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  73897. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  73898. 0x8def022dUL
  73899. },
  73900. {
  73901. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  73902. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  73903. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  73904. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  73905. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  73906. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  73907. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  73908. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  73909. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  73910. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  73911. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  73912. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  73913. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  73914. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  73915. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  73916. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  73917. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  73918. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  73919. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  73920. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  73921. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  73922. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  73923. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  73924. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  73925. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  73926. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  73927. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  73928. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  73929. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  73930. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  73931. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  73932. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  73933. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  73934. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  73935. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  73936. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  73937. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  73938. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  73939. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  73940. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  73941. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  73942. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  73943. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  73944. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  73945. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  73946. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  73947. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  73948. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  73949. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  73950. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  73951. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  73952. 0x72fd2493UL
  73953. },
  73954. {
  73955. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  73956. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  73957. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  73958. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  73959. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  73960. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  73961. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  73962. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  73963. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  73964. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  73965. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  73966. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  73967. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  73968. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  73969. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  73970. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  73971. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  73972. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  73973. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  73974. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  73975. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  73976. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  73977. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  73978. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  73979. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  73980. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  73981. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  73982. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  73983. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  73984. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  73985. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  73986. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  73987. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  73988. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  73989. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  73990. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  73991. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  73992. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  73993. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  73994. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  73995. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  73996. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  73997. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  73998. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  73999. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  74000. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  74001. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  74002. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  74003. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  74004. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  74005. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  74006. 0xed3498beUL
  74007. },
  74008. {
  74009. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  74010. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  74011. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  74012. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  74013. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  74014. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  74015. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  74016. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  74017. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  74018. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  74019. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  74020. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  74021. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  74022. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  74023. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  74024. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  74025. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  74026. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  74027. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  74028. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  74029. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  74030. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  74031. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  74032. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  74033. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  74034. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  74035. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  74036. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  74037. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  74038. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  74039. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  74040. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  74041. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  74042. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  74043. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  74044. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  74045. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  74046. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  74047. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  74048. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  74049. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  74050. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  74051. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  74052. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  74053. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  74054. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  74055. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  74056. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  74057. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  74058. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  74059. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  74060. 0xf10605deUL
  74061. #endif
  74062. }
  74063. };
  74064. /********* End of inlined file: crc32.h *********/
  74065. #endif /* DYNAMIC_CRC_TABLE */
  74066. /* =========================================================================
  74067. * This function can be used by asm versions of crc32()
  74068. */
  74069. const unsigned long FAR * ZEXPORT get_crc_table()
  74070. {
  74071. #ifdef DYNAMIC_CRC_TABLE
  74072. if (crc_table_empty)
  74073. make_crc_table();
  74074. #endif /* DYNAMIC_CRC_TABLE */
  74075. return (const unsigned long FAR *)crc_table;
  74076. }
  74077. /* ========================================================================= */
  74078. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  74079. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  74080. /* ========================================================================= */
  74081. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  74082. {
  74083. if (buf == Z_NULL) return 0UL;
  74084. #ifdef DYNAMIC_CRC_TABLE
  74085. if (crc_table_empty)
  74086. make_crc_table();
  74087. #endif /* DYNAMIC_CRC_TABLE */
  74088. #ifdef BYFOUR
  74089. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  74090. u4 endian;
  74091. endian = 1;
  74092. if (*((unsigned char *)(&endian)))
  74093. return crc32_little(crc, buf, len);
  74094. else
  74095. return crc32_big(crc, buf, len);
  74096. }
  74097. #endif /* BYFOUR */
  74098. crc = crc ^ 0xffffffffUL;
  74099. while (len >= 8) {
  74100. DO8;
  74101. len -= 8;
  74102. }
  74103. if (len) do {
  74104. DO1;
  74105. } while (--len);
  74106. return crc ^ 0xffffffffUL;
  74107. }
  74108. #ifdef BYFOUR
  74109. /* ========================================================================= */
  74110. #define DOLIT4 c ^= *buf4++; \
  74111. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  74112. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  74113. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  74114. /* ========================================================================= */
  74115. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  74116. {
  74117. register u4 c;
  74118. register const u4 FAR *buf4;
  74119. c = (u4)crc;
  74120. c = ~c;
  74121. while (len && ((ptrdiff_t)buf & 3)) {
  74122. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  74123. len--;
  74124. }
  74125. buf4 = (const u4 FAR *)(const void FAR *)buf;
  74126. while (len >= 32) {
  74127. DOLIT32;
  74128. len -= 32;
  74129. }
  74130. while (len >= 4) {
  74131. DOLIT4;
  74132. len -= 4;
  74133. }
  74134. buf = (const unsigned char FAR *)buf4;
  74135. if (len) do {
  74136. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  74137. } while (--len);
  74138. c = ~c;
  74139. return (unsigned long)c;
  74140. }
  74141. /* ========================================================================= */
  74142. #define DOBIG4 c ^= *++buf4; \
  74143. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  74144. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  74145. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  74146. /* ========================================================================= */
  74147. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  74148. {
  74149. register u4 c;
  74150. register const u4 FAR *buf4;
  74151. c = REV((u4)crc);
  74152. c = ~c;
  74153. while (len && ((ptrdiff_t)buf & 3)) {
  74154. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  74155. len--;
  74156. }
  74157. buf4 = (const u4 FAR *)(const void FAR *)buf;
  74158. buf4--;
  74159. while (len >= 32) {
  74160. DOBIG32;
  74161. len -= 32;
  74162. }
  74163. while (len >= 4) {
  74164. DOBIG4;
  74165. len -= 4;
  74166. }
  74167. buf4++;
  74168. buf = (const unsigned char FAR *)buf4;
  74169. if (len) do {
  74170. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  74171. } while (--len);
  74172. c = ~c;
  74173. return (unsigned long)(REV(c));
  74174. }
  74175. #endif /* BYFOUR */
  74176. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  74177. /* ========================================================================= */
  74178. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  74179. {
  74180. unsigned long sum;
  74181. sum = 0;
  74182. while (vec) {
  74183. if (vec & 1)
  74184. sum ^= *mat;
  74185. vec >>= 1;
  74186. mat++;
  74187. }
  74188. return sum;
  74189. }
  74190. /* ========================================================================= */
  74191. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  74192. {
  74193. int n;
  74194. for (n = 0; n < GF2_DIM; n++)
  74195. square[n] = gf2_matrix_times(mat, mat[n]);
  74196. }
  74197. /* ========================================================================= */
  74198. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  74199. {
  74200. int n;
  74201. unsigned long row;
  74202. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  74203. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  74204. /* degenerate case */
  74205. if (len2 == 0)
  74206. return crc1;
  74207. /* put operator for one zero bit in odd */
  74208. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  74209. row = 1;
  74210. for (n = 1; n < GF2_DIM; n++) {
  74211. odd[n] = row;
  74212. row <<= 1;
  74213. }
  74214. /* put operator for two zero bits in even */
  74215. gf2_matrix_square(even, odd);
  74216. /* put operator for four zero bits in odd */
  74217. gf2_matrix_square(odd, even);
  74218. /* apply len2 zeros to crc1 (first square will put the operator for one
  74219. zero byte, eight zero bits, in even) */
  74220. do {
  74221. /* apply zeros operator for this bit of len2 */
  74222. gf2_matrix_square(even, odd);
  74223. if (len2 & 1)
  74224. crc1 = gf2_matrix_times(even, crc1);
  74225. len2 >>= 1;
  74226. /* if no more bits set, then done */
  74227. if (len2 == 0)
  74228. break;
  74229. /* another iteration of the loop with odd and even swapped */
  74230. gf2_matrix_square(odd, even);
  74231. if (len2 & 1)
  74232. crc1 = gf2_matrix_times(odd, crc1);
  74233. len2 >>= 1;
  74234. /* if no more bits set, then done */
  74235. } while (len2 != 0);
  74236. /* return combined crc */
  74237. crc1 ^= crc2;
  74238. return crc1;
  74239. }
  74240. /********* End of inlined file: crc32.c *********/
  74241. /********* Start of inlined file: deflate.c *********/
  74242. /*
  74243. * ALGORITHM
  74244. *
  74245. * The "deflation" process depends on being able to identify portions
  74246. * of the input text which are identical to earlier input (within a
  74247. * sliding window trailing behind the input currently being processed).
  74248. *
  74249. * The most straightforward technique turns out to be the fastest for
  74250. * most input files: try all possible matches and select the longest.
  74251. * The key feature of this algorithm is that insertions into the string
  74252. * dictionary are very simple and thus fast, and deletions are avoided
  74253. * completely. Insertions are performed at each input character, whereas
  74254. * string matches are performed only when the previous match ends. So it
  74255. * is preferable to spend more time in matches to allow very fast string
  74256. * insertions and avoid deletions. The matching algorithm for small
  74257. * strings is inspired from that of Rabin & Karp. A brute force approach
  74258. * is used to find longer strings when a small match has been found.
  74259. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  74260. * (by Leonid Broukhis).
  74261. * A previous version of this file used a more sophisticated algorithm
  74262. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  74263. * time, but has a larger average cost, uses more memory and is patented.
  74264. * However the F&G algorithm may be faster for some highly redundant
  74265. * files if the parameter max_chain_length (described below) is too large.
  74266. *
  74267. * ACKNOWLEDGEMENTS
  74268. *
  74269. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  74270. * I found it in 'freeze' written by Leonid Broukhis.
  74271. * Thanks to many people for bug reports and testing.
  74272. *
  74273. * REFERENCES
  74274. *
  74275. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  74276. * Available in http://www.ietf.org/rfc/rfc1951.txt
  74277. *
  74278. * A description of the Rabin and Karp algorithm is given in the book
  74279. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  74280. *
  74281. * Fiala,E.R., and Greene,D.H.
  74282. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  74283. *
  74284. */
  74285. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74286. /********* Start of inlined file: deflate.h *********/
  74287. /* WARNING: this file should *not* be used by applications. It is
  74288. part of the implementation of the compression library and is
  74289. subject to change. Applications should only use zlib.h.
  74290. */
  74291. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74292. #ifndef DEFLATE_H
  74293. #define DEFLATE_H
  74294. /* define NO_GZIP when compiling if you want to disable gzip header and
  74295. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  74296. the crc code when it is not needed. For shared libraries, gzip encoding
  74297. should be left enabled. */
  74298. #ifndef NO_GZIP
  74299. # define GZIP
  74300. #endif
  74301. #define NO_DUMMY_DECL
  74302. /* ===========================================================================
  74303. * Internal compression state.
  74304. */
  74305. #define LENGTH_CODES 29
  74306. /* number of length codes, not counting the special END_BLOCK code */
  74307. #define LITERALS 256
  74308. /* number of literal bytes 0..255 */
  74309. #define L_CODES (LITERALS+1+LENGTH_CODES)
  74310. /* number of Literal or Length codes, including the END_BLOCK code */
  74311. #define D_CODES 30
  74312. /* number of distance codes */
  74313. #define BL_CODES 19
  74314. /* number of codes used to transfer the bit lengths */
  74315. #define HEAP_SIZE (2*L_CODES+1)
  74316. /* maximum heap size */
  74317. #define MAX_BITS 15
  74318. /* All codes must not exceed MAX_BITS bits */
  74319. #define INIT_STATE 42
  74320. #define EXTRA_STATE 69
  74321. #define NAME_STATE 73
  74322. #define COMMENT_STATE 91
  74323. #define HCRC_STATE 103
  74324. #define BUSY_STATE 113
  74325. #define FINISH_STATE 666
  74326. /* Stream status */
  74327. /* Data structure describing a single value and its code string. */
  74328. typedef struct ct_data_s {
  74329. union {
  74330. ush freq; /* frequency count */
  74331. ush code; /* bit string */
  74332. } fc;
  74333. union {
  74334. ush dad; /* father node in Huffman tree */
  74335. ush len; /* length of bit string */
  74336. } dl;
  74337. } FAR ct_data;
  74338. #define Freq fc.freq
  74339. #define Code fc.code
  74340. #define Dad dl.dad
  74341. #define Len dl.len
  74342. typedef struct static_tree_desc_s static_tree_desc;
  74343. typedef struct tree_desc_s {
  74344. ct_data *dyn_tree; /* the dynamic tree */
  74345. int max_code; /* largest code with non zero frequency */
  74346. static_tree_desc *stat_desc; /* the corresponding static tree */
  74347. } FAR tree_desc;
  74348. typedef ush Pos;
  74349. typedef Pos FAR Posf;
  74350. typedef unsigned IPos;
  74351. /* A Pos is an index in the character window. We use short instead of int to
  74352. * save space in the various tables. IPos is used only for parameter passing.
  74353. */
  74354. typedef struct internal_state {
  74355. z_streamp strm; /* pointer back to this zlib stream */
  74356. int status; /* as the name implies */
  74357. Bytef *pending_buf; /* output still pending */
  74358. ulg pending_buf_size; /* size of pending_buf */
  74359. Bytef *pending_out; /* next pending byte to output to the stream */
  74360. uInt pending; /* nb of bytes in the pending buffer */
  74361. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  74362. gz_headerp gzhead; /* gzip header information to write */
  74363. uInt gzindex; /* where in extra, name, or comment */
  74364. Byte method; /* STORED (for zip only) or DEFLATED */
  74365. int last_flush; /* value of flush param for previous deflate call */
  74366. /* used by deflate.c: */
  74367. uInt w_size; /* LZ77 window size (32K by default) */
  74368. uInt w_bits; /* log2(w_size) (8..16) */
  74369. uInt w_mask; /* w_size - 1 */
  74370. Bytef *window;
  74371. /* Sliding window. Input bytes are read into the second half of the window,
  74372. * and move to the first half later to keep a dictionary of at least wSize
  74373. * bytes. With this organization, matches are limited to a distance of
  74374. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  74375. * performed with a length multiple of the block size. Also, it limits
  74376. * the window size to 64K, which is quite useful on MSDOS.
  74377. * To do: use the user input buffer as sliding window.
  74378. */
  74379. ulg window_size;
  74380. /* Actual size of window: 2*wSize, except when the user input buffer
  74381. * is directly used as sliding window.
  74382. */
  74383. Posf *prev;
  74384. /* Link to older string with same hash index. To limit the size of this
  74385. * array to 64K, this link is maintained only for the last 32K strings.
  74386. * An index in this array is thus a window index modulo 32K.
  74387. */
  74388. Posf *head; /* Heads of the hash chains or NIL. */
  74389. uInt ins_h; /* hash index of string to be inserted */
  74390. uInt hash_size; /* number of elements in hash table */
  74391. uInt hash_bits; /* log2(hash_size) */
  74392. uInt hash_mask; /* hash_size-1 */
  74393. uInt hash_shift;
  74394. /* Number of bits by which ins_h must be shifted at each input
  74395. * step. It must be such that after MIN_MATCH steps, the oldest
  74396. * byte no longer takes part in the hash key, that is:
  74397. * hash_shift * MIN_MATCH >= hash_bits
  74398. */
  74399. long block_start;
  74400. /* Window position at the beginning of the current output block. Gets
  74401. * negative when the window is moved backwards.
  74402. */
  74403. uInt match_length; /* length of best match */
  74404. IPos prev_match; /* previous match */
  74405. int match_available; /* set if previous match exists */
  74406. uInt strstart; /* start of string to insert */
  74407. uInt match_start; /* start of matching string */
  74408. uInt lookahead; /* number of valid bytes ahead in window */
  74409. uInt prev_length;
  74410. /* Length of the best match at previous step. Matches not greater than this
  74411. * are discarded. This is used in the lazy match evaluation.
  74412. */
  74413. uInt max_chain_length;
  74414. /* To speed up deflation, hash chains are never searched beyond this
  74415. * length. A higher limit improves compression ratio but degrades the
  74416. * speed.
  74417. */
  74418. uInt max_lazy_match;
  74419. /* Attempt to find a better match only when the current match is strictly
  74420. * smaller than this value. This mechanism is used only for compression
  74421. * levels >= 4.
  74422. */
  74423. # define max_insert_length max_lazy_match
  74424. /* Insert new strings in the hash table only if the match length is not
  74425. * greater than this length. This saves time but degrades compression.
  74426. * max_insert_length is used only for compression levels <= 3.
  74427. */
  74428. int level; /* compression level (1..9) */
  74429. int strategy; /* favor or force Huffman coding*/
  74430. uInt good_match;
  74431. /* Use a faster search when the previous match is longer than this */
  74432. int nice_match; /* Stop searching when current match exceeds this */
  74433. /* used by trees.c: */
  74434. /* Didn't use ct_data typedef below to supress compiler warning */
  74435. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  74436. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  74437. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  74438. struct tree_desc_s l_desc; /* desc. for literal tree */
  74439. struct tree_desc_s d_desc; /* desc. for distance tree */
  74440. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  74441. ush bl_count[MAX_BITS+1];
  74442. /* number of codes at each bit length for an optimal tree */
  74443. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  74444. int heap_len; /* number of elements in the heap */
  74445. int heap_max; /* element of largest frequency */
  74446. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  74447. * The same heap array is used to build all trees.
  74448. */
  74449. uch depth[2*L_CODES+1];
  74450. /* Depth of each subtree used as tie breaker for trees of equal frequency
  74451. */
  74452. uchf *l_buf; /* buffer for literals or lengths */
  74453. uInt lit_bufsize;
  74454. /* Size of match buffer for literals/lengths. There are 4 reasons for
  74455. * limiting lit_bufsize to 64K:
  74456. * - frequencies can be kept in 16 bit counters
  74457. * - if compression is not successful for the first block, all input
  74458. * data is still in the window so we can still emit a stored block even
  74459. * when input comes from standard input. (This can also be done for
  74460. * all blocks if lit_bufsize is not greater than 32K.)
  74461. * - if compression is not successful for a file smaller than 64K, we can
  74462. * even emit a stored file instead of a stored block (saving 5 bytes).
  74463. * This is applicable only for zip (not gzip or zlib).
  74464. * - creating new Huffman trees less frequently may not provide fast
  74465. * adaptation to changes in the input data statistics. (Take for
  74466. * example a binary file with poorly compressible code followed by
  74467. * a highly compressible string table.) Smaller buffer sizes give
  74468. * fast adaptation but have of course the overhead of transmitting
  74469. * trees more frequently.
  74470. * - I can't count above 4
  74471. */
  74472. uInt last_lit; /* running index in l_buf */
  74473. ushf *d_buf;
  74474. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  74475. * the same number of elements. To use different lengths, an extra flag
  74476. * array would be necessary.
  74477. */
  74478. ulg opt_len; /* bit length of current block with optimal trees */
  74479. ulg static_len; /* bit length of current block with static trees */
  74480. uInt matches; /* number of string matches in current block */
  74481. int last_eob_len; /* bit length of EOB code for last block */
  74482. #ifdef DEBUG
  74483. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  74484. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  74485. #endif
  74486. ush bi_buf;
  74487. /* Output buffer. bits are inserted starting at the bottom (least
  74488. * significant bits).
  74489. */
  74490. int bi_valid;
  74491. /* Number of valid bits in bi_buf. All bits above the last valid bit
  74492. * are always zero.
  74493. */
  74494. } FAR deflate_state;
  74495. /* Output a byte on the stream.
  74496. * IN assertion: there is enough room in pending_buf.
  74497. */
  74498. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  74499. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  74500. /* Minimum amount of lookahead, except at the end of the input file.
  74501. * See deflate.c for comments about the MIN_MATCH+1.
  74502. */
  74503. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  74504. /* In order to simplify the code, particularly on 16 bit machines, match
  74505. * distances are limited to MAX_DIST instead of WSIZE.
  74506. */
  74507. /* in trees.c */
  74508. void _tr_init OF((deflate_state *s));
  74509. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  74510. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  74511. int eof));
  74512. void _tr_align OF((deflate_state *s));
  74513. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  74514. int eof));
  74515. #define d_code(dist) \
  74516. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  74517. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  74518. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  74519. * used.
  74520. */
  74521. #ifndef DEBUG
  74522. /* Inline versions of _tr_tally for speed: */
  74523. #if defined(GEN_TREES_H) || !defined(STDC)
  74524. extern uch _length_code[];
  74525. extern uch _dist_code[];
  74526. #else
  74527. extern const uch _length_code[];
  74528. extern const uch _dist_code[];
  74529. #endif
  74530. # define _tr_tally_lit(s, c, flush) \
  74531. { uch cc = (c); \
  74532. s->d_buf[s->last_lit] = 0; \
  74533. s->l_buf[s->last_lit++] = cc; \
  74534. s->dyn_ltree[cc].Freq++; \
  74535. flush = (s->last_lit == s->lit_bufsize-1); \
  74536. }
  74537. # define _tr_tally_dist(s, distance, length, flush) \
  74538. { uch len = (length); \
  74539. ush dist = (distance); \
  74540. s->d_buf[s->last_lit] = dist; \
  74541. s->l_buf[s->last_lit++] = len; \
  74542. dist--; \
  74543. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  74544. s->dyn_dtree[d_code(dist)].Freq++; \
  74545. flush = (s->last_lit == s->lit_bufsize-1); \
  74546. }
  74547. #else
  74548. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  74549. # define _tr_tally_dist(s, distance, length, flush) \
  74550. flush = _tr_tally(s, distance, length)
  74551. #endif
  74552. #endif /* DEFLATE_H */
  74553. /********* End of inlined file: deflate.h *********/
  74554. const char deflate_copyright[] =
  74555. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  74556. /*
  74557. If you use the zlib library in a product, an acknowledgment is welcome
  74558. in the documentation of your product. If for some reason you cannot
  74559. include such an acknowledgment, I would appreciate that you keep this
  74560. copyright string in the executable of your product.
  74561. */
  74562. /* ===========================================================================
  74563. * Function prototypes.
  74564. */
  74565. typedef enum {
  74566. need_more, /* block not completed, need more input or more output */
  74567. block_done, /* block flush performed */
  74568. finish_started, /* finish started, need only more output at next deflate */
  74569. finish_done /* finish done, accept no more input or output */
  74570. } block_state;
  74571. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  74572. /* Compression function. Returns the block state after the call. */
  74573. local void fill_window OF((deflate_state *s));
  74574. local block_state deflate_stored OF((deflate_state *s, int flush));
  74575. local block_state deflate_fast OF((deflate_state *s, int flush));
  74576. #ifndef FASTEST
  74577. local block_state deflate_slow OF((deflate_state *s, int flush));
  74578. #endif
  74579. local void lm_init OF((deflate_state *s));
  74580. local void putShortMSB OF((deflate_state *s, uInt b));
  74581. local void flush_pending OF((z_streamp strm));
  74582. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  74583. #ifndef FASTEST
  74584. #ifdef ASMV
  74585. void match_init OF((void)); /* asm code initialization */
  74586. uInt longest_match OF((deflate_state *s, IPos cur_match));
  74587. #else
  74588. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  74589. #endif
  74590. #endif
  74591. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  74592. #ifdef DEBUG
  74593. local void check_match OF((deflate_state *s, IPos start, IPos match,
  74594. int length));
  74595. #endif
  74596. /* ===========================================================================
  74597. * Local data
  74598. */
  74599. #define NIL 0
  74600. /* Tail of hash chains */
  74601. #ifndef TOO_FAR
  74602. # define TOO_FAR 4096
  74603. #endif
  74604. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  74605. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  74606. /* Minimum amount of lookahead, except at the end of the input file.
  74607. * See deflate.c for comments about the MIN_MATCH+1.
  74608. */
  74609. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  74610. * the desired pack level (0..9). The values given below have been tuned to
  74611. * exclude worst case performance for pathological files. Better values may be
  74612. * found for specific files.
  74613. */
  74614. typedef struct config_s {
  74615. ush good_length; /* reduce lazy search above this match length */
  74616. ush max_lazy; /* do not perform lazy search above this match length */
  74617. ush nice_length; /* quit search above this match length */
  74618. ush max_chain;
  74619. compress_func func;
  74620. } config;
  74621. #ifdef FASTEST
  74622. local const config configuration_table[2] = {
  74623. /* good lazy nice chain */
  74624. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  74625. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  74626. #else
  74627. local const config configuration_table[10] = {
  74628. /* good lazy nice chain */
  74629. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  74630. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  74631. /* 2 */ {4, 5, 16, 8, deflate_fast},
  74632. /* 3 */ {4, 6, 32, 32, deflate_fast},
  74633. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  74634. /* 5 */ {8, 16, 32, 32, deflate_slow},
  74635. /* 6 */ {8, 16, 128, 128, deflate_slow},
  74636. /* 7 */ {8, 32, 128, 256, deflate_slow},
  74637. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  74638. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  74639. #endif
  74640. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  74641. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  74642. * meaning.
  74643. */
  74644. #define EQUAL 0
  74645. /* result of memcmp for equal strings */
  74646. #ifndef NO_DUMMY_DECL
  74647. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  74648. #endif
  74649. /* ===========================================================================
  74650. * Update a hash value with the given input byte
  74651. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  74652. * input characters, so that a running hash key can be computed from the
  74653. * previous key instead of complete recalculation each time.
  74654. */
  74655. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  74656. /* ===========================================================================
  74657. * Insert string str in the dictionary and set match_head to the previous head
  74658. * of the hash chain (the most recent string with same hash key). Return
  74659. * the previous length of the hash chain.
  74660. * If this file is compiled with -DFASTEST, the compression level is forced
  74661. * to 1, and no hash chains are maintained.
  74662. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  74663. * input characters and the first MIN_MATCH bytes of str are valid
  74664. * (except for the last MIN_MATCH-1 bytes of the input file).
  74665. */
  74666. #ifdef FASTEST
  74667. #define INSERT_STRING(s, str, match_head) \
  74668. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  74669. match_head = s->head[s->ins_h], \
  74670. s->head[s->ins_h] = (Pos)(str))
  74671. #else
  74672. #define INSERT_STRING(s, str, match_head) \
  74673. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  74674. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  74675. s->head[s->ins_h] = (Pos)(str))
  74676. #endif
  74677. /* ===========================================================================
  74678. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  74679. * prev[] will be initialized on the fly.
  74680. */
  74681. #define CLEAR_HASH(s) \
  74682. s->head[s->hash_size-1] = NIL; \
  74683. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  74684. /* ========================================================================= */
  74685. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  74686. {
  74687. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  74688. Z_DEFAULT_STRATEGY, version, stream_size);
  74689. /* To do: ignore strm->next_in if we use it as window */
  74690. }
  74691. /* ========================================================================= */
  74692. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  74693. {
  74694. deflate_state *s;
  74695. int wrap = 1;
  74696. static const char my_version[] = ZLIB_VERSION;
  74697. ushf *overlay;
  74698. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  74699. * output size for (length,distance) codes is <= 24 bits.
  74700. */
  74701. if (version == Z_NULL || version[0] != my_version[0] ||
  74702. stream_size != sizeof(z_stream)) {
  74703. return Z_VERSION_ERROR;
  74704. }
  74705. if (strm == Z_NULL) return Z_STREAM_ERROR;
  74706. strm->msg = Z_NULL;
  74707. if (strm->zalloc == (alloc_func)0) {
  74708. strm->zalloc = zcalloc;
  74709. strm->opaque = (voidpf)0;
  74710. }
  74711. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  74712. #ifdef FASTEST
  74713. if (level != 0) level = 1;
  74714. #else
  74715. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  74716. #endif
  74717. if (windowBits < 0) { /* suppress zlib wrapper */
  74718. wrap = 0;
  74719. windowBits = -windowBits;
  74720. }
  74721. #ifdef GZIP
  74722. else if (windowBits > 15) {
  74723. wrap = 2; /* write gzip wrapper instead */
  74724. windowBits -= 16;
  74725. }
  74726. #endif
  74727. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  74728. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  74729. strategy < 0 || strategy > Z_FIXED) {
  74730. return Z_STREAM_ERROR;
  74731. }
  74732. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  74733. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  74734. if (s == Z_NULL) return Z_MEM_ERROR;
  74735. strm->state = (struct internal_state FAR *)s;
  74736. s->strm = strm;
  74737. s->wrap = wrap;
  74738. s->gzhead = Z_NULL;
  74739. s->w_bits = windowBits;
  74740. s->w_size = 1 << s->w_bits;
  74741. s->w_mask = s->w_size - 1;
  74742. s->hash_bits = memLevel + 7;
  74743. s->hash_size = 1 << s->hash_bits;
  74744. s->hash_mask = s->hash_size - 1;
  74745. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  74746. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  74747. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  74748. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  74749. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  74750. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  74751. s->pending_buf = (uchf *) overlay;
  74752. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  74753. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  74754. s->pending_buf == Z_NULL) {
  74755. s->status = FINISH_STATE;
  74756. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  74757. deflateEnd (strm);
  74758. return Z_MEM_ERROR;
  74759. }
  74760. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  74761. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  74762. s->level = level;
  74763. s->strategy = strategy;
  74764. s->method = (Byte)method;
  74765. return deflateReset(strm);
  74766. }
  74767. /* ========================================================================= */
  74768. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  74769. {
  74770. deflate_state *s;
  74771. uInt length = dictLength;
  74772. uInt n;
  74773. IPos hash_head = 0;
  74774. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  74775. strm->state->wrap == 2 ||
  74776. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  74777. return Z_STREAM_ERROR;
  74778. s = strm->state;
  74779. if (s->wrap)
  74780. strm->adler = adler32(strm->adler, dictionary, dictLength);
  74781. if (length < MIN_MATCH) return Z_OK;
  74782. if (length > MAX_DIST(s)) {
  74783. length = MAX_DIST(s);
  74784. dictionary += dictLength - length; /* use the tail of the dictionary */
  74785. }
  74786. zmemcpy(s->window, dictionary, length);
  74787. s->strstart = length;
  74788. s->block_start = (long)length;
  74789. /* Insert all strings in the hash table (except for the last two bytes).
  74790. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  74791. * call of fill_window.
  74792. */
  74793. s->ins_h = s->window[0];
  74794. UPDATE_HASH(s, s->ins_h, s->window[1]);
  74795. for (n = 0; n <= length - MIN_MATCH; n++) {
  74796. INSERT_STRING(s, n, hash_head);
  74797. }
  74798. if (hash_head) hash_head = 0; /* to make compiler happy */
  74799. return Z_OK;
  74800. }
  74801. /* ========================================================================= */
  74802. int ZEXPORT deflateReset (z_streamp strm)
  74803. {
  74804. deflate_state *s;
  74805. if (strm == Z_NULL || strm->state == Z_NULL ||
  74806. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  74807. return Z_STREAM_ERROR;
  74808. }
  74809. strm->total_in = strm->total_out = 0;
  74810. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  74811. strm->data_type = Z_UNKNOWN;
  74812. s = (deflate_state *)strm->state;
  74813. s->pending = 0;
  74814. s->pending_out = s->pending_buf;
  74815. if (s->wrap < 0) {
  74816. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  74817. }
  74818. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  74819. strm->adler =
  74820. #ifdef GZIP
  74821. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  74822. #endif
  74823. adler32(0L, Z_NULL, 0);
  74824. s->last_flush = Z_NO_FLUSH;
  74825. _tr_init(s);
  74826. lm_init(s);
  74827. return Z_OK;
  74828. }
  74829. /* ========================================================================= */
  74830. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  74831. {
  74832. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74833. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  74834. strm->state->gzhead = head;
  74835. return Z_OK;
  74836. }
  74837. /* ========================================================================= */
  74838. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  74839. {
  74840. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74841. strm->state->bi_valid = bits;
  74842. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  74843. return Z_OK;
  74844. }
  74845. /* ========================================================================= */
  74846. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  74847. {
  74848. deflate_state *s;
  74849. compress_func func;
  74850. int err = Z_OK;
  74851. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74852. s = strm->state;
  74853. #ifdef FASTEST
  74854. if (level != 0) level = 1;
  74855. #else
  74856. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  74857. #endif
  74858. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  74859. return Z_STREAM_ERROR;
  74860. }
  74861. func = configuration_table[s->level].func;
  74862. if (func != configuration_table[level].func && strm->total_in != 0) {
  74863. /* Flush the last buffer: */
  74864. err = deflate(strm, Z_PARTIAL_FLUSH);
  74865. }
  74866. if (s->level != level) {
  74867. s->level = level;
  74868. s->max_lazy_match = configuration_table[level].max_lazy;
  74869. s->good_match = configuration_table[level].good_length;
  74870. s->nice_match = configuration_table[level].nice_length;
  74871. s->max_chain_length = configuration_table[level].max_chain;
  74872. }
  74873. s->strategy = strategy;
  74874. return err;
  74875. }
  74876. /* ========================================================================= */
  74877. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  74878. {
  74879. deflate_state *s;
  74880. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74881. s = strm->state;
  74882. s->good_match = good_length;
  74883. s->max_lazy_match = max_lazy;
  74884. s->nice_match = nice_length;
  74885. s->max_chain_length = max_chain;
  74886. return Z_OK;
  74887. }
  74888. /* =========================================================================
  74889. * For the default windowBits of 15 and memLevel of 8, this function returns
  74890. * a close to exact, as well as small, upper bound on the compressed size.
  74891. * They are coded as constants here for a reason--if the #define's are
  74892. * changed, then this function needs to be changed as well. The return
  74893. * value for 15 and 8 only works for those exact settings.
  74894. *
  74895. * For any setting other than those defaults for windowBits and memLevel,
  74896. * the value returned is a conservative worst case for the maximum expansion
  74897. * resulting from using fixed blocks instead of stored blocks, which deflate
  74898. * can emit on compressed data for some combinations of the parameters.
  74899. *
  74900. * This function could be more sophisticated to provide closer upper bounds
  74901. * for every combination of windowBits and memLevel, as well as wrap.
  74902. * But even the conservative upper bound of about 14% expansion does not
  74903. * seem onerous for output buffer allocation.
  74904. */
  74905. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  74906. {
  74907. deflate_state *s;
  74908. uLong destLen;
  74909. /* conservative upper bound */
  74910. destLen = sourceLen +
  74911. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  74912. /* if can't get parameters, return conservative bound */
  74913. if (strm == Z_NULL || strm->state == Z_NULL)
  74914. return destLen;
  74915. /* if not default parameters, return conservative bound */
  74916. s = strm->state;
  74917. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  74918. return destLen;
  74919. /* default settings: return tight bound for that case */
  74920. return compressBound(sourceLen);
  74921. }
  74922. /* =========================================================================
  74923. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  74924. * IN assertion: the stream state is correct and there is enough room in
  74925. * pending_buf.
  74926. */
  74927. local void putShortMSB (deflate_state *s, uInt b)
  74928. {
  74929. put_byte(s, (Byte)(b >> 8));
  74930. put_byte(s, (Byte)(b & 0xff));
  74931. }
  74932. /* =========================================================================
  74933. * Flush as much pending output as possible. All deflate() output goes
  74934. * through this function so some applications may wish to modify it
  74935. * to avoid allocating a large strm->next_out buffer and copying into it.
  74936. * (See also read_buf()).
  74937. */
  74938. local void flush_pending (z_streamp strm)
  74939. {
  74940. unsigned len = strm->state->pending;
  74941. if (len > strm->avail_out) len = strm->avail_out;
  74942. if (len == 0) return;
  74943. zmemcpy(strm->next_out, strm->state->pending_out, len);
  74944. strm->next_out += len;
  74945. strm->state->pending_out += len;
  74946. strm->total_out += len;
  74947. strm->avail_out -= len;
  74948. strm->state->pending -= len;
  74949. if (strm->state->pending == 0) {
  74950. strm->state->pending_out = strm->state->pending_buf;
  74951. }
  74952. }
  74953. /* ========================================================================= */
  74954. int ZEXPORT deflate (z_streamp strm, int flush)
  74955. {
  74956. int old_flush; /* value of flush param for previous deflate call */
  74957. deflate_state *s;
  74958. if (strm == Z_NULL || strm->state == Z_NULL ||
  74959. flush > Z_FINISH || flush < 0) {
  74960. return Z_STREAM_ERROR;
  74961. }
  74962. s = strm->state;
  74963. if (strm->next_out == Z_NULL ||
  74964. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  74965. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  74966. ERR_RETURN(strm, Z_STREAM_ERROR);
  74967. }
  74968. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  74969. s->strm = strm; /* just in case */
  74970. old_flush = s->last_flush;
  74971. s->last_flush = flush;
  74972. /* Write the header */
  74973. if (s->status == INIT_STATE) {
  74974. #ifdef GZIP
  74975. if (s->wrap == 2) {
  74976. strm->adler = crc32(0L, Z_NULL, 0);
  74977. put_byte(s, 31);
  74978. put_byte(s, 139);
  74979. put_byte(s, 8);
  74980. if (s->gzhead == NULL) {
  74981. put_byte(s, 0);
  74982. put_byte(s, 0);
  74983. put_byte(s, 0);
  74984. put_byte(s, 0);
  74985. put_byte(s, 0);
  74986. put_byte(s, s->level == 9 ? 2 :
  74987. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  74988. 4 : 0));
  74989. put_byte(s, OS_CODE);
  74990. s->status = BUSY_STATE;
  74991. }
  74992. else {
  74993. put_byte(s, (s->gzhead->text ? 1 : 0) +
  74994. (s->gzhead->hcrc ? 2 : 0) +
  74995. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  74996. (s->gzhead->name == Z_NULL ? 0 : 8) +
  74997. (s->gzhead->comment == Z_NULL ? 0 : 16)
  74998. );
  74999. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  75000. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  75001. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  75002. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  75003. put_byte(s, s->level == 9 ? 2 :
  75004. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  75005. 4 : 0));
  75006. put_byte(s, s->gzhead->os & 0xff);
  75007. if (s->gzhead->extra != NULL) {
  75008. put_byte(s, s->gzhead->extra_len & 0xff);
  75009. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  75010. }
  75011. if (s->gzhead->hcrc)
  75012. strm->adler = crc32(strm->adler, s->pending_buf,
  75013. s->pending);
  75014. s->gzindex = 0;
  75015. s->status = EXTRA_STATE;
  75016. }
  75017. }
  75018. else
  75019. #endif
  75020. {
  75021. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  75022. uInt level_flags;
  75023. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  75024. level_flags = 0;
  75025. else if (s->level < 6)
  75026. level_flags = 1;
  75027. else if (s->level == 6)
  75028. level_flags = 2;
  75029. else
  75030. level_flags = 3;
  75031. header |= (level_flags << 6);
  75032. if (s->strstart != 0) header |= PRESET_DICT;
  75033. header += 31 - (header % 31);
  75034. s->status = BUSY_STATE;
  75035. putShortMSB(s, header);
  75036. /* Save the adler32 of the preset dictionary: */
  75037. if (s->strstart != 0) {
  75038. putShortMSB(s, (uInt)(strm->adler >> 16));
  75039. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  75040. }
  75041. strm->adler = adler32(0L, Z_NULL, 0);
  75042. }
  75043. }
  75044. #ifdef GZIP
  75045. if (s->status == EXTRA_STATE) {
  75046. if (s->gzhead->extra != NULL) {
  75047. uInt beg = s->pending; /* start of bytes to update crc */
  75048. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  75049. if (s->pending == s->pending_buf_size) {
  75050. if (s->gzhead->hcrc && s->pending > beg)
  75051. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75052. s->pending - beg);
  75053. flush_pending(strm);
  75054. beg = s->pending;
  75055. if (s->pending == s->pending_buf_size)
  75056. break;
  75057. }
  75058. put_byte(s, s->gzhead->extra[s->gzindex]);
  75059. s->gzindex++;
  75060. }
  75061. if (s->gzhead->hcrc && s->pending > beg)
  75062. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75063. s->pending - beg);
  75064. if (s->gzindex == s->gzhead->extra_len) {
  75065. s->gzindex = 0;
  75066. s->status = NAME_STATE;
  75067. }
  75068. }
  75069. else
  75070. s->status = NAME_STATE;
  75071. }
  75072. if (s->status == NAME_STATE) {
  75073. if (s->gzhead->name != NULL) {
  75074. uInt beg = s->pending; /* start of bytes to update crc */
  75075. int val;
  75076. do {
  75077. if (s->pending == s->pending_buf_size) {
  75078. if (s->gzhead->hcrc && s->pending > beg)
  75079. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75080. s->pending - beg);
  75081. flush_pending(strm);
  75082. beg = s->pending;
  75083. if (s->pending == s->pending_buf_size) {
  75084. val = 1;
  75085. break;
  75086. }
  75087. }
  75088. val = s->gzhead->name[s->gzindex++];
  75089. put_byte(s, val);
  75090. } while (val != 0);
  75091. if (s->gzhead->hcrc && s->pending > beg)
  75092. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75093. s->pending - beg);
  75094. if (val == 0) {
  75095. s->gzindex = 0;
  75096. s->status = COMMENT_STATE;
  75097. }
  75098. }
  75099. else
  75100. s->status = COMMENT_STATE;
  75101. }
  75102. if (s->status == COMMENT_STATE) {
  75103. if (s->gzhead->comment != NULL) {
  75104. uInt beg = s->pending; /* start of bytes to update crc */
  75105. int val;
  75106. do {
  75107. if (s->pending == s->pending_buf_size) {
  75108. if (s->gzhead->hcrc && s->pending > beg)
  75109. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75110. s->pending - beg);
  75111. flush_pending(strm);
  75112. beg = s->pending;
  75113. if (s->pending == s->pending_buf_size) {
  75114. val = 1;
  75115. break;
  75116. }
  75117. }
  75118. val = s->gzhead->comment[s->gzindex++];
  75119. put_byte(s, val);
  75120. } while (val != 0);
  75121. if (s->gzhead->hcrc && s->pending > beg)
  75122. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75123. s->pending - beg);
  75124. if (val == 0)
  75125. s->status = HCRC_STATE;
  75126. }
  75127. else
  75128. s->status = HCRC_STATE;
  75129. }
  75130. if (s->status == HCRC_STATE) {
  75131. if (s->gzhead->hcrc) {
  75132. if (s->pending + 2 > s->pending_buf_size)
  75133. flush_pending(strm);
  75134. if (s->pending + 2 <= s->pending_buf_size) {
  75135. put_byte(s, (Byte)(strm->adler & 0xff));
  75136. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  75137. strm->adler = crc32(0L, Z_NULL, 0);
  75138. s->status = BUSY_STATE;
  75139. }
  75140. }
  75141. else
  75142. s->status = BUSY_STATE;
  75143. }
  75144. #endif
  75145. /* Flush as much pending output as possible */
  75146. if (s->pending != 0) {
  75147. flush_pending(strm);
  75148. if (strm->avail_out == 0) {
  75149. /* Since avail_out is 0, deflate will be called again with
  75150. * more output space, but possibly with both pending and
  75151. * avail_in equal to zero. There won't be anything to do,
  75152. * but this is not an error situation so make sure we
  75153. * return OK instead of BUF_ERROR at next call of deflate:
  75154. */
  75155. s->last_flush = -1;
  75156. return Z_OK;
  75157. }
  75158. /* Make sure there is something to do and avoid duplicate consecutive
  75159. * flushes. For repeated and useless calls with Z_FINISH, we keep
  75160. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  75161. */
  75162. } else if (strm->avail_in == 0 && flush <= old_flush &&
  75163. flush != Z_FINISH) {
  75164. ERR_RETURN(strm, Z_BUF_ERROR);
  75165. }
  75166. /* User must not provide more input after the first FINISH: */
  75167. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  75168. ERR_RETURN(strm, Z_BUF_ERROR);
  75169. }
  75170. /* Start a new block or continue the current one.
  75171. */
  75172. if (strm->avail_in != 0 || s->lookahead != 0 ||
  75173. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  75174. block_state bstate;
  75175. bstate = (*(configuration_table[s->level].func))(s, flush);
  75176. if (bstate == finish_started || bstate == finish_done) {
  75177. s->status = FINISH_STATE;
  75178. }
  75179. if (bstate == need_more || bstate == finish_started) {
  75180. if (strm->avail_out == 0) {
  75181. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  75182. }
  75183. return Z_OK;
  75184. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  75185. * of deflate should use the same flush parameter to make sure
  75186. * that the flush is complete. So we don't have to output an
  75187. * empty block here, this will be done at next call. This also
  75188. * ensures that for a very small output buffer, we emit at most
  75189. * one empty block.
  75190. */
  75191. }
  75192. if (bstate == block_done) {
  75193. if (flush == Z_PARTIAL_FLUSH) {
  75194. _tr_align(s);
  75195. } else { /* FULL_FLUSH or SYNC_FLUSH */
  75196. _tr_stored_block(s, (char*)0, 0L, 0);
  75197. /* For a full flush, this empty block will be recognized
  75198. * as a special marker by inflate_sync().
  75199. */
  75200. if (flush == Z_FULL_FLUSH) {
  75201. CLEAR_HASH(s); /* forget history */
  75202. }
  75203. }
  75204. flush_pending(strm);
  75205. if (strm->avail_out == 0) {
  75206. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  75207. return Z_OK;
  75208. }
  75209. }
  75210. }
  75211. Assert(strm->avail_out > 0, "bug2");
  75212. if (flush != Z_FINISH) return Z_OK;
  75213. if (s->wrap <= 0) return Z_STREAM_END;
  75214. /* Write the trailer */
  75215. #ifdef GZIP
  75216. if (s->wrap == 2) {
  75217. put_byte(s, (Byte)(strm->adler & 0xff));
  75218. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  75219. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  75220. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  75221. put_byte(s, (Byte)(strm->total_in & 0xff));
  75222. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  75223. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  75224. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  75225. }
  75226. else
  75227. #endif
  75228. {
  75229. putShortMSB(s, (uInt)(strm->adler >> 16));
  75230. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  75231. }
  75232. flush_pending(strm);
  75233. /* If avail_out is zero, the application will call deflate again
  75234. * to flush the rest.
  75235. */
  75236. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  75237. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  75238. }
  75239. /* ========================================================================= */
  75240. int ZEXPORT deflateEnd (z_streamp strm)
  75241. {
  75242. int status;
  75243. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  75244. status = strm->state->status;
  75245. if (status != INIT_STATE &&
  75246. status != EXTRA_STATE &&
  75247. status != NAME_STATE &&
  75248. status != COMMENT_STATE &&
  75249. status != HCRC_STATE &&
  75250. status != BUSY_STATE &&
  75251. status != FINISH_STATE) {
  75252. return Z_STREAM_ERROR;
  75253. }
  75254. /* Deallocate in reverse order of allocations: */
  75255. TRY_FREE(strm, strm->state->pending_buf);
  75256. TRY_FREE(strm, strm->state->head);
  75257. TRY_FREE(strm, strm->state->prev);
  75258. TRY_FREE(strm, strm->state->window);
  75259. ZFREE(strm, strm->state);
  75260. strm->state = Z_NULL;
  75261. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  75262. }
  75263. /* =========================================================================
  75264. * Copy the source state to the destination state.
  75265. * To simplify the source, this is not supported for 16-bit MSDOS (which
  75266. * doesn't have enough memory anyway to duplicate compression states).
  75267. */
  75268. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  75269. {
  75270. #ifdef MAXSEG_64K
  75271. return Z_STREAM_ERROR;
  75272. #else
  75273. deflate_state *ds;
  75274. deflate_state *ss;
  75275. ushf *overlay;
  75276. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  75277. return Z_STREAM_ERROR;
  75278. }
  75279. ss = source->state;
  75280. zmemcpy(dest, source, sizeof(z_stream));
  75281. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  75282. if (ds == Z_NULL) return Z_MEM_ERROR;
  75283. dest->state = (struct internal_state FAR *) ds;
  75284. zmemcpy(ds, ss, sizeof(deflate_state));
  75285. ds->strm = dest;
  75286. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  75287. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  75288. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  75289. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  75290. ds->pending_buf = (uchf *) overlay;
  75291. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  75292. ds->pending_buf == Z_NULL) {
  75293. deflateEnd (dest);
  75294. return Z_MEM_ERROR;
  75295. }
  75296. /* following zmemcpy do not work for 16-bit MSDOS */
  75297. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  75298. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  75299. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  75300. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  75301. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  75302. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  75303. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  75304. ds->l_desc.dyn_tree = ds->dyn_ltree;
  75305. ds->d_desc.dyn_tree = ds->dyn_dtree;
  75306. ds->bl_desc.dyn_tree = ds->bl_tree;
  75307. return Z_OK;
  75308. #endif /* MAXSEG_64K */
  75309. }
  75310. /* ===========================================================================
  75311. * Read a new buffer from the current input stream, update the adler32
  75312. * and total number of bytes read. All deflate() input goes through
  75313. * this function so some applications may wish to modify it to avoid
  75314. * allocating a large strm->next_in buffer and copying from it.
  75315. * (See also flush_pending()).
  75316. */
  75317. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  75318. {
  75319. unsigned len = strm->avail_in;
  75320. if (len > size) len = size;
  75321. if (len == 0) return 0;
  75322. strm->avail_in -= len;
  75323. if (strm->state->wrap == 1) {
  75324. strm->adler = adler32(strm->adler, strm->next_in, len);
  75325. }
  75326. #ifdef GZIP
  75327. else if (strm->state->wrap == 2) {
  75328. strm->adler = crc32(strm->adler, strm->next_in, len);
  75329. }
  75330. #endif
  75331. zmemcpy(buf, strm->next_in, len);
  75332. strm->next_in += len;
  75333. strm->total_in += len;
  75334. return (int)len;
  75335. }
  75336. /* ===========================================================================
  75337. * Initialize the "longest match" routines for a new zlib stream
  75338. */
  75339. local void lm_init (deflate_state *s)
  75340. {
  75341. s->window_size = (ulg)2L*s->w_size;
  75342. CLEAR_HASH(s);
  75343. /* Set the default configuration parameters:
  75344. */
  75345. s->max_lazy_match = configuration_table[s->level].max_lazy;
  75346. s->good_match = configuration_table[s->level].good_length;
  75347. s->nice_match = configuration_table[s->level].nice_length;
  75348. s->max_chain_length = configuration_table[s->level].max_chain;
  75349. s->strstart = 0;
  75350. s->block_start = 0L;
  75351. s->lookahead = 0;
  75352. s->match_length = s->prev_length = MIN_MATCH-1;
  75353. s->match_available = 0;
  75354. s->ins_h = 0;
  75355. #ifndef FASTEST
  75356. #ifdef ASMV
  75357. match_init(); /* initialize the asm code */
  75358. #endif
  75359. #endif
  75360. }
  75361. #ifndef FASTEST
  75362. /* ===========================================================================
  75363. * Set match_start to the longest match starting at the given string and
  75364. * return its length. Matches shorter or equal to prev_length are discarded,
  75365. * in which case the result is equal to prev_length and match_start is
  75366. * garbage.
  75367. * IN assertions: cur_match is the head of the hash chain for the current
  75368. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  75369. * OUT assertion: the match length is not greater than s->lookahead.
  75370. */
  75371. #ifndef ASMV
  75372. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  75373. * match.S. The code will be functionally equivalent.
  75374. */
  75375. local uInt longest_match(deflate_state *s, IPos cur_match)
  75376. {
  75377. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  75378. register Bytef *scan = s->window + s->strstart; /* current string */
  75379. register Bytef *match; /* matched string */
  75380. register int len; /* length of current match */
  75381. int best_len = s->prev_length; /* best match length so far */
  75382. int nice_match = s->nice_match; /* stop if match long enough */
  75383. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  75384. s->strstart - (IPos)MAX_DIST(s) : NIL;
  75385. /* Stop when cur_match becomes <= limit. To simplify the code,
  75386. * we prevent matches with the string of window index 0.
  75387. */
  75388. Posf *prev = s->prev;
  75389. uInt wmask = s->w_mask;
  75390. #ifdef UNALIGNED_OK
  75391. /* Compare two bytes at a time. Note: this is not always beneficial.
  75392. * Try with and without -DUNALIGNED_OK to check.
  75393. */
  75394. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  75395. register ush scan_start = *(ushf*)scan;
  75396. register ush scan_end = *(ushf*)(scan+best_len-1);
  75397. #else
  75398. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  75399. register Byte scan_end1 = scan[best_len-1];
  75400. register Byte scan_end = scan[best_len];
  75401. #endif
  75402. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  75403. * It is easy to get rid of this optimization if necessary.
  75404. */
  75405. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  75406. /* Do not waste too much time if we already have a good match: */
  75407. if (s->prev_length >= s->good_match) {
  75408. chain_length >>= 2;
  75409. }
  75410. /* Do not look for matches beyond the end of the input. This is necessary
  75411. * to make deflate deterministic.
  75412. */
  75413. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  75414. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  75415. do {
  75416. Assert(cur_match < s->strstart, "no future");
  75417. match = s->window + cur_match;
  75418. /* Skip to next match if the match length cannot increase
  75419. * or if the match length is less than 2. Note that the checks below
  75420. * for insufficient lookahead only occur occasionally for performance
  75421. * reasons. Therefore uninitialized memory will be accessed, and
  75422. * conditional jumps will be made that depend on those values.
  75423. * However the length of the match is limited to the lookahead, so
  75424. * the output of deflate is not affected by the uninitialized values.
  75425. */
  75426. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  75427. /* This code assumes sizeof(unsigned short) == 2. Do not use
  75428. * UNALIGNED_OK if your compiler uses a different size.
  75429. */
  75430. if (*(ushf*)(match+best_len-1) != scan_end ||
  75431. *(ushf*)match != scan_start) continue;
  75432. /* It is not necessary to compare scan[2] and match[2] since they are
  75433. * always equal when the other bytes match, given that the hash keys
  75434. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  75435. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  75436. * lookahead only every 4th comparison; the 128th check will be made
  75437. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  75438. * necessary to put more guard bytes at the end of the window, or
  75439. * to check more often for insufficient lookahead.
  75440. */
  75441. Assert(scan[2] == match[2], "scan[2]?");
  75442. scan++, match++;
  75443. do {
  75444. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  75445. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  75446. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  75447. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  75448. scan < strend);
  75449. /* The funny "do {}" generates better code on most compilers */
  75450. /* Here, scan <= window+strstart+257 */
  75451. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  75452. if (*scan == *match) scan++;
  75453. len = (MAX_MATCH - 1) - (int)(strend-scan);
  75454. scan = strend - (MAX_MATCH-1);
  75455. #else /* UNALIGNED_OK */
  75456. if (match[best_len] != scan_end ||
  75457. match[best_len-1] != scan_end1 ||
  75458. *match != *scan ||
  75459. *++match != scan[1]) continue;
  75460. /* The check at best_len-1 can be removed because it will be made
  75461. * again later. (This heuristic is not always a win.)
  75462. * It is not necessary to compare scan[2] and match[2] since they
  75463. * are always equal when the other bytes match, given that
  75464. * the hash keys are equal and that HASH_BITS >= 8.
  75465. */
  75466. scan += 2, match++;
  75467. Assert(*scan == *match, "match[2]?");
  75468. /* We check for insufficient lookahead only every 8th comparison;
  75469. * the 256th check will be made at strstart+258.
  75470. */
  75471. do {
  75472. } while (*++scan == *++match && *++scan == *++match &&
  75473. *++scan == *++match && *++scan == *++match &&
  75474. *++scan == *++match && *++scan == *++match &&
  75475. *++scan == *++match && *++scan == *++match &&
  75476. scan < strend);
  75477. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  75478. len = MAX_MATCH - (int)(strend - scan);
  75479. scan = strend - MAX_MATCH;
  75480. #endif /* UNALIGNED_OK */
  75481. if (len > best_len) {
  75482. s->match_start = cur_match;
  75483. best_len = len;
  75484. if (len >= nice_match) break;
  75485. #ifdef UNALIGNED_OK
  75486. scan_end = *(ushf*)(scan+best_len-1);
  75487. #else
  75488. scan_end1 = scan[best_len-1];
  75489. scan_end = scan[best_len];
  75490. #endif
  75491. }
  75492. } while ((cur_match = prev[cur_match & wmask]) > limit
  75493. && --chain_length != 0);
  75494. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  75495. return s->lookahead;
  75496. }
  75497. #endif /* ASMV */
  75498. #endif /* FASTEST */
  75499. /* ---------------------------------------------------------------------------
  75500. * Optimized version for level == 1 or strategy == Z_RLE only
  75501. */
  75502. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  75503. {
  75504. register Bytef *scan = s->window + s->strstart; /* current string */
  75505. register Bytef *match; /* matched string */
  75506. register int len; /* length of current match */
  75507. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  75508. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  75509. * It is easy to get rid of this optimization if necessary.
  75510. */
  75511. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  75512. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  75513. Assert(cur_match < s->strstart, "no future");
  75514. match = s->window + cur_match;
  75515. /* Return failure if the match length is less than 2:
  75516. */
  75517. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  75518. /* The check at best_len-1 can be removed because it will be made
  75519. * again later. (This heuristic is not always a win.)
  75520. * It is not necessary to compare scan[2] and match[2] since they
  75521. * are always equal when the other bytes match, given that
  75522. * the hash keys are equal and that HASH_BITS >= 8.
  75523. */
  75524. scan += 2, match += 2;
  75525. Assert(*scan == *match, "match[2]?");
  75526. /* We check for insufficient lookahead only every 8th comparison;
  75527. * the 256th check will be made at strstart+258.
  75528. */
  75529. do {
  75530. } while (*++scan == *++match && *++scan == *++match &&
  75531. *++scan == *++match && *++scan == *++match &&
  75532. *++scan == *++match && *++scan == *++match &&
  75533. *++scan == *++match && *++scan == *++match &&
  75534. scan < strend);
  75535. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  75536. len = MAX_MATCH - (int)(strend - scan);
  75537. if (len < MIN_MATCH) return MIN_MATCH - 1;
  75538. s->match_start = cur_match;
  75539. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  75540. }
  75541. #ifdef DEBUG
  75542. /* ===========================================================================
  75543. * Check that the match at match_start is indeed a match.
  75544. */
  75545. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  75546. {
  75547. /* check that the match is indeed a match */
  75548. if (zmemcmp(s->window + match,
  75549. s->window + start, length) != EQUAL) {
  75550. fprintf(stderr, " start %u, match %u, length %d\n",
  75551. start, match, length);
  75552. do {
  75553. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  75554. } while (--length != 0);
  75555. z_error("invalid match");
  75556. }
  75557. if (z_verbose > 1) {
  75558. fprintf(stderr,"\\[%d,%d]", start-match, length);
  75559. do { putc(s->window[start++], stderr); } while (--length != 0);
  75560. }
  75561. }
  75562. #else
  75563. # define check_match(s, start, match, length)
  75564. #endif /* DEBUG */
  75565. /* ===========================================================================
  75566. * Fill the window when the lookahead becomes insufficient.
  75567. * Updates strstart and lookahead.
  75568. *
  75569. * IN assertion: lookahead < MIN_LOOKAHEAD
  75570. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  75571. * At least one byte has been read, or avail_in == 0; reads are
  75572. * performed for at least two bytes (required for the zip translate_eol
  75573. * option -- not supported here).
  75574. */
  75575. local void fill_window (deflate_state *s)
  75576. {
  75577. register unsigned n, m;
  75578. register Posf *p;
  75579. unsigned more; /* Amount of free space at the end of the window. */
  75580. uInt wsize = s->w_size;
  75581. do {
  75582. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  75583. /* Deal with !@#$% 64K limit: */
  75584. if (sizeof(int) <= 2) {
  75585. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  75586. more = wsize;
  75587. } else if (more == (unsigned)(-1)) {
  75588. /* Very unlikely, but possible on 16 bit machine if
  75589. * strstart == 0 && lookahead == 1 (input done a byte at time)
  75590. */
  75591. more--;
  75592. }
  75593. }
  75594. /* If the window is almost full and there is insufficient lookahead,
  75595. * move the upper half to the lower one to make room in the upper half.
  75596. */
  75597. if (s->strstart >= wsize+MAX_DIST(s)) {
  75598. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  75599. s->match_start -= wsize;
  75600. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  75601. s->block_start -= (long) wsize;
  75602. /* Slide the hash table (could be avoided with 32 bit values
  75603. at the expense of memory usage). We slide even when level == 0
  75604. to keep the hash table consistent if we switch back to level > 0
  75605. later. (Using level 0 permanently is not an optimal usage of
  75606. zlib, so we don't care about this pathological case.)
  75607. */
  75608. /* %%% avoid this when Z_RLE */
  75609. n = s->hash_size;
  75610. p = &s->head[n];
  75611. do {
  75612. m = *--p;
  75613. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  75614. } while (--n);
  75615. n = wsize;
  75616. #ifndef FASTEST
  75617. p = &s->prev[n];
  75618. do {
  75619. m = *--p;
  75620. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  75621. /* If n is not on any hash chain, prev[n] is garbage but
  75622. * its value will never be used.
  75623. */
  75624. } while (--n);
  75625. #endif
  75626. more += wsize;
  75627. }
  75628. if (s->strm->avail_in == 0) return;
  75629. /* If there was no sliding:
  75630. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  75631. * more == window_size - lookahead - strstart
  75632. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  75633. * => more >= window_size - 2*WSIZE + 2
  75634. * In the BIG_MEM or MMAP case (not yet supported),
  75635. * window_size == input_size + MIN_LOOKAHEAD &&
  75636. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  75637. * Otherwise, window_size == 2*WSIZE so more >= 2.
  75638. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  75639. */
  75640. Assert(more >= 2, "more < 2");
  75641. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  75642. s->lookahead += n;
  75643. /* Initialize the hash value now that we have some input: */
  75644. if (s->lookahead >= MIN_MATCH) {
  75645. s->ins_h = s->window[s->strstart];
  75646. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  75647. #if MIN_MATCH != 3
  75648. Call UPDATE_HASH() MIN_MATCH-3 more times
  75649. #endif
  75650. }
  75651. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  75652. * but this is not important since only literal bytes will be emitted.
  75653. */
  75654. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  75655. }
  75656. /* ===========================================================================
  75657. * Flush the current block, with given end-of-file flag.
  75658. * IN assertion: strstart is set to the end of the current match.
  75659. */
  75660. #define FLUSH_BLOCK_ONLY(s, eof) { \
  75661. _tr_flush_block(s, (s->block_start >= 0L ? \
  75662. (charf *)&s->window[(unsigned)s->block_start] : \
  75663. (charf *)Z_NULL), \
  75664. (ulg)((long)s->strstart - s->block_start), \
  75665. (eof)); \
  75666. s->block_start = s->strstart; \
  75667. flush_pending(s->strm); \
  75668. Tracev((stderr,"[FLUSH]")); \
  75669. }
  75670. /* Same but force premature exit if necessary. */
  75671. #define FLUSH_BLOCK(s, eof) { \
  75672. FLUSH_BLOCK_ONLY(s, eof); \
  75673. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  75674. }
  75675. /* ===========================================================================
  75676. * Copy without compression as much as possible from the input stream, return
  75677. * the current block state.
  75678. * This function does not insert new strings in the dictionary since
  75679. * uncompressible data is probably not useful. This function is used
  75680. * only for the level=0 compression option.
  75681. * NOTE: this function should be optimized to avoid extra copying from
  75682. * window to pending_buf.
  75683. */
  75684. local block_state deflate_stored(deflate_state *s, int flush)
  75685. {
  75686. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  75687. * to pending_buf_size, and each stored block has a 5 byte header:
  75688. */
  75689. ulg max_block_size = 0xffff;
  75690. ulg max_start;
  75691. if (max_block_size > s->pending_buf_size - 5) {
  75692. max_block_size = s->pending_buf_size - 5;
  75693. }
  75694. /* Copy as much as possible from input to output: */
  75695. for (;;) {
  75696. /* Fill the window as much as possible: */
  75697. if (s->lookahead <= 1) {
  75698. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  75699. s->block_start >= (long)s->w_size, "slide too late");
  75700. fill_window(s);
  75701. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  75702. if (s->lookahead == 0) break; /* flush the current block */
  75703. }
  75704. Assert(s->block_start >= 0L, "block gone");
  75705. s->strstart += s->lookahead;
  75706. s->lookahead = 0;
  75707. /* Emit a stored block if pending_buf will be full: */
  75708. max_start = s->block_start + max_block_size;
  75709. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  75710. /* strstart == 0 is possible when wraparound on 16-bit machine */
  75711. s->lookahead = (uInt)(s->strstart - max_start);
  75712. s->strstart = (uInt)max_start;
  75713. FLUSH_BLOCK(s, 0);
  75714. }
  75715. /* Flush if we may have to slide, otherwise block_start may become
  75716. * negative and the data will be gone:
  75717. */
  75718. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  75719. FLUSH_BLOCK(s, 0);
  75720. }
  75721. }
  75722. FLUSH_BLOCK(s, flush == Z_FINISH);
  75723. return flush == Z_FINISH ? finish_done : block_done;
  75724. }
  75725. /* ===========================================================================
  75726. * Compress as much as possible from the input stream, return the current
  75727. * block state.
  75728. * This function does not perform lazy evaluation of matches and inserts
  75729. * new strings in the dictionary only for unmatched strings or for short
  75730. * matches. It is used only for the fast compression options.
  75731. */
  75732. local block_state deflate_fast(deflate_state *s, int flush)
  75733. {
  75734. IPos hash_head = NIL; /* head of the hash chain */
  75735. int bflush; /* set if current block must be flushed */
  75736. for (;;) {
  75737. /* Make sure that we always have enough lookahead, except
  75738. * at the end of the input file. We need MAX_MATCH bytes
  75739. * for the next match, plus MIN_MATCH bytes to insert the
  75740. * string following the next match.
  75741. */
  75742. if (s->lookahead < MIN_LOOKAHEAD) {
  75743. fill_window(s);
  75744. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  75745. return need_more;
  75746. }
  75747. if (s->lookahead == 0) break; /* flush the current block */
  75748. }
  75749. /* Insert the string window[strstart .. strstart+2] in the
  75750. * dictionary, and set hash_head to the head of the hash chain:
  75751. */
  75752. if (s->lookahead >= MIN_MATCH) {
  75753. INSERT_STRING(s, s->strstart, hash_head);
  75754. }
  75755. /* Find the longest match, discarding those <= prev_length.
  75756. * At this point we have always match_length < MIN_MATCH
  75757. */
  75758. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  75759. /* To simplify the code, we prevent matches with the string
  75760. * of window index 0 (in particular we have to avoid a match
  75761. * of the string with itself at the start of the input file).
  75762. */
  75763. #ifdef FASTEST
  75764. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  75765. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  75766. s->match_length = longest_match_fast (s, hash_head);
  75767. }
  75768. #else
  75769. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  75770. s->match_length = longest_match (s, hash_head);
  75771. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  75772. s->match_length = longest_match_fast (s, hash_head);
  75773. }
  75774. #endif
  75775. /* longest_match() or longest_match_fast() sets match_start */
  75776. }
  75777. if (s->match_length >= MIN_MATCH) {
  75778. check_match(s, s->strstart, s->match_start, s->match_length);
  75779. _tr_tally_dist(s, s->strstart - s->match_start,
  75780. s->match_length - MIN_MATCH, bflush);
  75781. s->lookahead -= s->match_length;
  75782. /* Insert new strings in the hash table only if the match length
  75783. * is not too large. This saves time but degrades compression.
  75784. */
  75785. #ifndef FASTEST
  75786. if (s->match_length <= s->max_insert_length &&
  75787. s->lookahead >= MIN_MATCH) {
  75788. s->match_length--; /* string at strstart already in table */
  75789. do {
  75790. s->strstart++;
  75791. INSERT_STRING(s, s->strstart, hash_head);
  75792. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  75793. * always MIN_MATCH bytes ahead.
  75794. */
  75795. } while (--s->match_length != 0);
  75796. s->strstart++;
  75797. } else
  75798. #endif
  75799. {
  75800. s->strstart += s->match_length;
  75801. s->match_length = 0;
  75802. s->ins_h = s->window[s->strstart];
  75803. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  75804. #if MIN_MATCH != 3
  75805. Call UPDATE_HASH() MIN_MATCH-3 more times
  75806. #endif
  75807. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  75808. * matter since it will be recomputed at next deflate call.
  75809. */
  75810. }
  75811. } else {
  75812. /* No match, output a literal byte */
  75813. Tracevv((stderr,"%c", s->window[s->strstart]));
  75814. _tr_tally_lit (s, s->window[s->strstart], bflush);
  75815. s->lookahead--;
  75816. s->strstart++;
  75817. }
  75818. if (bflush) FLUSH_BLOCK(s, 0);
  75819. }
  75820. FLUSH_BLOCK(s, flush == Z_FINISH);
  75821. return flush == Z_FINISH ? finish_done : block_done;
  75822. }
  75823. #ifndef FASTEST
  75824. /* ===========================================================================
  75825. * Same as above, but achieves better compression. We use a lazy
  75826. * evaluation for matches: a match is finally adopted only if there is
  75827. * no better match at the next window position.
  75828. */
  75829. local block_state deflate_slow(deflate_state *s, int flush)
  75830. {
  75831. IPos hash_head = NIL; /* head of hash chain */
  75832. int bflush; /* set if current block must be flushed */
  75833. /* Process the input block. */
  75834. for (;;) {
  75835. /* Make sure that we always have enough lookahead, except
  75836. * at the end of the input file. We need MAX_MATCH bytes
  75837. * for the next match, plus MIN_MATCH bytes to insert the
  75838. * string following the next match.
  75839. */
  75840. if (s->lookahead < MIN_LOOKAHEAD) {
  75841. fill_window(s);
  75842. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  75843. return need_more;
  75844. }
  75845. if (s->lookahead == 0) break; /* flush the current block */
  75846. }
  75847. /* Insert the string window[strstart .. strstart+2] in the
  75848. * dictionary, and set hash_head to the head of the hash chain:
  75849. */
  75850. if (s->lookahead >= MIN_MATCH) {
  75851. INSERT_STRING(s, s->strstart, hash_head);
  75852. }
  75853. /* Find the longest match, discarding those <= prev_length.
  75854. */
  75855. s->prev_length = s->match_length, s->prev_match = s->match_start;
  75856. s->match_length = MIN_MATCH-1;
  75857. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  75858. s->strstart - hash_head <= MAX_DIST(s)) {
  75859. /* To simplify the code, we prevent matches with the string
  75860. * of window index 0 (in particular we have to avoid a match
  75861. * of the string with itself at the start of the input file).
  75862. */
  75863. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  75864. s->match_length = longest_match (s, hash_head);
  75865. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  75866. s->match_length = longest_match_fast (s, hash_head);
  75867. }
  75868. /* longest_match() or longest_match_fast() sets match_start */
  75869. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  75870. #if TOO_FAR <= 32767
  75871. || (s->match_length == MIN_MATCH &&
  75872. s->strstart - s->match_start > TOO_FAR)
  75873. #endif
  75874. )) {
  75875. /* If prev_match is also MIN_MATCH, match_start is garbage
  75876. * but we will ignore the current match anyway.
  75877. */
  75878. s->match_length = MIN_MATCH-1;
  75879. }
  75880. }
  75881. /* If there was a match at the previous step and the current
  75882. * match is not better, output the previous match:
  75883. */
  75884. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  75885. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  75886. /* Do not insert strings in hash table beyond this. */
  75887. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  75888. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  75889. s->prev_length - MIN_MATCH, bflush);
  75890. /* Insert in hash table all strings up to the end of the match.
  75891. * strstart-1 and strstart are already inserted. If there is not
  75892. * enough lookahead, the last two strings are not inserted in
  75893. * the hash table.
  75894. */
  75895. s->lookahead -= s->prev_length-1;
  75896. s->prev_length -= 2;
  75897. do {
  75898. if (++s->strstart <= max_insert) {
  75899. INSERT_STRING(s, s->strstart, hash_head);
  75900. }
  75901. } while (--s->prev_length != 0);
  75902. s->match_available = 0;
  75903. s->match_length = MIN_MATCH-1;
  75904. s->strstart++;
  75905. if (bflush) FLUSH_BLOCK(s, 0);
  75906. } else if (s->match_available) {
  75907. /* If there was no match at the previous position, output a
  75908. * single literal. If there was a match but the current match
  75909. * is longer, truncate the previous match to a single literal.
  75910. */
  75911. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  75912. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  75913. if (bflush) {
  75914. FLUSH_BLOCK_ONLY(s, 0);
  75915. }
  75916. s->strstart++;
  75917. s->lookahead--;
  75918. if (s->strm->avail_out == 0) return need_more;
  75919. } else {
  75920. /* There is no previous match to compare with, wait for
  75921. * the next step to decide.
  75922. */
  75923. s->match_available = 1;
  75924. s->strstart++;
  75925. s->lookahead--;
  75926. }
  75927. }
  75928. Assert (flush != Z_NO_FLUSH, "no flush?");
  75929. if (s->match_available) {
  75930. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  75931. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  75932. s->match_available = 0;
  75933. }
  75934. FLUSH_BLOCK(s, flush == Z_FINISH);
  75935. return flush == Z_FINISH ? finish_done : block_done;
  75936. }
  75937. #endif /* FASTEST */
  75938. #if 0
  75939. /* ===========================================================================
  75940. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  75941. * one. Do not maintain a hash table. (It will be regenerated if this run of
  75942. * deflate switches away from Z_RLE.)
  75943. */
  75944. local block_state deflate_rle(s, flush)
  75945. deflate_state *s;
  75946. int flush;
  75947. {
  75948. int bflush; /* set if current block must be flushed */
  75949. uInt run; /* length of run */
  75950. uInt max; /* maximum length of run */
  75951. uInt prev; /* byte at distance one to match */
  75952. Bytef *scan; /* scan for end of run */
  75953. for (;;) {
  75954. /* Make sure that we always have enough lookahead, except
  75955. * at the end of the input file. We need MAX_MATCH bytes
  75956. * for the longest encodable run.
  75957. */
  75958. if (s->lookahead < MAX_MATCH) {
  75959. fill_window(s);
  75960. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  75961. return need_more;
  75962. }
  75963. if (s->lookahead == 0) break; /* flush the current block */
  75964. }
  75965. /* See how many times the previous byte repeats */
  75966. run = 0;
  75967. if (s->strstart > 0) { /* if there is a previous byte, that is */
  75968. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  75969. scan = s->window + s->strstart - 1;
  75970. prev = *scan++;
  75971. do {
  75972. if (*scan++ != prev)
  75973. break;
  75974. } while (++run < max);
  75975. }
  75976. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  75977. if (run >= MIN_MATCH) {
  75978. check_match(s, s->strstart, s->strstart - 1, run);
  75979. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  75980. s->lookahead -= run;
  75981. s->strstart += run;
  75982. } else {
  75983. /* No match, output a literal byte */
  75984. Tracevv((stderr,"%c", s->window[s->strstart]));
  75985. _tr_tally_lit (s, s->window[s->strstart], bflush);
  75986. s->lookahead--;
  75987. s->strstart++;
  75988. }
  75989. if (bflush) FLUSH_BLOCK(s, 0);
  75990. }
  75991. FLUSH_BLOCK(s, flush == Z_FINISH);
  75992. return flush == Z_FINISH ? finish_done : block_done;
  75993. }
  75994. #endif
  75995. /********* End of inlined file: deflate.c *********/
  75996. /********* Start of inlined file: infback.c *********/
  75997. /*
  75998. This code is largely copied from inflate.c. Normally either infback.o or
  75999. inflate.o would be linked into an application--not both. The interface
  76000. with inffast.c is retained so that optimized assembler-coded versions of
  76001. inflate_fast() can be used with either inflate.c or infback.c.
  76002. */
  76003. /********* Start of inlined file: inftrees.h *********/
  76004. /* WARNING: this file should *not* be used by applications. It is
  76005. part of the implementation of the compression library and is
  76006. subject to change. Applications should only use zlib.h.
  76007. */
  76008. #ifndef _INFTREES_H_
  76009. #define _INFTREES_H_
  76010. /* Structure for decoding tables. Each entry provides either the
  76011. information needed to do the operation requested by the code that
  76012. indexed that table entry, or it provides a pointer to another
  76013. table that indexes more bits of the code. op indicates whether
  76014. the entry is a pointer to another table, a literal, a length or
  76015. distance, an end-of-block, or an invalid code. For a table
  76016. pointer, the low four bits of op is the number of index bits of
  76017. that table. For a length or distance, the low four bits of op
  76018. is the number of extra bits to get after the code. bits is
  76019. the number of bits in this code or part of the code to drop off
  76020. of the bit buffer. val is the actual byte to output in the case
  76021. of a literal, the base length or distance, or the offset from
  76022. the current table to the next table. Each entry is four bytes. */
  76023. typedef struct {
  76024. unsigned char op; /* operation, extra bits, table bits */
  76025. unsigned char bits; /* bits in this part of the code */
  76026. unsigned short val; /* offset in table or code value */
  76027. } code;
  76028. /* op values as set by inflate_table():
  76029. 00000000 - literal
  76030. 0000tttt - table link, tttt != 0 is the number of table index bits
  76031. 0001eeee - length or distance, eeee is the number of extra bits
  76032. 01100000 - end of block
  76033. 01000000 - invalid code
  76034. */
  76035. /* Maximum size of dynamic tree. The maximum found in a long but non-
  76036. exhaustive search was 1444 code structures (852 for length/literals
  76037. and 592 for distances, the latter actually the result of an
  76038. exhaustive search). The true maximum is not known, but the value
  76039. below is more than safe. */
  76040. #define ENOUGH 2048
  76041. #define MAXD 592
  76042. /* Type of code to build for inftable() */
  76043. typedef enum {
  76044. CODES,
  76045. LENS,
  76046. DISTS
  76047. } codetype;
  76048. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  76049. unsigned codes, code FAR * FAR *table,
  76050. unsigned FAR *bits, unsigned short FAR *work));
  76051. #endif
  76052. /********* End of inlined file: inftrees.h *********/
  76053. /********* Start of inlined file: inflate.h *********/
  76054. /* WARNING: this file should *not* be used by applications. It is
  76055. part of the implementation of the compression library and is
  76056. subject to change. Applications should only use zlib.h.
  76057. */
  76058. #ifndef _INFLATE_H_
  76059. #define _INFLATE_H_
  76060. /* define NO_GZIP when compiling if you want to disable gzip header and
  76061. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  76062. the crc code when it is not needed. For shared libraries, gzip decoding
  76063. should be left enabled. */
  76064. #ifndef NO_GZIP
  76065. # define GUNZIP
  76066. #endif
  76067. /* Possible inflate modes between inflate() calls */
  76068. typedef enum {
  76069. HEAD, /* i: waiting for magic header */
  76070. FLAGS, /* i: waiting for method and flags (gzip) */
  76071. TIME, /* i: waiting for modification time (gzip) */
  76072. OS, /* i: waiting for extra flags and operating system (gzip) */
  76073. EXLEN, /* i: waiting for extra length (gzip) */
  76074. EXTRA, /* i: waiting for extra bytes (gzip) */
  76075. NAME, /* i: waiting for end of file name (gzip) */
  76076. COMMENT, /* i: waiting for end of comment (gzip) */
  76077. HCRC, /* i: waiting for header crc (gzip) */
  76078. DICTID, /* i: waiting for dictionary check value */
  76079. DICT, /* waiting for inflateSetDictionary() call */
  76080. TYPE, /* i: waiting for type bits, including last-flag bit */
  76081. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  76082. STORED, /* i: waiting for stored size (length and complement) */
  76083. COPY, /* i/o: waiting for input or output to copy stored block */
  76084. TABLE, /* i: waiting for dynamic block table lengths */
  76085. LENLENS, /* i: waiting for code length code lengths */
  76086. CODELENS, /* i: waiting for length/lit and distance code lengths */
  76087. LEN, /* i: waiting for length/lit code */
  76088. LENEXT, /* i: waiting for length extra bits */
  76089. DIST, /* i: waiting for distance code */
  76090. DISTEXT, /* i: waiting for distance extra bits */
  76091. MATCH, /* o: waiting for output space to copy string */
  76092. LIT, /* o: waiting for output space to write literal */
  76093. CHECK, /* i: waiting for 32-bit check value */
  76094. LENGTH, /* i: waiting for 32-bit length (gzip) */
  76095. DONE, /* finished check, done -- remain here until reset */
  76096. BAD, /* got a data error -- remain here until reset */
  76097. MEM, /* got an inflate() memory error -- remain here until reset */
  76098. SYNC /* looking for synchronization bytes to restart inflate() */
  76099. } inflate_mode;
  76100. /*
  76101. State transitions between above modes -
  76102. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  76103. Process header:
  76104. HEAD -> (gzip) or (zlib)
  76105. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  76106. NAME -> COMMENT -> HCRC -> TYPE
  76107. (zlib) -> DICTID or TYPE
  76108. DICTID -> DICT -> TYPE
  76109. Read deflate blocks:
  76110. TYPE -> STORED or TABLE or LEN or CHECK
  76111. STORED -> COPY -> TYPE
  76112. TABLE -> LENLENS -> CODELENS -> LEN
  76113. Read deflate codes:
  76114. LEN -> LENEXT or LIT or TYPE
  76115. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  76116. LIT -> LEN
  76117. Process trailer:
  76118. CHECK -> LENGTH -> DONE
  76119. */
  76120. /* state maintained between inflate() calls. Approximately 7K bytes. */
  76121. struct inflate_state {
  76122. inflate_mode mode; /* current inflate mode */
  76123. int last; /* true if processing last block */
  76124. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  76125. int havedict; /* true if dictionary provided */
  76126. int flags; /* gzip header method and flags (0 if zlib) */
  76127. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  76128. unsigned long check; /* protected copy of check value */
  76129. unsigned long total; /* protected copy of output count */
  76130. gz_headerp head; /* where to save gzip header information */
  76131. /* sliding window */
  76132. unsigned wbits; /* log base 2 of requested window size */
  76133. unsigned wsize; /* window size or zero if not using window */
  76134. unsigned whave; /* valid bytes in the window */
  76135. unsigned write; /* window write index */
  76136. unsigned char FAR *window; /* allocated sliding window, if needed */
  76137. /* bit accumulator */
  76138. unsigned long hold; /* input bit accumulator */
  76139. unsigned bits; /* number of bits in "in" */
  76140. /* for string and stored block copying */
  76141. unsigned length; /* literal or length of data to copy */
  76142. unsigned offset; /* distance back to copy string from */
  76143. /* for table and code decoding */
  76144. unsigned extra; /* extra bits needed */
  76145. /* fixed and dynamic code tables */
  76146. code const FAR *lencode; /* starting table for length/literal codes */
  76147. code const FAR *distcode; /* starting table for distance codes */
  76148. unsigned lenbits; /* index bits for lencode */
  76149. unsigned distbits; /* index bits for distcode */
  76150. /* dynamic table building */
  76151. unsigned ncode; /* number of code length code lengths */
  76152. unsigned nlen; /* number of length code lengths */
  76153. unsigned ndist; /* number of distance code lengths */
  76154. unsigned have; /* number of code lengths in lens[] */
  76155. code FAR *next; /* next available space in codes[] */
  76156. unsigned short lens[320]; /* temporary storage for code lengths */
  76157. unsigned short work[288]; /* work area for code table building */
  76158. code codes[ENOUGH]; /* space for code tables */
  76159. };
  76160. #endif
  76161. /********* End of inlined file: inflate.h *********/
  76162. /********* Start of inlined file: inffast.h *********/
  76163. /* WARNING: this file should *not* be used by applications. It is
  76164. part of the implementation of the compression library and is
  76165. subject to change. Applications should only use zlib.h.
  76166. */
  76167. void inflate_fast OF((z_streamp strm, unsigned start));
  76168. /********* End of inlined file: inffast.h *********/
  76169. /* function prototypes */
  76170. local void fixedtables1 OF((struct inflate_state FAR *state));
  76171. /*
  76172. strm provides memory allocation functions in zalloc and zfree, or
  76173. Z_NULL to use the library memory allocation functions.
  76174. windowBits is in the range 8..15, and window is a user-supplied
  76175. window and output buffer that is 2**windowBits bytes.
  76176. */
  76177. int ZEXPORT inflateBackInit_(z_streamp strm, int windowBits, unsigned char FAR *window, const char *version, int stream_size)
  76178. {
  76179. struct inflate_state FAR *state;
  76180. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  76181. stream_size != (int)(sizeof(z_stream)))
  76182. return Z_VERSION_ERROR;
  76183. if (strm == Z_NULL || window == Z_NULL ||
  76184. windowBits < 8 || windowBits > 15)
  76185. return Z_STREAM_ERROR;
  76186. strm->msg = Z_NULL; /* in case we return an error */
  76187. if (strm->zalloc == (alloc_func)0) {
  76188. strm->zalloc = zcalloc;
  76189. strm->opaque = (voidpf)0;
  76190. }
  76191. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  76192. state = (struct inflate_state FAR *)ZALLOC(strm, 1,
  76193. sizeof(struct inflate_state));
  76194. if (state == Z_NULL) return Z_MEM_ERROR;
  76195. Tracev((stderr, "inflate: allocated\n"));
  76196. strm->state = (struct internal_state FAR *)state;
  76197. state->dmax = 32768U;
  76198. state->wbits = windowBits;
  76199. state->wsize = 1U << windowBits;
  76200. state->window = window;
  76201. state->write = 0;
  76202. state->whave = 0;
  76203. return Z_OK;
  76204. }
  76205. /*
  76206. Return state with length and distance decoding tables and index sizes set to
  76207. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  76208. If BUILDFIXED is defined, then instead this routine builds the tables the
  76209. first time it's called, and returns those tables the first time and
  76210. thereafter. This reduces the size of the code by about 2K bytes, in
  76211. exchange for a little execution time. However, BUILDFIXED should not be
  76212. used for threaded applications, since the rewriting of the tables and virgin
  76213. may not be thread-safe.
  76214. */
  76215. local void fixedtables1 (struct inflate_state FAR *state)
  76216. {
  76217. #ifdef BUILDFIXED
  76218. static int virgin = 1;
  76219. static code *lenfix, *distfix;
  76220. static code fixed[544];
  76221. /* build fixed huffman tables if first call (may not be thread safe) */
  76222. if (virgin) {
  76223. unsigned sym, bits;
  76224. static code *next;
  76225. /* literal/length table */
  76226. sym = 0;
  76227. while (sym < 144) state->lens[sym++] = 8;
  76228. while (sym < 256) state->lens[sym++] = 9;
  76229. while (sym < 280) state->lens[sym++] = 7;
  76230. while (sym < 288) state->lens[sym++] = 8;
  76231. next = fixed;
  76232. lenfix = next;
  76233. bits = 9;
  76234. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  76235. /* distance table */
  76236. sym = 0;
  76237. while (sym < 32) state->lens[sym++] = 5;
  76238. distfix = next;
  76239. bits = 5;
  76240. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  76241. /* do this just once */
  76242. virgin = 0;
  76243. }
  76244. #else /* !BUILDFIXED */
  76245. /********* Start of inlined file: inffixed.h *********/
  76246. /* inffixed.h -- table for decoding fixed codes
  76247. * Generated automatically by makefixed().
  76248. */
  76249. /* WARNING: this file should *not* be used by applications. It
  76250. is part of the implementation of the compression library and
  76251. is subject to change. Applications should only use zlib.h.
  76252. */
  76253. static const code lenfix[512] = {
  76254. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  76255. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  76256. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  76257. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  76258. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  76259. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  76260. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  76261. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  76262. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  76263. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  76264. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  76265. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  76266. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  76267. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  76268. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  76269. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  76270. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  76271. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  76272. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  76273. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  76274. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  76275. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  76276. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  76277. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  76278. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  76279. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  76280. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  76281. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  76282. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  76283. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  76284. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  76285. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  76286. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  76287. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  76288. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  76289. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  76290. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  76291. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  76292. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  76293. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  76294. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  76295. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  76296. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  76297. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  76298. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  76299. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  76300. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  76301. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  76302. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  76303. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  76304. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  76305. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  76306. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  76307. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  76308. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  76309. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  76310. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  76311. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  76312. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  76313. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  76314. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  76315. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  76316. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  76317. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  76318. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  76319. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  76320. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  76321. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  76322. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  76323. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  76324. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  76325. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  76326. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  76327. {0,9,255}
  76328. };
  76329. static const code distfix[32] = {
  76330. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  76331. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  76332. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  76333. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  76334. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  76335. {22,5,193},{64,5,0}
  76336. };
  76337. /********* End of inlined file: inffixed.h *********/
  76338. #endif /* BUILDFIXED */
  76339. state->lencode = lenfix;
  76340. state->lenbits = 9;
  76341. state->distcode = distfix;
  76342. state->distbits = 5;
  76343. }
  76344. /* Macros for inflateBack(): */
  76345. /* Load returned state from inflate_fast() */
  76346. #define LOAD() \
  76347. do { \
  76348. put = strm->next_out; \
  76349. left = strm->avail_out; \
  76350. next = strm->next_in; \
  76351. have = strm->avail_in; \
  76352. hold = state->hold; \
  76353. bits = state->bits; \
  76354. } while (0)
  76355. /* Set state from registers for inflate_fast() */
  76356. #define RESTORE() \
  76357. do { \
  76358. strm->next_out = put; \
  76359. strm->avail_out = left; \
  76360. strm->next_in = next; \
  76361. strm->avail_in = have; \
  76362. state->hold = hold; \
  76363. state->bits = bits; \
  76364. } while (0)
  76365. /* Clear the input bit accumulator */
  76366. #define INITBITS() \
  76367. do { \
  76368. hold = 0; \
  76369. bits = 0; \
  76370. } while (0)
  76371. /* Assure that some input is available. If input is requested, but denied,
  76372. then return a Z_BUF_ERROR from inflateBack(). */
  76373. #define PULL() \
  76374. do { \
  76375. if (have == 0) { \
  76376. have = in(in_desc, &next); \
  76377. if (have == 0) { \
  76378. next = Z_NULL; \
  76379. ret = Z_BUF_ERROR; \
  76380. goto inf_leave; \
  76381. } \
  76382. } \
  76383. } while (0)
  76384. /* Get a byte of input into the bit accumulator, or return from inflateBack()
  76385. with an error if there is no input available. */
  76386. #define PULLBYTE() \
  76387. do { \
  76388. PULL(); \
  76389. have--; \
  76390. hold += (unsigned long)(*next++) << bits; \
  76391. bits += 8; \
  76392. } while (0)
  76393. /* Assure that there are at least n bits in the bit accumulator. If there is
  76394. not enough available input to do that, then return from inflateBack() with
  76395. an error. */
  76396. #define NEEDBITS(n) \
  76397. do { \
  76398. while (bits < (unsigned)(n)) \
  76399. PULLBYTE(); \
  76400. } while (0)
  76401. /* Return the low n bits of the bit accumulator (n < 16) */
  76402. #define BITS(n) \
  76403. ((unsigned)hold & ((1U << (n)) - 1))
  76404. /* Remove n bits from the bit accumulator */
  76405. #define DROPBITS(n) \
  76406. do { \
  76407. hold >>= (n); \
  76408. bits -= (unsigned)(n); \
  76409. } while (0)
  76410. /* Remove zero to seven bits as needed to go to a byte boundary */
  76411. #define BYTEBITS() \
  76412. do { \
  76413. hold >>= bits & 7; \
  76414. bits -= bits & 7; \
  76415. } while (0)
  76416. /* Assure that some output space is available, by writing out the window
  76417. if it's full. If the write fails, return from inflateBack() with a
  76418. Z_BUF_ERROR. */
  76419. #define ROOM() \
  76420. do { \
  76421. if (left == 0) { \
  76422. put = state->window; \
  76423. left = state->wsize; \
  76424. state->whave = left; \
  76425. if (out(out_desc, put, left)) { \
  76426. ret = Z_BUF_ERROR; \
  76427. goto inf_leave; \
  76428. } \
  76429. } \
  76430. } while (0)
  76431. /*
  76432. strm provides the memory allocation functions and window buffer on input,
  76433. and provides information on the unused input on return. For Z_DATA_ERROR
  76434. returns, strm will also provide an error message.
  76435. in() and out() are the call-back input and output functions. When
  76436. inflateBack() needs more input, it calls in(). When inflateBack() has
  76437. filled the window with output, or when it completes with data in the
  76438. window, it calls out() to write out the data. The application must not
  76439. change the provided input until in() is called again or inflateBack()
  76440. returns. The application must not change the window/output buffer until
  76441. inflateBack() returns.
  76442. in() and out() are called with a descriptor parameter provided in the
  76443. inflateBack() call. This parameter can be a structure that provides the
  76444. information required to do the read or write, as well as accumulated
  76445. information on the input and output such as totals and check values.
  76446. in() should return zero on failure. out() should return non-zero on
  76447. failure. If either in() or out() fails, than inflateBack() returns a
  76448. Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it
  76449. was in() or out() that caused in the error. Otherwise, inflateBack()
  76450. returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
  76451. error, or Z_MEM_ERROR if it could not allocate memory for the state.
  76452. inflateBack() can also return Z_STREAM_ERROR if the input parameters
  76453. are not correct, i.e. strm is Z_NULL or the state was not initialized.
  76454. */
  76455. int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc, out_func out, void FAR *out_desc)
  76456. {
  76457. struct inflate_state FAR *state;
  76458. unsigned char FAR *next; /* next input */
  76459. unsigned char FAR *put; /* next output */
  76460. unsigned have, left; /* available input and output */
  76461. unsigned long hold; /* bit buffer */
  76462. unsigned bits; /* bits in bit buffer */
  76463. unsigned copy; /* number of stored or match bytes to copy */
  76464. unsigned char FAR *from; /* where to copy match bytes from */
  76465. code thisx; /* current decoding table entry */
  76466. code last; /* parent table entry */
  76467. unsigned len; /* length to copy for repeats, bits to drop */
  76468. int ret; /* return code */
  76469. static const unsigned short order[19] = /* permutation of code lengths */
  76470. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  76471. /* Check that the strm exists and that the state was initialized */
  76472. if (strm == Z_NULL || strm->state == Z_NULL)
  76473. return Z_STREAM_ERROR;
  76474. state = (struct inflate_state FAR *)strm->state;
  76475. /* Reset the state */
  76476. strm->msg = Z_NULL;
  76477. state->mode = TYPE;
  76478. state->last = 0;
  76479. state->whave = 0;
  76480. next = strm->next_in;
  76481. have = next != Z_NULL ? strm->avail_in : 0;
  76482. hold = 0;
  76483. bits = 0;
  76484. put = state->window;
  76485. left = state->wsize;
  76486. /* Inflate until end of block marked as last */
  76487. for (;;)
  76488. switch (state->mode) {
  76489. case TYPE:
  76490. /* determine and dispatch block type */
  76491. if (state->last) {
  76492. BYTEBITS();
  76493. state->mode = DONE;
  76494. break;
  76495. }
  76496. NEEDBITS(3);
  76497. state->last = BITS(1);
  76498. DROPBITS(1);
  76499. switch (BITS(2)) {
  76500. case 0: /* stored block */
  76501. Tracev((stderr, "inflate: stored block%s\n",
  76502. state->last ? " (last)" : ""));
  76503. state->mode = STORED;
  76504. break;
  76505. case 1: /* fixed block */
  76506. fixedtables1(state);
  76507. Tracev((stderr, "inflate: fixed codes block%s\n",
  76508. state->last ? " (last)" : ""));
  76509. state->mode = LEN; /* decode codes */
  76510. break;
  76511. case 2: /* dynamic block */
  76512. Tracev((stderr, "inflate: dynamic codes block%s\n",
  76513. state->last ? " (last)" : ""));
  76514. state->mode = TABLE;
  76515. break;
  76516. case 3:
  76517. strm->msg = (char *)"invalid block type";
  76518. state->mode = BAD;
  76519. }
  76520. DROPBITS(2);
  76521. break;
  76522. case STORED:
  76523. /* get and verify stored block length */
  76524. BYTEBITS(); /* go to byte boundary */
  76525. NEEDBITS(32);
  76526. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  76527. strm->msg = (char *)"invalid stored block lengths";
  76528. state->mode = BAD;
  76529. break;
  76530. }
  76531. state->length = (unsigned)hold & 0xffff;
  76532. Tracev((stderr, "inflate: stored length %u\n",
  76533. state->length));
  76534. INITBITS();
  76535. /* copy stored block from input to output */
  76536. while (state->length != 0) {
  76537. copy = state->length;
  76538. PULL();
  76539. ROOM();
  76540. if (copy > have) copy = have;
  76541. if (copy > left) copy = left;
  76542. zmemcpy(put, next, copy);
  76543. have -= copy;
  76544. next += copy;
  76545. left -= copy;
  76546. put += copy;
  76547. state->length -= copy;
  76548. }
  76549. Tracev((stderr, "inflate: stored end\n"));
  76550. state->mode = TYPE;
  76551. break;
  76552. case TABLE:
  76553. /* get dynamic table entries descriptor */
  76554. NEEDBITS(14);
  76555. state->nlen = BITS(5) + 257;
  76556. DROPBITS(5);
  76557. state->ndist = BITS(5) + 1;
  76558. DROPBITS(5);
  76559. state->ncode = BITS(4) + 4;
  76560. DROPBITS(4);
  76561. #ifndef PKZIP_BUG_WORKAROUND
  76562. if (state->nlen > 286 || state->ndist > 30) {
  76563. strm->msg = (char *)"too many length or distance symbols";
  76564. state->mode = BAD;
  76565. break;
  76566. }
  76567. #endif
  76568. Tracev((stderr, "inflate: table sizes ok\n"));
  76569. /* get code length code lengths (not a typo) */
  76570. state->have = 0;
  76571. while (state->have < state->ncode) {
  76572. NEEDBITS(3);
  76573. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  76574. DROPBITS(3);
  76575. }
  76576. while (state->have < 19)
  76577. state->lens[order[state->have++]] = 0;
  76578. state->next = state->codes;
  76579. state->lencode = (code const FAR *)(state->next);
  76580. state->lenbits = 7;
  76581. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  76582. &(state->lenbits), state->work);
  76583. if (ret) {
  76584. strm->msg = (char *)"invalid code lengths set";
  76585. state->mode = BAD;
  76586. break;
  76587. }
  76588. Tracev((stderr, "inflate: code lengths ok\n"));
  76589. /* get length and distance code code lengths */
  76590. state->have = 0;
  76591. while (state->have < state->nlen + state->ndist) {
  76592. for (;;) {
  76593. thisx = state->lencode[BITS(state->lenbits)];
  76594. if ((unsigned)(thisx.bits) <= bits) break;
  76595. PULLBYTE();
  76596. }
  76597. if (thisx.val < 16) {
  76598. NEEDBITS(thisx.bits);
  76599. DROPBITS(thisx.bits);
  76600. state->lens[state->have++] = thisx.val;
  76601. }
  76602. else {
  76603. if (thisx.val == 16) {
  76604. NEEDBITS(thisx.bits + 2);
  76605. DROPBITS(thisx.bits);
  76606. if (state->have == 0) {
  76607. strm->msg = (char *)"invalid bit length repeat";
  76608. state->mode = BAD;
  76609. break;
  76610. }
  76611. len = (unsigned)(state->lens[state->have - 1]);
  76612. copy = 3 + BITS(2);
  76613. DROPBITS(2);
  76614. }
  76615. else if (thisx.val == 17) {
  76616. NEEDBITS(thisx.bits + 3);
  76617. DROPBITS(thisx.bits);
  76618. len = 0;
  76619. copy = 3 + BITS(3);
  76620. DROPBITS(3);
  76621. }
  76622. else {
  76623. NEEDBITS(thisx.bits + 7);
  76624. DROPBITS(thisx.bits);
  76625. len = 0;
  76626. copy = 11 + BITS(7);
  76627. DROPBITS(7);
  76628. }
  76629. if (state->have + copy > state->nlen + state->ndist) {
  76630. strm->msg = (char *)"invalid bit length repeat";
  76631. state->mode = BAD;
  76632. break;
  76633. }
  76634. while (copy--)
  76635. state->lens[state->have++] = (unsigned short)len;
  76636. }
  76637. }
  76638. /* handle error breaks in while */
  76639. if (state->mode == BAD) break;
  76640. /* build code tables */
  76641. state->next = state->codes;
  76642. state->lencode = (code const FAR *)(state->next);
  76643. state->lenbits = 9;
  76644. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  76645. &(state->lenbits), state->work);
  76646. if (ret) {
  76647. strm->msg = (char *)"invalid literal/lengths set";
  76648. state->mode = BAD;
  76649. break;
  76650. }
  76651. state->distcode = (code const FAR *)(state->next);
  76652. state->distbits = 6;
  76653. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  76654. &(state->next), &(state->distbits), state->work);
  76655. if (ret) {
  76656. strm->msg = (char *)"invalid distances set";
  76657. state->mode = BAD;
  76658. break;
  76659. }
  76660. Tracev((stderr, "inflate: codes ok\n"));
  76661. state->mode = LEN;
  76662. case LEN:
  76663. /* use inflate_fast() if we have enough input and output */
  76664. if (have >= 6 && left >= 258) {
  76665. RESTORE();
  76666. if (state->whave < state->wsize)
  76667. state->whave = state->wsize - left;
  76668. inflate_fast(strm, state->wsize);
  76669. LOAD();
  76670. break;
  76671. }
  76672. /* get a literal, length, or end-of-block code */
  76673. for (;;) {
  76674. thisx = state->lencode[BITS(state->lenbits)];
  76675. if ((unsigned)(thisx.bits) <= bits) break;
  76676. PULLBYTE();
  76677. }
  76678. if (thisx.op && (thisx.op & 0xf0) == 0) {
  76679. last = thisx;
  76680. for (;;) {
  76681. thisx = state->lencode[last.val +
  76682. (BITS(last.bits + last.op) >> last.bits)];
  76683. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  76684. PULLBYTE();
  76685. }
  76686. DROPBITS(last.bits);
  76687. }
  76688. DROPBITS(thisx.bits);
  76689. state->length = (unsigned)thisx.val;
  76690. /* process literal */
  76691. if (thisx.op == 0) {
  76692. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  76693. "inflate: literal '%c'\n" :
  76694. "inflate: literal 0x%02x\n", thisx.val));
  76695. ROOM();
  76696. *put++ = (unsigned char)(state->length);
  76697. left--;
  76698. state->mode = LEN;
  76699. break;
  76700. }
  76701. /* process end of block */
  76702. if (thisx.op & 32) {
  76703. Tracevv((stderr, "inflate: end of block\n"));
  76704. state->mode = TYPE;
  76705. break;
  76706. }
  76707. /* invalid code */
  76708. if (thisx.op & 64) {
  76709. strm->msg = (char *)"invalid literal/length code";
  76710. state->mode = BAD;
  76711. break;
  76712. }
  76713. /* length code -- get extra bits, if any */
  76714. state->extra = (unsigned)(thisx.op) & 15;
  76715. if (state->extra != 0) {
  76716. NEEDBITS(state->extra);
  76717. state->length += BITS(state->extra);
  76718. DROPBITS(state->extra);
  76719. }
  76720. Tracevv((stderr, "inflate: length %u\n", state->length));
  76721. /* get distance code */
  76722. for (;;) {
  76723. thisx = state->distcode[BITS(state->distbits)];
  76724. if ((unsigned)(thisx.bits) <= bits) break;
  76725. PULLBYTE();
  76726. }
  76727. if ((thisx.op & 0xf0) == 0) {
  76728. last = thisx;
  76729. for (;;) {
  76730. thisx = state->distcode[last.val +
  76731. (BITS(last.bits + last.op) >> last.bits)];
  76732. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  76733. PULLBYTE();
  76734. }
  76735. DROPBITS(last.bits);
  76736. }
  76737. DROPBITS(thisx.bits);
  76738. if (thisx.op & 64) {
  76739. strm->msg = (char *)"invalid distance code";
  76740. state->mode = BAD;
  76741. break;
  76742. }
  76743. state->offset = (unsigned)thisx.val;
  76744. /* get distance extra bits, if any */
  76745. state->extra = (unsigned)(thisx.op) & 15;
  76746. if (state->extra != 0) {
  76747. NEEDBITS(state->extra);
  76748. state->offset += BITS(state->extra);
  76749. DROPBITS(state->extra);
  76750. }
  76751. if (state->offset > state->wsize - (state->whave < state->wsize ?
  76752. left : 0)) {
  76753. strm->msg = (char *)"invalid distance too far back";
  76754. state->mode = BAD;
  76755. break;
  76756. }
  76757. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  76758. /* copy match from window to output */
  76759. do {
  76760. ROOM();
  76761. copy = state->wsize - state->offset;
  76762. if (copy < left) {
  76763. from = put + copy;
  76764. copy = left - copy;
  76765. }
  76766. else {
  76767. from = put - state->offset;
  76768. copy = left;
  76769. }
  76770. if (copy > state->length) copy = state->length;
  76771. state->length -= copy;
  76772. left -= copy;
  76773. do {
  76774. *put++ = *from++;
  76775. } while (--copy);
  76776. } while (state->length != 0);
  76777. break;
  76778. case DONE:
  76779. /* inflate stream terminated properly -- write leftover output */
  76780. ret = Z_STREAM_END;
  76781. if (left < state->wsize) {
  76782. if (out(out_desc, state->window, state->wsize - left))
  76783. ret = Z_BUF_ERROR;
  76784. }
  76785. goto inf_leave;
  76786. case BAD:
  76787. ret = Z_DATA_ERROR;
  76788. goto inf_leave;
  76789. default: /* can't happen, but makes compilers happy */
  76790. ret = Z_STREAM_ERROR;
  76791. goto inf_leave;
  76792. }
  76793. /* Return unused input */
  76794. inf_leave:
  76795. strm->next_in = next;
  76796. strm->avail_in = have;
  76797. return ret;
  76798. }
  76799. int ZEXPORT inflateBackEnd (z_streamp strm)
  76800. {
  76801. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  76802. return Z_STREAM_ERROR;
  76803. ZFREE(strm, strm->state);
  76804. strm->state = Z_NULL;
  76805. Tracev((stderr, "inflate: end\n"));
  76806. return Z_OK;
  76807. }
  76808. /********* End of inlined file: infback.c *********/
  76809. /********* Start of inlined file: inffast.c *********/
  76810. /********* Start of inlined file: inffast.h *********/
  76811. /* WARNING: this file should *not* be used by applications. It is
  76812. part of the implementation of the compression library and is
  76813. subject to change. Applications should only use zlib.h.
  76814. */
  76815. void inflate_fast OF((z_streamp strm, unsigned start));
  76816. /********* End of inlined file: inffast.h *********/
  76817. #ifndef ASMINF
  76818. /* Allow machine dependent optimization for post-increment or pre-increment.
  76819. Based on testing to date,
  76820. Pre-increment preferred for:
  76821. - PowerPC G3 (Adler)
  76822. - MIPS R5000 (Randers-Pehrson)
  76823. Post-increment preferred for:
  76824. - none
  76825. No measurable difference:
  76826. - Pentium III (Anderson)
  76827. - M68060 (Nikl)
  76828. */
  76829. #ifdef POSTINC
  76830. # define OFF 0
  76831. # define PUP(a) *(a)++
  76832. #else
  76833. # define OFF 1
  76834. # define PUP(a) *++(a)
  76835. #endif
  76836. /*
  76837. Decode literal, length, and distance codes and write out the resulting
  76838. literal and match bytes until either not enough input or output is
  76839. available, an end-of-block is encountered, or a data error is encountered.
  76840. When large enough input and output buffers are supplied to inflate(), for
  76841. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  76842. inflate execution time is spent in this routine.
  76843. Entry assumptions:
  76844. state->mode == LEN
  76845. strm->avail_in >= 6
  76846. strm->avail_out >= 258
  76847. start >= strm->avail_out
  76848. state->bits < 8
  76849. On return, state->mode is one of:
  76850. LEN -- ran out of enough output space or enough available input
  76851. TYPE -- reached end of block code, inflate() to interpret next block
  76852. BAD -- error in block data
  76853. Notes:
  76854. - The maximum input bits used by a length/distance pair is 15 bits for the
  76855. length code, 5 bits for the length extra, 15 bits for the distance code,
  76856. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  76857. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  76858. checking for available input while decoding.
  76859. - The maximum bytes that a single length/distance pair can output is 258
  76860. bytes, which is the maximum length that can be coded. inflate_fast()
  76861. requires strm->avail_out >= 258 for each loop to avoid checking for
  76862. output space.
  76863. */
  76864. void inflate_fast (z_streamp strm, unsigned start)
  76865. {
  76866. struct inflate_state FAR *state;
  76867. unsigned char FAR *in; /* local strm->next_in */
  76868. unsigned char FAR *last; /* while in < last, enough input available */
  76869. unsigned char FAR *out; /* local strm->next_out */
  76870. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  76871. unsigned char FAR *end; /* while out < end, enough space available */
  76872. #ifdef INFLATE_STRICT
  76873. unsigned dmax; /* maximum distance from zlib header */
  76874. #endif
  76875. unsigned wsize; /* window size or zero if not using window */
  76876. unsigned whave; /* valid bytes in the window */
  76877. unsigned write; /* window write index */
  76878. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  76879. unsigned long hold; /* local strm->hold */
  76880. unsigned bits; /* local strm->bits */
  76881. code const FAR *lcode; /* local strm->lencode */
  76882. code const FAR *dcode; /* local strm->distcode */
  76883. unsigned lmask; /* mask for first level of length codes */
  76884. unsigned dmask; /* mask for first level of distance codes */
  76885. code thisx; /* retrieved table entry */
  76886. unsigned op; /* code bits, operation, extra bits, or */
  76887. /* window position, window bytes to copy */
  76888. unsigned len; /* match length, unused bytes */
  76889. unsigned dist; /* match distance */
  76890. unsigned char FAR *from; /* where to copy match from */
  76891. /* copy state to local variables */
  76892. state = (struct inflate_state FAR *)strm->state;
  76893. in = strm->next_in - OFF;
  76894. last = in + (strm->avail_in - 5);
  76895. out = strm->next_out - OFF;
  76896. beg = out - (start - strm->avail_out);
  76897. end = out + (strm->avail_out - 257);
  76898. #ifdef INFLATE_STRICT
  76899. dmax = state->dmax;
  76900. #endif
  76901. wsize = state->wsize;
  76902. whave = state->whave;
  76903. write = state->write;
  76904. window = state->window;
  76905. hold = state->hold;
  76906. bits = state->bits;
  76907. lcode = state->lencode;
  76908. dcode = state->distcode;
  76909. lmask = (1U << state->lenbits) - 1;
  76910. dmask = (1U << state->distbits) - 1;
  76911. /* decode literals and length/distances until end-of-block or not enough
  76912. input data or output space */
  76913. do {
  76914. if (bits < 15) {
  76915. hold += (unsigned long)(PUP(in)) << bits;
  76916. bits += 8;
  76917. hold += (unsigned long)(PUP(in)) << bits;
  76918. bits += 8;
  76919. }
  76920. thisx = lcode[hold & lmask];
  76921. dolen:
  76922. op = (unsigned)(thisx.bits);
  76923. hold >>= op;
  76924. bits -= op;
  76925. op = (unsigned)(thisx.op);
  76926. if (op == 0) { /* literal */
  76927. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  76928. "inflate: literal '%c'\n" :
  76929. "inflate: literal 0x%02x\n", thisx.val));
  76930. PUP(out) = (unsigned char)(thisx.val);
  76931. }
  76932. else if (op & 16) { /* length base */
  76933. len = (unsigned)(thisx.val);
  76934. op &= 15; /* number of extra bits */
  76935. if (op) {
  76936. if (bits < op) {
  76937. hold += (unsigned long)(PUP(in)) << bits;
  76938. bits += 8;
  76939. }
  76940. len += (unsigned)hold & ((1U << op) - 1);
  76941. hold >>= op;
  76942. bits -= op;
  76943. }
  76944. Tracevv((stderr, "inflate: length %u\n", len));
  76945. if (bits < 15) {
  76946. hold += (unsigned long)(PUP(in)) << bits;
  76947. bits += 8;
  76948. hold += (unsigned long)(PUP(in)) << bits;
  76949. bits += 8;
  76950. }
  76951. thisx = dcode[hold & dmask];
  76952. dodist:
  76953. op = (unsigned)(thisx.bits);
  76954. hold >>= op;
  76955. bits -= op;
  76956. op = (unsigned)(thisx.op);
  76957. if (op & 16) { /* distance base */
  76958. dist = (unsigned)(thisx.val);
  76959. op &= 15; /* number of extra bits */
  76960. if (bits < op) {
  76961. hold += (unsigned long)(PUP(in)) << bits;
  76962. bits += 8;
  76963. if (bits < op) {
  76964. hold += (unsigned long)(PUP(in)) << bits;
  76965. bits += 8;
  76966. }
  76967. }
  76968. dist += (unsigned)hold & ((1U << op) - 1);
  76969. #ifdef INFLATE_STRICT
  76970. if (dist > dmax) {
  76971. strm->msg = (char *)"invalid distance too far back";
  76972. state->mode = BAD;
  76973. break;
  76974. }
  76975. #endif
  76976. hold >>= op;
  76977. bits -= op;
  76978. Tracevv((stderr, "inflate: distance %u\n", dist));
  76979. op = (unsigned)(out - beg); /* max distance in output */
  76980. if (dist > op) { /* see if copy from window */
  76981. op = dist - op; /* distance back in window */
  76982. if (op > whave) {
  76983. strm->msg = (char *)"invalid distance too far back";
  76984. state->mode = BAD;
  76985. break;
  76986. }
  76987. from = window - OFF;
  76988. if (write == 0) { /* very common case */
  76989. from += wsize - op;
  76990. if (op < len) { /* some from window */
  76991. len -= op;
  76992. do {
  76993. PUP(out) = PUP(from);
  76994. } while (--op);
  76995. from = out - dist; /* rest from output */
  76996. }
  76997. }
  76998. else if (write < op) { /* wrap around window */
  76999. from += wsize + write - op;
  77000. op -= write;
  77001. if (op < len) { /* some from end of window */
  77002. len -= op;
  77003. do {
  77004. PUP(out) = PUP(from);
  77005. } while (--op);
  77006. from = window - OFF;
  77007. if (write < len) { /* some from start of window */
  77008. op = write;
  77009. len -= op;
  77010. do {
  77011. PUP(out) = PUP(from);
  77012. } while (--op);
  77013. from = out - dist; /* rest from output */
  77014. }
  77015. }
  77016. }
  77017. else { /* contiguous in window */
  77018. from += write - op;
  77019. if (op < len) { /* some from window */
  77020. len -= op;
  77021. do {
  77022. PUP(out) = PUP(from);
  77023. } while (--op);
  77024. from = out - dist; /* rest from output */
  77025. }
  77026. }
  77027. while (len > 2) {
  77028. PUP(out) = PUP(from);
  77029. PUP(out) = PUP(from);
  77030. PUP(out) = PUP(from);
  77031. len -= 3;
  77032. }
  77033. if (len) {
  77034. PUP(out) = PUP(from);
  77035. if (len > 1)
  77036. PUP(out) = PUP(from);
  77037. }
  77038. }
  77039. else {
  77040. from = out - dist; /* copy direct from output */
  77041. do { /* minimum length is three */
  77042. PUP(out) = PUP(from);
  77043. PUP(out) = PUP(from);
  77044. PUP(out) = PUP(from);
  77045. len -= 3;
  77046. } while (len > 2);
  77047. if (len) {
  77048. PUP(out) = PUP(from);
  77049. if (len > 1)
  77050. PUP(out) = PUP(from);
  77051. }
  77052. }
  77053. }
  77054. else if ((op & 64) == 0) { /* 2nd level distance code */
  77055. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  77056. goto dodist;
  77057. }
  77058. else {
  77059. strm->msg = (char *)"invalid distance code";
  77060. state->mode = BAD;
  77061. break;
  77062. }
  77063. }
  77064. else if ((op & 64) == 0) { /* 2nd level length code */
  77065. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  77066. goto dolen;
  77067. }
  77068. else if (op & 32) { /* end-of-block */
  77069. Tracevv((stderr, "inflate: end of block\n"));
  77070. state->mode = TYPE;
  77071. break;
  77072. }
  77073. else {
  77074. strm->msg = (char *)"invalid literal/length code";
  77075. state->mode = BAD;
  77076. break;
  77077. }
  77078. } while (in < last && out < end);
  77079. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  77080. len = bits >> 3;
  77081. in -= len;
  77082. bits -= len << 3;
  77083. hold &= (1U << bits) - 1;
  77084. /* update state and return */
  77085. strm->next_in = in + OFF;
  77086. strm->next_out = out + OFF;
  77087. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  77088. strm->avail_out = (unsigned)(out < end ?
  77089. 257 + (end - out) : 257 - (out - end));
  77090. state->hold = hold;
  77091. state->bits = bits;
  77092. return;
  77093. }
  77094. /*
  77095. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  77096. - Using bit fields for code structure
  77097. - Different op definition to avoid & for extra bits (do & for table bits)
  77098. - Three separate decoding do-loops for direct, window, and write == 0
  77099. - Special case for distance > 1 copies to do overlapped load and store copy
  77100. - Explicit branch predictions (based on measured branch probabilities)
  77101. - Deferring match copy and interspersed it with decoding subsequent codes
  77102. - Swapping literal/length else
  77103. - Swapping window/direct else
  77104. - Larger unrolled copy loops (three is about right)
  77105. - Moving len -= 3 statement into middle of loop
  77106. */
  77107. #endif /* !ASMINF */
  77108. /********* End of inlined file: inffast.c *********/
  77109. #undef PULLBYTE
  77110. #undef LOAD
  77111. #undef RESTORE
  77112. #undef INITBITS
  77113. #undef NEEDBITS
  77114. #undef DROPBITS
  77115. #undef BYTEBITS
  77116. /********* Start of inlined file: inflate.c *********/
  77117. /*
  77118. * Change history:
  77119. *
  77120. * 1.2.beta0 24 Nov 2002
  77121. * - First version -- complete rewrite of inflate to simplify code, avoid
  77122. * creation of window when not needed, minimize use of window when it is
  77123. * needed, make inffast.c even faster, implement gzip decoding, and to
  77124. * improve code readability and style over the previous zlib inflate code
  77125. *
  77126. * 1.2.beta1 25 Nov 2002
  77127. * - Use pointers for available input and output checking in inffast.c
  77128. * - Remove input and output counters in inffast.c
  77129. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  77130. * - Remove unnecessary second byte pull from length extra in inffast.c
  77131. * - Unroll direct copy to three copies per loop in inffast.c
  77132. *
  77133. * 1.2.beta2 4 Dec 2002
  77134. * - Change external routine names to reduce potential conflicts
  77135. * - Correct filename to inffixed.h for fixed tables in inflate.c
  77136. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  77137. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  77138. * to avoid negation problem on Alphas (64 bit) in inflate.c
  77139. *
  77140. * 1.2.beta3 22 Dec 2002
  77141. * - Add comments on state->bits assertion in inffast.c
  77142. * - Add comments on op field in inftrees.h
  77143. * - Fix bug in reuse of allocated window after inflateReset()
  77144. * - Remove bit fields--back to byte structure for speed
  77145. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  77146. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  77147. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  77148. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  77149. * - Use local copies of stream next and avail values, as well as local bit
  77150. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  77151. *
  77152. * 1.2.beta4 1 Jan 2003
  77153. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  77154. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  77155. * - Add comments in inffast.c to introduce the inflate_fast() routine
  77156. * - Rearrange window copies in inflate_fast() for speed and simplification
  77157. * - Unroll last copy for window match in inflate_fast()
  77158. * - Use local copies of window variables in inflate_fast() for speed
  77159. * - Pull out common write == 0 case for speed in inflate_fast()
  77160. * - Make op and len in inflate_fast() unsigned for consistency
  77161. * - Add FAR to lcode and dcode declarations in inflate_fast()
  77162. * - Simplified bad distance check in inflate_fast()
  77163. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  77164. * source file infback.c to provide a call-back interface to inflate for
  77165. * programs like gzip and unzip -- uses window as output buffer to avoid
  77166. * window copying
  77167. *
  77168. * 1.2.beta5 1 Jan 2003
  77169. * - Improved inflateBack() interface to allow the caller to provide initial
  77170. * input in strm.
  77171. * - Fixed stored blocks bug in inflateBack()
  77172. *
  77173. * 1.2.beta6 4 Jan 2003
  77174. * - Added comments in inffast.c on effectiveness of POSTINC
  77175. * - Typecasting all around to reduce compiler warnings
  77176. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  77177. * make compilers happy
  77178. * - Changed type of window in inflateBackInit() to unsigned char *
  77179. *
  77180. * 1.2.beta7 27 Jan 2003
  77181. * - Changed many types to unsigned or unsigned short to avoid warnings
  77182. * - Added inflateCopy() function
  77183. *
  77184. * 1.2.0 9 Mar 2003
  77185. * - Changed inflateBack() interface to provide separate opaque descriptors
  77186. * for the in() and out() functions
  77187. * - Changed inflateBack() argument and in_func typedef to swap the length
  77188. * and buffer address return values for the input function
  77189. * - Check next_in and next_out for Z_NULL on entry to inflate()
  77190. *
  77191. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  77192. */
  77193. /********* Start of inlined file: inffast.h *********/
  77194. /* WARNING: this file should *not* be used by applications. It is
  77195. part of the implementation of the compression library and is
  77196. subject to change. Applications should only use zlib.h.
  77197. */
  77198. void inflate_fast OF((z_streamp strm, unsigned start));
  77199. /********* End of inlined file: inffast.h *********/
  77200. #ifdef MAKEFIXED
  77201. # ifndef BUILDFIXED
  77202. # define BUILDFIXED
  77203. # endif
  77204. #endif
  77205. /* function prototypes */
  77206. local void fixedtables OF((struct inflate_state FAR *state));
  77207. local int updatewindow OF((z_streamp strm, unsigned out));
  77208. #ifdef BUILDFIXED
  77209. void makefixed OF((void));
  77210. #endif
  77211. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  77212. unsigned len));
  77213. int ZEXPORT inflateReset (z_streamp strm)
  77214. {
  77215. struct inflate_state FAR *state;
  77216. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77217. state = (struct inflate_state FAR *)strm->state;
  77218. strm->total_in = strm->total_out = state->total = 0;
  77219. strm->msg = Z_NULL;
  77220. strm->adler = 1; /* to support ill-conceived Java test suite */
  77221. state->mode = HEAD;
  77222. state->last = 0;
  77223. state->havedict = 0;
  77224. state->dmax = 32768U;
  77225. state->head = Z_NULL;
  77226. state->wsize = 0;
  77227. state->whave = 0;
  77228. state->write = 0;
  77229. state->hold = 0;
  77230. state->bits = 0;
  77231. state->lencode = state->distcode = state->next = state->codes;
  77232. Tracev((stderr, "inflate: reset\n"));
  77233. return Z_OK;
  77234. }
  77235. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  77236. {
  77237. struct inflate_state FAR *state;
  77238. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77239. state = (struct inflate_state FAR *)strm->state;
  77240. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  77241. value &= (1L << bits) - 1;
  77242. state->hold += value << state->bits;
  77243. state->bits += bits;
  77244. return Z_OK;
  77245. }
  77246. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  77247. {
  77248. struct inflate_state FAR *state;
  77249. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  77250. stream_size != (int)(sizeof(z_stream)))
  77251. return Z_VERSION_ERROR;
  77252. if (strm == Z_NULL) return Z_STREAM_ERROR;
  77253. strm->msg = Z_NULL; /* in case we return an error */
  77254. if (strm->zalloc == (alloc_func)0) {
  77255. strm->zalloc = zcalloc;
  77256. strm->opaque = (voidpf)0;
  77257. }
  77258. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  77259. state = (struct inflate_state FAR *)
  77260. ZALLOC(strm, 1, sizeof(struct inflate_state));
  77261. if (state == Z_NULL) return Z_MEM_ERROR;
  77262. Tracev((stderr, "inflate: allocated\n"));
  77263. strm->state = (struct internal_state FAR *)state;
  77264. if (windowBits < 0) {
  77265. state->wrap = 0;
  77266. windowBits = -windowBits;
  77267. }
  77268. else {
  77269. state->wrap = (windowBits >> 4) + 1;
  77270. #ifdef GUNZIP
  77271. if (windowBits < 48) windowBits &= 15;
  77272. #endif
  77273. }
  77274. if (windowBits < 8 || windowBits > 15) {
  77275. ZFREE(strm, state);
  77276. strm->state = Z_NULL;
  77277. return Z_STREAM_ERROR;
  77278. }
  77279. state->wbits = (unsigned)windowBits;
  77280. state->window = Z_NULL;
  77281. return inflateReset(strm);
  77282. }
  77283. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  77284. {
  77285. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  77286. }
  77287. /*
  77288. Return state with length and distance decoding tables and index sizes set to
  77289. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  77290. If BUILDFIXED is defined, then instead this routine builds the tables the
  77291. first time it's called, and returns those tables the first time and
  77292. thereafter. This reduces the size of the code by about 2K bytes, in
  77293. exchange for a little execution time. However, BUILDFIXED should not be
  77294. used for threaded applications, since the rewriting of the tables and virgin
  77295. may not be thread-safe.
  77296. */
  77297. local void fixedtables (struct inflate_state FAR *state)
  77298. {
  77299. #ifdef BUILDFIXED
  77300. static int virgin = 1;
  77301. static code *lenfix, *distfix;
  77302. static code fixed[544];
  77303. /* build fixed huffman tables if first call (may not be thread safe) */
  77304. if (virgin) {
  77305. unsigned sym, bits;
  77306. static code *next;
  77307. /* literal/length table */
  77308. sym = 0;
  77309. while (sym < 144) state->lens[sym++] = 8;
  77310. while (sym < 256) state->lens[sym++] = 9;
  77311. while (sym < 280) state->lens[sym++] = 7;
  77312. while (sym < 288) state->lens[sym++] = 8;
  77313. next = fixed;
  77314. lenfix = next;
  77315. bits = 9;
  77316. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  77317. /* distance table */
  77318. sym = 0;
  77319. while (sym < 32) state->lens[sym++] = 5;
  77320. distfix = next;
  77321. bits = 5;
  77322. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  77323. /* do this just once */
  77324. virgin = 0;
  77325. }
  77326. #else /* !BUILDFIXED */
  77327. /********* Start of inlined file: inffixed.h *********/
  77328. /* inffixed.h -- table for decoding fixed codes
  77329. * Generated automatically by makefixed().
  77330. */
  77331. /* WARNING: this file should *not* be used by applications. It
  77332. is part of the implementation of the compression library and
  77333. is subject to change. Applications should only use zlib.h.
  77334. */
  77335. static const code lenfix[512] = {
  77336. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  77337. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  77338. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  77339. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  77340. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  77341. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  77342. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  77343. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  77344. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  77345. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  77346. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  77347. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  77348. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  77349. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  77350. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  77351. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  77352. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  77353. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  77354. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  77355. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  77356. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  77357. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  77358. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  77359. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  77360. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  77361. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  77362. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  77363. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  77364. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  77365. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  77366. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  77367. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  77368. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  77369. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  77370. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  77371. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  77372. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  77373. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  77374. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  77375. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  77376. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  77377. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  77378. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  77379. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  77380. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  77381. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  77382. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  77383. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  77384. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  77385. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  77386. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  77387. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  77388. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  77389. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  77390. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  77391. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  77392. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  77393. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  77394. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  77395. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  77396. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  77397. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  77398. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  77399. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  77400. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  77401. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  77402. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  77403. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  77404. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  77405. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  77406. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  77407. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  77408. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  77409. {0,9,255}
  77410. };
  77411. static const code distfix[32] = {
  77412. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  77413. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  77414. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  77415. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  77416. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  77417. {22,5,193},{64,5,0}
  77418. };
  77419. /********* End of inlined file: inffixed.h *********/
  77420. #endif /* BUILDFIXED */
  77421. state->lencode = lenfix;
  77422. state->lenbits = 9;
  77423. state->distcode = distfix;
  77424. state->distbits = 5;
  77425. }
  77426. #ifdef MAKEFIXED
  77427. #include <stdio.h>
  77428. /*
  77429. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  77430. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  77431. those tables to stdout, which would be piped to inffixed.h. A small program
  77432. can simply call makefixed to do this:
  77433. void makefixed(void);
  77434. int main(void)
  77435. {
  77436. makefixed();
  77437. return 0;
  77438. }
  77439. Then that can be linked with zlib built with MAKEFIXED defined and run:
  77440. a.out > inffixed.h
  77441. */
  77442. void makefixed()
  77443. {
  77444. unsigned low, size;
  77445. struct inflate_state state;
  77446. fixedtables(&state);
  77447. puts(" /* inffixed.h -- table for decoding fixed codes");
  77448. puts(" * Generated automatically by makefixed().");
  77449. puts(" */");
  77450. puts("");
  77451. puts(" /* WARNING: this file should *not* be used by applications.");
  77452. puts(" It is part of the implementation of this library and is");
  77453. puts(" subject to change. Applications should only use zlib.h.");
  77454. puts(" */");
  77455. puts("");
  77456. size = 1U << 9;
  77457. printf(" static const code lenfix[%u] = {", size);
  77458. low = 0;
  77459. for (;;) {
  77460. if ((low % 7) == 0) printf("\n ");
  77461. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  77462. state.lencode[low].val);
  77463. if (++low == size) break;
  77464. putchar(',');
  77465. }
  77466. puts("\n };");
  77467. size = 1U << 5;
  77468. printf("\n static const code distfix[%u] = {", size);
  77469. low = 0;
  77470. for (;;) {
  77471. if ((low % 6) == 0) printf("\n ");
  77472. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  77473. state.distcode[low].val);
  77474. if (++low == size) break;
  77475. putchar(',');
  77476. }
  77477. puts("\n };");
  77478. }
  77479. #endif /* MAKEFIXED */
  77480. /*
  77481. Update the window with the last wsize (normally 32K) bytes written before
  77482. returning. If window does not exist yet, create it. This is only called
  77483. when a window is already in use, or when output has been written during this
  77484. inflate call, but the end of the deflate stream has not been reached yet.
  77485. It is also called to create a window for dictionary data when a dictionary
  77486. is loaded.
  77487. Providing output buffers larger than 32K to inflate() should provide a speed
  77488. advantage, since only the last 32K of output is copied to the sliding window
  77489. upon return from inflate(), and since all distances after the first 32K of
  77490. output will fall in the output data, making match copies simpler and faster.
  77491. The advantage may be dependent on the size of the processor's data caches.
  77492. */
  77493. local int updatewindow (z_streamp strm, unsigned out)
  77494. {
  77495. struct inflate_state FAR *state;
  77496. unsigned copy, dist;
  77497. state = (struct inflate_state FAR *)strm->state;
  77498. /* if it hasn't been done already, allocate space for the window */
  77499. if (state->window == Z_NULL) {
  77500. state->window = (unsigned char FAR *)
  77501. ZALLOC(strm, 1U << state->wbits,
  77502. sizeof(unsigned char));
  77503. if (state->window == Z_NULL) return 1;
  77504. }
  77505. /* if window not in use yet, initialize */
  77506. if (state->wsize == 0) {
  77507. state->wsize = 1U << state->wbits;
  77508. state->write = 0;
  77509. state->whave = 0;
  77510. }
  77511. /* copy state->wsize or less output bytes into the circular window */
  77512. copy = out - strm->avail_out;
  77513. if (copy >= state->wsize) {
  77514. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  77515. state->write = 0;
  77516. state->whave = state->wsize;
  77517. }
  77518. else {
  77519. dist = state->wsize - state->write;
  77520. if (dist > copy) dist = copy;
  77521. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  77522. copy -= dist;
  77523. if (copy) {
  77524. zmemcpy(state->window, strm->next_out - copy, copy);
  77525. state->write = copy;
  77526. state->whave = state->wsize;
  77527. }
  77528. else {
  77529. state->write += dist;
  77530. if (state->write == state->wsize) state->write = 0;
  77531. if (state->whave < state->wsize) state->whave += dist;
  77532. }
  77533. }
  77534. return 0;
  77535. }
  77536. /* Macros for inflate(): */
  77537. /* check function to use adler32() for zlib or crc32() for gzip */
  77538. #ifdef GUNZIP
  77539. # define UPDATE(check, buf, len) \
  77540. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  77541. #else
  77542. # define UPDATE(check, buf, len) adler32(check, buf, len)
  77543. #endif
  77544. /* check macros for header crc */
  77545. #ifdef GUNZIP
  77546. # define CRC2(check, word) \
  77547. do { \
  77548. hbuf[0] = (unsigned char)(word); \
  77549. hbuf[1] = (unsigned char)((word) >> 8); \
  77550. check = crc32(check, hbuf, 2); \
  77551. } while (0)
  77552. # define CRC4(check, word) \
  77553. do { \
  77554. hbuf[0] = (unsigned char)(word); \
  77555. hbuf[1] = (unsigned char)((word) >> 8); \
  77556. hbuf[2] = (unsigned char)((word) >> 16); \
  77557. hbuf[3] = (unsigned char)((word) >> 24); \
  77558. check = crc32(check, hbuf, 4); \
  77559. } while (0)
  77560. #endif
  77561. /* Load registers with state in inflate() for speed */
  77562. #define LOAD() \
  77563. do { \
  77564. put = strm->next_out; \
  77565. left = strm->avail_out; \
  77566. next = strm->next_in; \
  77567. have = strm->avail_in; \
  77568. hold = state->hold; \
  77569. bits = state->bits; \
  77570. } while (0)
  77571. /* Restore state from registers in inflate() */
  77572. #define RESTORE() \
  77573. do { \
  77574. strm->next_out = put; \
  77575. strm->avail_out = left; \
  77576. strm->next_in = next; \
  77577. strm->avail_in = have; \
  77578. state->hold = hold; \
  77579. state->bits = bits; \
  77580. } while (0)
  77581. /* Clear the input bit accumulator */
  77582. #define INITBITS() \
  77583. do { \
  77584. hold = 0; \
  77585. bits = 0; \
  77586. } while (0)
  77587. /* Get a byte of input into the bit accumulator, or return from inflate()
  77588. if there is no input available. */
  77589. #define PULLBYTE() \
  77590. do { \
  77591. if (have == 0) goto inf_leave; \
  77592. have--; \
  77593. hold += (unsigned long)(*next++) << bits; \
  77594. bits += 8; \
  77595. } while (0)
  77596. /* Assure that there are at least n bits in the bit accumulator. If there is
  77597. not enough available input to do that, then return from inflate(). */
  77598. #define NEEDBITS(n) \
  77599. do { \
  77600. while (bits < (unsigned)(n)) \
  77601. PULLBYTE(); \
  77602. } while (0)
  77603. /* Return the low n bits of the bit accumulator (n < 16) */
  77604. #define BITS(n) \
  77605. ((unsigned)hold & ((1U << (n)) - 1))
  77606. /* Remove n bits from the bit accumulator */
  77607. #define DROPBITS(n) \
  77608. do { \
  77609. hold >>= (n); \
  77610. bits -= (unsigned)(n); \
  77611. } while (0)
  77612. /* Remove zero to seven bits as needed to go to a byte boundary */
  77613. #define BYTEBITS() \
  77614. do { \
  77615. hold >>= bits & 7; \
  77616. bits -= bits & 7; \
  77617. } while (0)
  77618. /* Reverse the bytes in a 32-bit value */
  77619. #define REVERSE(q) \
  77620. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  77621. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  77622. /*
  77623. inflate() uses a state machine to process as much input data and generate as
  77624. much output data as possible before returning. The state machine is
  77625. structured roughly as follows:
  77626. for (;;) switch (state) {
  77627. ...
  77628. case STATEn:
  77629. if (not enough input data or output space to make progress)
  77630. return;
  77631. ... make progress ...
  77632. state = STATEm;
  77633. break;
  77634. ...
  77635. }
  77636. so when inflate() is called again, the same case is attempted again, and
  77637. if the appropriate resources are provided, the machine proceeds to the
  77638. next state. The NEEDBITS() macro is usually the way the state evaluates
  77639. whether it can proceed or should return. NEEDBITS() does the return if
  77640. the requested bits are not available. The typical use of the BITS macros
  77641. is:
  77642. NEEDBITS(n);
  77643. ... do something with BITS(n) ...
  77644. DROPBITS(n);
  77645. where NEEDBITS(n) either returns from inflate() if there isn't enough
  77646. input left to load n bits into the accumulator, or it continues. BITS(n)
  77647. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  77648. the low n bits off the accumulator. INITBITS() clears the accumulator
  77649. and sets the number of available bits to zero. BYTEBITS() discards just
  77650. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  77651. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  77652. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  77653. if there is no input available. The decoding of variable length codes uses
  77654. PULLBYTE() directly in order to pull just enough bytes to decode the next
  77655. code, and no more.
  77656. Some states loop until they get enough input, making sure that enough
  77657. state information is maintained to continue the loop where it left off
  77658. if NEEDBITS() returns in the loop. For example, want, need, and keep
  77659. would all have to actually be part of the saved state in case NEEDBITS()
  77660. returns:
  77661. case STATEw:
  77662. while (want < need) {
  77663. NEEDBITS(n);
  77664. keep[want++] = BITS(n);
  77665. DROPBITS(n);
  77666. }
  77667. state = STATEx;
  77668. case STATEx:
  77669. As shown above, if the next state is also the next case, then the break
  77670. is omitted.
  77671. A state may also return if there is not enough output space available to
  77672. complete that state. Those states are copying stored data, writing a
  77673. literal byte, and copying a matching string.
  77674. When returning, a "goto inf_leave" is used to update the total counters,
  77675. update the check value, and determine whether any progress has been made
  77676. during that inflate() call in order to return the proper return code.
  77677. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  77678. When there is a window, goto inf_leave will update the window with the last
  77679. output written. If a goto inf_leave occurs in the middle of decompression
  77680. and there is no window currently, goto inf_leave will create one and copy
  77681. output to the window for the next call of inflate().
  77682. In this implementation, the flush parameter of inflate() only affects the
  77683. return code (per zlib.h). inflate() always writes as much as possible to
  77684. strm->next_out, given the space available and the provided input--the effect
  77685. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  77686. the allocation of and copying into a sliding window until necessary, which
  77687. provides the effect documented in zlib.h for Z_FINISH when the entire input
  77688. stream available. So the only thing the flush parameter actually does is:
  77689. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  77690. will return Z_BUF_ERROR if it has not reached the end of the stream.
  77691. */
  77692. int ZEXPORT inflate (z_streamp strm, int flush)
  77693. {
  77694. struct inflate_state FAR *state;
  77695. unsigned char FAR *next; /* next input */
  77696. unsigned char FAR *put; /* next output */
  77697. unsigned have, left; /* available input and output */
  77698. unsigned long hold; /* bit buffer */
  77699. unsigned bits; /* bits in bit buffer */
  77700. unsigned in, out; /* save starting available input and output */
  77701. unsigned copy; /* number of stored or match bytes to copy */
  77702. unsigned char FAR *from; /* where to copy match bytes from */
  77703. code thisx; /* current decoding table entry */
  77704. code last; /* parent table entry */
  77705. unsigned len; /* length to copy for repeats, bits to drop */
  77706. int ret; /* return code */
  77707. #ifdef GUNZIP
  77708. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  77709. #endif
  77710. static const unsigned short order[19] = /* permutation of code lengths */
  77711. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  77712. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  77713. (strm->next_in == Z_NULL && strm->avail_in != 0))
  77714. return Z_STREAM_ERROR;
  77715. state = (struct inflate_state FAR *)strm->state;
  77716. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  77717. LOAD();
  77718. in = have;
  77719. out = left;
  77720. ret = Z_OK;
  77721. for (;;)
  77722. switch (state->mode) {
  77723. case HEAD:
  77724. if (state->wrap == 0) {
  77725. state->mode = TYPEDO;
  77726. break;
  77727. }
  77728. NEEDBITS(16);
  77729. #ifdef GUNZIP
  77730. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  77731. state->check = crc32(0L, Z_NULL, 0);
  77732. CRC2(state->check, hold);
  77733. INITBITS();
  77734. state->mode = FLAGS;
  77735. break;
  77736. }
  77737. state->flags = 0; /* expect zlib header */
  77738. if (state->head != Z_NULL)
  77739. state->head->done = -1;
  77740. if (!(state->wrap & 1) || /* check if zlib header allowed */
  77741. #else
  77742. if (
  77743. #endif
  77744. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  77745. strm->msg = (char *)"incorrect header check";
  77746. state->mode = BAD;
  77747. break;
  77748. }
  77749. if (BITS(4) != Z_DEFLATED) {
  77750. strm->msg = (char *)"unknown compression method";
  77751. state->mode = BAD;
  77752. break;
  77753. }
  77754. DROPBITS(4);
  77755. len = BITS(4) + 8;
  77756. if (len > state->wbits) {
  77757. strm->msg = (char *)"invalid window size";
  77758. state->mode = BAD;
  77759. break;
  77760. }
  77761. state->dmax = 1U << len;
  77762. Tracev((stderr, "inflate: zlib header ok\n"));
  77763. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  77764. state->mode = hold & 0x200 ? DICTID : TYPE;
  77765. INITBITS();
  77766. break;
  77767. #ifdef GUNZIP
  77768. case FLAGS:
  77769. NEEDBITS(16);
  77770. state->flags = (int)(hold);
  77771. if ((state->flags & 0xff) != Z_DEFLATED) {
  77772. strm->msg = (char *)"unknown compression method";
  77773. state->mode = BAD;
  77774. break;
  77775. }
  77776. if (state->flags & 0xe000) {
  77777. strm->msg = (char *)"unknown header flags set";
  77778. state->mode = BAD;
  77779. break;
  77780. }
  77781. if (state->head != Z_NULL)
  77782. state->head->text = (int)((hold >> 8) & 1);
  77783. if (state->flags & 0x0200) CRC2(state->check, hold);
  77784. INITBITS();
  77785. state->mode = TIME;
  77786. case TIME:
  77787. NEEDBITS(32);
  77788. if (state->head != Z_NULL)
  77789. state->head->time = hold;
  77790. if (state->flags & 0x0200) CRC4(state->check, hold);
  77791. INITBITS();
  77792. state->mode = OS;
  77793. case OS:
  77794. NEEDBITS(16);
  77795. if (state->head != Z_NULL) {
  77796. state->head->xflags = (int)(hold & 0xff);
  77797. state->head->os = (int)(hold >> 8);
  77798. }
  77799. if (state->flags & 0x0200) CRC2(state->check, hold);
  77800. INITBITS();
  77801. state->mode = EXLEN;
  77802. case EXLEN:
  77803. if (state->flags & 0x0400) {
  77804. NEEDBITS(16);
  77805. state->length = (unsigned)(hold);
  77806. if (state->head != Z_NULL)
  77807. state->head->extra_len = (unsigned)hold;
  77808. if (state->flags & 0x0200) CRC2(state->check, hold);
  77809. INITBITS();
  77810. }
  77811. else if (state->head != Z_NULL)
  77812. state->head->extra = Z_NULL;
  77813. state->mode = EXTRA;
  77814. case EXTRA:
  77815. if (state->flags & 0x0400) {
  77816. copy = state->length;
  77817. if (copy > have) copy = have;
  77818. if (copy) {
  77819. if (state->head != Z_NULL &&
  77820. state->head->extra != Z_NULL) {
  77821. len = state->head->extra_len - state->length;
  77822. zmemcpy(state->head->extra + len, next,
  77823. len + copy > state->head->extra_max ?
  77824. state->head->extra_max - len : copy);
  77825. }
  77826. if (state->flags & 0x0200)
  77827. state->check = crc32(state->check, next, copy);
  77828. have -= copy;
  77829. next += copy;
  77830. state->length -= copy;
  77831. }
  77832. if (state->length) goto inf_leave;
  77833. }
  77834. state->length = 0;
  77835. state->mode = NAME;
  77836. case NAME:
  77837. if (state->flags & 0x0800) {
  77838. if (have == 0) goto inf_leave;
  77839. copy = 0;
  77840. do {
  77841. len = (unsigned)(next[copy++]);
  77842. if (state->head != Z_NULL &&
  77843. state->head->name != Z_NULL &&
  77844. state->length < state->head->name_max)
  77845. state->head->name[state->length++] = len;
  77846. } while (len && copy < have);
  77847. if (state->flags & 0x0200)
  77848. state->check = crc32(state->check, next, copy);
  77849. have -= copy;
  77850. next += copy;
  77851. if (len) goto inf_leave;
  77852. }
  77853. else if (state->head != Z_NULL)
  77854. state->head->name = Z_NULL;
  77855. state->length = 0;
  77856. state->mode = COMMENT;
  77857. case COMMENT:
  77858. if (state->flags & 0x1000) {
  77859. if (have == 0) goto inf_leave;
  77860. copy = 0;
  77861. do {
  77862. len = (unsigned)(next[copy++]);
  77863. if (state->head != Z_NULL &&
  77864. state->head->comment != Z_NULL &&
  77865. state->length < state->head->comm_max)
  77866. state->head->comment[state->length++] = len;
  77867. } while (len && copy < have);
  77868. if (state->flags & 0x0200)
  77869. state->check = crc32(state->check, next, copy);
  77870. have -= copy;
  77871. next += copy;
  77872. if (len) goto inf_leave;
  77873. }
  77874. else if (state->head != Z_NULL)
  77875. state->head->comment = Z_NULL;
  77876. state->mode = HCRC;
  77877. case HCRC:
  77878. if (state->flags & 0x0200) {
  77879. NEEDBITS(16);
  77880. if (hold != (state->check & 0xffff)) {
  77881. strm->msg = (char *)"header crc mismatch";
  77882. state->mode = BAD;
  77883. break;
  77884. }
  77885. INITBITS();
  77886. }
  77887. if (state->head != Z_NULL) {
  77888. state->head->hcrc = (int)((state->flags >> 9) & 1);
  77889. state->head->done = 1;
  77890. }
  77891. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  77892. state->mode = TYPE;
  77893. break;
  77894. #endif
  77895. case DICTID:
  77896. NEEDBITS(32);
  77897. strm->adler = state->check = REVERSE(hold);
  77898. INITBITS();
  77899. state->mode = DICT;
  77900. case DICT:
  77901. if (state->havedict == 0) {
  77902. RESTORE();
  77903. return Z_NEED_DICT;
  77904. }
  77905. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  77906. state->mode = TYPE;
  77907. case TYPE:
  77908. if (flush == Z_BLOCK) goto inf_leave;
  77909. case TYPEDO:
  77910. if (state->last) {
  77911. BYTEBITS();
  77912. state->mode = CHECK;
  77913. break;
  77914. }
  77915. NEEDBITS(3);
  77916. state->last = BITS(1);
  77917. DROPBITS(1);
  77918. switch (BITS(2)) {
  77919. case 0: /* stored block */
  77920. Tracev((stderr, "inflate: stored block%s\n",
  77921. state->last ? " (last)" : ""));
  77922. state->mode = STORED;
  77923. break;
  77924. case 1: /* fixed block */
  77925. fixedtables(state);
  77926. Tracev((stderr, "inflate: fixed codes block%s\n",
  77927. state->last ? " (last)" : ""));
  77928. state->mode = LEN; /* decode codes */
  77929. break;
  77930. case 2: /* dynamic block */
  77931. Tracev((stderr, "inflate: dynamic codes block%s\n",
  77932. state->last ? " (last)" : ""));
  77933. state->mode = TABLE;
  77934. break;
  77935. case 3:
  77936. strm->msg = (char *)"invalid block type";
  77937. state->mode = BAD;
  77938. }
  77939. DROPBITS(2);
  77940. break;
  77941. case STORED:
  77942. BYTEBITS(); /* go to byte boundary */
  77943. NEEDBITS(32);
  77944. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  77945. strm->msg = (char *)"invalid stored block lengths";
  77946. state->mode = BAD;
  77947. break;
  77948. }
  77949. state->length = (unsigned)hold & 0xffff;
  77950. Tracev((stderr, "inflate: stored length %u\n",
  77951. state->length));
  77952. INITBITS();
  77953. state->mode = COPY;
  77954. case COPY:
  77955. copy = state->length;
  77956. if (copy) {
  77957. if (copy > have) copy = have;
  77958. if (copy > left) copy = left;
  77959. if (copy == 0) goto inf_leave;
  77960. zmemcpy(put, next, copy);
  77961. have -= copy;
  77962. next += copy;
  77963. left -= copy;
  77964. put += copy;
  77965. state->length -= copy;
  77966. break;
  77967. }
  77968. Tracev((stderr, "inflate: stored end\n"));
  77969. state->mode = TYPE;
  77970. break;
  77971. case TABLE:
  77972. NEEDBITS(14);
  77973. state->nlen = BITS(5) + 257;
  77974. DROPBITS(5);
  77975. state->ndist = BITS(5) + 1;
  77976. DROPBITS(5);
  77977. state->ncode = BITS(4) + 4;
  77978. DROPBITS(4);
  77979. #ifndef PKZIP_BUG_WORKAROUND
  77980. if (state->nlen > 286 || state->ndist > 30) {
  77981. strm->msg = (char *)"too many length or distance symbols";
  77982. state->mode = BAD;
  77983. break;
  77984. }
  77985. #endif
  77986. Tracev((stderr, "inflate: table sizes ok\n"));
  77987. state->have = 0;
  77988. state->mode = LENLENS;
  77989. case LENLENS:
  77990. while (state->have < state->ncode) {
  77991. NEEDBITS(3);
  77992. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  77993. DROPBITS(3);
  77994. }
  77995. while (state->have < 19)
  77996. state->lens[order[state->have++]] = 0;
  77997. state->next = state->codes;
  77998. state->lencode = (code const FAR *)(state->next);
  77999. state->lenbits = 7;
  78000. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  78001. &(state->lenbits), state->work);
  78002. if (ret) {
  78003. strm->msg = (char *)"invalid code lengths set";
  78004. state->mode = BAD;
  78005. break;
  78006. }
  78007. Tracev((stderr, "inflate: code lengths ok\n"));
  78008. state->have = 0;
  78009. state->mode = CODELENS;
  78010. case CODELENS:
  78011. while (state->have < state->nlen + state->ndist) {
  78012. for (;;) {
  78013. thisx = state->lencode[BITS(state->lenbits)];
  78014. if ((unsigned)(thisx.bits) <= bits) break;
  78015. PULLBYTE();
  78016. }
  78017. if (thisx.val < 16) {
  78018. NEEDBITS(thisx.bits);
  78019. DROPBITS(thisx.bits);
  78020. state->lens[state->have++] = thisx.val;
  78021. }
  78022. else {
  78023. if (thisx.val == 16) {
  78024. NEEDBITS(thisx.bits + 2);
  78025. DROPBITS(thisx.bits);
  78026. if (state->have == 0) {
  78027. strm->msg = (char *)"invalid bit length repeat";
  78028. state->mode = BAD;
  78029. break;
  78030. }
  78031. len = state->lens[state->have - 1];
  78032. copy = 3 + BITS(2);
  78033. DROPBITS(2);
  78034. }
  78035. else if (thisx.val == 17) {
  78036. NEEDBITS(thisx.bits + 3);
  78037. DROPBITS(thisx.bits);
  78038. len = 0;
  78039. copy = 3 + BITS(3);
  78040. DROPBITS(3);
  78041. }
  78042. else {
  78043. NEEDBITS(thisx.bits + 7);
  78044. DROPBITS(thisx.bits);
  78045. len = 0;
  78046. copy = 11 + BITS(7);
  78047. DROPBITS(7);
  78048. }
  78049. if (state->have + copy > state->nlen + state->ndist) {
  78050. strm->msg = (char *)"invalid bit length repeat";
  78051. state->mode = BAD;
  78052. break;
  78053. }
  78054. while (copy--)
  78055. state->lens[state->have++] = (unsigned short)len;
  78056. }
  78057. }
  78058. /* handle error breaks in while */
  78059. if (state->mode == BAD) break;
  78060. /* build code tables */
  78061. state->next = state->codes;
  78062. state->lencode = (code const FAR *)(state->next);
  78063. state->lenbits = 9;
  78064. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  78065. &(state->lenbits), state->work);
  78066. if (ret) {
  78067. strm->msg = (char *)"invalid literal/lengths set";
  78068. state->mode = BAD;
  78069. break;
  78070. }
  78071. state->distcode = (code const FAR *)(state->next);
  78072. state->distbits = 6;
  78073. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  78074. &(state->next), &(state->distbits), state->work);
  78075. if (ret) {
  78076. strm->msg = (char *)"invalid distances set";
  78077. state->mode = BAD;
  78078. break;
  78079. }
  78080. Tracev((stderr, "inflate: codes ok\n"));
  78081. state->mode = LEN;
  78082. case LEN:
  78083. if (have >= 6 && left >= 258) {
  78084. RESTORE();
  78085. inflate_fast(strm, out);
  78086. LOAD();
  78087. break;
  78088. }
  78089. for (;;) {
  78090. thisx = state->lencode[BITS(state->lenbits)];
  78091. if ((unsigned)(thisx.bits) <= bits) break;
  78092. PULLBYTE();
  78093. }
  78094. if (thisx.op && (thisx.op & 0xf0) == 0) {
  78095. last = thisx;
  78096. for (;;) {
  78097. thisx = state->lencode[last.val +
  78098. (BITS(last.bits + last.op) >> last.bits)];
  78099. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  78100. PULLBYTE();
  78101. }
  78102. DROPBITS(last.bits);
  78103. }
  78104. DROPBITS(thisx.bits);
  78105. state->length = (unsigned)thisx.val;
  78106. if ((int)(thisx.op) == 0) {
  78107. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  78108. "inflate: literal '%c'\n" :
  78109. "inflate: literal 0x%02x\n", thisx.val));
  78110. state->mode = LIT;
  78111. break;
  78112. }
  78113. if (thisx.op & 32) {
  78114. Tracevv((stderr, "inflate: end of block\n"));
  78115. state->mode = TYPE;
  78116. break;
  78117. }
  78118. if (thisx.op & 64) {
  78119. strm->msg = (char *)"invalid literal/length code";
  78120. state->mode = BAD;
  78121. break;
  78122. }
  78123. state->extra = (unsigned)(thisx.op) & 15;
  78124. state->mode = LENEXT;
  78125. case LENEXT:
  78126. if (state->extra) {
  78127. NEEDBITS(state->extra);
  78128. state->length += BITS(state->extra);
  78129. DROPBITS(state->extra);
  78130. }
  78131. Tracevv((stderr, "inflate: length %u\n", state->length));
  78132. state->mode = DIST;
  78133. case DIST:
  78134. for (;;) {
  78135. thisx = state->distcode[BITS(state->distbits)];
  78136. if ((unsigned)(thisx.bits) <= bits) break;
  78137. PULLBYTE();
  78138. }
  78139. if ((thisx.op & 0xf0) == 0) {
  78140. last = thisx;
  78141. for (;;) {
  78142. thisx = state->distcode[last.val +
  78143. (BITS(last.bits + last.op) >> last.bits)];
  78144. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  78145. PULLBYTE();
  78146. }
  78147. DROPBITS(last.bits);
  78148. }
  78149. DROPBITS(thisx.bits);
  78150. if (thisx.op & 64) {
  78151. strm->msg = (char *)"invalid distance code";
  78152. state->mode = BAD;
  78153. break;
  78154. }
  78155. state->offset = (unsigned)thisx.val;
  78156. state->extra = (unsigned)(thisx.op) & 15;
  78157. state->mode = DISTEXT;
  78158. case DISTEXT:
  78159. if (state->extra) {
  78160. NEEDBITS(state->extra);
  78161. state->offset += BITS(state->extra);
  78162. DROPBITS(state->extra);
  78163. }
  78164. #ifdef INFLATE_STRICT
  78165. if (state->offset > state->dmax) {
  78166. strm->msg = (char *)"invalid distance too far back";
  78167. state->mode = BAD;
  78168. break;
  78169. }
  78170. #endif
  78171. if (state->offset > state->whave + out - left) {
  78172. strm->msg = (char *)"invalid distance too far back";
  78173. state->mode = BAD;
  78174. break;
  78175. }
  78176. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  78177. state->mode = MATCH;
  78178. case MATCH:
  78179. if (left == 0) goto inf_leave;
  78180. copy = out - left;
  78181. if (state->offset > copy) { /* copy from window */
  78182. copy = state->offset - copy;
  78183. if (copy > state->write) {
  78184. copy -= state->write;
  78185. from = state->window + (state->wsize - copy);
  78186. }
  78187. else
  78188. from = state->window + (state->write - copy);
  78189. if (copy > state->length) copy = state->length;
  78190. }
  78191. else { /* copy from output */
  78192. from = put - state->offset;
  78193. copy = state->length;
  78194. }
  78195. if (copy > left) copy = left;
  78196. left -= copy;
  78197. state->length -= copy;
  78198. do {
  78199. *put++ = *from++;
  78200. } while (--copy);
  78201. if (state->length == 0) state->mode = LEN;
  78202. break;
  78203. case LIT:
  78204. if (left == 0) goto inf_leave;
  78205. *put++ = (unsigned char)(state->length);
  78206. left--;
  78207. state->mode = LEN;
  78208. break;
  78209. case CHECK:
  78210. if (state->wrap) {
  78211. NEEDBITS(32);
  78212. out -= left;
  78213. strm->total_out += out;
  78214. state->total += out;
  78215. if (out)
  78216. strm->adler = state->check =
  78217. UPDATE(state->check, put - out, out);
  78218. out = left;
  78219. if ((
  78220. #ifdef GUNZIP
  78221. state->flags ? hold :
  78222. #endif
  78223. REVERSE(hold)) != state->check) {
  78224. strm->msg = (char *)"incorrect data check";
  78225. state->mode = BAD;
  78226. break;
  78227. }
  78228. INITBITS();
  78229. Tracev((stderr, "inflate: check matches trailer\n"));
  78230. }
  78231. #ifdef GUNZIP
  78232. state->mode = LENGTH;
  78233. case LENGTH:
  78234. if (state->wrap && state->flags) {
  78235. NEEDBITS(32);
  78236. if (hold != (state->total & 0xffffffffUL)) {
  78237. strm->msg = (char *)"incorrect length check";
  78238. state->mode = BAD;
  78239. break;
  78240. }
  78241. INITBITS();
  78242. Tracev((stderr, "inflate: length matches trailer\n"));
  78243. }
  78244. #endif
  78245. state->mode = DONE;
  78246. case DONE:
  78247. ret = Z_STREAM_END;
  78248. goto inf_leave;
  78249. case BAD:
  78250. ret = Z_DATA_ERROR;
  78251. goto inf_leave;
  78252. case MEM:
  78253. return Z_MEM_ERROR;
  78254. case SYNC:
  78255. default:
  78256. return Z_STREAM_ERROR;
  78257. }
  78258. /*
  78259. Return from inflate(), updating the total counts and the check value.
  78260. If there was no progress during the inflate() call, return a buffer
  78261. error. Call updatewindow() to create and/or update the window state.
  78262. Note: a memory error from inflate() is non-recoverable.
  78263. */
  78264. inf_leave:
  78265. RESTORE();
  78266. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  78267. if (updatewindow(strm, out)) {
  78268. state->mode = MEM;
  78269. return Z_MEM_ERROR;
  78270. }
  78271. in -= strm->avail_in;
  78272. out -= strm->avail_out;
  78273. strm->total_in += in;
  78274. strm->total_out += out;
  78275. state->total += out;
  78276. if (state->wrap && out)
  78277. strm->adler = state->check =
  78278. UPDATE(state->check, strm->next_out - out, out);
  78279. strm->data_type = state->bits + (state->last ? 64 : 0) +
  78280. (state->mode == TYPE ? 128 : 0);
  78281. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  78282. ret = Z_BUF_ERROR;
  78283. return ret;
  78284. }
  78285. int ZEXPORT inflateEnd (z_streamp strm)
  78286. {
  78287. struct inflate_state FAR *state;
  78288. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  78289. return Z_STREAM_ERROR;
  78290. state = (struct inflate_state FAR *)strm->state;
  78291. if (state->window != Z_NULL) ZFREE(strm, state->window);
  78292. ZFREE(strm, strm->state);
  78293. strm->state = Z_NULL;
  78294. Tracev((stderr, "inflate: end\n"));
  78295. return Z_OK;
  78296. }
  78297. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  78298. {
  78299. struct inflate_state FAR *state;
  78300. unsigned long id_;
  78301. /* check state */
  78302. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78303. state = (struct inflate_state FAR *)strm->state;
  78304. if (state->wrap != 0 && state->mode != DICT)
  78305. return Z_STREAM_ERROR;
  78306. /* check for correct dictionary id */
  78307. if (state->mode == DICT) {
  78308. id_ = adler32(0L, Z_NULL, 0);
  78309. id_ = adler32(id_, dictionary, dictLength);
  78310. if (id_ != state->check)
  78311. return Z_DATA_ERROR;
  78312. }
  78313. /* copy dictionary to window */
  78314. if (updatewindow(strm, strm->avail_out)) {
  78315. state->mode = MEM;
  78316. return Z_MEM_ERROR;
  78317. }
  78318. if (dictLength > state->wsize) {
  78319. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  78320. state->wsize);
  78321. state->whave = state->wsize;
  78322. }
  78323. else {
  78324. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  78325. dictLength);
  78326. state->whave = dictLength;
  78327. }
  78328. state->havedict = 1;
  78329. Tracev((stderr, "inflate: dictionary set\n"));
  78330. return Z_OK;
  78331. }
  78332. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  78333. {
  78334. struct inflate_state FAR *state;
  78335. /* check state */
  78336. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78337. state = (struct inflate_state FAR *)strm->state;
  78338. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  78339. /* save header structure */
  78340. state->head = head;
  78341. head->done = 0;
  78342. return Z_OK;
  78343. }
  78344. /*
  78345. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  78346. or when out of input. When called, *have is the number of pattern bytes
  78347. found in order so far, in 0..3. On return *have is updated to the new
  78348. state. If on return *have equals four, then the pattern was found and the
  78349. return value is how many bytes were read including the last byte of the
  78350. pattern. If *have is less than four, then the pattern has not been found
  78351. yet and the return value is len. In the latter case, syncsearch() can be
  78352. called again with more data and the *have state. *have is initialized to
  78353. zero for the first call.
  78354. */
  78355. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  78356. {
  78357. unsigned got;
  78358. unsigned next;
  78359. got = *have;
  78360. next = 0;
  78361. while (next < len && got < 4) {
  78362. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  78363. got++;
  78364. else if (buf[next])
  78365. got = 0;
  78366. else
  78367. got = 4 - got;
  78368. next++;
  78369. }
  78370. *have = got;
  78371. return next;
  78372. }
  78373. int ZEXPORT inflateSync (z_streamp strm)
  78374. {
  78375. unsigned len; /* number of bytes to look at or looked at */
  78376. unsigned long in, out; /* temporary to save total_in and total_out */
  78377. unsigned char buf[4]; /* to restore bit buffer to byte string */
  78378. struct inflate_state FAR *state;
  78379. /* check parameters */
  78380. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78381. state = (struct inflate_state FAR *)strm->state;
  78382. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  78383. /* if first time, start search in bit buffer */
  78384. if (state->mode != SYNC) {
  78385. state->mode = SYNC;
  78386. state->hold <<= state->bits & 7;
  78387. state->bits -= state->bits & 7;
  78388. len = 0;
  78389. while (state->bits >= 8) {
  78390. buf[len++] = (unsigned char)(state->hold);
  78391. state->hold >>= 8;
  78392. state->bits -= 8;
  78393. }
  78394. state->have = 0;
  78395. syncsearch(&(state->have), buf, len);
  78396. }
  78397. /* search available input */
  78398. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  78399. strm->avail_in -= len;
  78400. strm->next_in += len;
  78401. strm->total_in += len;
  78402. /* return no joy or set up to restart inflate() on a new block */
  78403. if (state->have != 4) return Z_DATA_ERROR;
  78404. in = strm->total_in; out = strm->total_out;
  78405. inflateReset(strm);
  78406. strm->total_in = in; strm->total_out = out;
  78407. state->mode = TYPE;
  78408. return Z_OK;
  78409. }
  78410. /*
  78411. Returns true if inflate is currently at the end of a block generated by
  78412. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  78413. implementation to provide an additional safety check. PPP uses
  78414. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  78415. block. When decompressing, PPP checks that at the end of input packet,
  78416. inflate is waiting for these length bytes.
  78417. */
  78418. int ZEXPORT inflateSyncPoint (z_streamp strm)
  78419. {
  78420. struct inflate_state FAR *state;
  78421. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78422. state = (struct inflate_state FAR *)strm->state;
  78423. return state->mode == STORED && state->bits == 0;
  78424. }
  78425. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  78426. {
  78427. struct inflate_state FAR *state;
  78428. struct inflate_state FAR *copy;
  78429. unsigned char FAR *window;
  78430. unsigned wsize;
  78431. /* check input */
  78432. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  78433. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  78434. return Z_STREAM_ERROR;
  78435. state = (struct inflate_state FAR *)source->state;
  78436. /* allocate space */
  78437. copy = (struct inflate_state FAR *)
  78438. ZALLOC(source, 1, sizeof(struct inflate_state));
  78439. if (copy == Z_NULL) return Z_MEM_ERROR;
  78440. window = Z_NULL;
  78441. if (state->window != Z_NULL) {
  78442. window = (unsigned char FAR *)
  78443. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  78444. if (window == Z_NULL) {
  78445. ZFREE(source, copy);
  78446. return Z_MEM_ERROR;
  78447. }
  78448. }
  78449. /* copy state */
  78450. zmemcpy(dest, source, sizeof(z_stream));
  78451. zmemcpy(copy, state, sizeof(struct inflate_state));
  78452. if (state->lencode >= state->codes &&
  78453. state->lencode <= state->codes + ENOUGH - 1) {
  78454. copy->lencode = copy->codes + (state->lencode - state->codes);
  78455. copy->distcode = copy->codes + (state->distcode - state->codes);
  78456. }
  78457. copy->next = copy->codes + (state->next - state->codes);
  78458. if (window != Z_NULL) {
  78459. wsize = 1U << state->wbits;
  78460. zmemcpy(window, state->window, wsize);
  78461. }
  78462. copy->window = window;
  78463. dest->state = (struct internal_state FAR *)copy;
  78464. return Z_OK;
  78465. }
  78466. /********* End of inlined file: inflate.c *********/
  78467. /********* Start of inlined file: inftrees.c *********/
  78468. #define MAXBITS 15
  78469. const char inflate_copyright[] =
  78470. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  78471. /*
  78472. If you use the zlib library in a product, an acknowledgment is welcome
  78473. in the documentation of your product. If for some reason you cannot
  78474. include such an acknowledgment, I would appreciate that you keep this
  78475. copyright string in the executable of your product.
  78476. */
  78477. /*
  78478. Build a set of tables to decode the provided canonical Huffman code.
  78479. The code lengths are lens[0..codes-1]. The result starts at *table,
  78480. whose indices are 0..2^bits-1. work is a writable array of at least
  78481. lens shorts, which is used as a work area. type is the type of code
  78482. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  78483. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  78484. on return points to the next available entry's address. bits is the
  78485. requested root table index bits, and on return it is the actual root
  78486. table index bits. It will differ if the request is greater than the
  78487. longest code or if it is less than the shortest code.
  78488. */
  78489. int inflate_table (codetype type,
  78490. unsigned short FAR *lens,
  78491. unsigned codes,
  78492. code FAR * FAR *table,
  78493. unsigned FAR *bits,
  78494. unsigned short FAR *work)
  78495. {
  78496. unsigned len; /* a code's length in bits */
  78497. unsigned sym; /* index of code symbols */
  78498. unsigned min, max; /* minimum and maximum code lengths */
  78499. unsigned root; /* number of index bits for root table */
  78500. unsigned curr; /* number of index bits for current table */
  78501. unsigned drop; /* code bits to drop for sub-table */
  78502. int left; /* number of prefix codes available */
  78503. unsigned used; /* code entries in table used */
  78504. unsigned huff; /* Huffman code */
  78505. unsigned incr; /* for incrementing code, index */
  78506. unsigned fill; /* index for replicating entries */
  78507. unsigned low; /* low bits for current root entry */
  78508. unsigned mask; /* mask for low root bits */
  78509. code thisx; /* table entry for duplication */
  78510. code FAR *next; /* next available space in table */
  78511. const unsigned short FAR *base; /* base value table to use */
  78512. const unsigned short FAR *extra; /* extra bits table to use */
  78513. int end; /* use base and extra for symbol > end */
  78514. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  78515. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  78516. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  78517. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  78518. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  78519. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  78520. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  78521. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  78522. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  78523. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  78524. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  78525. 8193, 12289, 16385, 24577, 0, 0};
  78526. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  78527. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  78528. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  78529. 28, 28, 29, 29, 64, 64};
  78530. /*
  78531. Process a set of code lengths to create a canonical Huffman code. The
  78532. code lengths are lens[0..codes-1]. Each length corresponds to the
  78533. symbols 0..codes-1. The Huffman code is generated by first sorting the
  78534. symbols by length from short to long, and retaining the symbol order
  78535. for codes with equal lengths. Then the code starts with all zero bits
  78536. for the first code of the shortest length, and the codes are integer
  78537. increments for the same length, and zeros are appended as the length
  78538. increases. For the deflate format, these bits are stored backwards
  78539. from their more natural integer increment ordering, and so when the
  78540. decoding tables are built in the large loop below, the integer codes
  78541. are incremented backwards.
  78542. This routine assumes, but does not check, that all of the entries in
  78543. lens[] are in the range 0..MAXBITS. The caller must assure this.
  78544. 1..MAXBITS is interpreted as that code length. zero means that that
  78545. symbol does not occur in this code.
  78546. The codes are sorted by computing a count of codes for each length,
  78547. creating from that a table of starting indices for each length in the
  78548. sorted table, and then entering the symbols in order in the sorted
  78549. table. The sorted table is work[], with that space being provided by
  78550. the caller.
  78551. The length counts are used for other purposes as well, i.e. finding
  78552. the minimum and maximum length codes, determining if there are any
  78553. codes at all, checking for a valid set of lengths, and looking ahead
  78554. at length counts to determine sub-table sizes when building the
  78555. decoding tables.
  78556. */
  78557. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  78558. for (len = 0; len <= MAXBITS; len++)
  78559. count[len] = 0;
  78560. for (sym = 0; sym < codes; sym++)
  78561. count[lens[sym]]++;
  78562. /* bound code lengths, force root to be within code lengths */
  78563. root = *bits;
  78564. for (max = MAXBITS; max >= 1; max--)
  78565. if (count[max] != 0) break;
  78566. if (root > max) root = max;
  78567. if (max == 0) { /* no symbols to code at all */
  78568. thisx.op = (unsigned char)64; /* invalid code marker */
  78569. thisx.bits = (unsigned char)1;
  78570. thisx.val = (unsigned short)0;
  78571. *(*table)++ = thisx; /* make a table to force an error */
  78572. *(*table)++ = thisx;
  78573. *bits = 1;
  78574. return 0; /* no symbols, but wait for decoding to report error */
  78575. }
  78576. for (min = 1; min <= MAXBITS; min++)
  78577. if (count[min] != 0) break;
  78578. if (root < min) root = min;
  78579. /* check for an over-subscribed or incomplete set of lengths */
  78580. left = 1;
  78581. for (len = 1; len <= MAXBITS; len++) {
  78582. left <<= 1;
  78583. left -= count[len];
  78584. if (left < 0) return -1; /* over-subscribed */
  78585. }
  78586. if (left > 0 && (type == CODES || max != 1))
  78587. return -1; /* incomplete set */
  78588. /* generate offsets into symbol table for each length for sorting */
  78589. offs[1] = 0;
  78590. for (len = 1; len < MAXBITS; len++)
  78591. offs[len + 1] = offs[len] + count[len];
  78592. /* sort symbols by length, by symbol order within each length */
  78593. for (sym = 0; sym < codes; sym++)
  78594. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  78595. /*
  78596. Create and fill in decoding tables. In this loop, the table being
  78597. filled is at next and has curr index bits. The code being used is huff
  78598. with length len. That code is converted to an index by dropping drop
  78599. bits off of the bottom. For codes where len is less than drop + curr,
  78600. those top drop + curr - len bits are incremented through all values to
  78601. fill the table with replicated entries.
  78602. root is the number of index bits for the root table. When len exceeds
  78603. root, sub-tables are created pointed to by the root entry with an index
  78604. of the low root bits of huff. This is saved in low to check for when a
  78605. new sub-table should be started. drop is zero when the root table is
  78606. being filled, and drop is root when sub-tables are being filled.
  78607. When a new sub-table is needed, it is necessary to look ahead in the
  78608. code lengths to determine what size sub-table is needed. The length
  78609. counts are used for this, and so count[] is decremented as codes are
  78610. entered in the tables.
  78611. used keeps track of how many table entries have been allocated from the
  78612. provided *table space. It is checked when a LENS table is being made
  78613. against the space in *table, ENOUGH, minus the maximum space needed by
  78614. the worst case distance code, MAXD. This should never happen, but the
  78615. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  78616. This assumes that when type == LENS, bits == 9.
  78617. sym increments through all symbols, and the loop terminates when
  78618. all codes of length max, i.e. all codes, have been processed. This
  78619. routine permits incomplete codes, so another loop after this one fills
  78620. in the rest of the decoding tables with invalid code markers.
  78621. */
  78622. /* set up for code type */
  78623. switch (type) {
  78624. case CODES:
  78625. base = extra = work; /* dummy value--not used */
  78626. end = 19;
  78627. break;
  78628. case LENS:
  78629. base = lbase;
  78630. base -= 257;
  78631. extra = lext;
  78632. extra -= 257;
  78633. end = 256;
  78634. break;
  78635. default: /* DISTS */
  78636. base = dbase;
  78637. extra = dext;
  78638. end = -1;
  78639. }
  78640. /* initialize state for loop */
  78641. huff = 0; /* starting code */
  78642. sym = 0; /* starting code symbol */
  78643. len = min; /* starting code length */
  78644. next = *table; /* current table to fill in */
  78645. curr = root; /* current table index bits */
  78646. drop = 0; /* current bits to drop from code for index */
  78647. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  78648. used = 1U << root; /* use root table entries */
  78649. mask = used - 1; /* mask for comparing low */
  78650. /* check available table space */
  78651. if (type == LENS && used >= ENOUGH - MAXD)
  78652. return 1;
  78653. /* process all codes and make table entries */
  78654. for (;;) {
  78655. /* create table entry */
  78656. thisx.bits = (unsigned char)(len - drop);
  78657. if ((int)(work[sym]) < end) {
  78658. thisx.op = (unsigned char)0;
  78659. thisx.val = work[sym];
  78660. }
  78661. else if ((int)(work[sym]) > end) {
  78662. thisx.op = (unsigned char)(extra[work[sym]]);
  78663. thisx.val = base[work[sym]];
  78664. }
  78665. else {
  78666. thisx.op = (unsigned char)(32 + 64); /* end of block */
  78667. thisx.val = 0;
  78668. }
  78669. /* replicate for those indices with low len bits equal to huff */
  78670. incr = 1U << (len - drop);
  78671. fill = 1U << curr;
  78672. min = fill; /* save offset to next table */
  78673. do {
  78674. fill -= incr;
  78675. next[(huff >> drop) + fill] = thisx;
  78676. } while (fill != 0);
  78677. /* backwards increment the len-bit code huff */
  78678. incr = 1U << (len - 1);
  78679. while (huff & incr)
  78680. incr >>= 1;
  78681. if (incr != 0) {
  78682. huff &= incr - 1;
  78683. huff += incr;
  78684. }
  78685. else
  78686. huff = 0;
  78687. /* go to next symbol, update count, len */
  78688. sym++;
  78689. if (--(count[len]) == 0) {
  78690. if (len == max) break;
  78691. len = lens[work[sym]];
  78692. }
  78693. /* create new sub-table if needed */
  78694. if (len > root && (huff & mask) != low) {
  78695. /* if first time, transition to sub-tables */
  78696. if (drop == 0)
  78697. drop = root;
  78698. /* increment past last table */
  78699. next += min; /* here min is 1 << curr */
  78700. /* determine length of next table */
  78701. curr = len - drop;
  78702. left = (int)(1 << curr);
  78703. while (curr + drop < max) {
  78704. left -= count[curr + drop];
  78705. if (left <= 0) break;
  78706. curr++;
  78707. left <<= 1;
  78708. }
  78709. /* check for enough space */
  78710. used += 1U << curr;
  78711. if (type == LENS && used >= ENOUGH - MAXD)
  78712. return 1;
  78713. /* point entry in root table to sub-table */
  78714. low = huff & mask;
  78715. (*table)[low].op = (unsigned char)curr;
  78716. (*table)[low].bits = (unsigned char)root;
  78717. (*table)[low].val = (unsigned short)(next - *table);
  78718. }
  78719. }
  78720. /*
  78721. Fill in rest of table for incomplete codes. This loop is similar to the
  78722. loop above in incrementing huff for table indices. It is assumed that
  78723. len is equal to curr + drop, so there is no loop needed to increment
  78724. through high index bits. When the current sub-table is filled, the loop
  78725. drops back to the root table to fill in any remaining entries there.
  78726. */
  78727. thisx.op = (unsigned char)64; /* invalid code marker */
  78728. thisx.bits = (unsigned char)(len - drop);
  78729. thisx.val = (unsigned short)0;
  78730. while (huff != 0) {
  78731. /* when done with sub-table, drop back to root table */
  78732. if (drop != 0 && (huff & mask) != low) {
  78733. drop = 0;
  78734. len = root;
  78735. next = *table;
  78736. thisx.bits = (unsigned char)len;
  78737. }
  78738. /* put invalid code marker in table */
  78739. next[huff >> drop] = thisx;
  78740. /* backwards increment the len-bit code huff */
  78741. incr = 1U << (len - 1);
  78742. while (huff & incr)
  78743. incr >>= 1;
  78744. if (incr != 0) {
  78745. huff &= incr - 1;
  78746. huff += incr;
  78747. }
  78748. else
  78749. huff = 0;
  78750. }
  78751. /* set return parameters */
  78752. *table += used;
  78753. *bits = root;
  78754. return 0;
  78755. }
  78756. /********* End of inlined file: inftrees.c *********/
  78757. /********* Start of inlined file: trees.c *********/
  78758. /*
  78759. * ALGORITHM
  78760. *
  78761. * The "deflation" process uses several Huffman trees. The more
  78762. * common source values are represented by shorter bit sequences.
  78763. *
  78764. * Each code tree is stored in a compressed form which is itself
  78765. * a Huffman encoding of the lengths of all the code strings (in
  78766. * ascending order by source values). The actual code strings are
  78767. * reconstructed from the lengths in the inflate process, as described
  78768. * in the deflate specification.
  78769. *
  78770. * REFERENCES
  78771. *
  78772. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  78773. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  78774. *
  78775. * Storer, James A.
  78776. * Data Compression: Methods and Theory, pp. 49-50.
  78777. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  78778. *
  78779. * Sedgewick, R.
  78780. * Algorithms, p290.
  78781. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  78782. */
  78783. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78784. /* #define GEN_TREES_H */
  78785. #ifdef DEBUG
  78786. # include <ctype.h>
  78787. #endif
  78788. /* ===========================================================================
  78789. * Constants
  78790. */
  78791. #define MAX_BL_BITS 7
  78792. /* Bit length codes must not exceed MAX_BL_BITS bits */
  78793. #define END_BLOCK 256
  78794. /* end of block literal code */
  78795. #define REP_3_6 16
  78796. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  78797. #define REPZ_3_10 17
  78798. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  78799. #define REPZ_11_138 18
  78800. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  78801. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  78802. = {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};
  78803. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  78804. = {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};
  78805. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  78806. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  78807. local const uch bl_order[BL_CODES]
  78808. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  78809. /* The lengths of the bit length codes are sent in order of decreasing
  78810. * probability, to avoid transmitting the lengths for unused bit length codes.
  78811. */
  78812. #define Buf_size (8 * 2*sizeof(char))
  78813. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  78814. * more than 16 bits on some systems.)
  78815. */
  78816. /* ===========================================================================
  78817. * Local data. These are initialized only once.
  78818. */
  78819. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  78820. #if defined(GEN_TREES_H) || !defined(STDC)
  78821. /* non ANSI compilers may not accept trees.h */
  78822. local ct_data static_ltree[L_CODES+2];
  78823. /* The static literal tree. Since the bit lengths are imposed, there is no
  78824. * need for the L_CODES extra codes used during heap construction. However
  78825. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  78826. * below).
  78827. */
  78828. local ct_data static_dtree[D_CODES];
  78829. /* The static distance tree. (Actually a trivial tree since all codes use
  78830. * 5 bits.)
  78831. */
  78832. uch _dist_code[DIST_CODE_LEN];
  78833. /* Distance codes. The first 256 values correspond to the distances
  78834. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  78835. * the 15 bit distances.
  78836. */
  78837. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  78838. /* length code for each normalized match length (0 == MIN_MATCH) */
  78839. local int base_length[LENGTH_CODES];
  78840. /* First normalized length for each code (0 = MIN_MATCH) */
  78841. local int base_dist[D_CODES];
  78842. /* First normalized distance for each code (0 = distance of 1) */
  78843. #else
  78844. /********* Start of inlined file: trees.h *********/
  78845. local const ct_data static_ltree[L_CODES+2] = {
  78846. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  78847. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  78848. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  78849. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  78850. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  78851. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  78852. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  78853. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  78854. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  78855. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  78856. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  78857. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  78858. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  78859. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  78860. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  78861. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  78862. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  78863. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  78864. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  78865. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  78866. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  78867. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  78868. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  78869. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  78870. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  78871. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  78872. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  78873. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  78874. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  78875. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  78876. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  78877. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  78878. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  78879. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  78880. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  78881. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  78882. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  78883. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  78884. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  78885. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  78886. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  78887. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  78888. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  78889. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  78890. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  78891. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  78892. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  78893. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  78894. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  78895. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  78896. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  78897. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  78898. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  78899. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  78900. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  78901. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  78902. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  78903. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  78904. };
  78905. local const ct_data static_dtree[D_CODES] = {
  78906. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  78907. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  78908. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  78909. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  78910. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  78911. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  78912. };
  78913. const uch _dist_code[DIST_CODE_LEN] = {
  78914. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  78915. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  78916. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  78917. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  78918. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  78919. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  78920. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  78921. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  78922. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  78923. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  78924. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  78925. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  78926. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  78927. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  78928. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  78929. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  78930. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  78931. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  78932. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  78933. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  78934. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  78935. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  78936. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  78937. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  78938. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  78939. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  78940. };
  78941. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  78942. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  78943. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  78944. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  78945. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  78946. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  78947. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  78948. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  78949. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  78950. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  78951. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  78952. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  78953. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  78954. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  78955. };
  78956. local const int base_length[LENGTH_CODES] = {
  78957. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  78958. 64, 80, 96, 112, 128, 160, 192, 224, 0
  78959. };
  78960. local const int base_dist[D_CODES] = {
  78961. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  78962. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  78963. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  78964. };
  78965. /********* End of inlined file: trees.h *********/
  78966. #endif /* GEN_TREES_H */
  78967. struct static_tree_desc_s {
  78968. const ct_data *static_tree; /* static tree or NULL */
  78969. const intf *extra_bits; /* extra bits for each code or NULL */
  78970. int extra_base; /* base index for extra_bits */
  78971. int elems; /* max number of elements in the tree */
  78972. int max_length; /* max bit length for the codes */
  78973. };
  78974. local static_tree_desc static_l_desc =
  78975. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  78976. local static_tree_desc static_d_desc =
  78977. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  78978. local static_tree_desc static_bl_desc =
  78979. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  78980. /* ===========================================================================
  78981. * Local (static) routines in this file.
  78982. */
  78983. local void tr_static_init OF((void));
  78984. local void init_block OF((deflate_state *s));
  78985. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  78986. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  78987. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  78988. local void build_tree OF((deflate_state *s, tree_desc *desc));
  78989. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  78990. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  78991. local int build_bl_tree OF((deflate_state *s));
  78992. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  78993. int blcodes));
  78994. local void compress_block OF((deflate_state *s, ct_data *ltree,
  78995. ct_data *dtree));
  78996. local void set_data_type OF((deflate_state *s));
  78997. local unsigned bi_reverse OF((unsigned value, int length));
  78998. local void bi_windup OF((deflate_state *s));
  78999. local void bi_flush OF((deflate_state *s));
  79000. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  79001. int header));
  79002. #ifdef GEN_TREES_H
  79003. local void gen_trees_header OF((void));
  79004. #endif
  79005. #ifndef DEBUG
  79006. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  79007. /* Send a code of the given tree. c and tree must not have side effects */
  79008. #else /* DEBUG */
  79009. # define send_code(s, c, tree) \
  79010. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  79011. send_bits(s, tree[c].Code, tree[c].Len); }
  79012. #endif
  79013. /* ===========================================================================
  79014. * Output a short LSB first on the stream.
  79015. * IN assertion: there is enough room in pendingBuf.
  79016. */
  79017. #define put_short(s, w) { \
  79018. put_byte(s, (uch)((w) & 0xff)); \
  79019. put_byte(s, (uch)((ush)(w) >> 8)); \
  79020. }
  79021. /* ===========================================================================
  79022. * Send a value on a given number of bits.
  79023. * IN assertion: length <= 16 and value fits in length bits.
  79024. */
  79025. #ifdef DEBUG
  79026. local void send_bits OF((deflate_state *s, int value, int length));
  79027. local void send_bits (deflate_state *s, int value, int length)
  79028. {
  79029. Tracevv((stderr," l %2d v %4x ", length, value));
  79030. Assert(length > 0 && length <= 15, "invalid length");
  79031. s->bits_sent += (ulg)length;
  79032. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  79033. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  79034. * unused bits in value.
  79035. */
  79036. if (s->bi_valid > (int)Buf_size - length) {
  79037. s->bi_buf |= (value << s->bi_valid);
  79038. put_short(s, s->bi_buf);
  79039. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  79040. s->bi_valid += length - Buf_size;
  79041. } else {
  79042. s->bi_buf |= value << s->bi_valid;
  79043. s->bi_valid += length;
  79044. }
  79045. }
  79046. #else /* !DEBUG */
  79047. #define send_bits(s, value, length) \
  79048. { int len = length;\
  79049. if (s->bi_valid > (int)Buf_size - len) {\
  79050. int val = value;\
  79051. s->bi_buf |= (val << s->bi_valid);\
  79052. put_short(s, s->bi_buf);\
  79053. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  79054. s->bi_valid += len - Buf_size;\
  79055. } else {\
  79056. s->bi_buf |= (value) << s->bi_valid;\
  79057. s->bi_valid += len;\
  79058. }\
  79059. }
  79060. #endif /* DEBUG */
  79061. /* the arguments must not have side effects */
  79062. /* ===========================================================================
  79063. * Initialize the various 'constant' tables.
  79064. */
  79065. local void tr_static_init()
  79066. {
  79067. #if defined(GEN_TREES_H) || !defined(STDC)
  79068. static int static_init_done = 0;
  79069. int n; /* iterates over tree elements */
  79070. int bits; /* bit counter */
  79071. int length; /* length value */
  79072. int code; /* code value */
  79073. int dist; /* distance index */
  79074. ush bl_count[MAX_BITS+1];
  79075. /* number of codes at each bit length for an optimal tree */
  79076. if (static_init_done) return;
  79077. /* For some embedded targets, global variables are not initialized: */
  79078. static_l_desc.static_tree = static_ltree;
  79079. static_l_desc.extra_bits = extra_lbits;
  79080. static_d_desc.static_tree = static_dtree;
  79081. static_d_desc.extra_bits = extra_dbits;
  79082. static_bl_desc.extra_bits = extra_blbits;
  79083. /* Initialize the mapping length (0..255) -> length code (0..28) */
  79084. length = 0;
  79085. for (code = 0; code < LENGTH_CODES-1; code++) {
  79086. base_length[code] = length;
  79087. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  79088. _length_code[length++] = (uch)code;
  79089. }
  79090. }
  79091. Assert (length == 256, "tr_static_init: length != 256");
  79092. /* Note that the length 255 (match length 258) can be represented
  79093. * in two different ways: code 284 + 5 bits or code 285, so we
  79094. * overwrite length_code[255] to use the best encoding:
  79095. */
  79096. _length_code[length-1] = (uch)code;
  79097. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  79098. dist = 0;
  79099. for (code = 0 ; code < 16; code++) {
  79100. base_dist[code] = dist;
  79101. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  79102. _dist_code[dist++] = (uch)code;
  79103. }
  79104. }
  79105. Assert (dist == 256, "tr_static_init: dist != 256");
  79106. dist >>= 7; /* from now on, all distances are divided by 128 */
  79107. for ( ; code < D_CODES; code++) {
  79108. base_dist[code] = dist << 7;
  79109. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  79110. _dist_code[256 + dist++] = (uch)code;
  79111. }
  79112. }
  79113. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  79114. /* Construct the codes of the static literal tree */
  79115. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  79116. n = 0;
  79117. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  79118. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  79119. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  79120. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  79121. /* Codes 286 and 287 do not exist, but we must include them in the
  79122. * tree construction to get a canonical Huffman tree (longest code
  79123. * all ones)
  79124. */
  79125. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  79126. /* The static distance tree is trivial: */
  79127. for (n = 0; n < D_CODES; n++) {
  79128. static_dtree[n].Len = 5;
  79129. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  79130. }
  79131. static_init_done = 1;
  79132. # ifdef GEN_TREES_H
  79133. gen_trees_header();
  79134. # endif
  79135. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  79136. }
  79137. /* ===========================================================================
  79138. * Genererate the file trees.h describing the static trees.
  79139. */
  79140. #ifdef GEN_TREES_H
  79141. # ifndef DEBUG
  79142. # include <stdio.h>
  79143. # endif
  79144. # define SEPARATOR(i, last, width) \
  79145. ((i) == (last)? "\n};\n\n" : \
  79146. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  79147. void gen_trees_header()
  79148. {
  79149. FILE *header = fopen("trees.h", "w");
  79150. int i;
  79151. Assert (header != NULL, "Can't open trees.h");
  79152. fprintf(header,
  79153. "/* header created automatically with -DGEN_TREES_H */\n\n");
  79154. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  79155. for (i = 0; i < L_CODES+2; i++) {
  79156. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  79157. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  79158. }
  79159. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  79160. for (i = 0; i < D_CODES; i++) {
  79161. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  79162. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  79163. }
  79164. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  79165. for (i = 0; i < DIST_CODE_LEN; i++) {
  79166. fprintf(header, "%2u%s", _dist_code[i],
  79167. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  79168. }
  79169. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  79170. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  79171. fprintf(header, "%2u%s", _length_code[i],
  79172. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  79173. }
  79174. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  79175. for (i = 0; i < LENGTH_CODES; i++) {
  79176. fprintf(header, "%1u%s", base_length[i],
  79177. SEPARATOR(i, LENGTH_CODES-1, 20));
  79178. }
  79179. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  79180. for (i = 0; i < D_CODES; i++) {
  79181. fprintf(header, "%5u%s", base_dist[i],
  79182. SEPARATOR(i, D_CODES-1, 10));
  79183. }
  79184. fclose(header);
  79185. }
  79186. #endif /* GEN_TREES_H */
  79187. /* ===========================================================================
  79188. * Initialize the tree data structures for a new zlib stream.
  79189. */
  79190. void _tr_init(deflate_state *s)
  79191. {
  79192. tr_static_init();
  79193. s->l_desc.dyn_tree = s->dyn_ltree;
  79194. s->l_desc.stat_desc = &static_l_desc;
  79195. s->d_desc.dyn_tree = s->dyn_dtree;
  79196. s->d_desc.stat_desc = &static_d_desc;
  79197. s->bl_desc.dyn_tree = s->bl_tree;
  79198. s->bl_desc.stat_desc = &static_bl_desc;
  79199. s->bi_buf = 0;
  79200. s->bi_valid = 0;
  79201. s->last_eob_len = 8; /* enough lookahead for inflate */
  79202. #ifdef DEBUG
  79203. s->compressed_len = 0L;
  79204. s->bits_sent = 0L;
  79205. #endif
  79206. /* Initialize the first block of the first file: */
  79207. init_block(s);
  79208. }
  79209. /* ===========================================================================
  79210. * Initialize a new block.
  79211. */
  79212. local void init_block (deflate_state *s)
  79213. {
  79214. int n; /* iterates over tree elements */
  79215. /* Initialize the trees. */
  79216. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  79217. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  79218. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  79219. s->dyn_ltree[END_BLOCK].Freq = 1;
  79220. s->opt_len = s->static_len = 0L;
  79221. s->last_lit = s->matches = 0;
  79222. }
  79223. #define SMALLEST 1
  79224. /* Index within the heap array of least frequent node in the Huffman tree */
  79225. /* ===========================================================================
  79226. * Remove the smallest element from the heap and recreate the heap with
  79227. * one less element. Updates heap and heap_len.
  79228. */
  79229. #define pqremove(s, tree, top) \
  79230. {\
  79231. top = s->heap[SMALLEST]; \
  79232. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  79233. pqdownheap(s, tree, SMALLEST); \
  79234. }
  79235. /* ===========================================================================
  79236. * Compares to subtrees, using the tree depth as tie breaker when
  79237. * the subtrees have equal frequency. This minimizes the worst case length.
  79238. */
  79239. #define smaller(tree, n, m, depth) \
  79240. (tree[n].Freq < tree[m].Freq || \
  79241. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  79242. /* ===========================================================================
  79243. * Restore the heap property by moving down the tree starting at node k,
  79244. * exchanging a node with the smallest of its two sons if necessary, stopping
  79245. * when the heap property is re-established (each father smaller than its
  79246. * two sons).
  79247. */
  79248. local void pqdownheap (deflate_state *s,
  79249. ct_data *tree, /* the tree to restore */
  79250. int k) /* node to move down */
  79251. {
  79252. int v = s->heap[k];
  79253. int j = k << 1; /* left son of k */
  79254. while (j <= s->heap_len) {
  79255. /* Set j to the smallest of the two sons: */
  79256. if (j < s->heap_len &&
  79257. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  79258. j++;
  79259. }
  79260. /* Exit if v is smaller than both sons */
  79261. if (smaller(tree, v, s->heap[j], s->depth)) break;
  79262. /* Exchange v with the smallest son */
  79263. s->heap[k] = s->heap[j]; k = j;
  79264. /* And continue down the tree, setting j to the left son of k */
  79265. j <<= 1;
  79266. }
  79267. s->heap[k] = v;
  79268. }
  79269. /* ===========================================================================
  79270. * Compute the optimal bit lengths for a tree and update the total bit length
  79271. * for the current block.
  79272. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  79273. * above are the tree nodes sorted by increasing frequency.
  79274. * OUT assertions: the field len is set to the optimal bit length, the
  79275. * array bl_count contains the frequencies for each bit length.
  79276. * The length opt_len is updated; static_len is also updated if stree is
  79277. * not null.
  79278. */
  79279. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  79280. {
  79281. ct_data *tree = desc->dyn_tree;
  79282. int max_code = desc->max_code;
  79283. const ct_data *stree = desc->stat_desc->static_tree;
  79284. const intf *extra = desc->stat_desc->extra_bits;
  79285. int base = desc->stat_desc->extra_base;
  79286. int max_length = desc->stat_desc->max_length;
  79287. int h; /* heap index */
  79288. int n, m; /* iterate over the tree elements */
  79289. int bits; /* bit length */
  79290. int xbits; /* extra bits */
  79291. ush f; /* frequency */
  79292. int overflow = 0; /* number of elements with bit length too large */
  79293. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  79294. /* In a first pass, compute the optimal bit lengths (which may
  79295. * overflow in the case of the bit length tree).
  79296. */
  79297. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  79298. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  79299. n = s->heap[h];
  79300. bits = tree[tree[n].Dad].Len + 1;
  79301. if (bits > max_length) bits = max_length, overflow++;
  79302. tree[n].Len = (ush)bits;
  79303. /* We overwrite tree[n].Dad which is no longer needed */
  79304. if (n > max_code) continue; /* not a leaf node */
  79305. s->bl_count[bits]++;
  79306. xbits = 0;
  79307. if (n >= base) xbits = extra[n-base];
  79308. f = tree[n].Freq;
  79309. s->opt_len += (ulg)f * (bits + xbits);
  79310. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  79311. }
  79312. if (overflow == 0) return;
  79313. Trace((stderr,"\nbit length overflow\n"));
  79314. /* This happens for example on obj2 and pic of the Calgary corpus */
  79315. /* Find the first bit length which could increase: */
  79316. do {
  79317. bits = max_length-1;
  79318. while (s->bl_count[bits] == 0) bits--;
  79319. s->bl_count[bits]--; /* move one leaf down the tree */
  79320. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  79321. s->bl_count[max_length]--;
  79322. /* The brother of the overflow item also moves one step up,
  79323. * but this does not affect bl_count[max_length]
  79324. */
  79325. overflow -= 2;
  79326. } while (overflow > 0);
  79327. /* Now recompute all bit lengths, scanning in increasing frequency.
  79328. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  79329. * lengths instead of fixing only the wrong ones. This idea is taken
  79330. * from 'ar' written by Haruhiko Okumura.)
  79331. */
  79332. for (bits = max_length; bits != 0; bits--) {
  79333. n = s->bl_count[bits];
  79334. while (n != 0) {
  79335. m = s->heap[--h];
  79336. if (m > max_code) continue;
  79337. if ((unsigned) tree[m].Len != (unsigned) bits) {
  79338. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  79339. s->opt_len += ((long)bits - (long)tree[m].Len)
  79340. *(long)tree[m].Freq;
  79341. tree[m].Len = (ush)bits;
  79342. }
  79343. n--;
  79344. }
  79345. }
  79346. }
  79347. /* ===========================================================================
  79348. * Generate the codes for a given tree and bit counts (which need not be
  79349. * optimal).
  79350. * IN assertion: the array bl_count contains the bit length statistics for
  79351. * the given tree and the field len is set for all tree elements.
  79352. * OUT assertion: the field code is set for all tree elements of non
  79353. * zero code length.
  79354. */
  79355. local void gen_codes (ct_data *tree, /* the tree to decorate */
  79356. int max_code, /* largest code with non zero frequency */
  79357. ushf *bl_count) /* number of codes at each bit length */
  79358. {
  79359. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  79360. ush code = 0; /* running code value */
  79361. int bits; /* bit index */
  79362. int n; /* code index */
  79363. /* The distribution counts are first used to generate the code values
  79364. * without bit reversal.
  79365. */
  79366. for (bits = 1; bits <= MAX_BITS; bits++) {
  79367. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  79368. }
  79369. /* Check that the bit counts in bl_count are consistent. The last code
  79370. * must be all ones.
  79371. */
  79372. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  79373. "inconsistent bit counts");
  79374. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  79375. for (n = 0; n <= max_code; n++) {
  79376. int len = tree[n].Len;
  79377. if (len == 0) continue;
  79378. /* Now reverse the bits */
  79379. tree[n].Code = bi_reverse(next_code[len]++, len);
  79380. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  79381. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  79382. }
  79383. }
  79384. /* ===========================================================================
  79385. * Construct one Huffman tree and assigns the code bit strings and lengths.
  79386. * Update the total bit length for the current block.
  79387. * IN assertion: the field freq is set for all tree elements.
  79388. * OUT assertions: the fields len and code are set to the optimal bit length
  79389. * and corresponding code. The length opt_len is updated; static_len is
  79390. * also updated if stree is not null. The field max_code is set.
  79391. */
  79392. local void build_tree (deflate_state *s,
  79393. tree_desc *desc) /* the tree descriptor */
  79394. {
  79395. ct_data *tree = desc->dyn_tree;
  79396. const ct_data *stree = desc->stat_desc->static_tree;
  79397. int elems = desc->stat_desc->elems;
  79398. int n, m; /* iterate over heap elements */
  79399. int max_code = -1; /* largest code with non zero frequency */
  79400. int node; /* new node being created */
  79401. /* Construct the initial heap, with least frequent element in
  79402. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  79403. * heap[0] is not used.
  79404. */
  79405. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  79406. for (n = 0; n < elems; n++) {
  79407. if (tree[n].Freq != 0) {
  79408. s->heap[++(s->heap_len)] = max_code = n;
  79409. s->depth[n] = 0;
  79410. } else {
  79411. tree[n].Len = 0;
  79412. }
  79413. }
  79414. /* The pkzip format requires that at least one distance code exists,
  79415. * and that at least one bit should be sent even if there is only one
  79416. * possible code. So to avoid special checks later on we force at least
  79417. * two codes of non zero frequency.
  79418. */
  79419. while (s->heap_len < 2) {
  79420. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  79421. tree[node].Freq = 1;
  79422. s->depth[node] = 0;
  79423. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  79424. /* node is 0 or 1 so it does not have extra bits */
  79425. }
  79426. desc->max_code = max_code;
  79427. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  79428. * establish sub-heaps of increasing lengths:
  79429. */
  79430. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  79431. /* Construct the Huffman tree by repeatedly combining the least two
  79432. * frequent nodes.
  79433. */
  79434. node = elems; /* next internal node of the tree */
  79435. do {
  79436. pqremove(s, tree, n); /* n = node of least frequency */
  79437. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  79438. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  79439. s->heap[--(s->heap_max)] = m;
  79440. /* Create a new node father of n and m */
  79441. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  79442. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  79443. s->depth[n] : s->depth[m]) + 1);
  79444. tree[n].Dad = tree[m].Dad = (ush)node;
  79445. #ifdef DUMP_BL_TREE
  79446. if (tree == s->bl_tree) {
  79447. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  79448. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  79449. }
  79450. #endif
  79451. /* and insert the new node in the heap */
  79452. s->heap[SMALLEST] = node++;
  79453. pqdownheap(s, tree, SMALLEST);
  79454. } while (s->heap_len >= 2);
  79455. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  79456. /* At this point, the fields freq and dad are set. We can now
  79457. * generate the bit lengths.
  79458. */
  79459. gen_bitlen(s, (tree_desc *)desc);
  79460. /* The field len is now set, we can generate the bit codes */
  79461. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  79462. }
  79463. /* ===========================================================================
  79464. * Scan a literal or distance tree to determine the frequencies of the codes
  79465. * in the bit length tree.
  79466. */
  79467. local void scan_tree (deflate_state *s,
  79468. ct_data *tree, /* the tree to be scanned */
  79469. int max_code) /* and its largest code of non zero frequency */
  79470. {
  79471. int n; /* iterates over all tree elements */
  79472. int prevlen = -1; /* last emitted length */
  79473. int curlen; /* length of current code */
  79474. int nextlen = tree[0].Len; /* length of next code */
  79475. int count = 0; /* repeat count of the current code */
  79476. int max_count = 7; /* max repeat count */
  79477. int min_count = 4; /* min repeat count */
  79478. if (nextlen == 0) max_count = 138, min_count = 3;
  79479. tree[max_code+1].Len = (ush)0xffff; /* guard */
  79480. for (n = 0; n <= max_code; n++) {
  79481. curlen = nextlen; nextlen = tree[n+1].Len;
  79482. if (++count < max_count && curlen == nextlen) {
  79483. continue;
  79484. } else if (count < min_count) {
  79485. s->bl_tree[curlen].Freq += count;
  79486. } else if (curlen != 0) {
  79487. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  79488. s->bl_tree[REP_3_6].Freq++;
  79489. } else if (count <= 10) {
  79490. s->bl_tree[REPZ_3_10].Freq++;
  79491. } else {
  79492. s->bl_tree[REPZ_11_138].Freq++;
  79493. }
  79494. count = 0; prevlen = curlen;
  79495. if (nextlen == 0) {
  79496. max_count = 138, min_count = 3;
  79497. } else if (curlen == nextlen) {
  79498. max_count = 6, min_count = 3;
  79499. } else {
  79500. max_count = 7, min_count = 4;
  79501. }
  79502. }
  79503. }
  79504. /* ===========================================================================
  79505. * Send a literal or distance tree in compressed form, using the codes in
  79506. * bl_tree.
  79507. */
  79508. local void send_tree (deflate_state *s,
  79509. ct_data *tree, /* the tree to be scanned */
  79510. int max_code) /* and its largest code of non zero frequency */
  79511. {
  79512. int n; /* iterates over all tree elements */
  79513. int prevlen = -1; /* last emitted length */
  79514. int curlen; /* length of current code */
  79515. int nextlen = tree[0].Len; /* length of next code */
  79516. int count = 0; /* repeat count of the current code */
  79517. int max_count = 7; /* max repeat count */
  79518. int min_count = 4; /* min repeat count */
  79519. /* tree[max_code+1].Len = -1; */ /* guard already set */
  79520. if (nextlen == 0) max_count = 138, min_count = 3;
  79521. for (n = 0; n <= max_code; n++) {
  79522. curlen = nextlen; nextlen = tree[n+1].Len;
  79523. if (++count < max_count && curlen == nextlen) {
  79524. continue;
  79525. } else if (count < min_count) {
  79526. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  79527. } else if (curlen != 0) {
  79528. if (curlen != prevlen) {
  79529. send_code(s, curlen, s->bl_tree); count--;
  79530. }
  79531. Assert(count >= 3 && count <= 6, " 3_6?");
  79532. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  79533. } else if (count <= 10) {
  79534. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  79535. } else {
  79536. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  79537. }
  79538. count = 0; prevlen = curlen;
  79539. if (nextlen == 0) {
  79540. max_count = 138, min_count = 3;
  79541. } else if (curlen == nextlen) {
  79542. max_count = 6, min_count = 3;
  79543. } else {
  79544. max_count = 7, min_count = 4;
  79545. }
  79546. }
  79547. }
  79548. /* ===========================================================================
  79549. * Construct the Huffman tree for the bit lengths and return the index in
  79550. * bl_order of the last bit length code to send.
  79551. */
  79552. local int build_bl_tree (deflate_state *s)
  79553. {
  79554. int max_blindex; /* index of last bit length code of non zero freq */
  79555. /* Determine the bit length frequencies for literal and distance trees */
  79556. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  79557. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  79558. /* Build the bit length tree: */
  79559. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  79560. /* opt_len now includes the length of the tree representations, except
  79561. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  79562. */
  79563. /* Determine the number of bit length codes to send. The pkzip format
  79564. * requires that at least 4 bit length codes be sent. (appnote.txt says
  79565. * 3 but the actual value used is 4.)
  79566. */
  79567. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  79568. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  79569. }
  79570. /* Update opt_len to include the bit length tree and counts */
  79571. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  79572. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  79573. s->opt_len, s->static_len));
  79574. return max_blindex;
  79575. }
  79576. /* ===========================================================================
  79577. * Send the header for a block using dynamic Huffman trees: the counts, the
  79578. * lengths of the bit length codes, the literal tree and the distance tree.
  79579. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  79580. */
  79581. local void send_all_trees (deflate_state *s,
  79582. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  79583. {
  79584. int rank; /* index in bl_order */
  79585. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  79586. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  79587. "too many codes");
  79588. Tracev((stderr, "\nbl counts: "));
  79589. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  79590. send_bits(s, dcodes-1, 5);
  79591. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  79592. for (rank = 0; rank < blcodes; rank++) {
  79593. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  79594. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  79595. }
  79596. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  79597. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  79598. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  79599. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  79600. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  79601. }
  79602. /* ===========================================================================
  79603. * Send a stored block
  79604. */
  79605. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  79606. {
  79607. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  79608. #ifdef DEBUG
  79609. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  79610. s->compressed_len += (stored_len + 4) << 3;
  79611. #endif
  79612. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  79613. }
  79614. /* ===========================================================================
  79615. * Send one empty static block to give enough lookahead for inflate.
  79616. * This takes 10 bits, of which 7 may remain in the bit buffer.
  79617. * The current inflate code requires 9 bits of lookahead. If the
  79618. * last two codes for the previous block (real code plus EOB) were coded
  79619. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  79620. * the last real code. In this case we send two empty static blocks instead
  79621. * of one. (There are no problems if the previous block is stored or fixed.)
  79622. * To simplify the code, we assume the worst case of last real code encoded
  79623. * on one bit only.
  79624. */
  79625. void _tr_align (deflate_state *s)
  79626. {
  79627. send_bits(s, STATIC_TREES<<1, 3);
  79628. send_code(s, END_BLOCK, static_ltree);
  79629. #ifdef DEBUG
  79630. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  79631. #endif
  79632. bi_flush(s);
  79633. /* Of the 10 bits for the empty block, we have already sent
  79634. * (10 - bi_valid) bits. The lookahead for the last real code (before
  79635. * the EOB of the previous block) was thus at least one plus the length
  79636. * of the EOB plus what we have just sent of the empty static block.
  79637. */
  79638. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  79639. send_bits(s, STATIC_TREES<<1, 3);
  79640. send_code(s, END_BLOCK, static_ltree);
  79641. #ifdef DEBUG
  79642. s->compressed_len += 10L;
  79643. #endif
  79644. bi_flush(s);
  79645. }
  79646. s->last_eob_len = 7;
  79647. }
  79648. /* ===========================================================================
  79649. * Determine the best encoding for the current block: dynamic trees, static
  79650. * trees or store, and output the encoded block to the zip file.
  79651. */
  79652. void _tr_flush_block (deflate_state *s,
  79653. charf *buf, /* input block, or NULL if too old */
  79654. ulg stored_len, /* length of input block */
  79655. int eof) /* true if this is the last block for a file */
  79656. {
  79657. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  79658. int max_blindex = 0; /* index of last bit length code of non zero freq */
  79659. /* Build the Huffman trees unless a stored block is forced */
  79660. if (s->level > 0) {
  79661. /* Check if the file is binary or text */
  79662. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  79663. set_data_type(s);
  79664. /* Construct the literal and distance trees */
  79665. build_tree(s, (tree_desc *)(&(s->l_desc)));
  79666. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  79667. s->static_len));
  79668. build_tree(s, (tree_desc *)(&(s->d_desc)));
  79669. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  79670. s->static_len));
  79671. /* At this point, opt_len and static_len are the total bit lengths of
  79672. * the compressed block data, excluding the tree representations.
  79673. */
  79674. /* Build the bit length tree for the above two trees, and get the index
  79675. * in bl_order of the last bit length code to send.
  79676. */
  79677. max_blindex = build_bl_tree(s);
  79678. /* Determine the best encoding. Compute the block lengths in bytes. */
  79679. opt_lenb = (s->opt_len+3+7)>>3;
  79680. static_lenb = (s->static_len+3+7)>>3;
  79681. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  79682. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  79683. s->last_lit));
  79684. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  79685. } else {
  79686. Assert(buf != (char*)0, "lost buf");
  79687. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  79688. }
  79689. #ifdef FORCE_STORED
  79690. if (buf != (char*)0) { /* force stored block */
  79691. #else
  79692. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  79693. /* 4: two words for the lengths */
  79694. #endif
  79695. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  79696. * Otherwise we can't have processed more than WSIZE input bytes since
  79697. * the last block flush, because compression would have been
  79698. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  79699. * transform a block into a stored block.
  79700. */
  79701. _tr_stored_block(s, buf, stored_len, eof);
  79702. #ifdef FORCE_STATIC
  79703. } else if (static_lenb >= 0) { /* force static trees */
  79704. #else
  79705. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  79706. #endif
  79707. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  79708. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  79709. #ifdef DEBUG
  79710. s->compressed_len += 3 + s->static_len;
  79711. #endif
  79712. } else {
  79713. send_bits(s, (DYN_TREES<<1)+eof, 3);
  79714. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  79715. max_blindex+1);
  79716. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  79717. #ifdef DEBUG
  79718. s->compressed_len += 3 + s->opt_len;
  79719. #endif
  79720. }
  79721. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  79722. /* The above check is made mod 2^32, for files larger than 512 MB
  79723. * and uLong implemented on 32 bits.
  79724. */
  79725. init_block(s);
  79726. if (eof) {
  79727. bi_windup(s);
  79728. #ifdef DEBUG
  79729. s->compressed_len += 7; /* align on byte boundary */
  79730. #endif
  79731. }
  79732. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  79733. s->compressed_len-7*eof));
  79734. }
  79735. /* ===========================================================================
  79736. * Save the match info and tally the frequency counts. Return true if
  79737. * the current block must be flushed.
  79738. */
  79739. int _tr_tally (deflate_state *s,
  79740. unsigned dist, /* distance of matched string */
  79741. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  79742. {
  79743. s->d_buf[s->last_lit] = (ush)dist;
  79744. s->l_buf[s->last_lit++] = (uch)lc;
  79745. if (dist == 0) {
  79746. /* lc is the unmatched char */
  79747. s->dyn_ltree[lc].Freq++;
  79748. } else {
  79749. s->matches++;
  79750. /* Here, lc is the match length - MIN_MATCH */
  79751. dist--; /* dist = match distance - 1 */
  79752. Assert((ush)dist < (ush)MAX_DIST(s) &&
  79753. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  79754. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  79755. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  79756. s->dyn_dtree[d_code(dist)].Freq++;
  79757. }
  79758. #ifdef TRUNCATE_BLOCK
  79759. /* Try to guess if it is profitable to stop the current block here */
  79760. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  79761. /* Compute an upper bound for the compressed length */
  79762. ulg out_length = (ulg)s->last_lit*8L;
  79763. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  79764. int dcode;
  79765. for (dcode = 0; dcode < D_CODES; dcode++) {
  79766. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  79767. (5L+extra_dbits[dcode]);
  79768. }
  79769. out_length >>= 3;
  79770. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  79771. s->last_lit, in_length, out_length,
  79772. 100L - out_length*100L/in_length));
  79773. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  79774. }
  79775. #endif
  79776. return (s->last_lit == s->lit_bufsize-1);
  79777. /* We avoid equality with lit_bufsize because of wraparound at 64K
  79778. * on 16 bit machines and because stored blocks are restricted to
  79779. * 64K-1 bytes.
  79780. */
  79781. }
  79782. /* ===========================================================================
  79783. * Send the block data compressed using the given Huffman trees
  79784. */
  79785. local void compress_block (deflate_state *s,
  79786. ct_data *ltree, /* literal tree */
  79787. ct_data *dtree) /* distance tree */
  79788. {
  79789. unsigned dist; /* distance of matched string */
  79790. int lc; /* match length or unmatched char (if dist == 0) */
  79791. unsigned lx = 0; /* running index in l_buf */
  79792. unsigned code; /* the code to send */
  79793. int extra; /* number of extra bits to send */
  79794. if (s->last_lit != 0) do {
  79795. dist = s->d_buf[lx];
  79796. lc = s->l_buf[lx++];
  79797. if (dist == 0) {
  79798. send_code(s, lc, ltree); /* send a literal byte */
  79799. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  79800. } else {
  79801. /* Here, lc is the match length - MIN_MATCH */
  79802. code = _length_code[lc];
  79803. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  79804. extra = extra_lbits[code];
  79805. if (extra != 0) {
  79806. lc -= base_length[code];
  79807. send_bits(s, lc, extra); /* send the extra length bits */
  79808. }
  79809. dist--; /* dist is now the match distance - 1 */
  79810. code = d_code(dist);
  79811. Assert (code < D_CODES, "bad d_code");
  79812. send_code(s, code, dtree); /* send the distance code */
  79813. extra = extra_dbits[code];
  79814. if (extra != 0) {
  79815. dist -= base_dist[code];
  79816. send_bits(s, dist, extra); /* send the extra distance bits */
  79817. }
  79818. } /* literal or match pair ? */
  79819. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  79820. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  79821. "pendingBuf overflow");
  79822. } while (lx < s->last_lit);
  79823. send_code(s, END_BLOCK, ltree);
  79824. s->last_eob_len = ltree[END_BLOCK].Len;
  79825. }
  79826. /* ===========================================================================
  79827. * Set the data type to BINARY or TEXT, using a crude approximation:
  79828. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  79829. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  79830. * IN assertion: the fields Freq of dyn_ltree are set.
  79831. */
  79832. local void set_data_type (deflate_state *s)
  79833. {
  79834. int n;
  79835. for (n = 0; n < 9; n++)
  79836. if (s->dyn_ltree[n].Freq != 0)
  79837. break;
  79838. if (n == 9)
  79839. for (n = 14; n < 32; n++)
  79840. if (s->dyn_ltree[n].Freq != 0)
  79841. break;
  79842. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  79843. }
  79844. /* ===========================================================================
  79845. * Reverse the first len bits of a code, using straightforward code (a faster
  79846. * method would use a table)
  79847. * IN assertion: 1 <= len <= 15
  79848. */
  79849. local unsigned bi_reverse (unsigned code, int len)
  79850. {
  79851. register unsigned res = 0;
  79852. do {
  79853. res |= code & 1;
  79854. code >>= 1, res <<= 1;
  79855. } while (--len > 0);
  79856. return res >> 1;
  79857. }
  79858. /* ===========================================================================
  79859. * Flush the bit buffer, keeping at most 7 bits in it.
  79860. */
  79861. local void bi_flush (deflate_state *s)
  79862. {
  79863. if (s->bi_valid == 16) {
  79864. put_short(s, s->bi_buf);
  79865. s->bi_buf = 0;
  79866. s->bi_valid = 0;
  79867. } else if (s->bi_valid >= 8) {
  79868. put_byte(s, (Byte)s->bi_buf);
  79869. s->bi_buf >>= 8;
  79870. s->bi_valid -= 8;
  79871. }
  79872. }
  79873. /* ===========================================================================
  79874. * Flush the bit buffer and align the output on a byte boundary
  79875. */
  79876. local void bi_windup (deflate_state *s)
  79877. {
  79878. if (s->bi_valid > 8) {
  79879. put_short(s, s->bi_buf);
  79880. } else if (s->bi_valid > 0) {
  79881. put_byte(s, (Byte)s->bi_buf);
  79882. }
  79883. s->bi_buf = 0;
  79884. s->bi_valid = 0;
  79885. #ifdef DEBUG
  79886. s->bits_sent = (s->bits_sent+7) & ~7;
  79887. #endif
  79888. }
  79889. /* ===========================================================================
  79890. * Copy a stored block, storing first the length and its
  79891. * one's complement if requested.
  79892. */
  79893. local void copy_block(deflate_state *s,
  79894. charf *buf, /* the input data */
  79895. unsigned len, /* its length */
  79896. int header) /* true if block header must be written */
  79897. {
  79898. bi_windup(s); /* align on byte boundary */
  79899. s->last_eob_len = 8; /* enough lookahead for inflate */
  79900. if (header) {
  79901. put_short(s, (ush)len);
  79902. put_short(s, (ush)~len);
  79903. #ifdef DEBUG
  79904. s->bits_sent += 2*16;
  79905. #endif
  79906. }
  79907. #ifdef DEBUG
  79908. s->bits_sent += (ulg)len<<3;
  79909. #endif
  79910. while (len--) {
  79911. put_byte(s, *buf++);
  79912. }
  79913. }
  79914. /********* End of inlined file: trees.c *********/
  79915. /********* Start of inlined file: uncompr.c *********/
  79916. /* @(#) $Id: uncompr.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79917. #define ZLIB_INTERNAL
  79918. /* ===========================================================================
  79919. Decompresses the source buffer into the destination buffer. sourceLen is
  79920. the byte length of the source buffer. Upon entry, destLen is the total
  79921. size of the destination buffer, which must be large enough to hold the
  79922. entire uncompressed data. (The size of the uncompressed data must have
  79923. been saved previously by the compressor and transmitted to the decompressor
  79924. by some mechanism outside the scope of this compression library.)
  79925. Upon exit, destLen is the actual size of the compressed buffer.
  79926. This function can be used to decompress a whole file at once if the
  79927. input file is mmap'ed.
  79928. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79929. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79930. buffer, or Z_DATA_ERROR if the input data was corrupted.
  79931. */
  79932. int ZEXPORT uncompress (Bytef *dest,
  79933. uLongf *destLen,
  79934. const Bytef *source,
  79935. uLong sourceLen)
  79936. {
  79937. z_stream stream;
  79938. int err;
  79939. stream.next_in = (Bytef*)source;
  79940. stream.avail_in = (uInt)sourceLen;
  79941. /* Check for source > 64K on 16-bit machine: */
  79942. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79943. stream.next_out = dest;
  79944. stream.avail_out = (uInt)*destLen;
  79945. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79946. stream.zalloc = (alloc_func)0;
  79947. stream.zfree = (free_func)0;
  79948. err = inflateInit(&stream);
  79949. if (err != Z_OK) return err;
  79950. err = inflate(&stream, Z_FINISH);
  79951. if (err != Z_STREAM_END) {
  79952. inflateEnd(&stream);
  79953. if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))
  79954. return Z_DATA_ERROR;
  79955. return err;
  79956. }
  79957. *destLen = stream.total_out;
  79958. err = inflateEnd(&stream);
  79959. return err;
  79960. }
  79961. /********* End of inlined file: uncompr.c *********/
  79962. /********* Start of inlined file: zutil.c *********/
  79963. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79964. #ifndef NO_DUMMY_DECL
  79965. struct internal_state {int dummy;}; /* for buggy compilers */
  79966. #endif
  79967. const char * const z_errmsg[10] = {
  79968. "need dictionary", /* Z_NEED_DICT 2 */
  79969. "stream end", /* Z_STREAM_END 1 */
  79970. "", /* Z_OK 0 */
  79971. "file error", /* Z_ERRNO (-1) */
  79972. "stream error", /* Z_STREAM_ERROR (-2) */
  79973. "data error", /* Z_DATA_ERROR (-3) */
  79974. "insufficient memory", /* Z_MEM_ERROR (-4) */
  79975. "buffer error", /* Z_BUF_ERROR (-5) */
  79976. "incompatible version",/* Z_VERSION_ERROR (-6) */
  79977. ""};
  79978. /*const char * ZEXPORT zlibVersion()
  79979. {
  79980. return ZLIB_VERSION;
  79981. }
  79982. uLong ZEXPORT zlibCompileFlags()
  79983. {
  79984. uLong flags;
  79985. flags = 0;
  79986. switch (sizeof(uInt)) {
  79987. case 2: break;
  79988. case 4: flags += 1; break;
  79989. case 8: flags += 2; break;
  79990. default: flags += 3;
  79991. }
  79992. switch (sizeof(uLong)) {
  79993. case 2: break;
  79994. case 4: flags += 1 << 2; break;
  79995. case 8: flags += 2 << 2; break;
  79996. default: flags += 3 << 2;
  79997. }
  79998. switch (sizeof(voidpf)) {
  79999. case 2: break;
  80000. case 4: flags += 1 << 4; break;
  80001. case 8: flags += 2 << 4; break;
  80002. default: flags += 3 << 4;
  80003. }
  80004. switch (sizeof(z_off_t)) {
  80005. case 2: break;
  80006. case 4: flags += 1 << 6; break;
  80007. case 8: flags += 2 << 6; break;
  80008. default: flags += 3 << 6;
  80009. }
  80010. #ifdef DEBUG
  80011. flags += 1 << 8;
  80012. #endif
  80013. #if defined(ASMV) || defined(ASMINF)
  80014. flags += 1 << 9;
  80015. #endif
  80016. #ifdef ZLIB_WINAPI
  80017. flags += 1 << 10;
  80018. #endif
  80019. #ifdef BUILDFIXED
  80020. flags += 1 << 12;
  80021. #endif
  80022. #ifdef DYNAMIC_CRC_TABLE
  80023. flags += 1 << 13;
  80024. #endif
  80025. #ifdef NO_GZCOMPRESS
  80026. flags += 1L << 16;
  80027. #endif
  80028. #ifdef NO_GZIP
  80029. flags += 1L << 17;
  80030. #endif
  80031. #ifdef PKZIP_BUG_WORKAROUND
  80032. flags += 1L << 20;
  80033. #endif
  80034. #ifdef FASTEST
  80035. flags += 1L << 21;
  80036. #endif
  80037. #ifdef STDC
  80038. # ifdef NO_vsnprintf
  80039. flags += 1L << 25;
  80040. # ifdef HAS_vsprintf_void
  80041. flags += 1L << 26;
  80042. # endif
  80043. # else
  80044. # ifdef HAS_vsnprintf_void
  80045. flags += 1L << 26;
  80046. # endif
  80047. # endif
  80048. #else
  80049. flags += 1L << 24;
  80050. # ifdef NO_snprintf
  80051. flags += 1L << 25;
  80052. # ifdef HAS_sprintf_void
  80053. flags += 1L << 26;
  80054. # endif
  80055. # else
  80056. # ifdef HAS_snprintf_void
  80057. flags += 1L << 26;
  80058. # endif
  80059. # endif
  80060. #endif
  80061. return flags;
  80062. }*/
  80063. #ifdef DEBUG
  80064. # ifndef verbose
  80065. # define verbose 0
  80066. # endif
  80067. int z_verbose = verbose;
  80068. void z_error (char *m)
  80069. {
  80070. fprintf(stderr, "%s\n", m);
  80071. exit(1);
  80072. }
  80073. #endif
  80074. /* exported to allow conversion of error code to string for compress() and
  80075. * uncompress()
  80076. */
  80077. const char * ZEXPORT zError(int err)
  80078. {
  80079. return ERR_MSG(err);
  80080. }
  80081. #if defined(_WIN32_WCE)
  80082. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  80083. * errno. We define it as a global variable to simplify porting.
  80084. * Its value is always 0 and should not be used.
  80085. */
  80086. int errno = 0;
  80087. #endif
  80088. #ifndef HAVE_MEMCPY
  80089. void zmemcpy(dest, source, len)
  80090. Bytef* dest;
  80091. const Bytef* source;
  80092. uInt len;
  80093. {
  80094. if (len == 0) return;
  80095. do {
  80096. *dest++ = *source++; /* ??? to be unrolled */
  80097. } while (--len != 0);
  80098. }
  80099. int zmemcmp(s1, s2, len)
  80100. const Bytef* s1;
  80101. const Bytef* s2;
  80102. uInt len;
  80103. {
  80104. uInt j;
  80105. for (j = 0; j < len; j++) {
  80106. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  80107. }
  80108. return 0;
  80109. }
  80110. void zmemzero(dest, len)
  80111. Bytef* dest;
  80112. uInt len;
  80113. {
  80114. if (len == 0) return;
  80115. do {
  80116. *dest++ = 0; /* ??? to be unrolled */
  80117. } while (--len != 0);
  80118. }
  80119. #endif
  80120. #ifdef SYS16BIT
  80121. #ifdef __TURBOC__
  80122. /* Turbo C in 16-bit mode */
  80123. # define MY_ZCALLOC
  80124. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  80125. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  80126. * must fix the pointer. Warning: the pointer must be put back to its
  80127. * original form in order to free it, use zcfree().
  80128. */
  80129. #define MAX_PTR 10
  80130. /* 10*64K = 640K */
  80131. local int next_ptr = 0;
  80132. typedef struct ptr_table_s {
  80133. voidpf org_ptr;
  80134. voidpf new_ptr;
  80135. } ptr_table;
  80136. local ptr_table table[MAX_PTR];
  80137. /* This table is used to remember the original form of pointers
  80138. * to large buffers (64K). Such pointers are normalized with a zero offset.
  80139. * Since MSDOS is not a preemptive multitasking OS, this table is not
  80140. * protected from concurrent access. This hack doesn't work anyway on
  80141. * a protected system like OS/2. Use Microsoft C instead.
  80142. */
  80143. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  80144. {
  80145. voidpf buf = opaque; /* just to make some compilers happy */
  80146. ulg bsize = (ulg)items*size;
  80147. /* If we allocate less than 65520 bytes, we assume that farmalloc
  80148. * will return a usable pointer which doesn't have to be normalized.
  80149. */
  80150. if (bsize < 65520L) {
  80151. buf = farmalloc(bsize);
  80152. if (*(ush*)&buf != 0) return buf;
  80153. } else {
  80154. buf = farmalloc(bsize + 16L);
  80155. }
  80156. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  80157. table[next_ptr].org_ptr = buf;
  80158. /* Normalize the pointer to seg:0 */
  80159. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  80160. *(ush*)&buf = 0;
  80161. table[next_ptr++].new_ptr = buf;
  80162. return buf;
  80163. }
  80164. void zcfree (voidpf opaque, voidpf ptr)
  80165. {
  80166. int n;
  80167. if (*(ush*)&ptr != 0) { /* object < 64K */
  80168. farfree(ptr);
  80169. return;
  80170. }
  80171. /* Find the original pointer */
  80172. for (n = 0; n < next_ptr; n++) {
  80173. if (ptr != table[n].new_ptr) continue;
  80174. farfree(table[n].org_ptr);
  80175. while (++n < next_ptr) {
  80176. table[n-1] = table[n];
  80177. }
  80178. next_ptr--;
  80179. return;
  80180. }
  80181. ptr = opaque; /* just to make some compilers happy */
  80182. Assert(0, "zcfree: ptr not found");
  80183. }
  80184. #endif /* __TURBOC__ */
  80185. #ifdef M_I86
  80186. /* Microsoft C in 16-bit mode */
  80187. # define MY_ZCALLOC
  80188. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  80189. # define _halloc halloc
  80190. # define _hfree hfree
  80191. #endif
  80192. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  80193. {
  80194. if (opaque) opaque = 0; /* to make compiler happy */
  80195. return _halloc((long)items, size);
  80196. }
  80197. void zcfree (voidpf opaque, voidpf ptr)
  80198. {
  80199. if (opaque) opaque = 0; /* to make compiler happy */
  80200. _hfree(ptr);
  80201. }
  80202. #endif /* M_I86 */
  80203. #endif /* SYS16BIT */
  80204. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  80205. #ifndef STDC
  80206. extern voidp malloc OF((uInt size));
  80207. extern voidp calloc OF((uInt items, uInt size));
  80208. extern void free OF((voidpf ptr));
  80209. #endif
  80210. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  80211. {
  80212. if (opaque) items += size - size; /* make compiler happy */
  80213. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  80214. (voidpf)calloc(items, size);
  80215. }
  80216. void zcfree (voidpf opaque, voidpf ptr)
  80217. {
  80218. free(ptr);
  80219. if (opaque) return; /* make compiler happy */
  80220. }
  80221. #endif /* MY_ZCALLOC */
  80222. /********* End of inlined file: zutil.c *********/
  80223. #undef Byte
  80224. }
  80225. }
  80226. #if JUCE_MSVC
  80227. #pragma warning (pop)
  80228. #endif
  80229. BEGIN_JUCE_NAMESPACE
  80230. using namespace zlibNamespace;
  80231. // internal helper object that holds the zlib structures so they don't have to be
  80232. // included publicly.
  80233. class GZIPDecompressHelper
  80234. {
  80235. private:
  80236. z_stream* stream;
  80237. uint8* data;
  80238. int dataSize;
  80239. public:
  80240. bool finished, needsDictionary, error;
  80241. GZIPDecompressHelper (const bool noWrap) throw()
  80242. : data (0),
  80243. dataSize (0),
  80244. finished (false),
  80245. needsDictionary (false),
  80246. error (false)
  80247. {
  80248. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  80249. if (inflateInit2 (stream, (noWrap) ? -MAX_WBITS
  80250. : MAX_WBITS) != Z_OK)
  80251. {
  80252. juce_free (stream);
  80253. stream = 0;
  80254. error = true;
  80255. finished = true;
  80256. }
  80257. }
  80258. ~GZIPDecompressHelper() throw()
  80259. {
  80260. if (stream != 0)
  80261. {
  80262. inflateEnd (stream);
  80263. juce_free (stream);
  80264. }
  80265. }
  80266. bool needsInput() const throw() { return dataSize <= 0; }
  80267. void setInput (uint8* const data_, const int size) throw()
  80268. {
  80269. data = data_;
  80270. dataSize = size;
  80271. }
  80272. int doNextBlock (uint8* const dest, const int destSize) throw()
  80273. {
  80274. if (stream != 0 && data != 0 && ! finished)
  80275. {
  80276. stream->next_in = data;
  80277. stream->next_out = dest;
  80278. stream->avail_in = dataSize;
  80279. stream->avail_out = destSize;
  80280. switch (inflate (stream, Z_PARTIAL_FLUSH))
  80281. {
  80282. case Z_STREAM_END:
  80283. finished = true;
  80284. // deliberate fall-through
  80285. case Z_OK:
  80286. data += dataSize - stream->avail_in;
  80287. dataSize = stream->avail_in;
  80288. return destSize - stream->avail_out;
  80289. case Z_NEED_DICT:
  80290. needsDictionary = true;
  80291. data += dataSize - stream->avail_in;
  80292. dataSize = stream->avail_in;
  80293. break;
  80294. case Z_DATA_ERROR:
  80295. case Z_MEM_ERROR:
  80296. error = true;
  80297. default:
  80298. break;
  80299. }
  80300. }
  80301. return 0;
  80302. }
  80303. };
  80304. const int gzipDecompBufferSize = 32768;
  80305. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  80306. const bool deleteSourceWhenDestroyed_,
  80307. const bool noWrap_,
  80308. const int64 uncompressedStreamLength_)
  80309. : sourceStream (sourceStream_),
  80310. uncompressedStreamLength (uncompressedStreamLength_),
  80311. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  80312. noWrap (noWrap_),
  80313. isEof (false),
  80314. activeBufferSize (0),
  80315. originalSourcePos (sourceStream_->getPosition()),
  80316. currentPos (0)
  80317. {
  80318. buffer = (uint8*) juce_malloc (gzipDecompBufferSize);
  80319. helper = new GZIPDecompressHelper (noWrap_);
  80320. }
  80321. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  80322. {
  80323. juce_free (buffer);
  80324. if (deleteSourceWhenDestroyed)
  80325. delete sourceStream;
  80326. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  80327. delete h;
  80328. }
  80329. int64 GZIPDecompressorInputStream::getTotalLength()
  80330. {
  80331. return uncompressedStreamLength;
  80332. }
  80333. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  80334. {
  80335. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  80336. if ((howMany > 0) && ! isEof)
  80337. {
  80338. jassert (destBuffer != 0);
  80339. if (destBuffer != 0)
  80340. {
  80341. int numRead = 0;
  80342. uint8* d = (uint8*) destBuffer;
  80343. while (! h->error)
  80344. {
  80345. const int n = h->doNextBlock (d, howMany);
  80346. currentPos += n;
  80347. if (n == 0)
  80348. {
  80349. if (h->finished || h->needsDictionary)
  80350. {
  80351. isEof = true;
  80352. return numRead;
  80353. }
  80354. if (h->needsInput())
  80355. {
  80356. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  80357. if (activeBufferSize > 0)
  80358. {
  80359. h->setInput ((uint8*) buffer, activeBufferSize);
  80360. }
  80361. else
  80362. {
  80363. isEof = true;
  80364. return numRead;
  80365. }
  80366. }
  80367. }
  80368. else
  80369. {
  80370. numRead += n;
  80371. howMany -= n;
  80372. d += n;
  80373. if (howMany <= 0)
  80374. return numRead;
  80375. }
  80376. }
  80377. }
  80378. }
  80379. return 0;
  80380. }
  80381. bool GZIPDecompressorInputStream::isExhausted()
  80382. {
  80383. const GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  80384. return h->error || isEof;
  80385. }
  80386. int64 GZIPDecompressorInputStream::getPosition()
  80387. {
  80388. return currentPos;
  80389. }
  80390. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  80391. {
  80392. if (newPos != currentPos)
  80393. {
  80394. if (newPos > currentPos)
  80395. {
  80396. skipNextBytes (newPos - currentPos);
  80397. }
  80398. else
  80399. {
  80400. // reset the stream and start again..
  80401. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  80402. delete h;
  80403. isEof = false;
  80404. activeBufferSize = 0;
  80405. currentPos = 0;
  80406. helper = new GZIPDecompressHelper (noWrap);
  80407. sourceStream->setPosition (originalSourcePos);
  80408. skipNextBytes (newPos);
  80409. }
  80410. }
  80411. return true;
  80412. }
  80413. END_JUCE_NAMESPACE
  80414. /********* End of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  80415. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  80416. /********* Start of inlined file: juce_FlacAudioFormat.cpp *********/
  80417. #ifdef _MSC_VER
  80418. #include <windows.h>
  80419. #endif
  80420. #if JUCE_USE_FLAC
  80421. #ifdef _MSC_VER
  80422. #pragma warning (disable : 4505)
  80423. #pragma warning (push)
  80424. #endif
  80425. namespace FlacNamespace
  80426. {
  80427. #define FLAC__NO_DLL 1
  80428. #if ! defined (SIZE_MAX)
  80429. #define SIZE_MAX 0xffffffff
  80430. #endif
  80431. #define __STDC_LIMIT_MACROS 1
  80432. /********* Start of inlined file: all.h *********/
  80433. #ifndef FLAC__ALL_H
  80434. #define FLAC__ALL_H
  80435. /********* Start of inlined file: export.h *********/
  80436. #ifndef FLAC__EXPORT_H
  80437. #define FLAC__EXPORT_H
  80438. /** \file include/FLAC/export.h
  80439. *
  80440. * \brief
  80441. * This module contains #defines and symbols for exporting function
  80442. * calls, and providing version information and compiled-in features.
  80443. *
  80444. * See the \link flac_export export \endlink module.
  80445. */
  80446. /** \defgroup flac_export FLAC/export.h: export symbols
  80447. * \ingroup flac
  80448. *
  80449. * \brief
  80450. * This module contains #defines and symbols for exporting function
  80451. * calls, and providing version information and compiled-in features.
  80452. *
  80453. * If you are compiling with MSVC and will link to the static library
  80454. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  80455. * make sure the symbols are exported properly.
  80456. *
  80457. * \{
  80458. */
  80459. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  80460. #define FLAC_API
  80461. #else
  80462. #ifdef FLAC_API_EXPORTS
  80463. #define FLAC_API _declspec(dllexport)
  80464. #else
  80465. #define FLAC_API _declspec(dllimport)
  80466. #endif
  80467. #endif
  80468. /** These #defines will mirror the libtool-based library version number, see
  80469. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  80470. */
  80471. #define FLAC_API_VERSION_CURRENT 10
  80472. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  80473. #define FLAC_API_VERSION_AGE 2 /**< see above */
  80474. #ifdef __cplusplus
  80475. extern "C" {
  80476. #endif
  80477. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  80478. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  80479. #ifdef __cplusplus
  80480. }
  80481. #endif
  80482. /* \} */
  80483. #endif
  80484. /********* End of inlined file: export.h *********/
  80485. /********* Start of inlined file: assert.h *********/
  80486. #ifndef FLAC__ASSERT_H
  80487. #define FLAC__ASSERT_H
  80488. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  80489. #ifdef DEBUG
  80490. #include <assert.h>
  80491. #define FLAC__ASSERT(x) assert(x)
  80492. #define FLAC__ASSERT_DECLARATION(x) x
  80493. #else
  80494. #define FLAC__ASSERT(x)
  80495. #define FLAC__ASSERT_DECLARATION(x)
  80496. #endif
  80497. #endif
  80498. /********* End of inlined file: assert.h *********/
  80499. /********* Start of inlined file: callback.h *********/
  80500. #ifndef FLAC__CALLBACK_H
  80501. #define FLAC__CALLBACK_H
  80502. /********* Start of inlined file: ordinals.h *********/
  80503. #ifndef FLAC__ORDINALS_H
  80504. #define FLAC__ORDINALS_H
  80505. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  80506. #include <inttypes.h>
  80507. #endif
  80508. typedef signed char FLAC__int8;
  80509. typedef unsigned char FLAC__uint8;
  80510. #if defined(_MSC_VER) || defined(__BORLANDC__)
  80511. typedef __int16 FLAC__int16;
  80512. typedef __int32 FLAC__int32;
  80513. typedef __int64 FLAC__int64;
  80514. typedef unsigned __int16 FLAC__uint16;
  80515. typedef unsigned __int32 FLAC__uint32;
  80516. typedef unsigned __int64 FLAC__uint64;
  80517. #elif defined(__EMX__)
  80518. typedef short FLAC__int16;
  80519. typedef long FLAC__int32;
  80520. typedef long long FLAC__int64;
  80521. typedef unsigned short FLAC__uint16;
  80522. typedef unsigned long FLAC__uint32;
  80523. typedef unsigned long long FLAC__uint64;
  80524. #else
  80525. typedef int16_t FLAC__int16;
  80526. typedef int32_t FLAC__int32;
  80527. typedef int64_t FLAC__int64;
  80528. typedef uint16_t FLAC__uint16;
  80529. typedef uint32_t FLAC__uint32;
  80530. typedef uint64_t FLAC__uint64;
  80531. #endif
  80532. typedef int FLAC__bool;
  80533. typedef FLAC__uint8 FLAC__byte;
  80534. #ifdef true
  80535. #undef true
  80536. #endif
  80537. #ifdef false
  80538. #undef false
  80539. #endif
  80540. #ifndef __cplusplus
  80541. #define true 1
  80542. #define false 0
  80543. #endif
  80544. #endif
  80545. /********* End of inlined file: ordinals.h *********/
  80546. #include <stdlib.h> /* for size_t */
  80547. /** \file include/FLAC/callback.h
  80548. *
  80549. * \brief
  80550. * This module defines the structures for describing I/O callbacks
  80551. * to the other FLAC interfaces.
  80552. *
  80553. * See the detailed documentation for callbacks in the
  80554. * \link flac_callbacks callbacks \endlink module.
  80555. */
  80556. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  80557. * \ingroup flac
  80558. *
  80559. * \brief
  80560. * This module defines the structures for describing I/O callbacks
  80561. * to the other FLAC interfaces.
  80562. *
  80563. * The purpose of the I/O callback functions is to create a common way
  80564. * for the metadata interfaces to handle I/O.
  80565. *
  80566. * Originally the metadata interfaces required filenames as the way of
  80567. * specifying FLAC files to operate on. This is problematic in some
  80568. * environments so there is an additional option to specify a set of
  80569. * callbacks for doing I/O on the FLAC file, instead of the filename.
  80570. *
  80571. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  80572. * opaque structure for a data source.
  80573. *
  80574. * The callback function prototypes are similar (but not identical) to the
  80575. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  80576. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  80577. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  80578. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  80579. * is required. \warning You generally CANNOT directly use fseek or ftell
  80580. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  80581. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  80582. * large files. You will have to find an equivalent function (e.g. ftello),
  80583. * or write a wrapper. The same is true for feof() since this is usually
  80584. * implemented as a macro, not as a function whose address can be taken.
  80585. *
  80586. * \{
  80587. */
  80588. #ifdef __cplusplus
  80589. extern "C" {
  80590. #endif
  80591. /** This is the opaque handle type used by the callbacks. Typically
  80592. * this is a \c FILE* or address of a file descriptor.
  80593. */
  80594. typedef void* FLAC__IOHandle;
  80595. /** Signature for the read callback.
  80596. * The signature and semantics match POSIX fread() implementations
  80597. * and can generally be used interchangeably.
  80598. *
  80599. * \param ptr The address of the read buffer.
  80600. * \param size The size of the records to be read.
  80601. * \param nmemb The number of records to be read.
  80602. * \param handle The handle to the data source.
  80603. * \retval size_t
  80604. * The number of records read.
  80605. */
  80606. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  80607. /** Signature for the write callback.
  80608. * The signature and semantics match POSIX fwrite() implementations
  80609. * and can generally be used interchangeably.
  80610. *
  80611. * \param ptr The address of the write buffer.
  80612. * \param size The size of the records to be written.
  80613. * \param nmemb The number of records to be written.
  80614. * \param handle The handle to the data source.
  80615. * \retval size_t
  80616. * The number of records written.
  80617. */
  80618. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  80619. /** Signature for the seek callback.
  80620. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  80621. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  80622. * and 32-bits wide.
  80623. *
  80624. * \param handle The handle to the data source.
  80625. * \param offset The new position, relative to \a whence
  80626. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  80627. * \retval int
  80628. * \c 0 on success, \c -1 on error.
  80629. */
  80630. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  80631. /** Signature for the tell callback.
  80632. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  80633. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  80634. * and 32-bits wide.
  80635. *
  80636. * \param handle The handle to the data source.
  80637. * \retval FLAC__int64
  80638. * The current position on success, \c -1 on error.
  80639. */
  80640. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  80641. /** Signature for the EOF callback.
  80642. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  80643. * on many systems, feof() is a macro, so in this case a wrapper function
  80644. * must be provided instead.
  80645. *
  80646. * \param handle The handle to the data source.
  80647. * \retval int
  80648. * \c 0 if not at end of file, nonzero if at end of file.
  80649. */
  80650. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  80651. /** Signature for the close callback.
  80652. * The signature and semantics match POSIX fclose() implementations
  80653. * and can generally be used interchangeably.
  80654. *
  80655. * \param handle The handle to the data source.
  80656. * \retval int
  80657. * \c 0 on success, \c EOF on error.
  80658. */
  80659. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  80660. /** A structure for holding a set of callbacks.
  80661. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  80662. * describe which of the callbacks are required. The ones that are not
  80663. * required may be set to NULL.
  80664. *
  80665. * If the seek requirement for an interface is optional, you can signify that
  80666. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  80667. */
  80668. typedef struct {
  80669. FLAC__IOCallback_Read read;
  80670. FLAC__IOCallback_Write write;
  80671. FLAC__IOCallback_Seek seek;
  80672. FLAC__IOCallback_Tell tell;
  80673. FLAC__IOCallback_Eof eof;
  80674. FLAC__IOCallback_Close close;
  80675. } FLAC__IOCallbacks;
  80676. /* \} */
  80677. #ifdef __cplusplus
  80678. }
  80679. #endif
  80680. #endif
  80681. /********* End of inlined file: callback.h *********/
  80682. /********* Start of inlined file: format.h *********/
  80683. #ifndef FLAC__FORMAT_H
  80684. #define FLAC__FORMAT_H
  80685. #ifdef __cplusplus
  80686. extern "C" {
  80687. #endif
  80688. /** \file include/FLAC/format.h
  80689. *
  80690. * \brief
  80691. * This module contains structure definitions for the representation
  80692. * of FLAC format components in memory. These are the basic
  80693. * structures used by the rest of the interfaces.
  80694. *
  80695. * See the detailed documentation in the
  80696. * \link flac_format format \endlink module.
  80697. */
  80698. /** \defgroup flac_format FLAC/format.h: format components
  80699. * \ingroup flac
  80700. *
  80701. * \brief
  80702. * This module contains structure definitions for the representation
  80703. * of FLAC format components in memory. These are the basic
  80704. * structures used by the rest of the interfaces.
  80705. *
  80706. * First, you should be familiar with the
  80707. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  80708. * follow directly from the specification. As a user of libFLAC, the
  80709. * interesting parts really are the structures that describe the frame
  80710. * header and metadata blocks.
  80711. *
  80712. * The format structures here are very primitive, designed to store
  80713. * information in an efficient way. Reading information from the
  80714. * structures is easy but creating or modifying them directly is
  80715. * more complex. For the most part, as a user of a library, editing
  80716. * is not necessary; however, for metadata blocks it is, so there are
  80717. * convenience functions provided in the \link flac_metadata metadata
  80718. * module \endlink to simplify the manipulation of metadata blocks.
  80719. *
  80720. * \note
  80721. * It's not the best convention, but symbols ending in _LEN are in bits
  80722. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  80723. * global variables because they are usually used when declaring byte
  80724. * arrays and some compilers require compile-time knowledge of array
  80725. * sizes when declared on the stack.
  80726. *
  80727. * \{
  80728. */
  80729. /*
  80730. Most of the values described in this file are defined by the FLAC
  80731. format specification. There is nothing to tune here.
  80732. */
  80733. /** The largest legal metadata type code. */
  80734. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  80735. /** The minimum block size, in samples, permitted by the format. */
  80736. #define FLAC__MIN_BLOCK_SIZE (16u)
  80737. /** The maximum block size, in samples, permitted by the format. */
  80738. #define FLAC__MAX_BLOCK_SIZE (65535u)
  80739. /** The maximum block size, in samples, permitted by the FLAC subset for
  80740. * sample rates up to 48kHz. */
  80741. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  80742. /** The maximum number of channels permitted by the format. */
  80743. #define FLAC__MAX_CHANNELS (8u)
  80744. /** The minimum sample resolution permitted by the format. */
  80745. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  80746. /** The maximum sample resolution permitted by the format. */
  80747. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  80748. /** The maximum sample resolution permitted by libFLAC.
  80749. *
  80750. * \warning
  80751. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  80752. * the reference encoder/decoder is currently limited to 24 bits because
  80753. * of prevalent 32-bit math, so make sure and use this value when
  80754. * appropriate.
  80755. */
  80756. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  80757. /** The maximum sample rate permitted by the format. The value is
  80758. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  80759. * as to why.
  80760. */
  80761. #define FLAC__MAX_SAMPLE_RATE (655350u)
  80762. /** The maximum LPC order permitted by the format. */
  80763. #define FLAC__MAX_LPC_ORDER (32u)
  80764. /** The maximum LPC order permitted by the FLAC subset for sample rates
  80765. * up to 48kHz. */
  80766. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  80767. /** The minimum quantized linear predictor coefficient precision
  80768. * permitted by the format.
  80769. */
  80770. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  80771. /** The maximum quantized linear predictor coefficient precision
  80772. * permitted by the format.
  80773. */
  80774. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  80775. /** The maximum order of the fixed predictors permitted by the format. */
  80776. #define FLAC__MAX_FIXED_ORDER (4u)
  80777. /** The maximum Rice partition order permitted by the format. */
  80778. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  80779. /** The maximum Rice partition order permitted by the FLAC Subset. */
  80780. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  80781. /** The version string of the release, stamped onto the libraries and binaries.
  80782. *
  80783. * \note
  80784. * This does not correspond to the shared library version number, which
  80785. * is used to determine binary compatibility.
  80786. */
  80787. extern FLAC_API const char *FLAC__VERSION_STRING;
  80788. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  80789. * This is a NUL-terminated ASCII string; when inserted into the
  80790. * VORBIS_COMMENT the trailing null is stripped.
  80791. */
  80792. extern FLAC_API const char *FLAC__VENDOR_STRING;
  80793. /** The byte string representation of the beginning of a FLAC stream. */
  80794. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  80795. /** The 32-bit integer big-endian representation of the beginning of
  80796. * a FLAC stream.
  80797. */
  80798. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  80799. /** The length of the FLAC signature in bits. */
  80800. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  80801. /** The length of the FLAC signature in bytes. */
  80802. #define FLAC__STREAM_SYNC_LENGTH (4u)
  80803. /*****************************************************************************
  80804. *
  80805. * Subframe structures
  80806. *
  80807. *****************************************************************************/
  80808. /*****************************************************************************/
  80809. /** An enumeration of the available entropy coding methods. */
  80810. typedef enum {
  80811. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  80812. /**< Residual is coded by partitioning into contexts, each with it's own
  80813. * 4-bit Rice parameter. */
  80814. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  80815. /**< Residual is coded by partitioning into contexts, each with it's own
  80816. * 5-bit Rice parameter. */
  80817. } FLAC__EntropyCodingMethodType;
  80818. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  80819. *
  80820. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  80821. * give the string equivalent. The contents should not be modified.
  80822. */
  80823. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  80824. /** Contents of a Rice partitioned residual
  80825. */
  80826. typedef struct {
  80827. unsigned *parameters;
  80828. /**< The Rice parameters for each context. */
  80829. unsigned *raw_bits;
  80830. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  80831. * partitions and zero for unescaped partitions.
  80832. */
  80833. unsigned capacity_by_order;
  80834. /**< The capacity of the \a parameters and \a raw_bits arrays
  80835. * specified as an order, i.e. the number of array elements
  80836. * allocated is 2 ^ \a capacity_by_order.
  80837. */
  80838. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  80839. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  80840. */
  80841. typedef struct {
  80842. unsigned order;
  80843. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  80844. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  80845. /**< The context's Rice parameters and/or raw bits. */
  80846. } FLAC__EntropyCodingMethod_PartitionedRice;
  80847. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  80848. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  80849. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  80850. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  80851. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  80852. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  80853. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  80854. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  80855. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  80856. */
  80857. typedef struct {
  80858. FLAC__EntropyCodingMethodType type;
  80859. union {
  80860. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  80861. } data;
  80862. } FLAC__EntropyCodingMethod;
  80863. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  80864. /*****************************************************************************/
  80865. /** An enumeration of the available subframe types. */
  80866. typedef enum {
  80867. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  80868. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  80869. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  80870. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  80871. } FLAC__SubframeType;
  80872. /** Maps a FLAC__SubframeType to a C string.
  80873. *
  80874. * Using a FLAC__SubframeType as the index to this array will
  80875. * give the string equivalent. The contents should not be modified.
  80876. */
  80877. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  80878. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  80879. */
  80880. typedef struct {
  80881. FLAC__int32 value; /**< The constant signal value. */
  80882. } FLAC__Subframe_Constant;
  80883. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  80884. */
  80885. typedef struct {
  80886. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  80887. } FLAC__Subframe_Verbatim;
  80888. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  80889. */
  80890. typedef struct {
  80891. FLAC__EntropyCodingMethod entropy_coding_method;
  80892. /**< The residual coding method. */
  80893. unsigned order;
  80894. /**< The polynomial order. */
  80895. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  80896. /**< Warmup samples to prime the predictor, length == order. */
  80897. const FLAC__int32 *residual;
  80898. /**< The residual signal, length == (blocksize minus order) samples. */
  80899. } FLAC__Subframe_Fixed;
  80900. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  80901. */
  80902. typedef struct {
  80903. FLAC__EntropyCodingMethod entropy_coding_method;
  80904. /**< The residual coding method. */
  80905. unsigned order;
  80906. /**< The FIR order. */
  80907. unsigned qlp_coeff_precision;
  80908. /**< Quantized FIR filter coefficient precision in bits. */
  80909. int quantization_level;
  80910. /**< The qlp coeff shift needed. */
  80911. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  80912. /**< FIR filter coefficients. */
  80913. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  80914. /**< Warmup samples to prime the predictor, length == order. */
  80915. const FLAC__int32 *residual;
  80916. /**< The residual signal, length == (blocksize minus order) samples. */
  80917. } FLAC__Subframe_LPC;
  80918. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  80919. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  80920. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  80921. */
  80922. typedef struct {
  80923. FLAC__SubframeType type;
  80924. union {
  80925. FLAC__Subframe_Constant constant;
  80926. FLAC__Subframe_Fixed fixed;
  80927. FLAC__Subframe_LPC lpc;
  80928. FLAC__Subframe_Verbatim verbatim;
  80929. } data;
  80930. unsigned wasted_bits;
  80931. } FLAC__Subframe;
  80932. /** == 1 (bit)
  80933. *
  80934. * This used to be a zero-padding bit (hence the name
  80935. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  80936. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  80937. * to mean something else.
  80938. */
  80939. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  80940. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  80941. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  80942. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  80943. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  80944. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  80945. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  80946. /*****************************************************************************/
  80947. /*****************************************************************************
  80948. *
  80949. * Frame structures
  80950. *
  80951. *****************************************************************************/
  80952. /** An enumeration of the available channel assignments. */
  80953. typedef enum {
  80954. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  80955. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  80956. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  80957. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  80958. } FLAC__ChannelAssignment;
  80959. /** Maps a FLAC__ChannelAssignment to a C string.
  80960. *
  80961. * Using a FLAC__ChannelAssignment as the index to this array will
  80962. * give the string equivalent. The contents should not be modified.
  80963. */
  80964. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  80965. /** An enumeration of the possible frame numbering methods. */
  80966. typedef enum {
  80967. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  80968. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  80969. } FLAC__FrameNumberType;
  80970. /** Maps a FLAC__FrameNumberType to a C string.
  80971. *
  80972. * Using a FLAC__FrameNumberType as the index to this array will
  80973. * give the string equivalent. The contents should not be modified.
  80974. */
  80975. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  80976. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  80977. */
  80978. typedef struct {
  80979. unsigned blocksize;
  80980. /**< The number of samples per subframe. */
  80981. unsigned sample_rate;
  80982. /**< The sample rate in Hz. */
  80983. unsigned channels;
  80984. /**< The number of channels (== number of subframes). */
  80985. FLAC__ChannelAssignment channel_assignment;
  80986. /**< The channel assignment for the frame. */
  80987. unsigned bits_per_sample;
  80988. /**< The sample resolution. */
  80989. FLAC__FrameNumberType number_type;
  80990. /**< The numbering scheme used for the frame. As a convenience, the
  80991. * decoder will always convert a frame number to a sample number because
  80992. * the rules are complex. */
  80993. union {
  80994. FLAC__uint32 frame_number;
  80995. FLAC__uint64 sample_number;
  80996. } number;
  80997. /**< The frame number or sample number of first sample in frame;
  80998. * use the \a number_type value to determine which to use. */
  80999. FLAC__uint8 crc;
  81000. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  81001. * of the raw frame header bytes, meaning everything before the CRC byte
  81002. * including the sync code.
  81003. */
  81004. } FLAC__FrameHeader;
  81005. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  81006. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  81007. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  81008. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  81009. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  81010. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  81011. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  81012. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  81013. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  81014. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  81015. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  81016. */
  81017. typedef struct {
  81018. FLAC__uint16 crc;
  81019. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  81020. * 0) of the bytes before the crc, back to and including the frame header
  81021. * sync code.
  81022. */
  81023. } FLAC__FrameFooter;
  81024. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  81025. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  81026. */
  81027. typedef struct {
  81028. FLAC__FrameHeader header;
  81029. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  81030. FLAC__FrameFooter footer;
  81031. } FLAC__Frame;
  81032. /*****************************************************************************/
  81033. /*****************************************************************************
  81034. *
  81035. * Meta-data structures
  81036. *
  81037. *****************************************************************************/
  81038. /** An enumeration of the available metadata block types. */
  81039. typedef enum {
  81040. FLAC__METADATA_TYPE_STREAMINFO = 0,
  81041. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  81042. FLAC__METADATA_TYPE_PADDING = 1,
  81043. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  81044. FLAC__METADATA_TYPE_APPLICATION = 2,
  81045. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  81046. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  81047. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  81048. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  81049. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  81050. FLAC__METADATA_TYPE_CUESHEET = 5,
  81051. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  81052. FLAC__METADATA_TYPE_PICTURE = 6,
  81053. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  81054. FLAC__METADATA_TYPE_UNDEFINED = 7
  81055. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  81056. } FLAC__MetadataType;
  81057. /** Maps a FLAC__MetadataType to a C string.
  81058. *
  81059. * Using a FLAC__MetadataType as the index to this array will
  81060. * give the string equivalent. The contents should not be modified.
  81061. */
  81062. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  81063. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  81064. */
  81065. typedef struct {
  81066. unsigned min_blocksize, max_blocksize;
  81067. unsigned min_framesize, max_framesize;
  81068. unsigned sample_rate;
  81069. unsigned channels;
  81070. unsigned bits_per_sample;
  81071. FLAC__uint64 total_samples;
  81072. FLAC__byte md5sum[16];
  81073. } FLAC__StreamMetadata_StreamInfo;
  81074. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  81075. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  81076. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  81077. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  81078. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  81079. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  81080. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  81081. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  81082. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  81083. /** The total stream length of the STREAMINFO block in bytes. */
  81084. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  81085. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  81086. */
  81087. typedef struct {
  81088. int dummy;
  81089. /**< Conceptually this is an empty struct since we don't store the
  81090. * padding bytes. Empty structs are not allowed by some C compilers,
  81091. * hence the dummy.
  81092. */
  81093. } FLAC__StreamMetadata_Padding;
  81094. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  81095. */
  81096. typedef struct {
  81097. FLAC__byte id[4];
  81098. FLAC__byte *data;
  81099. } FLAC__StreamMetadata_Application;
  81100. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  81101. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  81102. */
  81103. typedef struct {
  81104. FLAC__uint64 sample_number;
  81105. /**< The sample number of the target frame. */
  81106. FLAC__uint64 stream_offset;
  81107. /**< The offset, in bytes, of the target frame with respect to
  81108. * beginning of the first frame. */
  81109. unsigned frame_samples;
  81110. /**< The number of samples in the target frame. */
  81111. } FLAC__StreamMetadata_SeekPoint;
  81112. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  81113. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  81114. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  81115. /** The total stream length of a seek point in bytes. */
  81116. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  81117. /** The value used in the \a sample_number field of
  81118. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  81119. * point (== 0xffffffffffffffff).
  81120. */
  81121. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  81122. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  81123. *
  81124. * \note From the format specification:
  81125. * - The seek points must be sorted by ascending sample number.
  81126. * - Each seek point's sample number must be the first sample of the
  81127. * target frame.
  81128. * - Each seek point's sample number must be unique within the table.
  81129. * - Existence of a SEEKTABLE block implies a correct setting of
  81130. * total_samples in the stream_info block.
  81131. * - Behavior is undefined when more than one SEEKTABLE block is
  81132. * present in a stream.
  81133. */
  81134. typedef struct {
  81135. unsigned num_points;
  81136. FLAC__StreamMetadata_SeekPoint *points;
  81137. } FLAC__StreamMetadata_SeekTable;
  81138. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  81139. *
  81140. * For convenience, the APIs maintain a trailing NUL character at the end of
  81141. * \a entry which is not counted toward \a length, i.e.
  81142. * \code strlen(entry) == length \endcode
  81143. */
  81144. typedef struct {
  81145. FLAC__uint32 length;
  81146. FLAC__byte *entry;
  81147. } FLAC__StreamMetadata_VorbisComment_Entry;
  81148. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  81149. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  81150. */
  81151. typedef struct {
  81152. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  81153. FLAC__uint32 num_comments;
  81154. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  81155. } FLAC__StreamMetadata_VorbisComment;
  81156. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  81157. /** FLAC CUESHEET track index structure. (See the
  81158. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  81159. * the full description of each field.)
  81160. */
  81161. typedef struct {
  81162. FLAC__uint64 offset;
  81163. /**< Offset in samples, relative to the track offset, of the index
  81164. * point.
  81165. */
  81166. FLAC__byte number;
  81167. /**< The index point number. */
  81168. } FLAC__StreamMetadata_CueSheet_Index;
  81169. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  81170. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  81171. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  81172. /** FLAC CUESHEET track structure. (See the
  81173. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  81174. * the full description of each field.)
  81175. */
  81176. typedef struct {
  81177. FLAC__uint64 offset;
  81178. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  81179. FLAC__byte number;
  81180. /**< The track number. */
  81181. char isrc[13];
  81182. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  81183. unsigned type:1;
  81184. /**< The track type: 0 for audio, 1 for non-audio. */
  81185. unsigned pre_emphasis:1;
  81186. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  81187. FLAC__byte num_indices;
  81188. /**< The number of track index points. */
  81189. FLAC__StreamMetadata_CueSheet_Index *indices;
  81190. /**< NULL if num_indices == 0, else pointer to array of index points. */
  81191. } FLAC__StreamMetadata_CueSheet_Track;
  81192. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  81193. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  81194. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  81195. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  81196. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  81197. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  81198. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  81199. /** FLAC CUESHEET structure. (See the
  81200. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  81201. * for the full description of each field.)
  81202. */
  81203. typedef struct {
  81204. char media_catalog_number[129];
  81205. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  81206. * general, the media catalog number may be 0 to 128 bytes long; any
  81207. * unused characters should be right-padded with NUL characters.
  81208. */
  81209. FLAC__uint64 lead_in;
  81210. /**< The number of lead-in samples. */
  81211. FLAC__bool is_cd;
  81212. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  81213. unsigned num_tracks;
  81214. /**< The number of tracks. */
  81215. FLAC__StreamMetadata_CueSheet_Track *tracks;
  81216. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  81217. } FLAC__StreamMetadata_CueSheet;
  81218. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  81219. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  81220. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  81221. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  81222. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  81223. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  81224. typedef enum {
  81225. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  81226. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  81227. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  81228. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  81229. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  81230. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  81231. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  81232. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  81233. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  81234. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  81235. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  81236. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  81237. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  81238. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  81239. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  81240. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  81241. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  81242. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  81243. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  81244. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  81245. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  81246. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  81247. } FLAC__StreamMetadata_Picture_Type;
  81248. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  81249. *
  81250. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  81251. * will give the string equivalent. The contents should not be
  81252. * modified.
  81253. */
  81254. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  81255. /** FLAC PICTURE structure. (See the
  81256. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  81257. * for the full description of each field.)
  81258. */
  81259. typedef struct {
  81260. FLAC__StreamMetadata_Picture_Type type;
  81261. /**< The kind of picture stored. */
  81262. char *mime_type;
  81263. /**< Picture data's MIME type, in ASCII printable characters
  81264. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  81265. * use picture data of MIME type \c image/jpeg or \c image/png. A
  81266. * MIME type of '-->' is also allowed, in which case the picture
  81267. * data should be a complete URL. In file storage, the MIME type is
  81268. * stored as a 32-bit length followed by the ASCII string with no NUL
  81269. * terminator, but is converted to a plain C string in this structure
  81270. * for convenience.
  81271. */
  81272. FLAC__byte *description;
  81273. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  81274. * the description is stored as a 32-bit length followed by the UTF-8
  81275. * string with no NUL terminator, but is converted to a plain C string
  81276. * in this structure for convenience.
  81277. */
  81278. FLAC__uint32 width;
  81279. /**< Picture's width in pixels. */
  81280. FLAC__uint32 height;
  81281. /**< Picture's height in pixels. */
  81282. FLAC__uint32 depth;
  81283. /**< Picture's color depth in bits-per-pixel. */
  81284. FLAC__uint32 colors;
  81285. /**< For indexed palettes (like GIF), picture's number of colors (the
  81286. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  81287. */
  81288. FLAC__uint32 data_length;
  81289. /**< Length of binary picture data in bytes. */
  81290. FLAC__byte *data;
  81291. /**< Binary picture data. */
  81292. } FLAC__StreamMetadata_Picture;
  81293. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  81294. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  81295. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  81296. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  81297. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  81298. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  81299. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  81300. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  81301. /** Structure that is used when a metadata block of unknown type is loaded.
  81302. * The contents are opaque. The structure is used only internally to
  81303. * correctly handle unknown metadata.
  81304. */
  81305. typedef struct {
  81306. FLAC__byte *data;
  81307. } FLAC__StreamMetadata_Unknown;
  81308. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  81309. */
  81310. typedef struct {
  81311. FLAC__MetadataType type;
  81312. /**< The type of the metadata block; used determine which member of the
  81313. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  81314. * then \a data.unknown must be used. */
  81315. FLAC__bool is_last;
  81316. /**< \c true if this metadata block is the last, else \a false */
  81317. unsigned length;
  81318. /**< Length, in bytes, of the block data as it appears in the stream. */
  81319. union {
  81320. FLAC__StreamMetadata_StreamInfo stream_info;
  81321. FLAC__StreamMetadata_Padding padding;
  81322. FLAC__StreamMetadata_Application application;
  81323. FLAC__StreamMetadata_SeekTable seek_table;
  81324. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  81325. FLAC__StreamMetadata_CueSheet cue_sheet;
  81326. FLAC__StreamMetadata_Picture picture;
  81327. FLAC__StreamMetadata_Unknown unknown;
  81328. } data;
  81329. /**< Polymorphic block data; use the \a type value to determine which
  81330. * to use. */
  81331. } FLAC__StreamMetadata;
  81332. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  81333. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  81334. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  81335. /** The total stream length of a metadata block header in bytes. */
  81336. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  81337. /*****************************************************************************/
  81338. /*****************************************************************************
  81339. *
  81340. * Utility functions
  81341. *
  81342. *****************************************************************************/
  81343. /** Tests that a sample rate is valid for FLAC.
  81344. *
  81345. * \param sample_rate The sample rate to test for compliance.
  81346. * \retval FLAC__bool
  81347. * \c true if the given sample rate conforms to the specification, else
  81348. * \c false.
  81349. */
  81350. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  81351. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  81352. * for valid sample rates are slightly more complex since the rate has to
  81353. * be expressible completely in the frame header.
  81354. *
  81355. * \param sample_rate The sample rate to test for compliance.
  81356. * \retval FLAC__bool
  81357. * \c true if the given sample rate conforms to the specification for the
  81358. * subset, else \c false.
  81359. */
  81360. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  81361. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  81362. * comment specification.
  81363. *
  81364. * Vorbis comment names must be composed only of characters from
  81365. * [0x20-0x3C,0x3E-0x7D].
  81366. *
  81367. * \param name A NUL-terminated string to be checked.
  81368. * \assert
  81369. * \code name != NULL \endcode
  81370. * \retval FLAC__bool
  81371. * \c false if entry name is illegal, else \c true.
  81372. */
  81373. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  81374. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  81375. * comment specification.
  81376. *
  81377. * Vorbis comment values must be valid UTF-8 sequences.
  81378. *
  81379. * \param value A string to be checked.
  81380. * \param length A the length of \a value in bytes. May be
  81381. * \c (unsigned)(-1) to indicate that \a value is a plain
  81382. * UTF-8 NUL-terminated string.
  81383. * \assert
  81384. * \code value != NULL \endcode
  81385. * \retval FLAC__bool
  81386. * \c false if entry name is illegal, else \c true.
  81387. */
  81388. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  81389. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  81390. * comment specification.
  81391. *
  81392. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  81393. * 'value' must be legal according to
  81394. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  81395. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  81396. *
  81397. * \param entry An entry to be checked.
  81398. * \param length The length of \a entry in bytes.
  81399. * \assert
  81400. * \code value != NULL \endcode
  81401. * \retval FLAC__bool
  81402. * \c false if entry name is illegal, else \c true.
  81403. */
  81404. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  81405. /** Check a seek table to see if it conforms to the FLAC specification.
  81406. * See the format specification for limits on the contents of the
  81407. * seek table.
  81408. *
  81409. * \param seek_table A pointer to a seek table to be checked.
  81410. * \assert
  81411. * \code seek_table != NULL \endcode
  81412. * \retval FLAC__bool
  81413. * \c false if seek table is illegal, else \c true.
  81414. */
  81415. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  81416. /** Sort a seek table's seek points according to the format specification.
  81417. * This includes a "unique-ification" step to remove duplicates, i.e.
  81418. * seek points with identical \a sample_number values. Duplicate seek
  81419. * points are converted into placeholder points and sorted to the end of
  81420. * the table.
  81421. *
  81422. * \param seek_table A pointer to a seek table to be sorted.
  81423. * \assert
  81424. * \code seek_table != NULL \endcode
  81425. * \retval unsigned
  81426. * The number of duplicate seek points converted into placeholders.
  81427. */
  81428. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  81429. /** Check a cue sheet to see if it conforms to the FLAC specification.
  81430. * See the format specification for limits on the contents of the
  81431. * cue sheet.
  81432. *
  81433. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  81434. * \param check_cd_da_subset If \c true, check CUESHEET against more
  81435. * stringent requirements for a CD-DA (audio) disc.
  81436. * \param violation Address of a pointer to a string. If there is a
  81437. * violation, a pointer to a string explanation of the
  81438. * violation will be returned here. \a violation may be
  81439. * \c NULL if you don't need the returned string. Do not
  81440. * free the returned string; it will always point to static
  81441. * data.
  81442. * \assert
  81443. * \code cue_sheet != NULL \endcode
  81444. * \retval FLAC__bool
  81445. * \c false if cue sheet is illegal, else \c true.
  81446. */
  81447. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  81448. /** Check picture data to see if it conforms to the FLAC specification.
  81449. * See the format specification for limits on the contents of the
  81450. * PICTURE block.
  81451. *
  81452. * \param picture A pointer to existing picture data to be checked.
  81453. * \param violation Address of a pointer to a string. If there is a
  81454. * violation, a pointer to a string explanation of the
  81455. * violation will be returned here. \a violation may be
  81456. * \c NULL if you don't need the returned string. Do not
  81457. * free the returned string; it will always point to static
  81458. * data.
  81459. * \assert
  81460. * \code picture != NULL \endcode
  81461. * \retval FLAC__bool
  81462. * \c false if picture data is illegal, else \c true.
  81463. */
  81464. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  81465. /* \} */
  81466. #ifdef __cplusplus
  81467. }
  81468. #endif
  81469. #endif
  81470. /********* End of inlined file: format.h *********/
  81471. /********* Start of inlined file: metadata.h *********/
  81472. #ifndef FLAC__METADATA_H
  81473. #define FLAC__METADATA_H
  81474. #include <sys/types.h> /* for off_t */
  81475. /* --------------------------------------------------------------------
  81476. (For an example of how all these routines are used, see the source
  81477. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  81478. metaflac in src/metaflac/)
  81479. ------------------------------------------------------------------*/
  81480. /** \file include/FLAC/metadata.h
  81481. *
  81482. * \brief
  81483. * This module provides functions for creating and manipulating FLAC
  81484. * metadata blocks in memory, and three progressively more powerful
  81485. * interfaces for traversing and editing metadata in FLAC files.
  81486. *
  81487. * See the detailed documentation for each interface in the
  81488. * \link flac_metadata metadata \endlink module.
  81489. */
  81490. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  81491. * \ingroup flac
  81492. *
  81493. * \brief
  81494. * This module provides functions for creating and manipulating FLAC
  81495. * metadata blocks in memory, and three progressively more powerful
  81496. * interfaces for traversing and editing metadata in native FLAC files.
  81497. * Note that currently only the Chain interface (level 2) supports Ogg
  81498. * FLAC files, and it is read-only i.e. no writing back changed
  81499. * metadata to file.
  81500. *
  81501. * There are three metadata interfaces of increasing complexity:
  81502. *
  81503. * Level 0:
  81504. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  81505. * PICTURE blocks.
  81506. *
  81507. * Level 1:
  81508. * Read-write access to all metadata blocks. This level is write-
  81509. * efficient in most cases (more on this below), and uses less memory
  81510. * than level 2.
  81511. *
  81512. * Level 2:
  81513. * Read-write access to all metadata blocks. This level is write-
  81514. * efficient in all cases, but uses more memory since all metadata for
  81515. * the whole file is read into memory and manipulated before writing
  81516. * out again.
  81517. *
  81518. * What do we mean by efficient? Since FLAC metadata appears at the
  81519. * beginning of the file, when writing metadata back to a FLAC file
  81520. * it is possible to grow or shrink the metadata such that the entire
  81521. * file must be rewritten. However, if the size remains the same during
  81522. * changes or PADDING blocks are utilized, only the metadata needs to be
  81523. * overwritten, which is much faster.
  81524. *
  81525. * Efficient means the whole file is rewritten at most one time, and only
  81526. * when necessary. Level 1 is not efficient only in the case that you
  81527. * cause more than one metadata block to grow or shrink beyond what can
  81528. * be accomodated by padding. In this case you should probably use level
  81529. * 2, which allows you to edit all the metadata for a file in memory and
  81530. * write it out all at once.
  81531. *
  81532. * All levels know how to skip over and not disturb an ID3v2 tag at the
  81533. * front of the file.
  81534. *
  81535. * All levels access files via their filenames. In addition, level 2
  81536. * has additional alternative read and write functions that take an I/O
  81537. * handle and callbacks, for situations where access by filename is not
  81538. * possible.
  81539. *
  81540. * In addition to the three interfaces, this module defines functions for
  81541. * creating and manipulating various metadata objects in memory. As we see
  81542. * from the Format module, FLAC metadata blocks in memory are very primitive
  81543. * structures for storing information in an efficient way. Reading
  81544. * information from the structures is easy but creating or modifying them
  81545. * directly is more complex. The metadata object routines here facilitate
  81546. * this by taking care of the consistency and memory management drudgery.
  81547. *
  81548. * Unless you will be using the level 1 or 2 interfaces to modify existing
  81549. * metadata however, you will not probably not need these.
  81550. *
  81551. * From a dependency standpoint, none of the encoders or decoders require
  81552. * the metadata module. This is so that embedded users can strip out the
  81553. * metadata module from libFLAC to reduce the size and complexity.
  81554. */
  81555. #ifdef __cplusplus
  81556. extern "C" {
  81557. #endif
  81558. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  81559. * \ingroup flac_metadata
  81560. *
  81561. * \brief
  81562. * The level 0 interface consists of individual routines to read the
  81563. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  81564. * only a filename.
  81565. *
  81566. * They try to skip any ID3v2 tag at the head of the file.
  81567. *
  81568. * \{
  81569. */
  81570. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  81571. * will try to skip any ID3v2 tag at the head of the file.
  81572. *
  81573. * \param filename The path to the FLAC file to read.
  81574. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  81575. * FLAC__StreamMetadata is a simple structure with no
  81576. * memory allocation involved, you pass the address of
  81577. * an existing structure. It need not be initialized.
  81578. * \assert
  81579. * \code filename != NULL \endcode
  81580. * \code streaminfo != NULL \endcode
  81581. * \retval FLAC__bool
  81582. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  81583. * \c false if there was a memory allocation error, a file decoder error,
  81584. * or the file contained no STREAMINFO block. (A memory allocation error
  81585. * is possible because this function must set up a file decoder.)
  81586. */
  81587. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  81588. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  81589. * function will try to skip any ID3v2 tag at the head of the file.
  81590. *
  81591. * \param filename The path to the FLAC file to read.
  81592. * \param tags The address where the returned pointer will be
  81593. * stored. The \a tags object must be deleted by
  81594. * the caller using FLAC__metadata_object_delete().
  81595. * \assert
  81596. * \code filename != NULL \endcode
  81597. * \code tags != NULL \endcode
  81598. * \retval FLAC__bool
  81599. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  81600. * and \a *tags will be set to the address of the metadata structure.
  81601. * Returns \c false if there was a memory allocation error, a file
  81602. * decoder error, or the file contained no VORBIS_COMMENT block, and
  81603. * \a *tags will be set to \c NULL.
  81604. */
  81605. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  81606. /** Read the CUESHEET metadata block of the given FLAC file. This
  81607. * function will try to skip any ID3v2 tag at the head of the file.
  81608. *
  81609. * \param filename The path to the FLAC file to read.
  81610. * \param cuesheet The address where the returned pointer will be
  81611. * stored. The \a cuesheet object must be deleted by
  81612. * the caller using FLAC__metadata_object_delete().
  81613. * \assert
  81614. * \code filename != NULL \endcode
  81615. * \code cuesheet != NULL \endcode
  81616. * \retval FLAC__bool
  81617. * \c true if a valid CUESHEET block was read from \a filename,
  81618. * and \a *cuesheet will be set to the address of the metadata
  81619. * structure. Returns \c false if there was a memory allocation
  81620. * error, a file decoder error, or the file contained no CUESHEET
  81621. * block, and \a *cuesheet will be set to \c NULL.
  81622. */
  81623. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  81624. /** Read a PICTURE metadata block of the given FLAC file. This
  81625. * function will try to skip any ID3v2 tag at the head of the file.
  81626. * Since there can be more than one PICTURE block in a file, this
  81627. * function takes a number of parameters that act as constraints to
  81628. * the search. The PICTURE block with the largest area matching all
  81629. * the constraints will be returned, or \a *picture will be set to
  81630. * \c NULL if there was no such block.
  81631. *
  81632. * \param filename The path to the FLAC file to read.
  81633. * \param picture The address where the returned pointer will be
  81634. * stored. The \a picture object must be deleted by
  81635. * the caller using FLAC__metadata_object_delete().
  81636. * \param type The desired picture type. Use \c -1 to mean
  81637. * "any type".
  81638. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  81639. * string will be matched exactly. Use \c NULL to
  81640. * mean "any MIME type".
  81641. * \param description The desired description. The string will be
  81642. * matched exactly. Use \c NULL to mean "any
  81643. * description".
  81644. * \param max_width The maximum width in pixels desired. Use
  81645. * \c (unsigned)(-1) to mean "any width".
  81646. * \param max_height The maximum height in pixels desired. Use
  81647. * \c (unsigned)(-1) to mean "any height".
  81648. * \param max_depth The maximum color depth in bits-per-pixel desired.
  81649. * Use \c (unsigned)(-1) to mean "any depth".
  81650. * \param max_colors The maximum number of colors desired. Use
  81651. * \c (unsigned)(-1) to mean "any number of colors".
  81652. * \assert
  81653. * \code filename != NULL \endcode
  81654. * \code picture != NULL \endcode
  81655. * \retval FLAC__bool
  81656. * \c true if a valid PICTURE block was read from \a filename,
  81657. * and \a *picture will be set to the address of the metadata
  81658. * structure. Returns \c false if there was a memory allocation
  81659. * error, a file decoder error, or the file contained no PICTURE
  81660. * block, and \a *picture will be set to \c NULL.
  81661. */
  81662. 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);
  81663. /* \} */
  81664. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  81665. * \ingroup flac_metadata
  81666. *
  81667. * \brief
  81668. * The level 1 interface provides read-write access to FLAC file metadata and
  81669. * operates directly on the FLAC file.
  81670. *
  81671. * The general usage of this interface is:
  81672. *
  81673. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  81674. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  81675. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  81676. * see if the file is writable, or only read access is allowed.
  81677. * - Use FLAC__metadata_simple_iterator_next() and
  81678. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  81679. * This is does not read the actual blocks themselves.
  81680. * FLAC__metadata_simple_iterator_next() is relatively fast.
  81681. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  81682. * forward from the front of the file.
  81683. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  81684. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  81685. * the current iterator position. The returned object is yours to modify
  81686. * and free.
  81687. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  81688. * back. You must have write permission to the original file. Make sure to
  81689. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  81690. * below.
  81691. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  81692. * Use the object creation functions from
  81693. * \link flac_metadata_object here \endlink to generate new objects.
  81694. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  81695. * currently referred to by the iterator, or replace it with padding.
  81696. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  81697. * finished.
  81698. *
  81699. * \note
  81700. * The FLAC file remains open the whole time between
  81701. * FLAC__metadata_simple_iterator_init() and
  81702. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  81703. * the file during this time.
  81704. *
  81705. * \note
  81706. * Do not modify the \a is_last, \a length, or \a type fields of returned
  81707. * FLAC__StreamMetadata objects. These are managed automatically.
  81708. *
  81709. * \note
  81710. * If any of the modification functions
  81711. * (FLAC__metadata_simple_iterator_set_block(),
  81712. * FLAC__metadata_simple_iterator_delete_block(),
  81713. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  81714. * you should delete the iterator as it may no longer be valid.
  81715. *
  81716. * \{
  81717. */
  81718. struct FLAC__Metadata_SimpleIterator;
  81719. /** The opaque structure definition for the level 1 iterator type.
  81720. * See the
  81721. * \link flac_metadata_level1 metadata level 1 module \endlink
  81722. * for a detailed description.
  81723. */
  81724. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  81725. /** Status type for FLAC__Metadata_SimpleIterator.
  81726. *
  81727. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  81728. */
  81729. typedef enum {
  81730. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  81731. /**< The iterator is in the normal OK state */
  81732. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  81733. /**< The data passed into a function violated the function's usage criteria */
  81734. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  81735. /**< The iterator could not open the target file */
  81736. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  81737. /**< The iterator could not find the FLAC signature at the start of the file */
  81738. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  81739. /**< The iterator tried to write to a file that was not writable */
  81740. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  81741. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  81742. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  81743. /**< The iterator encountered an error while reading the FLAC file */
  81744. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  81745. /**< The iterator encountered an error while seeking in the FLAC file */
  81746. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  81747. /**< The iterator encountered an error while writing the FLAC file */
  81748. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  81749. /**< The iterator encountered an error renaming the FLAC file */
  81750. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  81751. /**< The iterator encountered an error removing the temporary file */
  81752. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  81753. /**< Memory allocation failed */
  81754. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  81755. /**< The caller violated an assertion or an unexpected error occurred */
  81756. } FLAC__Metadata_SimpleIteratorStatus;
  81757. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  81758. *
  81759. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  81760. * will give the string equivalent. The contents should not be modified.
  81761. */
  81762. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  81763. /** Create a new iterator instance.
  81764. *
  81765. * \retval FLAC__Metadata_SimpleIterator*
  81766. * \c NULL if there was an error allocating memory, else the new instance.
  81767. */
  81768. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  81769. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  81770. *
  81771. * \param iterator A pointer to an existing iterator.
  81772. * \assert
  81773. * \code iterator != NULL \endcode
  81774. */
  81775. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  81776. /** Get the current status of the iterator. Call this after a function
  81777. * returns \c false to get the reason for the error. Also resets the status
  81778. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  81779. *
  81780. * \param iterator A pointer to an existing iterator.
  81781. * \assert
  81782. * \code iterator != NULL \endcode
  81783. * \retval FLAC__Metadata_SimpleIteratorStatus
  81784. * The current status of the iterator.
  81785. */
  81786. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  81787. /** Initialize the iterator to point to the first metadata block in the
  81788. * given FLAC file.
  81789. *
  81790. * \param iterator A pointer to an existing iterator.
  81791. * \param filename The path to the FLAC file.
  81792. * \param read_only If \c true, the FLAC file will be opened
  81793. * in read-only mode; if \c false, the FLAC
  81794. * file will be opened for edit even if no
  81795. * edits are performed.
  81796. * \param preserve_file_stats If \c true, the owner and modification
  81797. * time will be preserved even if the FLAC
  81798. * file is written to.
  81799. * \assert
  81800. * \code iterator != NULL \endcode
  81801. * \code filename != NULL \endcode
  81802. * \retval FLAC__bool
  81803. * \c false if a memory allocation error occurs, the file can't be
  81804. * opened, or another error occurs, else \c true.
  81805. */
  81806. 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);
  81807. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  81808. * FLAC__metadata_simple_iterator_set_block() and
  81809. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  81810. *
  81811. * \param iterator A pointer to an existing iterator.
  81812. * \assert
  81813. * \code iterator != NULL \endcode
  81814. * \retval FLAC__bool
  81815. * See above.
  81816. */
  81817. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  81818. /** Moves the iterator forward one metadata block, returning \c false if
  81819. * already at the end.
  81820. *
  81821. * \param iterator A pointer to an existing initialized iterator.
  81822. * \assert
  81823. * \code iterator != NULL \endcode
  81824. * \a iterator has been successfully initialized with
  81825. * FLAC__metadata_simple_iterator_init()
  81826. * \retval FLAC__bool
  81827. * \c false if already at the last metadata block of the chain, else
  81828. * \c true.
  81829. */
  81830. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  81831. /** Moves the iterator backward one metadata block, returning \c false if
  81832. * already at the beginning.
  81833. *
  81834. * \param iterator A pointer to an existing initialized iterator.
  81835. * \assert
  81836. * \code iterator != NULL \endcode
  81837. * \a iterator has been successfully initialized with
  81838. * FLAC__metadata_simple_iterator_init()
  81839. * \retval FLAC__bool
  81840. * \c false if already at the first metadata block of the chain, else
  81841. * \c true.
  81842. */
  81843. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  81844. /** Returns a flag telling if the current metadata block is the last.
  81845. *
  81846. * \param iterator A pointer to an existing initialized iterator.
  81847. * \assert
  81848. * \code iterator != NULL \endcode
  81849. * \a iterator has been successfully initialized with
  81850. * FLAC__metadata_simple_iterator_init()
  81851. * \retval FLAC__bool
  81852. * \c true if the current metadata block is the last in the file,
  81853. * else \c false.
  81854. */
  81855. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  81856. /** Get the offset of the metadata block at the current position. This
  81857. * avoids reading the actual block data which can save time for large
  81858. * blocks.
  81859. *
  81860. * \param iterator A pointer to an existing initialized iterator.
  81861. * \assert
  81862. * \code iterator != NULL \endcode
  81863. * \a iterator has been successfully initialized with
  81864. * FLAC__metadata_simple_iterator_init()
  81865. * \retval off_t
  81866. * The offset of the metadata block at the current iterator position.
  81867. * This is the byte offset relative to the beginning of the file of
  81868. * the current metadata block's header.
  81869. */
  81870. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  81871. /** Get the type of the metadata block at the current position. This
  81872. * avoids reading the actual block data which can save time for large
  81873. * blocks.
  81874. *
  81875. * \param iterator A pointer to an existing initialized iterator.
  81876. * \assert
  81877. * \code iterator != NULL \endcode
  81878. * \a iterator has been successfully initialized with
  81879. * FLAC__metadata_simple_iterator_init()
  81880. * \retval FLAC__MetadataType
  81881. * The type of the metadata block at the current iterator position.
  81882. */
  81883. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  81884. /** Get the length of the metadata block at the current position. This
  81885. * avoids reading the actual block data which can save time for large
  81886. * blocks.
  81887. *
  81888. * \param iterator A pointer to an existing initialized iterator.
  81889. * \assert
  81890. * \code iterator != NULL \endcode
  81891. * \a iterator has been successfully initialized with
  81892. * FLAC__metadata_simple_iterator_init()
  81893. * \retval unsigned
  81894. * The length of the metadata block at the current iterator position.
  81895. * The is same length as that in the
  81896. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  81897. * i.e. the length of the metadata body that follows the header.
  81898. */
  81899. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  81900. /** Get the application ID of the \c APPLICATION block at the current
  81901. * position. This avoids reading the actual block data which can save
  81902. * time for large blocks.
  81903. *
  81904. * \param iterator A pointer to an existing initialized iterator.
  81905. * \param id A pointer to a buffer of at least \c 4 bytes where
  81906. * the ID will be stored.
  81907. * \assert
  81908. * \code iterator != NULL \endcode
  81909. * \code id != NULL \endcode
  81910. * \a iterator has been successfully initialized with
  81911. * FLAC__metadata_simple_iterator_init()
  81912. * \retval FLAC__bool
  81913. * \c true if the ID was successfully read, else \c false, in which
  81914. * case you should check FLAC__metadata_simple_iterator_status() to
  81915. * find out why. If the status is
  81916. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  81917. * current metadata block is not an \c APPLICATION block. Otherwise
  81918. * if the status is
  81919. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  81920. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  81921. * occurred and the iterator can no longer be used.
  81922. */
  81923. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  81924. /** Get the metadata block at the current position. You can modify the
  81925. * block but must use FLAC__metadata_simple_iterator_set_block() to
  81926. * write it back to the FLAC file.
  81927. *
  81928. * You must call FLAC__metadata_object_delete() on the returned object
  81929. * when you are finished with it.
  81930. *
  81931. * \param iterator A pointer to an existing initialized iterator.
  81932. * \assert
  81933. * \code iterator != NULL \endcode
  81934. * \a iterator has been successfully initialized with
  81935. * FLAC__metadata_simple_iterator_init()
  81936. * \retval FLAC__StreamMetadata*
  81937. * The current metadata block, or \c NULL if there was a memory
  81938. * allocation error.
  81939. */
  81940. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  81941. /** Write a block back to the FLAC file. This function tries to be
  81942. * as efficient as possible; how the block is actually written is
  81943. * shown by the following:
  81944. *
  81945. * Existing block is a STREAMINFO block and the new block is a
  81946. * STREAMINFO block: the new block is written in place. Make sure
  81947. * you know what you're doing when changing the values of a
  81948. * STREAMINFO block.
  81949. *
  81950. * Existing block is a STREAMINFO block and the new block is a
  81951. * not a STREAMINFO block: this is an error since the first block
  81952. * must be a STREAMINFO block. Returns \c false without altering the
  81953. * file.
  81954. *
  81955. * Existing block is not a STREAMINFO block and the new block is a
  81956. * STREAMINFO block: this is an error since there may be only one
  81957. * STREAMINFO block. Returns \c false without altering the file.
  81958. *
  81959. * Existing block and new block are the same length: the existing
  81960. * block will be replaced by the new block, written in place.
  81961. *
  81962. * Existing block is longer than new block: if use_padding is \c true,
  81963. * the existing block will be overwritten in place with the new
  81964. * block followed by a PADDING block, if possible, to make the total
  81965. * size the same as the existing block. Remember that a padding
  81966. * block requires at least four bytes so if the difference in size
  81967. * between the new block and existing block is less than that, the
  81968. * entire file will have to be rewritten, using the new block's
  81969. * exact size. If use_padding is \c false, the entire file will be
  81970. * rewritten, replacing the existing block by the new block.
  81971. *
  81972. * Existing block is shorter than new block: if use_padding is \c true,
  81973. * the function will try and expand the new block into the following
  81974. * PADDING block, if it exists and doing so won't shrink the PADDING
  81975. * block to less than 4 bytes. If there is no following PADDING
  81976. * block, or it will shrink to less than 4 bytes, or use_padding is
  81977. * \c false, the entire file is rewritten, replacing the existing block
  81978. * with the new block. Note that in this case any following PADDING
  81979. * block is preserved as is.
  81980. *
  81981. * After writing the block, the iterator will remain in the same
  81982. * place, i.e. pointing to the new block.
  81983. *
  81984. * \param iterator A pointer to an existing initialized iterator.
  81985. * \param block The block to set.
  81986. * \param use_padding See above.
  81987. * \assert
  81988. * \code iterator != NULL \endcode
  81989. * \a iterator has been successfully initialized with
  81990. * FLAC__metadata_simple_iterator_init()
  81991. * \code block != NULL \endcode
  81992. * \retval FLAC__bool
  81993. * \c true if successful, else \c false.
  81994. */
  81995. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  81996. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  81997. * except that instead of writing over an existing block, it appends
  81998. * a block after the existing block. \a use_padding is again used to
  81999. * tell the function to try an expand into following padding in an
  82000. * attempt to avoid rewriting the entire file.
  82001. *
  82002. * This function will fail and return \c false if given a STREAMINFO
  82003. * block.
  82004. *
  82005. * After writing the block, the iterator will be pointing to the
  82006. * new block.
  82007. *
  82008. * \param iterator A pointer to an existing initialized iterator.
  82009. * \param block The block to set.
  82010. * \param use_padding See above.
  82011. * \assert
  82012. * \code iterator != NULL \endcode
  82013. * \a iterator has been successfully initialized with
  82014. * FLAC__metadata_simple_iterator_init()
  82015. * \code block != NULL \endcode
  82016. * \retval FLAC__bool
  82017. * \c true if successful, else \c false.
  82018. */
  82019. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  82020. /** Deletes the block at the current position. This will cause the
  82021. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  82022. * in which case the block will be replaced by an equal-sized PADDING
  82023. * block. The iterator will be left pointing to the block before the
  82024. * one just deleted.
  82025. *
  82026. * You may not delete the STREAMINFO block.
  82027. *
  82028. * \param iterator A pointer to an existing initialized iterator.
  82029. * \param use_padding See above.
  82030. * \assert
  82031. * \code iterator != NULL \endcode
  82032. * \a iterator has been successfully initialized with
  82033. * FLAC__metadata_simple_iterator_init()
  82034. * \retval FLAC__bool
  82035. * \c true if successful, else \c false.
  82036. */
  82037. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  82038. /* \} */
  82039. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  82040. * \ingroup flac_metadata
  82041. *
  82042. * \brief
  82043. * The level 2 interface provides read-write access to FLAC file metadata;
  82044. * all metadata is read into memory, operated on in memory, and then written
  82045. * to file, which is more efficient than level 1 when editing multiple blocks.
  82046. *
  82047. * Currently Ogg FLAC is supported for read only, via
  82048. * FLAC__metadata_chain_read_ogg() but a subsequent
  82049. * FLAC__metadata_chain_write() will fail.
  82050. *
  82051. * The general usage of this interface is:
  82052. *
  82053. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  82054. * linked list of FLAC metadata blocks.
  82055. * - Read all metadata into the the chain from a FLAC file using
  82056. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  82057. * check the status.
  82058. * - Optionally, consolidate the padding using
  82059. * FLAC__metadata_chain_merge_padding() or
  82060. * FLAC__metadata_chain_sort_padding().
  82061. * - Create a new iterator using FLAC__metadata_iterator_new()
  82062. * - Initialize the iterator to point to the first element in the chain
  82063. * using FLAC__metadata_iterator_init()
  82064. * - Traverse the chain using FLAC__metadata_iterator_next and
  82065. * FLAC__metadata_iterator_prev().
  82066. * - Get a block for reading or modification using
  82067. * FLAC__metadata_iterator_get_block(). The pointer to the object
  82068. * inside the chain is returned, so the block is yours to modify.
  82069. * Changes will be reflected in the FLAC file when you write the
  82070. * chain. You can also add and delete blocks (see functions below).
  82071. * - When done, write out the chain using FLAC__metadata_chain_write().
  82072. * Make sure to read the whole comment to the function below.
  82073. * - Delete the chain using FLAC__metadata_chain_delete().
  82074. *
  82075. * \note
  82076. * Even though the FLAC file is not open while the chain is being
  82077. * manipulated, you must not alter the file externally during
  82078. * this time. The chain assumes the FLAC file will not change
  82079. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  82080. * and FLAC__metadata_chain_write().
  82081. *
  82082. * \note
  82083. * Do not modify the is_last, length, or type fields of returned
  82084. * FLAC__StreamMetadata objects. These are managed automatically.
  82085. *
  82086. * \note
  82087. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  82088. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  82089. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  82090. * become owned by the chain and they will be deleted when the chain is
  82091. * deleted.
  82092. *
  82093. * \{
  82094. */
  82095. struct FLAC__Metadata_Chain;
  82096. /** The opaque structure definition for the level 2 chain type.
  82097. */
  82098. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  82099. struct FLAC__Metadata_Iterator;
  82100. /** The opaque structure definition for the level 2 iterator type.
  82101. */
  82102. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  82103. typedef enum {
  82104. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  82105. /**< The chain is in the normal OK state */
  82106. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  82107. /**< The data passed into a function violated the function's usage criteria */
  82108. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  82109. /**< The chain could not open the target file */
  82110. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  82111. /**< The chain could not find the FLAC signature at the start of the file */
  82112. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  82113. /**< The chain tried to write to a file that was not writable */
  82114. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  82115. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  82116. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  82117. /**< The chain encountered an error while reading the FLAC file */
  82118. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  82119. /**< The chain encountered an error while seeking in the FLAC file */
  82120. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  82121. /**< The chain encountered an error while writing the FLAC file */
  82122. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  82123. /**< The chain encountered an error renaming the FLAC file */
  82124. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  82125. /**< The chain encountered an error removing the temporary file */
  82126. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  82127. /**< Memory allocation failed */
  82128. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  82129. /**< The caller violated an assertion or an unexpected error occurred */
  82130. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  82131. /**< One or more of the required callbacks was NULL */
  82132. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  82133. /**< FLAC__metadata_chain_write() was called on a chain read by
  82134. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  82135. * or
  82136. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  82137. * was called on a chain read by
  82138. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  82139. * Matching read/write methods must always be used. */
  82140. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  82141. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  82142. * chain write requires a tempfile; use
  82143. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  82144. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  82145. * called when the chain write does not require a tempfile; use
  82146. * FLAC__metadata_chain_write_with_callbacks() instead.
  82147. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  82148. * before writing via callbacks. */
  82149. } FLAC__Metadata_ChainStatus;
  82150. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  82151. *
  82152. * Using a FLAC__Metadata_ChainStatus as the index to this array
  82153. * will give the string equivalent. The contents should not be modified.
  82154. */
  82155. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  82156. /*********** FLAC__Metadata_Chain ***********/
  82157. /** Create a new chain instance.
  82158. *
  82159. * \retval FLAC__Metadata_Chain*
  82160. * \c NULL if there was an error allocating memory, else the new instance.
  82161. */
  82162. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  82163. /** Free a chain instance. Deletes the object pointed to by \a chain.
  82164. *
  82165. * \param chain A pointer to an existing chain.
  82166. * \assert
  82167. * \code chain != NULL \endcode
  82168. */
  82169. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  82170. /** Get the current status of the chain. Call this after a function
  82171. * returns \c false to get the reason for the error. Also resets the
  82172. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  82173. *
  82174. * \param chain A pointer to an existing chain.
  82175. * \assert
  82176. * \code chain != NULL \endcode
  82177. * \retval FLAC__Metadata_ChainStatus
  82178. * The current status of the chain.
  82179. */
  82180. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  82181. /** Read all metadata from a FLAC file into the chain.
  82182. *
  82183. * \param chain A pointer to an existing chain.
  82184. * \param filename The path to the FLAC file to read.
  82185. * \assert
  82186. * \code chain != NULL \endcode
  82187. * \code filename != NULL \endcode
  82188. * \retval FLAC__bool
  82189. * \c true if a valid list of metadata blocks was read from
  82190. * \a filename, else \c false. On failure, check the status with
  82191. * FLAC__metadata_chain_status().
  82192. */
  82193. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  82194. /** Read all metadata from an Ogg FLAC file into the chain.
  82195. *
  82196. * \note Ogg FLAC metadata data writing is not supported yet and
  82197. * FLAC__metadata_chain_write() will fail.
  82198. *
  82199. * \param chain A pointer to an existing chain.
  82200. * \param filename The path to the Ogg FLAC file to read.
  82201. * \assert
  82202. * \code chain != NULL \endcode
  82203. * \code filename != NULL \endcode
  82204. * \retval FLAC__bool
  82205. * \c true if a valid list of metadata blocks was read from
  82206. * \a filename, else \c false. On failure, check the status with
  82207. * FLAC__metadata_chain_status().
  82208. */
  82209. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  82210. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  82211. *
  82212. * The \a handle need only be open for reading, but must be seekable.
  82213. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  82214. * for Windows).
  82215. *
  82216. * \param chain A pointer to an existing chain.
  82217. * \param handle The I/O handle of the FLAC stream to read. The
  82218. * handle will NOT be closed after the metadata is read;
  82219. * that is the duty of the caller.
  82220. * \param callbacks
  82221. * A set of callbacks to use for I/O. The mandatory
  82222. * callbacks are \a read, \a seek, and \a tell.
  82223. * \assert
  82224. * \code chain != NULL \endcode
  82225. * \retval FLAC__bool
  82226. * \c true if a valid list of metadata blocks was read from
  82227. * \a handle, else \c false. On failure, check the status with
  82228. * FLAC__metadata_chain_status().
  82229. */
  82230. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  82231. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  82232. *
  82233. * The \a handle need only be open for reading, but must be seekable.
  82234. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  82235. * for Windows).
  82236. *
  82237. * \note Ogg FLAC metadata data writing is not supported yet and
  82238. * FLAC__metadata_chain_write() will fail.
  82239. *
  82240. * \param chain A pointer to an existing chain.
  82241. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  82242. * handle will NOT be closed after the metadata is read;
  82243. * that is the duty of the caller.
  82244. * \param callbacks
  82245. * A set of callbacks to use for I/O. The mandatory
  82246. * callbacks are \a read, \a seek, and \a tell.
  82247. * \assert
  82248. * \code chain != NULL \endcode
  82249. * \retval FLAC__bool
  82250. * \c true if a valid list of metadata blocks was read from
  82251. * \a handle, else \c false. On failure, check the status with
  82252. * FLAC__metadata_chain_status().
  82253. */
  82254. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  82255. /** Checks if writing the given chain would require the use of a
  82256. * temporary file, or if it could be written in place.
  82257. *
  82258. * Under certain conditions, padding can be utilized so that writing
  82259. * edited metadata back to the FLAC file does not require rewriting the
  82260. * entire file. If rewriting is required, then a temporary workfile is
  82261. * required. When writing metadata using callbacks, you must check
  82262. * this function to know whether to call
  82263. * FLAC__metadata_chain_write_with_callbacks() or
  82264. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  82265. * writing with FLAC__metadata_chain_write(), the temporary file is
  82266. * handled internally.
  82267. *
  82268. * \param chain A pointer to an existing chain.
  82269. * \param use_padding
  82270. * Whether or not padding will be allowed to be used
  82271. * during the write. The value of \a use_padding given
  82272. * here must match the value later passed to
  82273. * FLAC__metadata_chain_write_with_callbacks() or
  82274. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  82275. * \assert
  82276. * \code chain != NULL \endcode
  82277. * \retval FLAC__bool
  82278. * \c true if writing the current chain would require a tempfile, or
  82279. * \c false if metadata can be written in place.
  82280. */
  82281. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  82282. /** Write all metadata out to the FLAC file. This function tries to be as
  82283. * efficient as possible; how the metadata is actually written is shown by
  82284. * the following:
  82285. *
  82286. * If the current chain is the same size as the existing metadata, the new
  82287. * data is written in place.
  82288. *
  82289. * If the current chain is longer than the existing metadata, and
  82290. * \a use_padding is \c true, and the last block is a PADDING block of
  82291. * sufficient length, the function will truncate the final padding block
  82292. * so that the overall size of the metadata is the same as the existing
  82293. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  82294. * the above conditions are met, the entire FLAC file must be rewritten.
  82295. * If you want to use padding this way it is a good idea to call
  82296. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  82297. * amount of padding to work with, unless you need to preserve ordering
  82298. * of the PADDING blocks for some reason.
  82299. *
  82300. * If the current chain is shorter than the existing metadata, and
  82301. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  82302. * is extended to make the overall size the same as the existing data. If
  82303. * \a use_padding is \c true and the last block is not a PADDING block, a new
  82304. * PADDING block is added to the end of the new data to make it the same
  82305. * size as the existing data (if possible, see the note to
  82306. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  82307. * and the new data is written in place. If none of the above apply or
  82308. * \a use_padding is \c false, the entire FLAC file is rewritten.
  82309. *
  82310. * If \a preserve_file_stats is \c true, the owner and modification time will
  82311. * be preserved even if the FLAC file is written.
  82312. *
  82313. * For this write function to be used, the chain must have been read with
  82314. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  82315. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  82316. *
  82317. * \param chain A pointer to an existing chain.
  82318. * \param use_padding See above.
  82319. * \param preserve_file_stats See above.
  82320. * \assert
  82321. * \code chain != NULL \endcode
  82322. * \retval FLAC__bool
  82323. * \c true if the write succeeded, else \c false. On failure,
  82324. * check the status with FLAC__metadata_chain_status().
  82325. */
  82326. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  82327. /** Write all metadata out to a FLAC stream via callbacks.
  82328. *
  82329. * (See FLAC__metadata_chain_write() for the details on how padding is
  82330. * used to write metadata in place if possible.)
  82331. *
  82332. * The \a handle must be open for updating and be seekable. The
  82333. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  82334. * for Windows).
  82335. *
  82336. * For this write function to be used, the chain must have been read with
  82337. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  82338. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  82339. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  82340. * \c false.
  82341. *
  82342. * \param chain A pointer to an existing chain.
  82343. * \param use_padding See FLAC__metadata_chain_write()
  82344. * \param handle The I/O handle of the FLAC stream to write. The
  82345. * handle will NOT be closed after the metadata is
  82346. * written; that is the duty of the caller.
  82347. * \param callbacks A set of callbacks to use for I/O. The mandatory
  82348. * callbacks are \a write and \a seek.
  82349. * \assert
  82350. * \code chain != NULL \endcode
  82351. * \retval FLAC__bool
  82352. * \c true if the write succeeded, else \c false. On failure,
  82353. * check the status with FLAC__metadata_chain_status().
  82354. */
  82355. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  82356. /** Write all metadata out to a FLAC stream via callbacks.
  82357. *
  82358. * (See FLAC__metadata_chain_write() for the details on how padding is
  82359. * used to write metadata in place if possible.)
  82360. *
  82361. * This version of the write-with-callbacks function must be used when
  82362. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  82363. * this function, you must supply an I/O handle corresponding to the
  82364. * FLAC file to edit, and a temporary handle to which the new FLAC
  82365. * file will be written. It is the caller's job to move this temporary
  82366. * FLAC file on top of the original FLAC file to complete the metadata
  82367. * edit.
  82368. *
  82369. * The \a handle must be open for reading and be seekable. The
  82370. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  82371. * for Windows).
  82372. *
  82373. * The \a temp_handle must be open for writing. The
  82374. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  82375. * for Windows). It should be an empty stream, or at least positioned
  82376. * at the start-of-file (in which case it is the caller's duty to
  82377. * truncate it on return).
  82378. *
  82379. * For this write function to be used, the chain must have been read with
  82380. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  82381. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  82382. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  82383. * \c true.
  82384. *
  82385. * \param chain A pointer to an existing chain.
  82386. * \param use_padding See FLAC__metadata_chain_write()
  82387. * \param handle The I/O handle of the original FLAC stream to read.
  82388. * The handle will NOT be closed after the metadata is
  82389. * written; that is the duty of the caller.
  82390. * \param callbacks A set of callbacks to use for I/O on \a handle.
  82391. * The mandatory callbacks are \a read, \a seek, and
  82392. * \a eof.
  82393. * \param temp_handle The I/O handle of the FLAC stream to write. The
  82394. * handle will NOT be closed after the metadata is
  82395. * written; that is the duty of the caller.
  82396. * \param temp_callbacks
  82397. * A set of callbacks to use for I/O on temp_handle.
  82398. * The only mandatory callback is \a write.
  82399. * \assert
  82400. * \code chain != NULL \endcode
  82401. * \retval FLAC__bool
  82402. * \c true if the write succeeded, else \c false. On failure,
  82403. * check the status with FLAC__metadata_chain_status().
  82404. */
  82405. 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);
  82406. /** Merge adjacent PADDING blocks into a single block.
  82407. *
  82408. * \note This function does not write to the FLAC file, it only
  82409. * modifies the chain.
  82410. *
  82411. * \warning Any iterator on the current chain will become invalid after this
  82412. * call. You should delete the iterator and get a new one.
  82413. *
  82414. * \param chain A pointer to an existing chain.
  82415. * \assert
  82416. * \code chain != NULL \endcode
  82417. */
  82418. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  82419. /** This function will move all PADDING blocks to the end on the metadata,
  82420. * then merge them into a single block.
  82421. *
  82422. * \note This function does not write to the FLAC file, it only
  82423. * modifies the chain.
  82424. *
  82425. * \warning Any iterator on the current chain will become invalid after this
  82426. * call. You should delete the iterator and get a new one.
  82427. *
  82428. * \param chain A pointer to an existing chain.
  82429. * \assert
  82430. * \code chain != NULL \endcode
  82431. */
  82432. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  82433. /*********** FLAC__Metadata_Iterator ***********/
  82434. /** Create a new iterator instance.
  82435. *
  82436. * \retval FLAC__Metadata_Iterator*
  82437. * \c NULL if there was an error allocating memory, else the new instance.
  82438. */
  82439. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  82440. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  82441. *
  82442. * \param iterator A pointer to an existing iterator.
  82443. * \assert
  82444. * \code iterator != NULL \endcode
  82445. */
  82446. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  82447. /** Initialize the iterator to point to the first metadata block in the
  82448. * given chain.
  82449. *
  82450. * \param iterator A pointer to an existing iterator.
  82451. * \param chain A pointer to an existing and initialized (read) chain.
  82452. * \assert
  82453. * \code iterator != NULL \endcode
  82454. * \code chain != NULL \endcode
  82455. */
  82456. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  82457. /** Moves the iterator forward one metadata block, returning \c false if
  82458. * already at the end.
  82459. *
  82460. * \param iterator A pointer to an existing initialized iterator.
  82461. * \assert
  82462. * \code iterator != NULL \endcode
  82463. * \a iterator has been successfully initialized with
  82464. * FLAC__metadata_iterator_init()
  82465. * \retval FLAC__bool
  82466. * \c false if already at the last metadata block of the chain, else
  82467. * \c true.
  82468. */
  82469. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  82470. /** Moves the iterator backward one metadata block, returning \c false if
  82471. * already at the beginning.
  82472. *
  82473. * \param iterator A pointer to an existing initialized iterator.
  82474. * \assert
  82475. * \code iterator != NULL \endcode
  82476. * \a iterator has been successfully initialized with
  82477. * FLAC__metadata_iterator_init()
  82478. * \retval FLAC__bool
  82479. * \c false if already at the first metadata block of the chain, else
  82480. * \c true.
  82481. */
  82482. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  82483. /** Get the type of the metadata block at the current position.
  82484. *
  82485. * \param iterator A pointer to an existing initialized iterator.
  82486. * \assert
  82487. * \code iterator != NULL \endcode
  82488. * \a iterator has been successfully initialized with
  82489. * FLAC__metadata_iterator_init()
  82490. * \retval FLAC__MetadataType
  82491. * The type of the metadata block at the current iterator position.
  82492. */
  82493. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  82494. /** Get the metadata block at the current position. You can modify
  82495. * the block in place but must write the chain before the changes
  82496. * are reflected to the FLAC file. You do not need to call
  82497. * FLAC__metadata_iterator_set_block() to reflect the changes;
  82498. * the pointer returned by FLAC__metadata_iterator_get_block()
  82499. * points directly into the chain.
  82500. *
  82501. * \warning
  82502. * Do not call FLAC__metadata_object_delete() on the returned object;
  82503. * to delete a block use FLAC__metadata_iterator_delete_block().
  82504. *
  82505. * \param iterator A pointer to an existing initialized iterator.
  82506. * \assert
  82507. * \code iterator != NULL \endcode
  82508. * \a iterator has been successfully initialized with
  82509. * FLAC__metadata_iterator_init()
  82510. * \retval FLAC__StreamMetadata*
  82511. * The current metadata block.
  82512. */
  82513. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  82514. /** Set the metadata block at the current position, replacing the existing
  82515. * block. The new block passed in becomes owned by the chain and it will be
  82516. * deleted when the chain is deleted.
  82517. *
  82518. * \param iterator A pointer to an existing initialized iterator.
  82519. * \param block A pointer to a metadata block.
  82520. * \assert
  82521. * \code iterator != NULL \endcode
  82522. * \a iterator has been successfully initialized with
  82523. * FLAC__metadata_iterator_init()
  82524. * \code block != NULL \endcode
  82525. * \retval FLAC__bool
  82526. * \c false if the conditions in the above description are not met, or
  82527. * a memory allocation error occurs, otherwise \c true.
  82528. */
  82529. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  82530. /** Removes the current block from the chain. If \a replace_with_padding is
  82531. * \c true, the block will instead be replaced with a padding block of equal
  82532. * size. You can not delete the STREAMINFO block. The iterator will be
  82533. * left pointing to the block before the one just "deleted", even if
  82534. * \a replace_with_padding is \c true.
  82535. *
  82536. * \param iterator A pointer to an existing initialized iterator.
  82537. * \param replace_with_padding See above.
  82538. * \assert
  82539. * \code iterator != NULL \endcode
  82540. * \a iterator has been successfully initialized with
  82541. * FLAC__metadata_iterator_init()
  82542. * \retval FLAC__bool
  82543. * \c false if the conditions in the above description are not met,
  82544. * otherwise \c true.
  82545. */
  82546. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  82547. /** Insert a new block before the current block. You cannot insert a block
  82548. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  82549. * as there can be only one, the one that already exists at the head when you
  82550. * read in a chain. The chain takes ownership of the new block and it will be
  82551. * deleted when the chain is deleted. The iterator will be left pointing to
  82552. * the new block.
  82553. *
  82554. * \param iterator A pointer to an existing initialized iterator.
  82555. * \param block A pointer to a metadata block to insert.
  82556. * \assert
  82557. * \code iterator != NULL \endcode
  82558. * \a iterator has been successfully initialized with
  82559. * FLAC__metadata_iterator_init()
  82560. * \retval FLAC__bool
  82561. * \c false if the conditions in the above description are not met, or
  82562. * a memory allocation error occurs, otherwise \c true.
  82563. */
  82564. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  82565. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  82566. * block as there can be only one, the one that already exists at the head when
  82567. * you read in a chain. The chain takes ownership of the new block and it will
  82568. * be deleted when the chain is deleted. The iterator will be left pointing to
  82569. * the new block.
  82570. *
  82571. * \param iterator A pointer to an existing initialized iterator.
  82572. * \param block A pointer to a metadata block to insert.
  82573. * \assert
  82574. * \code iterator != NULL \endcode
  82575. * \a iterator has been successfully initialized with
  82576. * FLAC__metadata_iterator_init()
  82577. * \retval FLAC__bool
  82578. * \c false if the conditions in the above description are not met, or
  82579. * a memory allocation error occurs, otherwise \c true.
  82580. */
  82581. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  82582. /* \} */
  82583. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  82584. * \ingroup flac_metadata
  82585. *
  82586. * \brief
  82587. * This module contains methods for manipulating FLAC metadata objects.
  82588. *
  82589. * Since many are variable length we have to be careful about the memory
  82590. * management. We decree that all pointers to data in the object are
  82591. * owned by the object and memory-managed by the object.
  82592. *
  82593. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  82594. * functions to create all instances. When using the
  82595. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  82596. * \a copy to \c true to have the function make it's own copy of the data, or
  82597. * to \c false to give the object ownership of your data. In the latter case
  82598. * your pointer must be freeable by free() and will be free()d when the object
  82599. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  82600. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  82601. * the length argument is 0 and the \a copy argument is \c false.
  82602. *
  82603. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  82604. * will return \c NULL in the case of a memory allocation error, otherwise a new
  82605. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  82606. * case of a memory allocation error.
  82607. *
  82608. * We don't have the convenience of C++ here, so note that the library relies
  82609. * on you to keep the types straight. In other words, if you pass, for
  82610. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  82611. * FLAC__metadata_object_application_set_data(), you will get an assertion
  82612. * failure.
  82613. *
  82614. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  82615. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  82616. * toward the length or stored in the stream, but it can make working with plain
  82617. * comments (those that don't contain embedded-NULs in the value) easier.
  82618. * Entries passed into these functions have trailing NULs added if missing, and
  82619. * returned entries are guaranteed to have a trailing NUL.
  82620. *
  82621. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  82622. * comment entry/name/value will first validate that it complies with the Vorbis
  82623. * comment specification and return false if it does not.
  82624. *
  82625. * There is no need to recalculate the length field on metadata blocks you
  82626. * have modified. They will be calculated automatically before they are
  82627. * written back to a file.
  82628. *
  82629. * \{
  82630. */
  82631. /** Create a new metadata object instance of the given type.
  82632. *
  82633. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  82634. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  82635. * the vendor string set (but zero comments).
  82636. *
  82637. * Do not pass in a value greater than or equal to
  82638. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  82639. * doing.
  82640. *
  82641. * \param type Type of object to create
  82642. * \retval FLAC__StreamMetadata*
  82643. * \c NULL if there was an error allocating memory or the type code is
  82644. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  82645. */
  82646. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  82647. /** Create a copy of an existing metadata object.
  82648. *
  82649. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  82650. * object is also copied. The caller takes ownership of the new block and
  82651. * is responsible for freeing it with FLAC__metadata_object_delete().
  82652. *
  82653. * \param object Pointer to object to copy.
  82654. * \assert
  82655. * \code object != NULL \endcode
  82656. * \retval FLAC__StreamMetadata*
  82657. * \c NULL if there was an error allocating memory, else the new instance.
  82658. */
  82659. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  82660. /** Free a metadata object. Deletes the object pointed to by \a object.
  82661. *
  82662. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  82663. * object is also deleted.
  82664. *
  82665. * \param object A pointer to an existing object.
  82666. * \assert
  82667. * \code object != NULL \endcode
  82668. */
  82669. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  82670. /** Compares two metadata objects.
  82671. *
  82672. * The compare is "deep", i.e. dynamically allocated data within the
  82673. * object is also compared.
  82674. *
  82675. * \param block1 A pointer to an existing object.
  82676. * \param block2 A pointer to an existing object.
  82677. * \assert
  82678. * \code block1 != NULL \endcode
  82679. * \code block2 != NULL \endcode
  82680. * \retval FLAC__bool
  82681. * \c true if objects are identical, else \c false.
  82682. */
  82683. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  82684. /** Sets the application data of an APPLICATION block.
  82685. *
  82686. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  82687. * takes ownership of the pointer. The existing data will be freed if this
  82688. * function is successful, otherwise the original data will remain if \a copy
  82689. * is \c true and malloc() fails.
  82690. *
  82691. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  82692. *
  82693. * \param object A pointer to an existing APPLICATION object.
  82694. * \param data A pointer to the data to set.
  82695. * \param length The length of \a data in bytes.
  82696. * \param copy See above.
  82697. * \assert
  82698. * \code object != NULL \endcode
  82699. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  82700. * \code (data != NULL && length > 0) ||
  82701. * (data == NULL && length == 0 && copy == false) \endcode
  82702. * \retval FLAC__bool
  82703. * \c false if \a copy is \c true and malloc() fails, else \c true.
  82704. */
  82705. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  82706. /** Resize the seekpoint array.
  82707. *
  82708. * If the size shrinks, elements will truncated; if it grows, new placeholder
  82709. * points will be added to the end.
  82710. *
  82711. * \param object A pointer to an existing SEEKTABLE object.
  82712. * \param new_num_points The desired length of the array; may be \c 0.
  82713. * \assert
  82714. * \code object != NULL \endcode
  82715. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82716. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  82717. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  82718. * \retval FLAC__bool
  82719. * \c false if memory allocation error, else \c true.
  82720. */
  82721. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  82722. /** Set a seekpoint in a seektable.
  82723. *
  82724. * \param object A pointer to an existing SEEKTABLE object.
  82725. * \param point_num Index into seekpoint array to set.
  82726. * \param point The point to set.
  82727. * \assert
  82728. * \code object != NULL \endcode
  82729. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82730. * \code object->data.seek_table.num_points > point_num \endcode
  82731. */
  82732. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  82733. /** Insert a seekpoint into a seektable.
  82734. *
  82735. * \param object A pointer to an existing SEEKTABLE object.
  82736. * \param point_num Index into seekpoint array to set.
  82737. * \param point The point to set.
  82738. * \assert
  82739. * \code object != NULL \endcode
  82740. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82741. * \code object->data.seek_table.num_points >= point_num \endcode
  82742. * \retval FLAC__bool
  82743. * \c false if memory allocation error, else \c true.
  82744. */
  82745. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  82746. /** Delete a seekpoint from a seektable.
  82747. *
  82748. * \param object A pointer to an existing SEEKTABLE object.
  82749. * \param point_num Index into seekpoint array to set.
  82750. * \assert
  82751. * \code object != NULL \endcode
  82752. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82753. * \code object->data.seek_table.num_points > point_num \endcode
  82754. * \retval FLAC__bool
  82755. * \c false if memory allocation error, else \c true.
  82756. */
  82757. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  82758. /** Check a seektable to see if it conforms to the FLAC specification.
  82759. * See the format specification for limits on the contents of the
  82760. * seektable.
  82761. *
  82762. * \param object A pointer to an existing SEEKTABLE object.
  82763. * \assert
  82764. * \code object != NULL \endcode
  82765. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82766. * \retval FLAC__bool
  82767. * \c false if seek table is illegal, else \c true.
  82768. */
  82769. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  82770. /** Append a number of placeholder points to the end of a seek table.
  82771. *
  82772. * \note
  82773. * As with the other ..._seektable_template_... functions, you should
  82774. * call FLAC__metadata_object_seektable_template_sort() when finished
  82775. * to make the seek table legal.
  82776. *
  82777. * \param object A pointer to an existing SEEKTABLE object.
  82778. * \param num The number of placeholder points to append.
  82779. * \assert
  82780. * \code object != NULL \endcode
  82781. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82782. * \retval FLAC__bool
  82783. * \c false if memory allocation fails, else \c true.
  82784. */
  82785. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  82786. /** Append a specific seek point template to the end of a seek table.
  82787. *
  82788. * \note
  82789. * As with the other ..._seektable_template_... functions, you should
  82790. * call FLAC__metadata_object_seektable_template_sort() when finished
  82791. * to make the seek table legal.
  82792. *
  82793. * \param object A pointer to an existing SEEKTABLE object.
  82794. * \param sample_number The sample number of the seek point template.
  82795. * \assert
  82796. * \code object != NULL \endcode
  82797. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82798. * \retval FLAC__bool
  82799. * \c false if memory allocation fails, else \c true.
  82800. */
  82801. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  82802. /** Append specific seek point templates to the end of a seek table.
  82803. *
  82804. * \note
  82805. * As with the other ..._seektable_template_... functions, you should
  82806. * call FLAC__metadata_object_seektable_template_sort() when finished
  82807. * to make the seek table legal.
  82808. *
  82809. * \param object A pointer to an existing SEEKTABLE object.
  82810. * \param sample_numbers An array of sample numbers for the seek points.
  82811. * \param num The number of seek point templates to append.
  82812. * \assert
  82813. * \code object != NULL \endcode
  82814. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82815. * \retval FLAC__bool
  82816. * \c false if memory allocation fails, else \c true.
  82817. */
  82818. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  82819. /** Append a set of evenly-spaced seek point templates to the end of a
  82820. * seek table.
  82821. *
  82822. * \note
  82823. * As with the other ..._seektable_template_... functions, you should
  82824. * call FLAC__metadata_object_seektable_template_sort() when finished
  82825. * to make the seek table legal.
  82826. *
  82827. * \param object A pointer to an existing SEEKTABLE object.
  82828. * \param num The number of placeholder points to append.
  82829. * \param total_samples The total number of samples to be encoded;
  82830. * the seekpoints will be spaced approximately
  82831. * \a total_samples / \a num samples apart.
  82832. * \assert
  82833. * \code object != NULL \endcode
  82834. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82835. * \code total_samples > 0 \endcode
  82836. * \retval FLAC__bool
  82837. * \c false if memory allocation fails, else \c true.
  82838. */
  82839. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  82840. /** Append a set of evenly-spaced seek point templates to the end of a
  82841. * seek table.
  82842. *
  82843. * \note
  82844. * As with the other ..._seektable_template_... functions, you should
  82845. * call FLAC__metadata_object_seektable_template_sort() when finished
  82846. * to make the seek table legal.
  82847. *
  82848. * \param object A pointer to an existing SEEKTABLE object.
  82849. * \param samples The number of samples apart to space the placeholder
  82850. * points. The first point will be at sample \c 0, the
  82851. * second at sample \a samples, then 2*\a samples, and
  82852. * so on. As long as \a samples and \a total_samples
  82853. * are greater than \c 0, there will always be at least
  82854. * one seekpoint at sample \c 0.
  82855. * \param total_samples The total number of samples to be encoded;
  82856. * the seekpoints will be spaced
  82857. * \a samples samples apart.
  82858. * \assert
  82859. * \code object != NULL \endcode
  82860. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82861. * \code samples > 0 \endcode
  82862. * \code total_samples > 0 \endcode
  82863. * \retval FLAC__bool
  82864. * \c false if memory allocation fails, else \c true.
  82865. */
  82866. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  82867. /** Sort a seek table's seek points according to the format specification,
  82868. * removing duplicates.
  82869. *
  82870. * \param object A pointer to a seek table to be sorted.
  82871. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  82872. * If \c true, duplicates are deleted and the seek table is
  82873. * shrunk appropriately; the number of placeholder points
  82874. * present in the seek table will be the same after the call
  82875. * as before.
  82876. * \assert
  82877. * \code object != NULL \endcode
  82878. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82879. * \retval FLAC__bool
  82880. * \c false if realloc() fails, else \c true.
  82881. */
  82882. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  82883. /** Sets the vendor string in a VORBIS_COMMENT block.
  82884. *
  82885. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82886. * one already.
  82887. *
  82888. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82889. * takes ownership of the \c entry.entry pointer.
  82890. *
  82891. * \note If this function returns \c false, the caller still owns the
  82892. * pointer.
  82893. *
  82894. * \param object A pointer to an existing VORBIS_COMMENT object.
  82895. * \param entry The entry to set the vendor string to.
  82896. * \param copy See above.
  82897. * \assert
  82898. * \code object != NULL \endcode
  82899. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82900. * \code (entry.entry != NULL && entry.length > 0) ||
  82901. * (entry.entry == NULL && entry.length == 0) \endcode
  82902. * \retval FLAC__bool
  82903. * \c false if memory allocation fails or \a entry does not comply with the
  82904. * Vorbis comment specification, else \c true.
  82905. */
  82906. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82907. /** Resize the comment array.
  82908. *
  82909. * If the size shrinks, elements will truncated; if it grows, new empty
  82910. * fields will be added to the end.
  82911. *
  82912. * \param object A pointer to an existing VORBIS_COMMENT object.
  82913. * \param new_num_comments The desired length of the array; may be \c 0.
  82914. * \assert
  82915. * \code object != NULL \endcode
  82916. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82917. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  82918. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  82919. * \retval FLAC__bool
  82920. * \c false if memory allocation fails, else \c true.
  82921. */
  82922. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  82923. /** Sets a comment in a VORBIS_COMMENT block.
  82924. *
  82925. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82926. * one already.
  82927. *
  82928. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82929. * takes ownership of the \c entry.entry pointer.
  82930. *
  82931. * \note If this function returns \c false, the caller still owns the
  82932. * pointer.
  82933. *
  82934. * \param object A pointer to an existing VORBIS_COMMENT object.
  82935. * \param comment_num Index into comment array to set.
  82936. * \param entry The entry to set the comment to.
  82937. * \param copy See above.
  82938. * \assert
  82939. * \code object != NULL \endcode
  82940. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82941. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  82942. * \code (entry.entry != NULL && entry.length > 0) ||
  82943. * (entry.entry == NULL && entry.length == 0) \endcode
  82944. * \retval FLAC__bool
  82945. * \c false if memory allocation fails or \a entry does not comply with the
  82946. * Vorbis comment specification, else \c true.
  82947. */
  82948. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82949. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  82950. *
  82951. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82952. * one already.
  82953. *
  82954. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82955. * takes ownership of the \c entry.entry pointer.
  82956. *
  82957. * \note If this function returns \c false, the caller still owns the
  82958. * pointer.
  82959. *
  82960. * \param object A pointer to an existing VORBIS_COMMENT object.
  82961. * \param comment_num The index at which to insert the comment. The comments
  82962. * at and after \a comment_num move right one position.
  82963. * To append a comment to the end, set \a comment_num to
  82964. * \c object->data.vorbis_comment.num_comments .
  82965. * \param entry The comment to insert.
  82966. * \param copy See above.
  82967. * \assert
  82968. * \code object != NULL \endcode
  82969. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82970. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  82971. * \code (entry.entry != NULL && entry.length > 0) ||
  82972. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  82973. * \retval FLAC__bool
  82974. * \c false if memory allocation fails or \a entry does not comply with the
  82975. * Vorbis comment specification, else \c true.
  82976. */
  82977. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82978. /** Appends a comment to a VORBIS_COMMENT block.
  82979. *
  82980. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82981. * one already.
  82982. *
  82983. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82984. * takes ownership of the \c entry.entry pointer.
  82985. *
  82986. * \note If this function returns \c false, the caller still owns the
  82987. * pointer.
  82988. *
  82989. * \param object A pointer to an existing VORBIS_COMMENT object.
  82990. * \param entry The comment to insert.
  82991. * \param copy See above.
  82992. * \assert
  82993. * \code object != NULL \endcode
  82994. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82995. * \code (entry.entry != NULL && entry.length > 0) ||
  82996. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  82997. * \retval FLAC__bool
  82998. * \c false if memory allocation fails or \a entry does not comply with the
  82999. * Vorbis comment specification, else \c true.
  83000. */
  83001. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  83002. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  83003. *
  83004. * For convenience, a trailing NUL is added to the entry if it doesn't have
  83005. * one already.
  83006. *
  83007. * Depending on the the value of \a all, either all or just the first comment
  83008. * whose field name(s) match the given entry's name will be replaced by the
  83009. * given entry. If no comments match, \a entry will simply be appended.
  83010. *
  83011. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  83012. * takes ownership of the \c entry.entry pointer.
  83013. *
  83014. * \note If this function returns \c false, the caller still owns the
  83015. * pointer.
  83016. *
  83017. * \param object A pointer to an existing VORBIS_COMMENT object.
  83018. * \param entry The comment to insert.
  83019. * \param all If \c true, all comments whose field name matches
  83020. * \a entry's field name will be removed, and \a entry will
  83021. * be inserted at the position of the first matching
  83022. * comment. If \c false, only the first comment whose
  83023. * field name matches \a entry's field name will be
  83024. * replaced with \a entry.
  83025. * \param copy See above.
  83026. * \assert
  83027. * \code object != NULL \endcode
  83028. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83029. * \code (entry.entry != NULL && entry.length > 0) ||
  83030. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  83031. * \retval FLAC__bool
  83032. * \c false if memory allocation fails or \a entry does not comply with the
  83033. * Vorbis comment specification, else \c true.
  83034. */
  83035. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  83036. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  83037. *
  83038. * \param object A pointer to an existing VORBIS_COMMENT object.
  83039. * \param comment_num The index of the comment to delete.
  83040. * \assert
  83041. * \code object != NULL \endcode
  83042. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83043. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  83044. * \retval FLAC__bool
  83045. * \c false if realloc() fails, else \c true.
  83046. */
  83047. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  83048. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  83049. *
  83050. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  83051. * memory and shall be owned by the caller. For convenience the entry will
  83052. * have a terminating NUL.
  83053. *
  83054. * \param entry A pointer to a Vorbis comment entry. The entry's
  83055. * \c entry pointer should not point to allocated
  83056. * memory as it will be overwritten.
  83057. * \param field_name The field name in ASCII, \c NUL terminated.
  83058. * \param field_value The field value in UTF-8, \c NUL terminated.
  83059. * \assert
  83060. * \code entry != NULL \endcode
  83061. * \code field_name != NULL \endcode
  83062. * \code field_value != NULL \endcode
  83063. * \retval FLAC__bool
  83064. * \c false if malloc() fails, or if \a field_name or \a field_value does
  83065. * not comply with the Vorbis comment specification, else \c true.
  83066. */
  83067. 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);
  83068. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  83069. *
  83070. * The returned pointers to name and value will be allocated by malloc()
  83071. * and shall be owned by the caller.
  83072. *
  83073. * \param entry An existing Vorbis comment entry.
  83074. * \param field_name The address of where the returned pointer to the
  83075. * field name will be stored.
  83076. * \param field_value The address of where the returned pointer to the
  83077. * field value will be stored.
  83078. * \assert
  83079. * \code (entry.entry != NULL && entry.length > 0) \endcode
  83080. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  83081. * \code field_name != NULL \endcode
  83082. * \code field_value != NULL \endcode
  83083. * \retval FLAC__bool
  83084. * \c false if memory allocation fails or \a entry does not comply with the
  83085. * Vorbis comment specification, else \c true.
  83086. */
  83087. 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);
  83088. /** Check if the given Vorbis comment entry's field name matches the given
  83089. * field name.
  83090. *
  83091. * \param entry An existing Vorbis comment entry.
  83092. * \param field_name The field name to check.
  83093. * \param field_name_length The length of \a field_name, not including the
  83094. * terminating \c NUL.
  83095. * \assert
  83096. * \code (entry.entry != NULL && entry.length > 0) \endcode
  83097. * \retval FLAC__bool
  83098. * \c true if the field names match, else \c false
  83099. */
  83100. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  83101. /** Find a Vorbis comment with the given field name.
  83102. *
  83103. * The search begins at entry number \a offset; use an offset of 0 to
  83104. * search from the beginning of the comment array.
  83105. *
  83106. * \param object A pointer to an existing VORBIS_COMMENT object.
  83107. * \param offset The offset into the comment array from where to start
  83108. * the search.
  83109. * \param field_name The field name of the comment to find.
  83110. * \assert
  83111. * \code object != NULL \endcode
  83112. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83113. * \code field_name != NULL \endcode
  83114. * \retval int
  83115. * The offset in the comment array of the first comment whose field
  83116. * name matches \a field_name, or \c -1 if no match was found.
  83117. */
  83118. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  83119. /** Remove first Vorbis comment matching the given field name.
  83120. *
  83121. * \param object A pointer to an existing VORBIS_COMMENT object.
  83122. * \param field_name The field name of comment to delete.
  83123. * \assert
  83124. * \code object != NULL \endcode
  83125. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83126. * \retval int
  83127. * \c -1 for memory allocation error, \c 0 for no matching entries,
  83128. * \c 1 for one matching entry deleted.
  83129. */
  83130. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  83131. /** Remove all Vorbis comments matching the given field name.
  83132. *
  83133. * \param object A pointer to an existing VORBIS_COMMENT object.
  83134. * \param field_name The field name of comments to delete.
  83135. * \assert
  83136. * \code object != NULL \endcode
  83137. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83138. * \retval int
  83139. * \c -1 for memory allocation error, \c 0 for no matching entries,
  83140. * else the number of matching entries deleted.
  83141. */
  83142. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  83143. /** Create a new CUESHEET track instance.
  83144. *
  83145. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  83146. *
  83147. * \retval FLAC__StreamMetadata_CueSheet_Track*
  83148. * \c NULL if there was an error allocating memory, else the new instance.
  83149. */
  83150. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  83151. /** Create a copy of an existing CUESHEET track object.
  83152. *
  83153. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  83154. * object is also copied. The caller takes ownership of the new object and
  83155. * is responsible for freeing it with
  83156. * FLAC__metadata_object_cuesheet_track_delete().
  83157. *
  83158. * \param object Pointer to object to copy.
  83159. * \assert
  83160. * \code object != NULL \endcode
  83161. * \retval FLAC__StreamMetadata_CueSheet_Track*
  83162. * \c NULL if there was an error allocating memory, else the new instance.
  83163. */
  83164. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  83165. /** Delete a CUESHEET track object
  83166. *
  83167. * \param object A pointer to an existing CUESHEET track object.
  83168. * \assert
  83169. * \code object != NULL \endcode
  83170. */
  83171. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  83172. /** Resize a track's index point array.
  83173. *
  83174. * If the size shrinks, elements will truncated; if it grows, new blank
  83175. * indices will be added to the end.
  83176. *
  83177. * \param object A pointer to an existing CUESHEET object.
  83178. * \param track_num The index of the track to modify. NOTE: this is not
  83179. * necessarily the same as the track's \a number field.
  83180. * \param new_num_indices The desired length of the array; may be \c 0.
  83181. * \assert
  83182. * \code object != NULL \endcode
  83183. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83184. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83185. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  83186. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  83187. * \retval FLAC__bool
  83188. * \c false if memory allocation error, else \c true.
  83189. */
  83190. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  83191. /** Insert an index point in a CUESHEET track at the given index.
  83192. *
  83193. * \param object A pointer to an existing CUESHEET object.
  83194. * \param track_num The index of the track to modify. NOTE: this is not
  83195. * necessarily the same as the track's \a number field.
  83196. * \param index_num The index into the track's index array at which to
  83197. * insert the index point. NOTE: this is not necessarily
  83198. * the same as the index point's \a number field. The
  83199. * indices at and after \a index_num move right one
  83200. * position. To append an index point to the end, set
  83201. * \a index_num to
  83202. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  83203. * \param index The index point to insert.
  83204. * \assert
  83205. * \code object != NULL \endcode
  83206. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83207. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83208. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  83209. * \retval FLAC__bool
  83210. * \c false if realloc() fails, else \c true.
  83211. */
  83212. 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);
  83213. /** Insert a blank index point in a CUESHEET track at the given index.
  83214. *
  83215. * A blank index point is one in which all field values are zero.
  83216. *
  83217. * \param object A pointer to an existing CUESHEET object.
  83218. * \param track_num The index of the track to modify. NOTE: this is not
  83219. * necessarily the same as the track's \a number field.
  83220. * \param index_num The index into the track's index array at which to
  83221. * insert the index point. NOTE: this is not necessarily
  83222. * the same as the index point's \a number field. The
  83223. * indices at and after \a index_num move right one
  83224. * position. To append an index point to the end, set
  83225. * \a index_num to
  83226. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  83227. * \assert
  83228. * \code object != NULL \endcode
  83229. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83230. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83231. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  83232. * \retval FLAC__bool
  83233. * \c false if realloc() fails, else \c true.
  83234. */
  83235. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  83236. /** Delete an index point in a CUESHEET track at the given index.
  83237. *
  83238. * \param object A pointer to an existing CUESHEET object.
  83239. * \param track_num The index into the track array of the track to
  83240. * modify. NOTE: this is not necessarily the same
  83241. * as the track's \a number field.
  83242. * \param index_num The index into the track's index array of the index
  83243. * to delete. NOTE: this is not necessarily the same
  83244. * as the index's \a number field.
  83245. * \assert
  83246. * \code object != NULL \endcode
  83247. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83248. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83249. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  83250. * \retval FLAC__bool
  83251. * \c false if realloc() fails, else \c true.
  83252. */
  83253. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  83254. /** Resize the track array.
  83255. *
  83256. * If the size shrinks, elements will truncated; if it grows, new blank
  83257. * tracks will be added to the end.
  83258. *
  83259. * \param object A pointer to an existing CUESHEET object.
  83260. * \param new_num_tracks The desired length of the array; may be \c 0.
  83261. * \assert
  83262. * \code object != NULL \endcode
  83263. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83264. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  83265. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  83266. * \retval FLAC__bool
  83267. * \c false if memory allocation error, else \c true.
  83268. */
  83269. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  83270. /** Sets a track in a CUESHEET block.
  83271. *
  83272. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  83273. * takes ownership of the \a track pointer.
  83274. *
  83275. * \param object A pointer to an existing CUESHEET object.
  83276. * \param track_num Index into track array to set. NOTE: this is not
  83277. * necessarily the same as the track's \a number field.
  83278. * \param track The track to set the track to. You may safely pass in
  83279. * a const pointer if \a copy is \c true.
  83280. * \param copy See above.
  83281. * \assert
  83282. * \code object != NULL \endcode
  83283. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83284. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  83285. * \code (track->indices != NULL && track->num_indices > 0) ||
  83286. * (track->indices == NULL && track->num_indices == 0)
  83287. * \retval FLAC__bool
  83288. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83289. */
  83290. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  83291. /** Insert a track in a CUESHEET block at the given index.
  83292. *
  83293. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  83294. * takes ownership of the \a track pointer.
  83295. *
  83296. * \param object A pointer to an existing CUESHEET object.
  83297. * \param track_num The index at which to insert the track. NOTE: this
  83298. * is not necessarily the same as the track's \a number
  83299. * field. The tracks at and after \a track_num move right
  83300. * one position. To append a track to the end, set
  83301. * \a track_num to \c object->data.cue_sheet.num_tracks .
  83302. * \param track The track to insert. You may safely pass in a const
  83303. * pointer if \a copy is \c true.
  83304. * \param copy See above.
  83305. * \assert
  83306. * \code object != NULL \endcode
  83307. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83308. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  83309. * \retval FLAC__bool
  83310. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83311. */
  83312. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  83313. /** Insert a blank track in a CUESHEET block at the given index.
  83314. *
  83315. * A blank track is one in which all field values are zero.
  83316. *
  83317. * \param object A pointer to an existing CUESHEET object.
  83318. * \param track_num The index at which to insert the track. NOTE: this
  83319. * is not necessarily the same as the track's \a number
  83320. * field. The tracks at and after \a track_num move right
  83321. * one position. To append a track to the end, set
  83322. * \a track_num to \c object->data.cue_sheet.num_tracks .
  83323. * \assert
  83324. * \code object != NULL \endcode
  83325. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83326. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  83327. * \retval FLAC__bool
  83328. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83329. */
  83330. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  83331. /** Delete a track in a CUESHEET block at the given index.
  83332. *
  83333. * \param object A pointer to an existing CUESHEET object.
  83334. * \param track_num The index into the track array of the track to
  83335. * delete. NOTE: this is not necessarily the same
  83336. * as the track's \a number field.
  83337. * \assert
  83338. * \code object != NULL \endcode
  83339. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83340. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83341. * \retval FLAC__bool
  83342. * \c false if realloc() fails, else \c true.
  83343. */
  83344. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  83345. /** Check a cue sheet to see if it conforms to the FLAC specification.
  83346. * See the format specification for limits on the contents of the
  83347. * cue sheet.
  83348. *
  83349. * \param object A pointer to an existing CUESHEET object.
  83350. * \param check_cd_da_subset If \c true, check CUESHEET against more
  83351. * stringent requirements for a CD-DA (audio) disc.
  83352. * \param violation Address of a pointer to a string. If there is a
  83353. * violation, a pointer to a string explanation of the
  83354. * violation will be returned here. \a violation may be
  83355. * \c NULL if you don't need the returned string. Do not
  83356. * free the returned string; it will always point to static
  83357. * data.
  83358. * \assert
  83359. * \code object != NULL \endcode
  83360. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83361. * \retval FLAC__bool
  83362. * \c false if cue sheet is illegal, else \c true.
  83363. */
  83364. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  83365. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  83366. * assumes the cue sheet corresponds to a CD; the result is undefined
  83367. * if the cuesheet's is_cd bit is not set.
  83368. *
  83369. * \param object A pointer to an existing CUESHEET object.
  83370. * \assert
  83371. * \code object != NULL \endcode
  83372. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83373. * \retval FLAC__uint32
  83374. * The unsigned integer representation of the CDDB/freedb ID
  83375. */
  83376. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  83377. /** Sets the MIME type of a PICTURE block.
  83378. *
  83379. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  83380. * takes ownership of the pointer. The existing string will be freed if this
  83381. * function is successful, otherwise the original string will remain if \a copy
  83382. * is \c true and malloc() fails.
  83383. *
  83384. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  83385. *
  83386. * \param object A pointer to an existing PICTURE object.
  83387. * \param mime_type A pointer to the MIME type string. The string must be
  83388. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  83389. * is done.
  83390. * \param copy See above.
  83391. * \assert
  83392. * \code object != NULL \endcode
  83393. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  83394. * \code (mime_type != NULL) \endcode
  83395. * \retval FLAC__bool
  83396. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83397. */
  83398. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  83399. /** Sets the description of a PICTURE block.
  83400. *
  83401. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  83402. * takes ownership of the pointer. The existing string will be freed if this
  83403. * function is successful, otherwise the original string will remain if \a copy
  83404. * is \c true and malloc() fails.
  83405. *
  83406. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  83407. *
  83408. * \param object A pointer to an existing PICTURE object.
  83409. * \param description A pointer to the description string. The string must be
  83410. * valid UTF-8, NUL-terminated. No validation is done.
  83411. * \param copy See above.
  83412. * \assert
  83413. * \code object != NULL \endcode
  83414. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  83415. * \code (description != NULL) \endcode
  83416. * \retval FLAC__bool
  83417. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83418. */
  83419. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  83420. /** Sets the picture data of a PICTURE block.
  83421. *
  83422. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  83423. * takes ownership of the pointer. Also sets the \a data_length field of the
  83424. * metadata object to what is passed in as the \a length parameter. The
  83425. * existing data will be freed if this function is successful, otherwise the
  83426. * original data and data_length will remain if \a copy is \c true and
  83427. * malloc() fails.
  83428. *
  83429. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  83430. *
  83431. * \param object A pointer to an existing PICTURE object.
  83432. * \param data A pointer to the data to set.
  83433. * \param length The length of \a data in bytes.
  83434. * \param copy See above.
  83435. * \assert
  83436. * \code object != NULL \endcode
  83437. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  83438. * \code (data != NULL && length > 0) ||
  83439. * (data == NULL && length == 0 && copy == false) \endcode
  83440. * \retval FLAC__bool
  83441. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83442. */
  83443. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  83444. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  83445. * See the format specification for limits on the contents of the
  83446. * PICTURE block.
  83447. *
  83448. * \param object A pointer to existing PICTURE block to be checked.
  83449. * \param violation Address of a pointer to a string. If there is a
  83450. * violation, a pointer to a string explanation of the
  83451. * violation will be returned here. \a violation may be
  83452. * \c NULL if you don't need the returned string. Do not
  83453. * free the returned string; it will always point to static
  83454. * data.
  83455. * \assert
  83456. * \code object != NULL \endcode
  83457. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  83458. * \retval FLAC__bool
  83459. * \c false if PICTURE block is illegal, else \c true.
  83460. */
  83461. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  83462. /* \} */
  83463. #ifdef __cplusplus
  83464. }
  83465. #endif
  83466. #endif
  83467. /********* End of inlined file: metadata.h *********/
  83468. /********* Start of inlined file: stream_decoder.h *********/
  83469. #ifndef FLAC__STREAM_DECODER_H
  83470. #define FLAC__STREAM_DECODER_H
  83471. #include <stdio.h> /* for FILE */
  83472. #ifdef __cplusplus
  83473. extern "C" {
  83474. #endif
  83475. /** \file include/FLAC/stream_decoder.h
  83476. *
  83477. * \brief
  83478. * This module contains the functions which implement the stream
  83479. * decoder.
  83480. *
  83481. * See the detailed documentation in the
  83482. * \link flac_stream_decoder stream decoder \endlink module.
  83483. */
  83484. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  83485. * \ingroup flac
  83486. *
  83487. * \brief
  83488. * This module describes the decoder layers provided by libFLAC.
  83489. *
  83490. * The stream decoder can be used to decode complete streams either from
  83491. * the client via callbacks, or directly from a file, depending on how
  83492. * it is initialized. When decoding via callbacks, the client provides
  83493. * callbacks for reading FLAC data and writing decoded samples, and
  83494. * handling metadata and errors. If the client also supplies seek-related
  83495. * callback, the decoder function for sample-accurate seeking within the
  83496. * FLAC input is also available. When decoding from a file, the client
  83497. * needs only supply a filename or open \c FILE* and write/metadata/error
  83498. * callbacks; the rest of the callbacks are supplied internally. For more
  83499. * info see the \link flac_stream_decoder stream decoder \endlink module.
  83500. */
  83501. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  83502. * \ingroup flac_decoder
  83503. *
  83504. * \brief
  83505. * This module contains the functions which implement the stream
  83506. * decoder.
  83507. *
  83508. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  83509. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  83510. *
  83511. * The basic usage of this decoder is as follows:
  83512. * - The program creates an instance of a decoder using
  83513. * FLAC__stream_decoder_new().
  83514. * - The program overrides the default settings using
  83515. * FLAC__stream_decoder_set_*() functions.
  83516. * - The program initializes the instance to validate the settings and
  83517. * prepare for decoding using
  83518. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  83519. * or FLAC__stream_decoder_init_file() for native FLAC,
  83520. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  83521. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  83522. * - The program calls the FLAC__stream_decoder_process_*() functions
  83523. * to decode data, which subsequently calls the callbacks.
  83524. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  83525. * which flushes the input and output and resets the decoder to the
  83526. * uninitialized state.
  83527. * - The instance may be used again or deleted with
  83528. * FLAC__stream_decoder_delete().
  83529. *
  83530. * In more detail, the program will create a new instance by calling
  83531. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  83532. * functions to override the default decoder options, and call
  83533. * one of the FLAC__stream_decoder_init_*() functions.
  83534. *
  83535. * There are three initialization functions for native FLAC, one for
  83536. * setting up the decoder to decode FLAC data from the client via
  83537. * callbacks, and two for decoding directly from a FLAC file.
  83538. *
  83539. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  83540. * You must also supply several callbacks for handling I/O. Some (like
  83541. * seeking) are optional, depending on the capabilities of the input.
  83542. *
  83543. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  83544. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  83545. * \c FILE* or filename and fewer callbacks; the decoder will handle
  83546. * the other callbacks internally.
  83547. *
  83548. * There are three similarly-named init functions for decoding from Ogg
  83549. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  83550. * library has been built with Ogg support.
  83551. *
  83552. * Once the decoder is initialized, your program will call one of several
  83553. * functions to start the decoding process:
  83554. *
  83555. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  83556. * most one metadata block or audio frame and return, calling either the
  83557. * metadata callback or write callback, respectively, once. If the decoder
  83558. * loses sync it will return with only the error callback being called.
  83559. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  83560. * to process the stream from the current location and stop upon reaching
  83561. * the first audio frame. The client will get one metadata, write, or error
  83562. * callback per metadata block, audio frame, or sync error, respectively.
  83563. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  83564. * to process the stream from the current location until the read callback
  83565. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  83566. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  83567. * write, or error callback per metadata block, audio frame, or sync error,
  83568. * respectively.
  83569. *
  83570. * When the decoder has finished decoding (normally or through an abort),
  83571. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  83572. * ensures the decoder is in the correct state and frees memory. Then the
  83573. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  83574. * again to decode another stream.
  83575. *
  83576. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  83577. * At any point after the stream decoder has been initialized, the client can
  83578. * call this function to seek to an exact sample within the stream.
  83579. * Subsequently, the first time the write callback is called it will be
  83580. * passed a (possibly partial) block starting at that sample.
  83581. *
  83582. * If the client cannot seek via the callback interface provided, but still
  83583. * has another way of seeking, it can flush the decoder using
  83584. * FLAC__stream_decoder_flush() and start feeding data from the new position
  83585. * through the read callback.
  83586. *
  83587. * The stream decoder also provides MD5 signature checking. If this is
  83588. * turned on before initialization, FLAC__stream_decoder_finish() will
  83589. * report when the decoded MD5 signature does not match the one stored
  83590. * in the STREAMINFO block. MD5 checking is automatically turned off
  83591. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  83592. * in the STREAMINFO block or when a seek is attempted.
  83593. *
  83594. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  83595. * attention. By default, the decoder only calls the metadata_callback for
  83596. * the STREAMINFO block. These functions allow you to tell the decoder
  83597. * explicitly which blocks to parse and return via the metadata_callback
  83598. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  83599. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  83600. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  83601. * which blocks to return. Remember that metadata blocks can potentially
  83602. * be big (for example, cover art) so filtering out the ones you don't
  83603. * use can reduce the memory requirements of the decoder. Also note the
  83604. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  83605. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  83606. * filtering APPLICATION blocks based on the application ID.
  83607. *
  83608. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  83609. * they still can legally be filtered from the metadata_callback.
  83610. *
  83611. * \note
  83612. * The "set" functions may only be called when the decoder is in the
  83613. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  83614. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  83615. * before FLAC__stream_decoder_init_*(). If this is the case they will
  83616. * return \c true, otherwise \c false.
  83617. *
  83618. * \note
  83619. * FLAC__stream_decoder_finish() resets all settings to the constructor
  83620. * defaults, including the callbacks.
  83621. *
  83622. * \{
  83623. */
  83624. /** State values for a FLAC__StreamDecoder
  83625. *
  83626. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  83627. */
  83628. typedef enum {
  83629. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  83630. /**< The decoder is ready to search for metadata. */
  83631. FLAC__STREAM_DECODER_READ_METADATA,
  83632. /**< The decoder is ready to or is in the process of reading metadata. */
  83633. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  83634. /**< The decoder is ready to or is in the process of searching for the
  83635. * frame sync code.
  83636. */
  83637. FLAC__STREAM_DECODER_READ_FRAME,
  83638. /**< The decoder is ready to or is in the process of reading a frame. */
  83639. FLAC__STREAM_DECODER_END_OF_STREAM,
  83640. /**< The decoder has reached the end of the stream. */
  83641. FLAC__STREAM_DECODER_OGG_ERROR,
  83642. /**< An error occurred in the underlying Ogg layer. */
  83643. FLAC__STREAM_DECODER_SEEK_ERROR,
  83644. /**< An error occurred while seeking. The decoder must be flushed
  83645. * with FLAC__stream_decoder_flush() or reset with
  83646. * FLAC__stream_decoder_reset() before decoding can continue.
  83647. */
  83648. FLAC__STREAM_DECODER_ABORTED,
  83649. /**< The decoder was aborted by the read callback. */
  83650. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  83651. /**< An error occurred allocating memory. The decoder is in an invalid
  83652. * state and can no longer be used.
  83653. */
  83654. FLAC__STREAM_DECODER_UNINITIALIZED
  83655. /**< The decoder is in the uninitialized state; one of the
  83656. * FLAC__stream_decoder_init_*() functions must be called before samples
  83657. * can be processed.
  83658. */
  83659. } FLAC__StreamDecoderState;
  83660. /** Maps a FLAC__StreamDecoderState to a C string.
  83661. *
  83662. * Using a FLAC__StreamDecoderState 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__StreamDecoderStateString[];
  83666. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  83667. */
  83668. typedef enum {
  83669. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  83670. /**< Initialization was successful. */
  83671. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  83672. /**< The library was not compiled with support for the given container
  83673. * format.
  83674. */
  83675. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  83676. /**< A required callback was not supplied. */
  83677. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  83678. /**< An error occurred allocating memory. */
  83679. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  83680. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  83681. * FLAC__stream_decoder_init_ogg_file(). */
  83682. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  83683. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  83684. * already initialized, usually because
  83685. * FLAC__stream_decoder_finish() was not called.
  83686. */
  83687. } FLAC__StreamDecoderInitStatus;
  83688. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  83689. *
  83690. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  83691. * will give the string equivalent. The contents should not be modified.
  83692. */
  83693. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  83694. /** Return values for the FLAC__StreamDecoder read callback.
  83695. */
  83696. typedef enum {
  83697. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  83698. /**< The read was OK and decoding can continue. */
  83699. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  83700. /**< The read was attempted while at the end of the stream. Note that
  83701. * the client must only return this value when the read callback was
  83702. * called when already at the end of the stream. Otherwise, if the read
  83703. * itself moves to the end of the stream, the client should still return
  83704. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  83705. * the next read callback it should return
  83706. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  83707. * of \c 0.
  83708. */
  83709. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  83710. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  83711. } FLAC__StreamDecoderReadStatus;
  83712. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  83713. *
  83714. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  83715. * will give the string equivalent. The contents should not be modified.
  83716. */
  83717. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  83718. /** Return values for the FLAC__StreamDecoder seek callback.
  83719. */
  83720. typedef enum {
  83721. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  83722. /**< The seek was OK and decoding can continue. */
  83723. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  83724. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  83725. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  83726. /**< Client does not support seeking. */
  83727. } FLAC__StreamDecoderSeekStatus;
  83728. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  83729. *
  83730. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  83731. * will give the string equivalent. The contents should not be modified.
  83732. */
  83733. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  83734. /** Return values for the FLAC__StreamDecoder tell callback.
  83735. */
  83736. typedef enum {
  83737. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  83738. /**< The tell was OK and decoding can continue. */
  83739. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  83740. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  83741. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  83742. /**< Client does not support telling the position. */
  83743. } FLAC__StreamDecoderTellStatus;
  83744. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  83745. *
  83746. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  83747. * will give the string equivalent. The contents should not be modified.
  83748. */
  83749. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  83750. /** Return values for the FLAC__StreamDecoder length callback.
  83751. */
  83752. typedef enum {
  83753. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  83754. /**< The length call was OK and decoding can continue. */
  83755. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  83756. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  83757. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  83758. /**< Client does not support reporting the length. */
  83759. } FLAC__StreamDecoderLengthStatus;
  83760. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  83761. *
  83762. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  83763. * will give the string equivalent. The contents should not be modified.
  83764. */
  83765. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  83766. /** Return values for the FLAC__StreamDecoder write callback.
  83767. */
  83768. typedef enum {
  83769. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  83770. /**< The write was OK and decoding can continue. */
  83771. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  83772. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  83773. } FLAC__StreamDecoderWriteStatus;
  83774. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  83775. *
  83776. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  83777. * will give the string equivalent. The contents should not be modified.
  83778. */
  83779. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  83780. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  83781. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  83782. * all. The rest could be caused by bad sync (false synchronization on
  83783. * data that is not the start of a frame) or corrupted data. The error
  83784. * itself is the decoder's best guess at what happened assuming a correct
  83785. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  83786. * could be caused by a correct sync on the start of a frame, but some
  83787. * data in the frame header was corrupted. Or it could be the result of
  83788. * syncing on a point the stream that looked like the starting of a frame
  83789. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  83790. * could be because the decoder encountered a valid frame made by a future
  83791. * version of the encoder which it cannot parse, or because of a false
  83792. * sync making it appear as though an encountered frame was generated by
  83793. * a future encoder.
  83794. */
  83795. typedef enum {
  83796. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  83797. /**< An error in the stream caused the decoder to lose synchronization. */
  83798. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  83799. /**< The decoder encountered a corrupted frame header. */
  83800. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  83801. /**< The frame's data did not match the CRC in the footer. */
  83802. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  83803. /**< The decoder encountered reserved fields in use in the stream. */
  83804. } FLAC__StreamDecoderErrorStatus;
  83805. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  83806. *
  83807. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  83808. * will give the string equivalent. The contents should not be modified.
  83809. */
  83810. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  83811. /***********************************************************************
  83812. *
  83813. * class FLAC__StreamDecoder
  83814. *
  83815. ***********************************************************************/
  83816. struct FLAC__StreamDecoderProtected;
  83817. struct FLAC__StreamDecoderPrivate;
  83818. /** The opaque structure definition for the stream decoder type.
  83819. * See the \link flac_stream_decoder stream decoder module \endlink
  83820. * for a detailed description.
  83821. */
  83822. typedef struct {
  83823. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  83824. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  83825. } FLAC__StreamDecoder;
  83826. /** Signature for the read callback.
  83827. *
  83828. * A function pointer matching this signature must be passed to
  83829. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83830. * called when the decoder needs more input data. The address of the
  83831. * buffer to be filled is supplied, along with the number of bytes the
  83832. * buffer can hold. The callback may choose to supply less data and
  83833. * modify the byte count but must be careful not to overflow the buffer.
  83834. * The callback then returns a status code chosen from
  83835. * FLAC__StreamDecoderReadStatus.
  83836. *
  83837. * Here is an example of a read callback for stdio streams:
  83838. * \code
  83839. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  83840. * {
  83841. * FILE *file = ((MyClientData*)client_data)->file;
  83842. * if(*bytes > 0) {
  83843. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  83844. * if(ferror(file))
  83845. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  83846. * else if(*bytes == 0)
  83847. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  83848. * else
  83849. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  83850. * }
  83851. * else
  83852. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  83853. * }
  83854. * \endcode
  83855. *
  83856. * \note In general, FLAC__StreamDecoder functions which change the
  83857. * state should not be called on the \a decoder while in the callback.
  83858. *
  83859. * \param decoder The decoder instance calling the callback.
  83860. * \param buffer A pointer to a location for the callee to store
  83861. * data to be decoded.
  83862. * \param bytes A pointer to the size of the buffer. On entry
  83863. * to the callback, it contains the maximum number
  83864. * of bytes that may be stored in \a buffer. The
  83865. * callee must set it to the actual number of bytes
  83866. * stored (0 in case of error or end-of-stream) before
  83867. * returning.
  83868. * \param client_data The callee's client data set through
  83869. * FLAC__stream_decoder_init_*().
  83870. * \retval FLAC__StreamDecoderReadStatus
  83871. * The callee's return status. Note that the callback should return
  83872. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  83873. * zero bytes were read and there is no more data to be read.
  83874. */
  83875. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  83876. /** Signature for the seek callback.
  83877. *
  83878. * A function pointer matching this signature may be passed to
  83879. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83880. * called when the decoder needs to seek the input stream. The decoder
  83881. * will pass the absolute byte offset to seek to, 0 meaning the
  83882. * beginning of the stream.
  83883. *
  83884. * Here is an example of a seek callback for stdio streams:
  83885. * \code
  83886. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  83887. * {
  83888. * FILE *file = ((MyClientData*)client_data)->file;
  83889. * if(file == stdin)
  83890. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  83891. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  83892. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  83893. * else
  83894. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  83895. * }
  83896. * \endcode
  83897. *
  83898. * \note In general, FLAC__StreamDecoder functions which change the
  83899. * state should not be called on the \a decoder while in the callback.
  83900. *
  83901. * \param decoder The decoder instance calling the callback.
  83902. * \param absolute_byte_offset The offset from the beginning of the stream
  83903. * to seek to.
  83904. * \param client_data The callee's client data set through
  83905. * FLAC__stream_decoder_init_*().
  83906. * \retval FLAC__StreamDecoderSeekStatus
  83907. * The callee's return status.
  83908. */
  83909. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  83910. /** Signature for the tell callback.
  83911. *
  83912. * A function pointer matching this signature may be passed to
  83913. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83914. * called when the decoder wants to know the current position of the
  83915. * stream. The callback should return the byte offset from the
  83916. * beginning of the stream.
  83917. *
  83918. * Here is an example of a tell callback for stdio streams:
  83919. * \code
  83920. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  83921. * {
  83922. * FILE *file = ((MyClientData*)client_data)->file;
  83923. * off_t pos;
  83924. * if(file == stdin)
  83925. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  83926. * else if((pos = ftello(file)) < 0)
  83927. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  83928. * else {
  83929. * *absolute_byte_offset = (FLAC__uint64)pos;
  83930. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  83931. * }
  83932. * }
  83933. * \endcode
  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 absolute_byte_offset A pointer to storage for the current offset
  83940. * from the beginning of the stream.
  83941. * \param client_data The callee's client data set through
  83942. * FLAC__stream_decoder_init_*().
  83943. * \retval FLAC__StreamDecoderTellStatus
  83944. * The callee's return status.
  83945. */
  83946. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  83947. /** Signature for the length callback.
  83948. *
  83949. * A function pointer matching this signature may be passed to
  83950. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83951. * called when the decoder wants to know the total length of the stream
  83952. * in bytes.
  83953. *
  83954. * Here is an example of a length callback for stdio streams:
  83955. * \code
  83956. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  83957. * {
  83958. * FILE *file = ((MyClientData*)client_data)->file;
  83959. * struct stat filestats;
  83960. *
  83961. * if(file == stdin)
  83962. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  83963. * else if(fstat(fileno(file), &filestats) != 0)
  83964. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  83965. * else {
  83966. * *stream_length = (FLAC__uint64)filestats.st_size;
  83967. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  83968. * }
  83969. * }
  83970. * \endcode
  83971. *
  83972. * \note In general, FLAC__StreamDecoder functions which change the
  83973. * state should not be called on the \a decoder while in the callback.
  83974. *
  83975. * \param decoder The decoder instance calling the callback.
  83976. * \param stream_length A pointer to storage for the length of the stream
  83977. * in bytes.
  83978. * \param client_data The callee's client data set through
  83979. * FLAC__stream_decoder_init_*().
  83980. * \retval FLAC__StreamDecoderLengthStatus
  83981. * The callee's return status.
  83982. */
  83983. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  83984. /** Signature for the EOF callback.
  83985. *
  83986. * A function pointer matching this signature may be passed to
  83987. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83988. * called when the decoder needs to know if the end of the stream has
  83989. * been reached.
  83990. *
  83991. * Here is an example of a EOF callback for stdio streams:
  83992. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  83993. * \code
  83994. * {
  83995. * FILE *file = ((MyClientData*)client_data)->file;
  83996. * return feof(file)? true : false;
  83997. * }
  83998. * \endcode
  83999. *
  84000. * \note In general, FLAC__StreamDecoder functions which change the
  84001. * state should not be called on the \a decoder while in the callback.
  84002. *
  84003. * \param decoder The decoder instance calling the callback.
  84004. * \param client_data The callee's client data set through
  84005. * FLAC__stream_decoder_init_*().
  84006. * \retval FLAC__bool
  84007. * \c true if the currently at the end of the stream, else \c false.
  84008. */
  84009. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  84010. /** Signature for the write callback.
  84011. *
  84012. * A function pointer matching this signature must be passed to one of
  84013. * the FLAC__stream_decoder_init_*() functions.
  84014. * The supplied function will be called when the decoder has decoded a
  84015. * single audio frame. The decoder will pass the frame metadata as well
  84016. * as an array of pointers (one for each channel) pointing to the
  84017. * decoded audio.
  84018. *
  84019. * \note In general, FLAC__StreamDecoder functions which change the
  84020. * state should not be called on the \a decoder while in the callback.
  84021. *
  84022. * \param decoder The decoder instance calling the callback.
  84023. * \param frame The description of the decoded frame. See
  84024. * FLAC__Frame.
  84025. * \param buffer An array of pointers to decoded channels of data.
  84026. * Each pointer will point to an array of signed
  84027. * samples of length \a frame->header.blocksize.
  84028. * Channels will be ordered according to the FLAC
  84029. * specification; see the documentation for the
  84030. * <A HREF="../format.html#frame_header">frame header</A>.
  84031. * \param client_data The callee's client data set through
  84032. * FLAC__stream_decoder_init_*().
  84033. * \retval FLAC__StreamDecoderWriteStatus
  84034. * The callee's return status.
  84035. */
  84036. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  84037. /** Signature for the metadata callback.
  84038. *
  84039. * A function pointer matching this signature must be passed to one of
  84040. * the FLAC__stream_decoder_init_*() functions.
  84041. * The supplied function will be called when the decoder has decoded a
  84042. * metadata block. In a valid FLAC file there will always be one
  84043. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  84044. * These will be supplied by the decoder in the same order as they
  84045. * appear in the stream and always before the first audio frame (i.e.
  84046. * write callback). The metadata block that is passed in must not be
  84047. * modified, and it doesn't live beyond the callback, so you should make
  84048. * a copy of it with FLAC__metadata_object_clone() if you will need it
  84049. * elsewhere. Since metadata blocks can potentially be large, by
  84050. * default the decoder only calls the metadata callback for the
  84051. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  84052. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  84053. *
  84054. * \note In general, FLAC__StreamDecoder functions which change the
  84055. * state should not be called on the \a decoder while in the callback.
  84056. *
  84057. * \param decoder The decoder instance calling the callback.
  84058. * \param metadata The decoded metadata block.
  84059. * \param client_data The callee's client data set through
  84060. * FLAC__stream_decoder_init_*().
  84061. */
  84062. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  84063. /** Signature for the error callback.
  84064. *
  84065. * A function pointer matching this signature must be passed to one of
  84066. * the FLAC__stream_decoder_init_*() functions.
  84067. * The supplied function will be called whenever an error occurs during
  84068. * decoding.
  84069. *
  84070. * \note In general, FLAC__StreamDecoder functions which change the
  84071. * state should not be called on the \a decoder while in the callback.
  84072. *
  84073. * \param decoder The decoder instance calling the callback.
  84074. * \param status The error encountered by the decoder.
  84075. * \param client_data The callee's client data set through
  84076. * FLAC__stream_decoder_init_*().
  84077. */
  84078. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  84079. /***********************************************************************
  84080. *
  84081. * Class constructor/destructor
  84082. *
  84083. ***********************************************************************/
  84084. /** Create a new stream decoder instance. The instance is created with
  84085. * default settings; see the individual FLAC__stream_decoder_set_*()
  84086. * functions for each setting's default.
  84087. *
  84088. * \retval FLAC__StreamDecoder*
  84089. * \c NULL if there was an error allocating memory, else the new instance.
  84090. */
  84091. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  84092. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  84093. *
  84094. * \param decoder A pointer to an existing decoder.
  84095. * \assert
  84096. * \code decoder != NULL \endcode
  84097. */
  84098. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  84099. /***********************************************************************
  84100. *
  84101. * Public class method prototypes
  84102. *
  84103. ***********************************************************************/
  84104. /** Set the serial number for the FLAC stream within the Ogg container.
  84105. * The default behavior is to use the serial number of the first Ogg
  84106. * page. Setting a serial number here will explicitly specify which
  84107. * stream is to be decoded.
  84108. *
  84109. * \note
  84110. * This does not need to be set for native FLAC decoding.
  84111. *
  84112. * \default \c use serial number of first page
  84113. * \param decoder A decoder instance to set.
  84114. * \param serial_number See above.
  84115. * \assert
  84116. * \code decoder != NULL \endcode
  84117. * \retval FLAC__bool
  84118. * \c false if the decoder is already initialized, else \c true.
  84119. */
  84120. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  84121. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  84122. * compute the MD5 signature of the unencoded audio data while decoding
  84123. * and compare it to the signature from the STREAMINFO block, if it
  84124. * exists, during FLAC__stream_decoder_finish().
  84125. *
  84126. * MD5 signature checking will be turned off (until the next
  84127. * FLAC__stream_decoder_reset()) if there is no signature in the
  84128. * STREAMINFO block or when a seek is attempted.
  84129. *
  84130. * Clients that do not use the MD5 check should leave this off to speed
  84131. * up decoding.
  84132. *
  84133. * \default \c false
  84134. * \param decoder A decoder instance to set.
  84135. * \param value Flag value (see above).
  84136. * \assert
  84137. * \code decoder != NULL \endcode
  84138. * \retval FLAC__bool
  84139. * \c false if the decoder is already initialized, else \c true.
  84140. */
  84141. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  84142. /** Direct the decoder to pass on all metadata blocks of type \a type.
  84143. *
  84144. * \default By default, only the \c STREAMINFO block is returned via the
  84145. * metadata callback.
  84146. * \param decoder A decoder instance to set.
  84147. * \param type See above.
  84148. * \assert
  84149. * \code decoder != NULL \endcode
  84150. * \a type is valid
  84151. * \retval FLAC__bool
  84152. * \c false if the decoder is already initialized, else \c true.
  84153. */
  84154. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  84155. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  84156. * given \a id.
  84157. *
  84158. * \default By default, only the \c STREAMINFO block is returned via the
  84159. * metadata callback.
  84160. * \param decoder A decoder instance to set.
  84161. * \param id See above.
  84162. * \assert
  84163. * \code decoder != NULL \endcode
  84164. * \code id != NULL \endcode
  84165. * \retval FLAC__bool
  84166. * \c false if the decoder is already initialized, else \c true.
  84167. */
  84168. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  84169. /** Direct the decoder to pass on all metadata blocks of any type.
  84170. *
  84171. * \default By default, only the \c STREAMINFO block is returned via the
  84172. * metadata callback.
  84173. * \param decoder A decoder instance to set.
  84174. * \assert
  84175. * \code decoder != NULL \endcode
  84176. * \retval FLAC__bool
  84177. * \c false if the decoder is already initialized, else \c true.
  84178. */
  84179. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  84180. /** Direct the decoder to filter out all metadata blocks of type \a type.
  84181. *
  84182. * \default By default, only the \c STREAMINFO block is returned via the
  84183. * metadata callback.
  84184. * \param decoder A decoder instance to set.
  84185. * \param type See above.
  84186. * \assert
  84187. * \code decoder != NULL \endcode
  84188. * \a type is valid
  84189. * \retval FLAC__bool
  84190. * \c false if the decoder is already initialized, else \c true.
  84191. */
  84192. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  84193. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  84194. * the given \a id.
  84195. *
  84196. * \default By default, only the \c STREAMINFO block is returned via the
  84197. * metadata callback.
  84198. * \param decoder A decoder instance to set.
  84199. * \param id See above.
  84200. * \assert
  84201. * \code decoder != NULL \endcode
  84202. * \code id != NULL \endcode
  84203. * \retval FLAC__bool
  84204. * \c false if the decoder is already initialized, else \c true.
  84205. */
  84206. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  84207. /** Direct the decoder to filter out all metadata blocks of any type.
  84208. *
  84209. * \default By default, only the \c STREAMINFO block is returned via the
  84210. * metadata callback.
  84211. * \param decoder A decoder instance to set.
  84212. * \assert
  84213. * \code decoder != NULL \endcode
  84214. * \retval FLAC__bool
  84215. * \c false if the decoder is already initialized, else \c true.
  84216. */
  84217. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  84218. /** Get the current decoder state.
  84219. *
  84220. * \param decoder A decoder instance to query.
  84221. * \assert
  84222. * \code decoder != NULL \endcode
  84223. * \retval FLAC__StreamDecoderState
  84224. * The current decoder state.
  84225. */
  84226. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  84227. /** Get the current decoder state as a C string.
  84228. *
  84229. * \param decoder A decoder instance to query.
  84230. * \assert
  84231. * \code decoder != NULL \endcode
  84232. * \retval const char *
  84233. * The decoder state as a C string. Do not modify the contents.
  84234. */
  84235. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  84236. /** Get the "MD5 signature checking" flag.
  84237. * This is the value of the setting, not whether or not the decoder is
  84238. * currently checking the MD5 (remember, it can be turned off automatically
  84239. * by a seek). When the decoder is reset the flag will be restored to the
  84240. * value returned by this function.
  84241. *
  84242. * \param decoder A decoder instance to query.
  84243. * \assert
  84244. * \code decoder != NULL \endcode
  84245. * \retval FLAC__bool
  84246. * See above.
  84247. */
  84248. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  84249. /** Get the total number of samples in the stream being decoded.
  84250. * Will only be valid after decoding has started and will contain the
  84251. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  84252. *
  84253. * \param decoder A decoder instance to query.
  84254. * \assert
  84255. * \code decoder != NULL \endcode
  84256. * \retval unsigned
  84257. * See above.
  84258. */
  84259. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  84260. /** Get the current number of channels in the stream being decoded.
  84261. * Will only be valid after decoding has started and will contain the
  84262. * value from the most recently decoded frame header.
  84263. *
  84264. * \param decoder A decoder instance to query.
  84265. * \assert
  84266. * \code decoder != NULL \endcode
  84267. * \retval unsigned
  84268. * See above.
  84269. */
  84270. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  84271. /** Get the current channel assignment in the stream being decoded.
  84272. * Will only be valid after decoding has started and will contain the
  84273. * value from the most recently decoded frame header.
  84274. *
  84275. * \param decoder A decoder instance to query.
  84276. * \assert
  84277. * \code decoder != NULL \endcode
  84278. * \retval FLAC__ChannelAssignment
  84279. * See above.
  84280. */
  84281. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  84282. /** Get the current sample resolution in the stream being decoded.
  84283. * Will only be valid after decoding has started and will contain the
  84284. * value from the most recently decoded frame header.
  84285. *
  84286. * \param decoder A decoder instance to query.
  84287. * \assert
  84288. * \code decoder != NULL \endcode
  84289. * \retval unsigned
  84290. * See above.
  84291. */
  84292. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  84293. /** Get the current sample rate in Hz of the stream being decoded.
  84294. * Will only be valid after decoding has started and will contain the
  84295. * value from the most recently decoded frame header.
  84296. *
  84297. * \param decoder A decoder instance to query.
  84298. * \assert
  84299. * \code decoder != NULL \endcode
  84300. * \retval unsigned
  84301. * See above.
  84302. */
  84303. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  84304. /** Get the current blocksize of the stream being decoded.
  84305. * Will only be valid after decoding has started and will contain the
  84306. * value from the most recently decoded frame header.
  84307. *
  84308. * \param decoder A decoder instance to query.
  84309. * \assert
  84310. * \code decoder != NULL \endcode
  84311. * \retval unsigned
  84312. * See above.
  84313. */
  84314. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  84315. /** Returns the decoder's current read position within the stream.
  84316. * The position is the byte offset from the start of the stream.
  84317. * Bytes before this position have been fully decoded. Note that
  84318. * there may still be undecoded bytes in the decoder's read FIFO.
  84319. * The returned position is correct even after a seek.
  84320. *
  84321. * \warning This function currently only works for native FLAC,
  84322. * not Ogg FLAC streams.
  84323. *
  84324. * \param decoder A decoder instance to query.
  84325. * \param position Address at which to return the desired position.
  84326. * \assert
  84327. * \code decoder != NULL \endcode
  84328. * \code position != NULL \endcode
  84329. * \retval FLAC__bool
  84330. * \c true if successful, \c false if the stream is not native FLAC,
  84331. * or there was an error from the 'tell' callback or it returned
  84332. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  84333. */
  84334. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  84335. /** Initialize the decoder instance to decode native FLAC streams.
  84336. *
  84337. * This flavor of initialization sets up the decoder to decode from a
  84338. * native FLAC stream. I/O is performed via callbacks to the client.
  84339. * For decoding from a plain file via filename or open FILE*,
  84340. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  84341. * provide a simpler interface.
  84342. *
  84343. * This function should be called after FLAC__stream_decoder_new() and
  84344. * FLAC__stream_decoder_set_*() but before any of the
  84345. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84346. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84347. * if initialization succeeded.
  84348. *
  84349. * \param decoder An uninitialized decoder instance.
  84350. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  84351. * pointer must not be \c NULL.
  84352. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  84353. * pointer may be \c NULL if seeking is not
  84354. * supported. If \a seek_callback is not \c NULL then a
  84355. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  84356. * Alternatively, a dummy seek callback that just
  84357. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  84358. * may also be supplied, all though this is slightly
  84359. * less efficient for the decoder.
  84360. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  84361. * pointer may be \c NULL if not supported by the client. If
  84362. * \a seek_callback is not \c NULL then a
  84363. * \a tell_callback must also be supplied.
  84364. * Alternatively, a dummy tell callback that just
  84365. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  84366. * may also be supplied, all though this is slightly
  84367. * less efficient for the decoder.
  84368. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  84369. * pointer may be \c NULL if not supported by the client. If
  84370. * \a seek_callback is not \c NULL then a
  84371. * \a length_callback must also be supplied.
  84372. * Alternatively, a dummy length callback that just
  84373. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  84374. * may also be supplied, all though this is slightly
  84375. * less efficient for the decoder.
  84376. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  84377. * pointer may be \c NULL if not supported by the client. If
  84378. * \a seek_callback is not \c NULL then a
  84379. * \a eof_callback must also be supplied.
  84380. * Alternatively, a dummy length callback that just
  84381. * returns \c false
  84382. * may also be supplied, all though this is slightly
  84383. * less efficient for the decoder.
  84384. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84385. * pointer must not be \c NULL.
  84386. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84387. * pointer may be \c NULL if the callback is not
  84388. * desired.
  84389. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84390. * pointer must not be \c NULL.
  84391. * \param client_data This value will be supplied to callbacks in their
  84392. * \a client_data argument.
  84393. * \assert
  84394. * \code decoder != NULL \endcode
  84395. * \retval FLAC__StreamDecoderInitStatus
  84396. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84397. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84398. */
  84399. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  84400. FLAC__StreamDecoder *decoder,
  84401. FLAC__StreamDecoderReadCallback read_callback,
  84402. FLAC__StreamDecoderSeekCallback seek_callback,
  84403. FLAC__StreamDecoderTellCallback tell_callback,
  84404. FLAC__StreamDecoderLengthCallback length_callback,
  84405. FLAC__StreamDecoderEofCallback eof_callback,
  84406. FLAC__StreamDecoderWriteCallback write_callback,
  84407. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84408. FLAC__StreamDecoderErrorCallback error_callback,
  84409. void *client_data
  84410. );
  84411. /** Initialize the decoder instance to decode Ogg FLAC streams.
  84412. *
  84413. * This flavor of initialization sets up the decoder to decode from a
  84414. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  84415. * client. For decoding from a plain file via filename or open FILE*,
  84416. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  84417. * provide a simpler interface.
  84418. *
  84419. * This function should be called after FLAC__stream_decoder_new() and
  84420. * FLAC__stream_decoder_set_*() but before any of the
  84421. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84422. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84423. * if initialization succeeded.
  84424. *
  84425. * \note Support for Ogg FLAC in the library is optional. If this
  84426. * library has been built without support for Ogg FLAC, this function
  84427. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  84428. *
  84429. * \param decoder An uninitialized decoder instance.
  84430. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  84431. * pointer must not be \c NULL.
  84432. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  84433. * pointer may be \c NULL if seeking is not
  84434. * supported. If \a seek_callback is not \c NULL then a
  84435. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  84436. * Alternatively, a dummy seek callback that just
  84437. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  84438. * may also be supplied, all though this is slightly
  84439. * less efficient for the decoder.
  84440. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  84441. * pointer may be \c NULL if not supported by the client. If
  84442. * \a seek_callback is not \c NULL then a
  84443. * \a tell_callback must also be supplied.
  84444. * Alternatively, a dummy tell callback that just
  84445. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  84446. * may also be supplied, all though this is slightly
  84447. * less efficient for the decoder.
  84448. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  84449. * pointer may be \c NULL if not supported by the client. If
  84450. * \a seek_callback is not \c NULL then a
  84451. * \a length_callback must also be supplied.
  84452. * Alternatively, a dummy length callback that just
  84453. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  84454. * may also be supplied, all though this is slightly
  84455. * less efficient for the decoder.
  84456. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  84457. * pointer may be \c NULL if not supported by the client. If
  84458. * \a seek_callback is not \c NULL then a
  84459. * \a eof_callback must also be supplied.
  84460. * Alternatively, a dummy length callback that just
  84461. * returns \c false
  84462. * may also be supplied, all though this is slightly
  84463. * less efficient for the decoder.
  84464. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84465. * pointer must not be \c NULL.
  84466. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84467. * pointer may be \c NULL if the callback is not
  84468. * desired.
  84469. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84470. * pointer must not be \c NULL.
  84471. * \param client_data This value will be supplied to callbacks in their
  84472. * \a client_data argument.
  84473. * \assert
  84474. * \code decoder != NULL \endcode
  84475. * \retval FLAC__StreamDecoderInitStatus
  84476. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84477. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84478. */
  84479. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  84480. FLAC__StreamDecoder *decoder,
  84481. FLAC__StreamDecoderReadCallback read_callback,
  84482. FLAC__StreamDecoderSeekCallback seek_callback,
  84483. FLAC__StreamDecoderTellCallback tell_callback,
  84484. FLAC__StreamDecoderLengthCallback length_callback,
  84485. FLAC__StreamDecoderEofCallback eof_callback,
  84486. FLAC__StreamDecoderWriteCallback write_callback,
  84487. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84488. FLAC__StreamDecoderErrorCallback error_callback,
  84489. void *client_data
  84490. );
  84491. /** Initialize the decoder instance to decode native FLAC files.
  84492. *
  84493. * This flavor of initialization sets up the decoder to decode from a
  84494. * plain native FLAC file. For non-stdio streams, you must use
  84495. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  84496. *
  84497. * This function should be called after FLAC__stream_decoder_new() and
  84498. * FLAC__stream_decoder_set_*() but before any of the
  84499. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84500. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84501. * if initialization succeeded.
  84502. *
  84503. * \param decoder An uninitialized decoder instance.
  84504. * \param file An open FLAC file. The file should have been
  84505. * opened with mode \c "rb" and rewound. The file
  84506. * becomes owned by the decoder and should not be
  84507. * manipulated by the client while decoding.
  84508. * Unless \a file is \c stdin, it will be closed
  84509. * when FLAC__stream_decoder_finish() is called.
  84510. * Note however that seeking will not work when
  84511. * decoding from \c stdout since it is not seekable.
  84512. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84513. * pointer must not be \c NULL.
  84514. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84515. * pointer may be \c NULL if the callback is not
  84516. * desired.
  84517. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84518. * pointer must not be \c NULL.
  84519. * \param client_data This value will be supplied to callbacks in their
  84520. * \a client_data argument.
  84521. * \assert
  84522. * \code decoder != NULL \endcode
  84523. * \code file != NULL \endcode
  84524. * \retval FLAC__StreamDecoderInitStatus
  84525. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84526. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84527. */
  84528. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  84529. FLAC__StreamDecoder *decoder,
  84530. FILE *file,
  84531. FLAC__StreamDecoderWriteCallback write_callback,
  84532. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84533. FLAC__StreamDecoderErrorCallback error_callback,
  84534. void *client_data
  84535. );
  84536. /** Initialize the decoder instance to decode Ogg FLAC files.
  84537. *
  84538. * This flavor of initialization sets up the decoder to decode from a
  84539. * plain Ogg FLAC file. For non-stdio streams, you must use
  84540. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  84541. *
  84542. * This function should be called after FLAC__stream_decoder_new() and
  84543. * FLAC__stream_decoder_set_*() but before any of the
  84544. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84545. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84546. * if initialization succeeded.
  84547. *
  84548. * \note Support for Ogg FLAC in the library is optional. If this
  84549. * library has been built without support for Ogg FLAC, this function
  84550. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  84551. *
  84552. * \param decoder An uninitialized decoder instance.
  84553. * \param file An open FLAC file. The file should have been
  84554. * opened with mode \c "rb" and rewound. The file
  84555. * becomes owned by the decoder and should not be
  84556. * manipulated by the client while decoding.
  84557. * Unless \a file is \c stdin, it will be closed
  84558. * when FLAC__stream_decoder_finish() is called.
  84559. * Note however that seeking will not work when
  84560. * decoding from \c stdout since it is not seekable.
  84561. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84562. * pointer must not be \c NULL.
  84563. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84564. * pointer may be \c NULL if the callback is not
  84565. * desired.
  84566. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84567. * pointer must not be \c NULL.
  84568. * \param client_data This value will be supplied to callbacks in their
  84569. * \a client_data argument.
  84570. * \assert
  84571. * \code decoder != NULL \endcode
  84572. * \code file != NULL \endcode
  84573. * \retval FLAC__StreamDecoderInitStatus
  84574. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84575. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84576. */
  84577. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  84578. FLAC__StreamDecoder *decoder,
  84579. FILE *file,
  84580. FLAC__StreamDecoderWriteCallback write_callback,
  84581. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84582. FLAC__StreamDecoderErrorCallback error_callback,
  84583. void *client_data
  84584. );
  84585. /** Initialize the decoder instance to decode native FLAC files.
  84586. *
  84587. * This flavor of initialization sets up the decoder to decode from a plain
  84588. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  84589. * example, with Unicode filenames on Windows), you must use
  84590. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  84591. * and provide callbacks for the I/O.
  84592. *
  84593. * This function should be called after FLAC__stream_decoder_new() and
  84594. * FLAC__stream_decoder_set_*() but before any of the
  84595. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84596. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84597. * if initialization succeeded.
  84598. *
  84599. * \param decoder An uninitialized decoder instance.
  84600. * \param filename The name of the file to decode from. The file will
  84601. * be opened with fopen(). Use \c NULL to decode from
  84602. * \c stdin. Note that \c stdin is not seekable.
  84603. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84604. * pointer must not be \c NULL.
  84605. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84606. * pointer may be \c NULL if the callback is not
  84607. * desired.
  84608. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84609. * pointer must not be \c NULL.
  84610. * \param client_data This value will be supplied to callbacks in their
  84611. * \a client_data argument.
  84612. * \assert
  84613. * \code decoder != NULL \endcode
  84614. * \retval FLAC__StreamDecoderInitStatus
  84615. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84616. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84617. */
  84618. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  84619. FLAC__StreamDecoder *decoder,
  84620. const char *filename,
  84621. FLAC__StreamDecoderWriteCallback write_callback,
  84622. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84623. FLAC__StreamDecoderErrorCallback error_callback,
  84624. void *client_data
  84625. );
  84626. /** Initialize the decoder instance to decode Ogg FLAC files.
  84627. *
  84628. * This flavor of initialization sets up the decoder to decode from a plain
  84629. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  84630. * example, with Unicode filenames on Windows), you must use
  84631. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  84632. * and provide callbacks for the I/O.
  84633. *
  84634. * This function should be called after FLAC__stream_decoder_new() and
  84635. * FLAC__stream_decoder_set_*() but before any of the
  84636. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84637. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84638. * if initialization succeeded.
  84639. *
  84640. * \note Support for Ogg FLAC in the library is optional. If this
  84641. * library has been built without support for Ogg FLAC, this function
  84642. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  84643. *
  84644. * \param decoder An uninitialized decoder instance.
  84645. * \param filename The name of the file to decode from. The file will
  84646. * be opened with fopen(). Use \c NULL to decode from
  84647. * \c stdin. Note that \c stdin is not seekable.
  84648. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84649. * pointer must not be \c NULL.
  84650. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84651. * pointer may be \c NULL if the callback is not
  84652. * desired.
  84653. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84654. * pointer must not be \c NULL.
  84655. * \param client_data This value will be supplied to callbacks in their
  84656. * \a client_data argument.
  84657. * \assert
  84658. * \code decoder != NULL \endcode
  84659. * \retval FLAC__StreamDecoderInitStatus
  84660. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84661. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84662. */
  84663. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  84664. FLAC__StreamDecoder *decoder,
  84665. const char *filename,
  84666. FLAC__StreamDecoderWriteCallback write_callback,
  84667. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84668. FLAC__StreamDecoderErrorCallback error_callback,
  84669. void *client_data
  84670. );
  84671. /** Finish the decoding process.
  84672. * Flushes the decoding buffer, releases resources, resets the decoder
  84673. * settings to their defaults, and returns the decoder state to
  84674. * FLAC__STREAM_DECODER_UNINITIALIZED.
  84675. *
  84676. * In the event of a prematurely-terminated decode, it is not strictly
  84677. * necessary to call this immediately before FLAC__stream_decoder_delete()
  84678. * but it is good practice to match every FLAC__stream_decoder_init_*()
  84679. * with a FLAC__stream_decoder_finish().
  84680. *
  84681. * \param decoder An uninitialized decoder instance.
  84682. * \assert
  84683. * \code decoder != NULL \endcode
  84684. * \retval FLAC__bool
  84685. * \c false if MD5 checking is on AND a STREAMINFO block was available
  84686. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  84687. * signature does not match the one computed by the decoder; else
  84688. * \c true.
  84689. */
  84690. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  84691. /** Flush the stream input.
  84692. * The decoder's input buffer will be cleared and the state set to
  84693. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  84694. * off MD5 checking.
  84695. *
  84696. * \param decoder A decoder instance.
  84697. * \assert
  84698. * \code decoder != NULL \endcode
  84699. * \retval FLAC__bool
  84700. * \c true if successful, else \c false if a memory allocation
  84701. * error occurs (in which case the state will be set to
  84702. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  84703. */
  84704. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  84705. /** Reset the decoding process.
  84706. * The decoder's input buffer will be cleared and the state set to
  84707. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  84708. * FLAC__stream_decoder_finish() except that the settings are
  84709. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  84710. * before decoding again. MD5 checking will be restored to its original
  84711. * setting.
  84712. *
  84713. * If the decoder is seekable, or was initialized with
  84714. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  84715. * the decoder will also attempt to seek to the beginning of the file.
  84716. * If this rewind fails, this function will return \c false. It follows
  84717. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  84718. * \c stdin.
  84719. *
  84720. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  84721. * and is not seekable (i.e. no seek callback was provided or the seek
  84722. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  84723. * is the duty of the client to start feeding data from the beginning of
  84724. * the stream on the next FLAC__stream_decoder_process() or
  84725. * FLAC__stream_decoder_process_interleaved() call.
  84726. *
  84727. * \param decoder A decoder instance.
  84728. * \assert
  84729. * \code decoder != NULL \endcode
  84730. * \retval FLAC__bool
  84731. * \c true if successful, else \c false if a memory allocation occurs
  84732. * (in which case the state will be set to
  84733. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  84734. * occurs (the state will be unchanged).
  84735. */
  84736. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  84737. /** Decode one metadata block or audio frame.
  84738. * This version instructs the decoder to decode a either a single metadata
  84739. * block or a single frame and stop, unless the callbacks return a fatal
  84740. * error or the read callback returns
  84741. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  84742. *
  84743. * As the decoder needs more input it will call the read callback.
  84744. * Depending on what was decoded, the metadata or write callback will be
  84745. * called with the decoded metadata block or audio frame.
  84746. *
  84747. * Unless there is a fatal read error or end of stream, this function
  84748. * will return once one whole frame is decoded. In other words, if the
  84749. * stream is not synchronized or points to a corrupt frame header, the
  84750. * decoder will continue to try and resync until it gets to a valid
  84751. * frame, then decode one frame, then return. If the decoder points to
  84752. * a frame whose frame CRC in the frame footer does not match the
  84753. * computed frame CRC, this function will issue a
  84754. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  84755. * error callback, and return, having decoded one complete, although
  84756. * corrupt, frame. (Such corrupted frames are sent as silence of the
  84757. * correct length to the write callback.)
  84758. *
  84759. * \param decoder An initialized decoder instance.
  84760. * \assert
  84761. * \code decoder != NULL \endcode
  84762. * \retval FLAC__bool
  84763. * \c false if any fatal read, write, or memory allocation error
  84764. * occurred (meaning decoding must stop), else \c true; for more
  84765. * information about the decoder, check the decoder state with
  84766. * FLAC__stream_decoder_get_state().
  84767. */
  84768. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  84769. /** Decode until the end of the metadata.
  84770. * This version instructs the decoder to decode from the current position
  84771. * and continue until all the metadata has been read, or until the
  84772. * callbacks return a fatal error or the read callback returns
  84773. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  84774. *
  84775. * As the decoder needs more input it will call the read callback.
  84776. * As each metadata block is decoded, the metadata callback will be called
  84777. * with the decoded metadata.
  84778. *
  84779. * \param decoder An initialized decoder instance.
  84780. * \assert
  84781. * \code decoder != NULL \endcode
  84782. * \retval FLAC__bool
  84783. * \c false if any fatal read, write, or memory allocation error
  84784. * occurred (meaning decoding must stop), else \c true; for more
  84785. * information about the decoder, check the decoder state with
  84786. * FLAC__stream_decoder_get_state().
  84787. */
  84788. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  84789. /** Decode until the end of the stream.
  84790. * This version instructs the decoder to decode from the current position
  84791. * and continue until the end of stream (the read callback returns
  84792. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  84793. * callbacks return a fatal error.
  84794. *
  84795. * As the decoder needs more input it will call the read callback.
  84796. * As each metadata block and frame is decoded, the metadata or write
  84797. * callback will be called with the decoded metadata or frame.
  84798. *
  84799. * \param decoder An initialized decoder instance.
  84800. * \assert
  84801. * \code decoder != NULL \endcode
  84802. * \retval FLAC__bool
  84803. * \c false if any fatal read, write, or memory allocation error
  84804. * occurred (meaning decoding must stop), else \c true; for more
  84805. * information about the decoder, check the decoder state with
  84806. * FLAC__stream_decoder_get_state().
  84807. */
  84808. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  84809. /** Skip one audio frame.
  84810. * This version instructs the decoder to 'skip' a single frame and stop,
  84811. * unless the callbacks return a fatal error or the read callback returns
  84812. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  84813. *
  84814. * The decoding flow is the same as what occurs when
  84815. * FLAC__stream_decoder_process_single() is called to process an audio
  84816. * frame, except that this function does not decode the parsed data into
  84817. * PCM or call the write callback. The integrity of the frame is still
  84818. * checked the same way as in the other process functions.
  84819. *
  84820. * This function will return once one whole frame is skipped, in the
  84821. * same way that FLAC__stream_decoder_process_single() will return once
  84822. * one whole frame is decoded.
  84823. *
  84824. * This function can be used in more quickly determining FLAC frame
  84825. * boundaries when decoding of the actual data is not needed, for
  84826. * example when an application is separating a FLAC stream into frames
  84827. * for editing or storing in a container. To do this, the application
  84828. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  84829. * to the next frame, then use
  84830. * FLAC__stream_decoder_get_decode_position() to find the new frame
  84831. * boundary.
  84832. *
  84833. * This function should only be called when the stream has advanced
  84834. * past all the metadata, otherwise it will return \c false.
  84835. *
  84836. * \param decoder An initialized decoder instance not in a metadata
  84837. * state.
  84838. * \assert
  84839. * \code decoder != NULL \endcode
  84840. * \retval FLAC__bool
  84841. * \c false if any fatal read, write, or memory allocation error
  84842. * occurred (meaning decoding must stop), or if the decoder
  84843. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  84844. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  84845. * information about the decoder, check the decoder state with
  84846. * FLAC__stream_decoder_get_state().
  84847. */
  84848. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  84849. /** Flush the input and seek to an absolute sample.
  84850. * Decoding will resume at the given sample. Note that because of
  84851. * this, the next write callback may contain a partial block. The
  84852. * client must support seeking the input or this function will fail
  84853. * and return \c false. Furthermore, if the decoder state is
  84854. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  84855. * with FLAC__stream_decoder_flush() or reset with
  84856. * FLAC__stream_decoder_reset() before decoding can continue.
  84857. *
  84858. * \param decoder A decoder instance.
  84859. * \param sample The target sample number to seek to.
  84860. * \assert
  84861. * \code decoder != NULL \endcode
  84862. * \retval FLAC__bool
  84863. * \c true if successful, else \c false.
  84864. */
  84865. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  84866. /* \} */
  84867. #ifdef __cplusplus
  84868. }
  84869. #endif
  84870. #endif
  84871. /********* End of inlined file: stream_decoder.h *********/
  84872. /********* Start of inlined file: stream_encoder.h *********/
  84873. #ifndef FLAC__STREAM_ENCODER_H
  84874. #define FLAC__STREAM_ENCODER_H
  84875. #include <stdio.h> /* for FILE */
  84876. #ifdef __cplusplus
  84877. extern "C" {
  84878. #endif
  84879. /** \file include/FLAC/stream_encoder.h
  84880. *
  84881. * \brief
  84882. * This module contains the functions which implement the stream
  84883. * encoder.
  84884. *
  84885. * See the detailed documentation in the
  84886. * \link flac_stream_encoder stream encoder \endlink module.
  84887. */
  84888. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  84889. * \ingroup flac
  84890. *
  84891. * \brief
  84892. * This module describes the encoder layers provided by libFLAC.
  84893. *
  84894. * The stream encoder can be used to encode complete streams either to the
  84895. * client via callbacks, or directly to a file, depending on how it is
  84896. * initialized. When encoding via callbacks, the client provides a write
  84897. * callback which will be called whenever FLAC data is ready to be written.
  84898. * If the client also supplies a seek callback, the encoder will also
  84899. * automatically handle the writing back of metadata discovered while
  84900. * encoding, like stream info, seek points offsets, etc. When encoding to
  84901. * a file, the client needs only supply a filename or open \c FILE* and an
  84902. * optional progress callback for periodic notification of progress; the
  84903. * write and seek callbacks are supplied internally. For more info see the
  84904. * \link flac_stream_encoder stream encoder \endlink module.
  84905. */
  84906. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  84907. * \ingroup flac_encoder
  84908. *
  84909. * \brief
  84910. * This module contains the functions which implement the stream
  84911. * encoder.
  84912. *
  84913. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  84914. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  84915. *
  84916. * The basic usage of this encoder is as follows:
  84917. * - The program creates an instance of an encoder using
  84918. * FLAC__stream_encoder_new().
  84919. * - The program overrides the default settings using
  84920. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  84921. * functions should be called:
  84922. * - FLAC__stream_encoder_set_channels()
  84923. * - FLAC__stream_encoder_set_bits_per_sample()
  84924. * - FLAC__stream_encoder_set_sample_rate()
  84925. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  84926. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  84927. * - If the application wants to control the compression level or set its own
  84928. * metadata, then the following should also be called:
  84929. * - FLAC__stream_encoder_set_compression_level()
  84930. * - FLAC__stream_encoder_set_verify()
  84931. * - FLAC__stream_encoder_set_metadata()
  84932. * - The rest of the set functions should only be called if the client needs
  84933. * exact control over how the audio is compressed; thorough understanding
  84934. * of the FLAC format is necessary to achieve good results.
  84935. * - The program initializes the instance to validate the settings and
  84936. * prepare for encoding using
  84937. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  84938. * or FLAC__stream_encoder_init_file() for native FLAC
  84939. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  84940. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  84941. * - The program calls FLAC__stream_encoder_process() or
  84942. * FLAC__stream_encoder_process_interleaved() to encode data, which
  84943. * subsequently calls the callbacks when there is encoder data ready
  84944. * to be written.
  84945. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  84946. * which causes the encoder to encode any data still in its input pipe,
  84947. * update the metadata with the final encoding statistics if output
  84948. * seeking is possible, and finally reset the encoder to the
  84949. * uninitialized state.
  84950. * - The instance may be used again or deleted with
  84951. * FLAC__stream_encoder_delete().
  84952. *
  84953. * In more detail, the stream encoder functions similarly to the
  84954. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  84955. * callbacks and more options. Typically the client will create a new
  84956. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  84957. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  84958. * calling one of the FLAC__stream_encoder_init_*() functions.
  84959. *
  84960. * Unlike the decoders, the stream encoder has many options that can
  84961. * affect the speed and compression ratio. When setting these parameters
  84962. * you should have some basic knowledge of the format (see the
  84963. * <A HREF="../documentation.html#format">user-level documentation</A>
  84964. * or the <A HREF="../format.html">formal description</A>). The
  84965. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  84966. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  84967. * functions will do this, so make sure to pay attention to the state
  84968. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  84969. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  84970. * before FLAC__stream_encoder_init_*() will take on the defaults from
  84971. * the constructor.
  84972. *
  84973. * There are three initialization functions for native FLAC, one for
  84974. * setting up the encoder to encode FLAC data to the client via
  84975. * callbacks, and two for encoding directly to a file.
  84976. *
  84977. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  84978. * You must also supply a write callback which will be called anytime
  84979. * there is raw encoded data to write. If the client can seek the output
  84980. * it is best to also supply seek and tell callbacks, as this allows the
  84981. * encoder to go back after encoding is finished to write back
  84982. * information that was collected while encoding, like seek point offsets,
  84983. * frame sizes, etc.
  84984. *
  84985. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  84986. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  84987. * filename or open \c FILE*; the encoder will handle all the callbacks
  84988. * internally. You may also supply a progress callback for periodic
  84989. * notification of the encoding progress.
  84990. *
  84991. * There are three similarly-named init functions for encoding to Ogg
  84992. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  84993. * library has been built with Ogg support.
  84994. *
  84995. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  84996. * call the write callback several times, once with the \c fLaC signature,
  84997. * and once for each encoded metadata block. Note that for Ogg FLAC
  84998. * encoding you will usually get at least twice the number of callbacks than
  84999. * with native FLAC, one for the Ogg page header and one for the page body.
  85000. *
  85001. * After initializing the instance, the client may feed audio data to the
  85002. * encoder in one of two ways:
  85003. *
  85004. * - Channel separate, through FLAC__stream_encoder_process() - The client
  85005. * will pass an array of pointers to buffers, one for each channel, to
  85006. * the encoder, each of the same length. The samples need not be
  85007. * block-aligned, but each channel should have the same number of samples.
  85008. * - Channel interleaved, through
  85009. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  85010. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  85011. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  85012. * Again, the samples need not be block-aligned but they must be
  85013. * sample-aligned, i.e. the first value should be channel0_sample0 and
  85014. * the last value channelN_sampleM.
  85015. *
  85016. * Note that for either process call, each sample in the buffers should be a
  85017. * signed integer, right-justified to the resolution set by
  85018. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  85019. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  85020. *
  85021. * When the client is finished encoding data, it calls
  85022. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  85023. * data still in its input pipe, and call the metadata callback with the
  85024. * final encoding statistics. Then the instance may be deleted with
  85025. * FLAC__stream_encoder_delete() or initialized again to encode another
  85026. * stream.
  85027. *
  85028. * For programs that write their own metadata, but that do not know the
  85029. * actual metadata until after encoding, it is advantageous to instruct
  85030. * the encoder to write a PADDING block of the correct size, so that
  85031. * instead of rewriting the whole stream after encoding, the program can
  85032. * just overwrite the PADDING block. If only the maximum size of the
  85033. * metadata is known, the program can write a slightly larger padding
  85034. * block, then split it after encoding.
  85035. *
  85036. * Make sure you understand how lengths are calculated. All FLAC metadata
  85037. * blocks have a 4 byte header which contains the type and length. This
  85038. * length does not include the 4 bytes of the header. See the format page
  85039. * for the specification of metadata blocks and their lengths.
  85040. *
  85041. * \note
  85042. * If you are writing the FLAC data to a file via callbacks, make sure it
  85043. * is open for update (e.g. mode "w+" for stdio streams). This is because
  85044. * after the first encoding pass, the encoder will try to seek back to the
  85045. * beginning of the stream, to the STREAMINFO block, to write some data
  85046. * there. (If using FLAC__stream_encoder_init*_file() or
  85047. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  85048. *
  85049. * \note
  85050. * The "set" functions may only be called when the encoder is in the
  85051. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  85052. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  85053. * before FLAC__stream_encoder_init_*(). If this is the case they will
  85054. * return \c true, otherwise \c false.
  85055. *
  85056. * \note
  85057. * FLAC__stream_encoder_finish() resets all settings to the constructor
  85058. * defaults.
  85059. *
  85060. * \{
  85061. */
  85062. /** State values for a FLAC__StreamEncoder.
  85063. *
  85064. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  85065. *
  85066. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  85067. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  85068. * must be deleted with FLAC__stream_encoder_delete().
  85069. */
  85070. typedef enum {
  85071. FLAC__STREAM_ENCODER_OK = 0,
  85072. /**< The encoder is in the normal OK state and samples can be processed. */
  85073. FLAC__STREAM_ENCODER_UNINITIALIZED,
  85074. /**< The encoder is in the uninitialized state; one of the
  85075. * FLAC__stream_encoder_init_*() functions must be called before samples
  85076. * can be processed.
  85077. */
  85078. FLAC__STREAM_ENCODER_OGG_ERROR,
  85079. /**< An error occurred in the underlying Ogg layer. */
  85080. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  85081. /**< An error occurred in the underlying verify stream decoder;
  85082. * check FLAC__stream_encoder_get_verify_decoder_state().
  85083. */
  85084. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  85085. /**< The verify decoder detected a mismatch between the original
  85086. * audio signal and the decoded audio signal.
  85087. */
  85088. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  85089. /**< One of the callbacks returned a fatal error. */
  85090. FLAC__STREAM_ENCODER_IO_ERROR,
  85091. /**< An I/O error occurred while opening/reading/writing a file.
  85092. * Check \c errno.
  85093. */
  85094. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  85095. /**< An error occurred while writing the stream; usually, the
  85096. * write_callback returned an error.
  85097. */
  85098. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  85099. /**< Memory allocation failed. */
  85100. } FLAC__StreamEncoderState;
  85101. /** Maps a FLAC__StreamEncoderState to a C string.
  85102. *
  85103. * Using a FLAC__StreamEncoderState 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__StreamEncoderStateString[];
  85107. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  85108. */
  85109. typedef enum {
  85110. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  85111. /**< Initialization was successful. */
  85112. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  85113. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  85114. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  85115. /**< The library was not compiled with support for the given container
  85116. * format.
  85117. */
  85118. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  85119. /**< A required callback was not supplied. */
  85120. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  85121. /**< The encoder has an invalid setting for number of channels. */
  85122. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  85123. /**< The encoder has an invalid setting for bits-per-sample.
  85124. * FLAC supports 4-32 bps but the reference encoder currently supports
  85125. * only up to 24 bps.
  85126. */
  85127. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  85128. /**< The encoder has an invalid setting for the input sample rate. */
  85129. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  85130. /**< The encoder has an invalid setting for the block size. */
  85131. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  85132. /**< The encoder has an invalid setting for the maximum LPC order. */
  85133. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  85134. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  85135. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  85136. /**< The specified block size is less than the maximum LPC order. */
  85137. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  85138. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  85139. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  85140. /**< The metadata input to the encoder is invalid, in one of the following ways:
  85141. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  85142. * - One of the metadata blocks contains an undefined type
  85143. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  85144. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  85145. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  85146. */
  85147. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  85148. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  85149. * already initialized, usually because
  85150. * FLAC__stream_encoder_finish() was not called.
  85151. */
  85152. } FLAC__StreamEncoderInitStatus;
  85153. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  85154. *
  85155. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  85156. * will give the string equivalent. The contents should not be modified.
  85157. */
  85158. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  85159. /** Return values for the FLAC__StreamEncoder read callback.
  85160. */
  85161. typedef enum {
  85162. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  85163. /**< The read was OK and decoding can continue. */
  85164. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  85165. /**< The read was attempted at the end of the stream. */
  85166. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  85167. /**< An unrecoverable error occurred. */
  85168. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  85169. /**< Client does not support reading back from the output. */
  85170. } FLAC__StreamEncoderReadStatus;
  85171. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  85172. *
  85173. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  85174. * will give the string equivalent. The contents should not be modified.
  85175. */
  85176. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  85177. /** Return values for the FLAC__StreamEncoder write callback.
  85178. */
  85179. typedef enum {
  85180. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  85181. /**< The write was OK and encoding can continue. */
  85182. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  85183. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  85184. } FLAC__StreamEncoderWriteStatus;
  85185. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  85186. *
  85187. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  85188. * will give the string equivalent. The contents should not be modified.
  85189. */
  85190. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  85191. /** Return values for the FLAC__StreamEncoder seek callback.
  85192. */
  85193. typedef enum {
  85194. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  85195. /**< The seek was OK and encoding can continue. */
  85196. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  85197. /**< An unrecoverable error occurred. */
  85198. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  85199. /**< Client does not support seeking. */
  85200. } FLAC__StreamEncoderSeekStatus;
  85201. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  85202. *
  85203. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  85204. * will give the string equivalent. The contents should not be modified.
  85205. */
  85206. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  85207. /** Return values for the FLAC__StreamEncoder tell callback.
  85208. */
  85209. typedef enum {
  85210. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  85211. /**< The tell was OK and encoding can continue. */
  85212. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  85213. /**< An unrecoverable error occurred. */
  85214. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  85215. /**< Client does not support seeking. */
  85216. } FLAC__StreamEncoderTellStatus;
  85217. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  85218. *
  85219. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  85220. * will give the string equivalent. The contents should not be modified.
  85221. */
  85222. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  85223. /***********************************************************************
  85224. *
  85225. * class FLAC__StreamEncoder
  85226. *
  85227. ***********************************************************************/
  85228. struct FLAC__StreamEncoderProtected;
  85229. struct FLAC__StreamEncoderPrivate;
  85230. /** The opaque structure definition for the stream encoder type.
  85231. * See the \link flac_stream_encoder stream encoder module \endlink
  85232. * for a detailed description.
  85233. */
  85234. typedef struct {
  85235. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  85236. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  85237. } FLAC__StreamEncoder;
  85238. /** Signature for the read callback.
  85239. *
  85240. * A function pointer matching this signature must be passed to
  85241. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  85242. * The supplied function will be called when the encoder needs to read back
  85243. * encoded data. This happens during the metadata callback, when the encoder
  85244. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  85245. * while encoding. The address of the buffer to be filled is supplied, along
  85246. * with the number of bytes the buffer can hold. The callback may choose to
  85247. * supply less data and modify the byte count but must be careful not to
  85248. * overflow the buffer. The callback then returns a status code chosen from
  85249. * FLAC__StreamEncoderReadStatus.
  85250. *
  85251. * Here is an example of a read callback for stdio streams:
  85252. * \code
  85253. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  85254. * {
  85255. * FILE *file = ((MyClientData*)client_data)->file;
  85256. * if(*bytes > 0) {
  85257. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  85258. * if(ferror(file))
  85259. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  85260. * else if(*bytes == 0)
  85261. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  85262. * else
  85263. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  85264. * }
  85265. * else
  85266. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  85267. * }
  85268. * \endcode
  85269. *
  85270. * \note In general, FLAC__StreamEncoder functions which change the
  85271. * state should not be called on the \a encoder while in the callback.
  85272. *
  85273. * \param encoder The encoder instance calling the callback.
  85274. * \param buffer A pointer to a location for the callee to store
  85275. * data to be encoded.
  85276. * \param bytes A pointer to the size of the buffer. On entry
  85277. * to the callback, it contains the maximum number
  85278. * of bytes that may be stored in \a buffer. The
  85279. * callee must set it to the actual number of bytes
  85280. * stored (0 in case of error or end-of-stream) before
  85281. * returning.
  85282. * \param client_data The callee's client data set through
  85283. * FLAC__stream_encoder_set_client_data().
  85284. * \retval FLAC__StreamEncoderReadStatus
  85285. * The callee's return status.
  85286. */
  85287. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  85288. /** Signature for the write callback.
  85289. *
  85290. * A function pointer matching this signature must be passed to
  85291. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  85292. * by the encoder anytime there is raw encoded data ready to write. It may
  85293. * include metadata mixed with encoded audio frames and the data is not
  85294. * guaranteed to be aligned on frame or metadata block boundaries.
  85295. *
  85296. * The only duty of the callback is to write out the \a bytes worth of data
  85297. * in \a buffer to the current position in the output stream. The arguments
  85298. * \a samples and \a current_frame are purely informational. If \a samples
  85299. * is greater than \c 0, then \a current_frame will hold the current frame
  85300. * number that is being written; otherwise it indicates that the write
  85301. * callback is being called to write metadata.
  85302. *
  85303. * \note
  85304. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  85305. * write callback will be called twice when writing each audio
  85306. * frame; once for the page header, and once for the page body.
  85307. * When writing the page header, the \a samples argument to the
  85308. * write callback will be \c 0.
  85309. *
  85310. * \note In general, FLAC__StreamEncoder functions which change the
  85311. * state should not be called on the \a encoder while in the callback.
  85312. *
  85313. * \param encoder The encoder instance calling the callback.
  85314. * \param buffer An array of encoded data of length \a bytes.
  85315. * \param bytes The byte length of \a buffer.
  85316. * \param samples The number of samples encoded by \a buffer.
  85317. * \c 0 has a special meaning; see above.
  85318. * \param current_frame The number of the current frame being encoded.
  85319. * \param client_data The callee's client data set through
  85320. * FLAC__stream_encoder_init_*().
  85321. * \retval FLAC__StreamEncoderWriteStatus
  85322. * The callee's return status.
  85323. */
  85324. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  85325. /** Signature for the seek callback.
  85326. *
  85327. * A function pointer matching this signature may be passed to
  85328. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  85329. * when the encoder needs to seek the output stream. The encoder will pass
  85330. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  85331. *
  85332. * Here is an example of a seek callback for stdio streams:
  85333. * \code
  85334. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  85335. * {
  85336. * FILE *file = ((MyClientData*)client_data)->file;
  85337. * if(file == stdin)
  85338. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  85339. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  85340. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  85341. * else
  85342. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  85343. * }
  85344. * \endcode
  85345. *
  85346. * \note In general, FLAC__StreamEncoder functions which change the
  85347. * state should not be called on the \a encoder while in the callback.
  85348. *
  85349. * \param encoder The encoder instance calling the callback.
  85350. * \param absolute_byte_offset The offset from the beginning of the stream
  85351. * to seek to.
  85352. * \param client_data The callee's client data set through
  85353. * FLAC__stream_encoder_init_*().
  85354. * \retval FLAC__StreamEncoderSeekStatus
  85355. * The callee's return status.
  85356. */
  85357. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  85358. /** Signature for the tell callback.
  85359. *
  85360. * A function pointer matching this signature may be passed to
  85361. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  85362. * when the encoder needs to know the current position of the output stream.
  85363. *
  85364. * \warning
  85365. * The callback must return the true current byte offset of the output to
  85366. * which the encoder is writing. If you are buffering the output, make
  85367. * sure and take this into account. If you are writing directly to a
  85368. * FILE* from your write callback, ftell() is sufficient. If you are
  85369. * writing directly to a file descriptor from your write callback, you
  85370. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  85371. * these points to rewrite metadata after encoding.
  85372. *
  85373. * Here is an example of a tell callback for stdio streams:
  85374. * \code
  85375. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  85376. * {
  85377. * FILE *file = ((MyClientData*)client_data)->file;
  85378. * off_t pos;
  85379. * if(file == stdin)
  85380. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  85381. * else if((pos = ftello(file)) < 0)
  85382. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  85383. * else {
  85384. * *absolute_byte_offset = (FLAC__uint64)pos;
  85385. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  85386. * }
  85387. * }
  85388. * \endcode
  85389. *
  85390. * \note In general, FLAC__StreamEncoder functions which change the
  85391. * state should not be called on the \a encoder while in the callback.
  85392. *
  85393. * \param encoder The encoder instance calling the callback.
  85394. * \param absolute_byte_offset The address at which to store the current
  85395. * position of the output.
  85396. * \param client_data The callee's client data set through
  85397. * FLAC__stream_encoder_init_*().
  85398. * \retval FLAC__StreamEncoderTellStatus
  85399. * The callee's return status.
  85400. */
  85401. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  85402. /** Signature for the metadata callback.
  85403. *
  85404. * A function pointer matching this signature may be passed to
  85405. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  85406. * once at the end of encoding with the populated STREAMINFO structure. This
  85407. * is so the client can seek back to the beginning of the file and write the
  85408. * STREAMINFO block with the correct statistics after encoding (like
  85409. * minimum/maximum frame size and total samples).
  85410. *
  85411. * \note In general, FLAC__StreamEncoder functions which change the
  85412. * state should not be called on the \a encoder while in the callback.
  85413. *
  85414. * \param encoder The encoder instance calling the callback.
  85415. * \param metadata The final populated STREAMINFO block.
  85416. * \param client_data The callee's client data set through
  85417. * FLAC__stream_encoder_init_*().
  85418. */
  85419. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  85420. /** Signature for the progress callback.
  85421. *
  85422. * A function pointer matching this signature may be passed to
  85423. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  85424. * The supplied function will be called when the encoder has finished
  85425. * writing a frame. The \c total_frames_estimate argument to the
  85426. * callback will be based on the value from
  85427. * FLAC__stream_encoder_set_total_samples_estimate().
  85428. *
  85429. * \note In general, FLAC__StreamEncoder functions which change the
  85430. * state should not be called on the \a encoder while in the callback.
  85431. *
  85432. * \param encoder The encoder instance calling the callback.
  85433. * \param bytes_written Bytes written so far.
  85434. * \param samples_written Samples written so far.
  85435. * \param frames_written Frames written so far.
  85436. * \param total_frames_estimate The estimate of the total number of
  85437. * frames to be written.
  85438. * \param client_data The callee's client data set through
  85439. * FLAC__stream_encoder_init_*().
  85440. */
  85441. 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);
  85442. /***********************************************************************
  85443. *
  85444. * Class constructor/destructor
  85445. *
  85446. ***********************************************************************/
  85447. /** Create a new stream encoder instance. The instance is created with
  85448. * default settings; see the individual FLAC__stream_encoder_set_*()
  85449. * functions for each setting's default.
  85450. *
  85451. * \retval FLAC__StreamEncoder*
  85452. * \c NULL if there was an error allocating memory, else the new instance.
  85453. */
  85454. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  85455. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  85456. *
  85457. * \param encoder A pointer to an existing encoder.
  85458. * \assert
  85459. * \code encoder != NULL \endcode
  85460. */
  85461. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  85462. /***********************************************************************
  85463. *
  85464. * Public class method prototypes
  85465. *
  85466. ***********************************************************************/
  85467. /** Set the serial number for the FLAC stream to use in the Ogg container.
  85468. *
  85469. * \note
  85470. * This does not need to be set for native FLAC encoding.
  85471. *
  85472. * \note
  85473. * It is recommended to set a serial number explicitly as the default of '0'
  85474. * may collide with other streams.
  85475. *
  85476. * \default \c 0
  85477. * \param encoder An encoder instance to set.
  85478. * \param serial_number See above.
  85479. * \assert
  85480. * \code encoder != NULL \endcode
  85481. * \retval FLAC__bool
  85482. * \c false if the encoder is already initialized, else \c true.
  85483. */
  85484. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  85485. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  85486. * encoded output by feeding it through an internal decoder and comparing
  85487. * the original signal against the decoded signal. If a mismatch occurs,
  85488. * the process call will return \c false. Note that this will slow the
  85489. * encoding process by the extra time required for decoding and comparison.
  85490. *
  85491. * \default \c false
  85492. * \param encoder An encoder instance to set.
  85493. * \param value Flag value (see above).
  85494. * \assert
  85495. * \code encoder != NULL \endcode
  85496. * \retval FLAC__bool
  85497. * \c false if the encoder is already initialized, else \c true.
  85498. */
  85499. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85500. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  85501. * the encoder will comply with the Subset and will check the
  85502. * settings during FLAC__stream_encoder_init_*() to see if all settings
  85503. * comply. If \c false, the settings may take advantage of the full
  85504. * range that the format allows.
  85505. *
  85506. * Make sure you know what it entails before setting this to \c false.
  85507. *
  85508. * \default \c true
  85509. * \param encoder An encoder instance to set.
  85510. * \param value Flag value (see above).
  85511. * \assert
  85512. * \code encoder != NULL \endcode
  85513. * \retval FLAC__bool
  85514. * \c false if the encoder is already initialized, else \c true.
  85515. */
  85516. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85517. /** Set the number of channels to be encoded.
  85518. *
  85519. * \default \c 2
  85520. * \param encoder An encoder instance to set.
  85521. * \param value See above.
  85522. * \assert
  85523. * \code encoder != NULL \endcode
  85524. * \retval FLAC__bool
  85525. * \c false if the encoder is already initialized, else \c true.
  85526. */
  85527. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  85528. /** Set the sample resolution of the input to be encoded.
  85529. *
  85530. * \warning
  85531. * Do not feed the encoder data that is wider than the value you
  85532. * set here or you will generate an invalid stream.
  85533. *
  85534. * \default \c 16
  85535. * \param encoder An encoder instance to set.
  85536. * \param value See above.
  85537. * \assert
  85538. * \code encoder != NULL \endcode
  85539. * \retval FLAC__bool
  85540. * \c false if the encoder is already initialized, else \c true.
  85541. */
  85542. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  85543. /** Set the sample rate (in Hz) of the input to be encoded.
  85544. *
  85545. * \default \c 44100
  85546. * \param encoder An encoder instance to set.
  85547. * \param value See above.
  85548. * \assert
  85549. * \code encoder != NULL \endcode
  85550. * \retval FLAC__bool
  85551. * \c false if the encoder is already initialized, else \c true.
  85552. */
  85553. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  85554. /** Set the compression level
  85555. *
  85556. * The compression level is roughly proportional to the amount of effort
  85557. * the encoder expends to compress the file. A higher level usually
  85558. * means more computation but higher compression. The default level is
  85559. * suitable for most applications.
  85560. *
  85561. * Currently the levels range from \c 0 (fastest, least compression) to
  85562. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  85563. * treated as \c 8.
  85564. *
  85565. * This function automatically calls the following other \c _set_
  85566. * functions with appropriate values, so the client does not need to
  85567. * unless it specifically wants to override them:
  85568. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  85569. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  85570. * - FLAC__stream_encoder_set_apodization()
  85571. * - FLAC__stream_encoder_set_max_lpc_order()
  85572. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  85573. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  85574. * - FLAC__stream_encoder_set_do_escape_coding()
  85575. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  85576. * - FLAC__stream_encoder_set_min_residual_partition_order()
  85577. * - FLAC__stream_encoder_set_max_residual_partition_order()
  85578. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  85579. *
  85580. * The actual values set for each level are:
  85581. * <table>
  85582. * <tr>
  85583. * <td><b>level</b><td>
  85584. * <td>do mid-side stereo<td>
  85585. * <td>loose mid-side stereo<td>
  85586. * <td>apodization<td>
  85587. * <td>max lpc order<td>
  85588. * <td>qlp coeff precision<td>
  85589. * <td>qlp coeff prec search<td>
  85590. * <td>escape coding<td>
  85591. * <td>exhaustive model search<td>
  85592. * <td>min residual partition order<td>
  85593. * <td>max residual partition order<td>
  85594. * <td>rice parameter search dist<td>
  85595. * </tr>
  85596. * <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>
  85597. * <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>
  85598. * <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>
  85599. * <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>
  85600. * <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>
  85601. * <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>
  85602. * <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>
  85603. * <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>
  85604. * <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>
  85605. * </table>
  85606. *
  85607. * \default \c 5
  85608. * \param encoder An encoder instance to set.
  85609. * \param value See above.
  85610. * \assert
  85611. * \code encoder != NULL \endcode
  85612. * \retval FLAC__bool
  85613. * \c false if the encoder is already initialized, else \c true.
  85614. */
  85615. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  85616. /** Set the blocksize to use while encoding.
  85617. *
  85618. * The number of samples to use per frame. Use \c 0 to let the encoder
  85619. * estimate a blocksize; this is usually best.
  85620. *
  85621. * \default \c 0
  85622. * \param encoder An encoder instance to set.
  85623. * \param value See above.
  85624. * \assert
  85625. * \code encoder != NULL \endcode
  85626. * \retval FLAC__bool
  85627. * \c false if the encoder is already initialized, else \c true.
  85628. */
  85629. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  85630. /** Set to \c true to enable mid-side encoding on stereo input. The
  85631. * number of channels must be 2 for this to have any effect. Set to
  85632. * \c false to use only independent channel coding.
  85633. *
  85634. * \default \c false
  85635. * \param encoder An encoder instance to set.
  85636. * \param value Flag value (see above).
  85637. * \assert
  85638. * \code encoder != NULL \endcode
  85639. * \retval FLAC__bool
  85640. * \c false if the encoder is already initialized, else \c true.
  85641. */
  85642. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85643. /** Set to \c true to enable adaptive switching between mid-side and
  85644. * left-right encoding on stereo input. Set to \c false to use
  85645. * exhaustive searching. Setting this to \c true requires
  85646. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  85647. * \c true in order to have any effect.
  85648. *
  85649. * \default \c false
  85650. * \param encoder An encoder instance to set.
  85651. * \param value Flag value (see above).
  85652. * \assert
  85653. * \code encoder != NULL \endcode
  85654. * \retval FLAC__bool
  85655. * \c false if the encoder is already initialized, else \c true.
  85656. */
  85657. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85658. /** Sets the apodization function(s) the encoder will use when windowing
  85659. * audio data for LPC analysis.
  85660. *
  85661. * The \a specification is a plain ASCII string which specifies exactly
  85662. * which functions to use. There may be more than one (up to 32),
  85663. * separated by \c ';' characters. Some functions take one or more
  85664. * comma-separated arguments in parentheses.
  85665. *
  85666. * The available functions are \c bartlett, \c bartlett_hann,
  85667. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  85668. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  85669. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  85670. *
  85671. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  85672. * (0<STDDEV<=0.5).
  85673. *
  85674. * For \c tukey(P), P specifies the fraction of the window that is
  85675. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  85676. * corresponds to \c hann.
  85677. *
  85678. * Example specifications are \c "blackman" or
  85679. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  85680. *
  85681. * Any function that is specified erroneously is silently dropped. Up
  85682. * to 32 functions are kept, the rest are dropped. If the specification
  85683. * is empty the encoder defaults to \c "tukey(0.5)".
  85684. *
  85685. * When more than one function is specified, then for every subframe the
  85686. * encoder will try each of them separately and choose the window that
  85687. * results in the smallest compressed subframe.
  85688. *
  85689. * Note that each function specified causes the encoder to occupy a
  85690. * floating point array in which to store the window.
  85691. *
  85692. * \default \c "tukey(0.5)"
  85693. * \param encoder An encoder instance to set.
  85694. * \param specification See above.
  85695. * \assert
  85696. * \code encoder != NULL \endcode
  85697. * \code specification != NULL \endcode
  85698. * \retval FLAC__bool
  85699. * \c false if the encoder is already initialized, else \c true.
  85700. */
  85701. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  85702. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  85703. *
  85704. * \default \c 0
  85705. * \param encoder An encoder instance to set.
  85706. * \param value See above.
  85707. * \assert
  85708. * \code encoder != NULL \endcode
  85709. * \retval FLAC__bool
  85710. * \c false if the encoder is already initialized, else \c true.
  85711. */
  85712. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  85713. /** Set the precision, in bits, of the quantized linear predictor
  85714. * coefficients, or \c 0 to let the encoder select it based on the
  85715. * blocksize.
  85716. *
  85717. * \note
  85718. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  85719. * be less than 32.
  85720. *
  85721. * \default \c 0
  85722. * \param encoder An encoder instance to set.
  85723. * \param value See above.
  85724. * \assert
  85725. * \code encoder != NULL \endcode
  85726. * \retval FLAC__bool
  85727. * \c false if the encoder is already initialized, else \c true.
  85728. */
  85729. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  85730. /** Set to \c false to use only the specified quantized linear predictor
  85731. * coefficient precision, or \c true to search neighboring precision
  85732. * values and use the best one.
  85733. *
  85734. * \default \c false
  85735. * \param encoder An encoder instance to set.
  85736. * \param value See above.
  85737. * \assert
  85738. * \code encoder != NULL \endcode
  85739. * \retval FLAC__bool
  85740. * \c false if the encoder is already initialized, else \c true.
  85741. */
  85742. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85743. /** Deprecated. Setting this value has no effect.
  85744. *
  85745. * \default \c false
  85746. * \param encoder An encoder instance to set.
  85747. * \param value See above.
  85748. * \assert
  85749. * \code encoder != NULL \endcode
  85750. * \retval FLAC__bool
  85751. * \c false if the encoder is already initialized, else \c true.
  85752. */
  85753. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85754. /** Set to \c false to let the encoder estimate the best model order
  85755. * based on the residual signal energy, or \c true to force the
  85756. * encoder to evaluate all order models and select the best.
  85757. *
  85758. * \default \c false
  85759. * \param encoder An encoder instance to set.
  85760. * \param value See above.
  85761. * \assert
  85762. * \code encoder != NULL \endcode
  85763. * \retval FLAC__bool
  85764. * \c false if the encoder is already initialized, else \c true.
  85765. */
  85766. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85767. /** Set the minimum partition order to search when coding the residual.
  85768. * This is used in tandem with
  85769. * FLAC__stream_encoder_set_max_residual_partition_order().
  85770. *
  85771. * The partition order determines the context size in the residual.
  85772. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  85773. *
  85774. * Set both min and max values to \c 0 to force a single context,
  85775. * whose Rice parameter is based on the residual signal variance.
  85776. * Otherwise, set a min and max order, and the encoder will search
  85777. * all orders, using the mean of each context for its Rice parameter,
  85778. * and use the best.
  85779. *
  85780. * \default \c 0
  85781. * \param encoder An encoder instance to set.
  85782. * \param value See above.
  85783. * \assert
  85784. * \code encoder != NULL \endcode
  85785. * \retval FLAC__bool
  85786. * \c false if the encoder is already initialized, else \c true.
  85787. */
  85788. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  85789. /** Set the maximum partition order to search when coding the residual.
  85790. * This is used in tandem with
  85791. * FLAC__stream_encoder_set_min_residual_partition_order().
  85792. *
  85793. * The partition order determines the context size in the residual.
  85794. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  85795. *
  85796. * Set both min and max values to \c 0 to force a single context,
  85797. * whose Rice parameter is based on the residual signal variance.
  85798. * Otherwise, set a min and max order, and the encoder will search
  85799. * all orders, using the mean of each context for its Rice parameter,
  85800. * and use the best.
  85801. *
  85802. * \default \c 0
  85803. * \param encoder An encoder instance to set.
  85804. * \param value See above.
  85805. * \assert
  85806. * \code encoder != NULL \endcode
  85807. * \retval FLAC__bool
  85808. * \c false if the encoder is already initialized, else \c true.
  85809. */
  85810. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  85811. /** Deprecated. Setting this value has no effect.
  85812. *
  85813. * \default \c 0
  85814. * \param encoder An encoder instance to set.
  85815. * \param value See above.
  85816. * \assert
  85817. * \code encoder != NULL \endcode
  85818. * \retval FLAC__bool
  85819. * \c false if the encoder is already initialized, else \c true.
  85820. */
  85821. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  85822. /** Set an estimate of the total samples that will be encoded.
  85823. * This is merely an estimate and may be set to \c 0 if unknown.
  85824. * This value will be written to the STREAMINFO block before encoding,
  85825. * and can remove the need for the caller to rewrite the value later
  85826. * if the value is known before encoding.
  85827. *
  85828. * \default \c 0
  85829. * \param encoder An encoder instance to set.
  85830. * \param value See above.
  85831. * \assert
  85832. * \code encoder != NULL \endcode
  85833. * \retval FLAC__bool
  85834. * \c false if the encoder is already initialized, else \c true.
  85835. */
  85836. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  85837. /** Set the metadata blocks to be emitted to the stream before encoding.
  85838. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  85839. * array of pointers to metadata blocks. The array is non-const since
  85840. * the encoder may need to change the \a is_last flag inside them, and
  85841. * in some cases update seek point offsets. Otherwise, the encoder will
  85842. * not modify or free the blocks. It is up to the caller to free the
  85843. * metadata blocks after encoding finishes.
  85844. *
  85845. * \note
  85846. * The encoder stores only copies of the pointers in the \a metadata array;
  85847. * the metadata blocks themselves must survive at least until after
  85848. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  85849. *
  85850. * \note
  85851. * The STREAMINFO block is always written and no STREAMINFO block may
  85852. * occur in the supplied array.
  85853. *
  85854. * \note
  85855. * By default the encoder does not create a SEEKTABLE. If one is supplied
  85856. * in the \a metadata array, but the client has specified that it does not
  85857. * support seeking, then the SEEKTABLE will be written verbatim. However
  85858. * by itself this is not very useful as the client will not know the stream
  85859. * offsets for the seekpoints ahead of time. In order to get a proper
  85860. * seektable the client must support seeking. See next note.
  85861. *
  85862. * \note
  85863. * SEEKTABLE blocks are handled specially. Since you will not know
  85864. * the values for the seek point stream offsets, you should pass in
  85865. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  85866. * required sample numbers (or placeholder points), with \c 0 for the
  85867. * \a frame_samples and \a stream_offset fields for each point. If the
  85868. * client has specified that it supports seeking by providing a seek
  85869. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  85870. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  85871. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  85872. * then while it is encoding the encoder will fill the stream offsets in
  85873. * for you and when encoding is finished, it will seek back and write the
  85874. * real values into the SEEKTABLE block in the stream. There are helper
  85875. * routines for manipulating seektable template blocks; see metadata.h:
  85876. * FLAC__metadata_object_seektable_template_*(). If the client does
  85877. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  85878. * will slow down or remove the ability to seek in the FLAC stream.
  85879. *
  85880. * \note
  85881. * The encoder instance \b will modify the first \c SEEKTABLE block
  85882. * as it transforms the template to a valid seektable while encoding,
  85883. * but it is still up to the caller to free all metadata blocks after
  85884. * encoding.
  85885. *
  85886. * \note
  85887. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  85888. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  85889. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  85890. * will simply write it's own into the stream. If no VORBIS_COMMENT
  85891. * block is present in the \a metadata array, libFLAC will write an
  85892. * empty one, containing only the vendor string.
  85893. *
  85894. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  85895. * the second metadata block of the stream. The encoder already supplies
  85896. * the STREAMINFO block automatically. If \a metadata does not contain a
  85897. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  85898. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  85899. * first, the init function will reorder \a metadata by moving the
  85900. * VORBIS_COMMENT block to the front; the relative ordering of the other
  85901. * blocks will remain as they were.
  85902. *
  85903. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  85904. * stream to \c 65535. If \a num_blocks exceeds this the function will
  85905. * return \c false.
  85906. *
  85907. * \default \c NULL, 0
  85908. * \param encoder An encoder instance to set.
  85909. * \param metadata See above.
  85910. * \param num_blocks See above.
  85911. * \assert
  85912. * \code encoder != NULL \endcode
  85913. * \retval FLAC__bool
  85914. * \c false if the encoder is already initialized, else \c true.
  85915. * \c false if the encoder is already initialized, or if
  85916. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  85917. */
  85918. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  85919. /** Get the current encoder state.
  85920. *
  85921. * \param encoder An encoder instance to query.
  85922. * \assert
  85923. * \code encoder != NULL \endcode
  85924. * \retval FLAC__StreamEncoderState
  85925. * The current encoder state.
  85926. */
  85927. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  85928. /** Get the state of the verify stream decoder.
  85929. * Useful when the stream encoder state is
  85930. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  85931. *
  85932. * \param encoder An encoder instance to query.
  85933. * \assert
  85934. * \code encoder != NULL \endcode
  85935. * \retval FLAC__StreamDecoderState
  85936. * The verify stream decoder state.
  85937. */
  85938. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  85939. /** Get the current encoder state as a C string.
  85940. * This version automatically resolves
  85941. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  85942. * verify decoder's state.
  85943. *
  85944. * \param encoder A encoder instance to query.
  85945. * \assert
  85946. * \code encoder != NULL \endcode
  85947. * \retval const char *
  85948. * The encoder state as a C string. Do not modify the contents.
  85949. */
  85950. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  85951. /** Get relevant values about the nature of a verify decoder error.
  85952. * Useful when the stream encoder state is
  85953. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  85954. * be addresses in which the stats will be returned, or NULL if value
  85955. * is not desired.
  85956. *
  85957. * \param encoder An encoder instance to query.
  85958. * \param absolute_sample The absolute sample number of the mismatch.
  85959. * \param frame_number The number of the frame in which the mismatch occurred.
  85960. * \param channel The channel in which the mismatch occurred.
  85961. * \param sample The number of the sample (relative to the frame) in
  85962. * which the mismatch occurred.
  85963. * \param expected The expected value for the sample in question.
  85964. * \param got The actual value returned by the decoder.
  85965. * \assert
  85966. * \code encoder != NULL \endcode
  85967. */
  85968. 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);
  85969. /** Get the "verify" flag.
  85970. *
  85971. * \param encoder An encoder instance to query.
  85972. * \assert
  85973. * \code encoder != NULL \endcode
  85974. * \retval FLAC__bool
  85975. * See FLAC__stream_encoder_set_verify().
  85976. */
  85977. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  85978. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  85979. *
  85980. * \param encoder An encoder instance to query.
  85981. * \assert
  85982. * \code encoder != NULL \endcode
  85983. * \retval FLAC__bool
  85984. * See FLAC__stream_encoder_set_streamable_subset().
  85985. */
  85986. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  85987. /** Get the number of input channels being processed.
  85988. *
  85989. * \param encoder An encoder instance to query.
  85990. * \assert
  85991. * \code encoder != NULL \endcode
  85992. * \retval unsigned
  85993. * See FLAC__stream_encoder_set_channels().
  85994. */
  85995. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  85996. /** Get the input sample resolution setting.
  85997. *
  85998. * \param encoder An encoder instance to query.
  85999. * \assert
  86000. * \code encoder != NULL \endcode
  86001. * \retval unsigned
  86002. * See FLAC__stream_encoder_set_bits_per_sample().
  86003. */
  86004. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  86005. /** Get the input sample rate setting.
  86006. *
  86007. * \param encoder An encoder instance to query.
  86008. * \assert
  86009. * \code encoder != NULL \endcode
  86010. * \retval unsigned
  86011. * See FLAC__stream_encoder_set_sample_rate().
  86012. */
  86013. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  86014. /** Get the blocksize setting.
  86015. *
  86016. * \param encoder An encoder instance to query.
  86017. * \assert
  86018. * \code encoder != NULL \endcode
  86019. * \retval unsigned
  86020. * See FLAC__stream_encoder_set_blocksize().
  86021. */
  86022. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  86023. /** Get the "mid/side stereo coding" flag.
  86024. *
  86025. * \param encoder An encoder instance to query.
  86026. * \assert
  86027. * \code encoder != NULL \endcode
  86028. * \retval FLAC__bool
  86029. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  86030. */
  86031. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  86032. /** Get the "adaptive mid/side switching" flag.
  86033. *
  86034. * \param encoder An encoder instance to query.
  86035. * \assert
  86036. * \code encoder != NULL \endcode
  86037. * \retval FLAC__bool
  86038. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  86039. */
  86040. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  86041. /** Get the maximum LPC order setting.
  86042. *
  86043. * \param encoder An encoder instance to query.
  86044. * \assert
  86045. * \code encoder != NULL \endcode
  86046. * \retval unsigned
  86047. * See FLAC__stream_encoder_set_max_lpc_order().
  86048. */
  86049. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  86050. /** Get the quantized linear predictor coefficient precision setting.
  86051. *
  86052. * \param encoder An encoder instance to query.
  86053. * \assert
  86054. * \code encoder != NULL \endcode
  86055. * \retval unsigned
  86056. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  86057. */
  86058. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  86059. /** Get the qlp coefficient precision search flag.
  86060. *
  86061. * \param encoder An encoder instance to query.
  86062. * \assert
  86063. * \code encoder != NULL \endcode
  86064. * \retval FLAC__bool
  86065. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  86066. */
  86067. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  86068. /** Get the "escape coding" flag.
  86069. *
  86070. * \param encoder An encoder instance to query.
  86071. * \assert
  86072. * \code encoder != NULL \endcode
  86073. * \retval FLAC__bool
  86074. * See FLAC__stream_encoder_set_do_escape_coding().
  86075. */
  86076. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  86077. /** Get the exhaustive model search flag.
  86078. *
  86079. * \param encoder An encoder instance to query.
  86080. * \assert
  86081. * \code encoder != NULL \endcode
  86082. * \retval FLAC__bool
  86083. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  86084. */
  86085. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  86086. /** Get the minimum residual partition order setting.
  86087. *
  86088. * \param encoder An encoder instance to query.
  86089. * \assert
  86090. * \code encoder != NULL \endcode
  86091. * \retval unsigned
  86092. * See FLAC__stream_encoder_set_min_residual_partition_order().
  86093. */
  86094. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  86095. /** Get maximum residual partition order setting.
  86096. *
  86097. * \param encoder An encoder instance to query.
  86098. * \assert
  86099. * \code encoder != NULL \endcode
  86100. * \retval unsigned
  86101. * See FLAC__stream_encoder_set_max_residual_partition_order().
  86102. */
  86103. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  86104. /** Get the Rice parameter search distance setting.
  86105. *
  86106. * \param encoder An encoder instance to query.
  86107. * \assert
  86108. * \code encoder != NULL \endcode
  86109. * \retval unsigned
  86110. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  86111. */
  86112. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  86113. /** Get the previously set estimate of the total samples to be encoded.
  86114. * The encoder merely mimics back the value given to
  86115. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  86116. * other way of knowing how many samples the client will encode.
  86117. *
  86118. * \param encoder An encoder instance to set.
  86119. * \assert
  86120. * \code encoder != NULL \endcode
  86121. * \retval FLAC__uint64
  86122. * See FLAC__stream_encoder_get_total_samples_estimate().
  86123. */
  86124. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  86125. /** Initialize the encoder instance to encode native FLAC streams.
  86126. *
  86127. * This flavor of initialization sets up the encoder to encode to a
  86128. * native FLAC stream. I/O is performed via callbacks to the client.
  86129. * For encoding to a plain file via filename or open \c FILE*,
  86130. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  86131. * provide a simpler interface.
  86132. *
  86133. * This function should be called after FLAC__stream_encoder_new() and
  86134. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86135. * or FLAC__stream_encoder_process_interleaved().
  86136. * initialization succeeded.
  86137. *
  86138. * The call to FLAC__stream_encoder_init_stream() currently will also
  86139. * immediately call the write callback several times, once with the \c fLaC
  86140. * signature, and once for each encoded metadata block.
  86141. *
  86142. * \param encoder An uninitialized encoder instance.
  86143. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  86144. * pointer must not be \c NULL.
  86145. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  86146. * pointer may be \c NULL if seeking is not
  86147. * supported. The encoder uses seeking to go back
  86148. * and write some some stream statistics to the
  86149. * STREAMINFO block; this is recommended but not
  86150. * necessary to create a valid FLAC stream. If
  86151. * \a seek_callback is not \c NULL then a
  86152. * \a tell_callback must also be supplied.
  86153. * Alternatively, a dummy seek callback that just
  86154. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  86155. * may also be supplied, all though this is slightly
  86156. * less efficient for the encoder.
  86157. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  86158. * pointer may be \c NULL if seeking is not
  86159. * supported. If \a seek_callback is \c NULL then
  86160. * this argument will be ignored. If
  86161. * \a seek_callback is not \c NULL then a
  86162. * \a tell_callback must also be supplied.
  86163. * Alternatively, a dummy tell callback that just
  86164. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  86165. * may also be supplied, all though this is slightly
  86166. * less efficient for the encoder.
  86167. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  86168. * pointer may be \c NULL if the callback is not
  86169. * desired. If the client provides a seek callback,
  86170. * this function is not necessary as the encoder
  86171. * will automatically seek back and update the
  86172. * STREAMINFO block. It may also be \c NULL if the
  86173. * client does not support seeking, since it will
  86174. * have no way of going back to update the
  86175. * STREAMINFO. However the client can still supply
  86176. * a callback if it would like to know the details
  86177. * from the STREAMINFO.
  86178. * \param client_data This value will be supplied to callbacks in their
  86179. * \a client_data argument.
  86180. * \assert
  86181. * \code encoder != NULL \endcode
  86182. * \retval FLAC__StreamEncoderInitStatus
  86183. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86184. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86185. */
  86186. 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);
  86187. /** Initialize the encoder instance to encode Ogg FLAC streams.
  86188. *
  86189. * This flavor of initialization sets up the encoder to encode to a FLAC
  86190. * stream in an Ogg container. I/O is performed via callbacks to the
  86191. * client. For encoding to a plain file via filename or open \c FILE*,
  86192. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  86193. * provide a simpler interface.
  86194. *
  86195. * This function should be called after FLAC__stream_encoder_new() and
  86196. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86197. * or FLAC__stream_encoder_process_interleaved().
  86198. * initialization succeeded.
  86199. *
  86200. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  86201. * immediately call the write callback several times to write the metadata
  86202. * packets.
  86203. *
  86204. * \param encoder An uninitialized encoder instance.
  86205. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  86206. * pointer must not be \c NULL if \a seek_callback
  86207. * is non-NULL since they are both needed to be
  86208. * able to write data back to the Ogg FLAC stream
  86209. * in the post-encode phase.
  86210. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  86211. * pointer must not be \c NULL.
  86212. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  86213. * pointer may be \c NULL if seeking is not
  86214. * supported. The encoder uses seeking to go back
  86215. * and write some some stream statistics to the
  86216. * STREAMINFO block; this is recommended but not
  86217. * necessary to create a valid FLAC stream. If
  86218. * \a seek_callback is not \c NULL then a
  86219. * \a tell_callback must also be supplied.
  86220. * Alternatively, a dummy seek callback that just
  86221. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  86222. * may also be supplied, all though this is slightly
  86223. * less efficient for the encoder.
  86224. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  86225. * pointer may be \c NULL if seeking is not
  86226. * supported. If \a seek_callback is \c NULL then
  86227. * this argument will be ignored. If
  86228. * \a seek_callback is not \c NULL then a
  86229. * \a tell_callback must also be supplied.
  86230. * Alternatively, a dummy tell callback that just
  86231. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  86232. * may also be supplied, all though this is slightly
  86233. * less efficient for the encoder.
  86234. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  86235. * pointer may be \c NULL if the callback is not
  86236. * desired. If the client provides a seek callback,
  86237. * this function is not necessary as the encoder
  86238. * will automatically seek back and update the
  86239. * STREAMINFO block. It may also be \c NULL if the
  86240. * client does not support seeking, since it will
  86241. * have no way of going back to update the
  86242. * STREAMINFO. However the client can still supply
  86243. * a callback if it would like to know the details
  86244. * from the STREAMINFO.
  86245. * \param client_data This value will be supplied to callbacks in their
  86246. * \a client_data argument.
  86247. * \assert
  86248. * \code encoder != NULL \endcode
  86249. * \retval FLAC__StreamEncoderInitStatus
  86250. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86251. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86252. */
  86253. 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);
  86254. /** Initialize the encoder instance to encode native FLAC files.
  86255. *
  86256. * This flavor of initialization sets up the encoder to encode to a
  86257. * plain native FLAC file. For non-stdio streams, you must use
  86258. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  86259. *
  86260. * This function should be called after FLAC__stream_encoder_new() and
  86261. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86262. * or FLAC__stream_encoder_process_interleaved().
  86263. * initialization succeeded.
  86264. *
  86265. * \param encoder An uninitialized encoder instance.
  86266. * \param file An open file. The file should have been opened
  86267. * with mode \c "w+b" and rewound. The file
  86268. * becomes owned by the encoder and should not be
  86269. * manipulated by the client while encoding.
  86270. * Unless \a file is \c stdout, it will be closed
  86271. * when FLAC__stream_encoder_finish() is called.
  86272. * Note however that a proper SEEKTABLE cannot be
  86273. * created when encoding to \c stdout since it is
  86274. * not seekable.
  86275. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  86276. * pointer may be \c NULL if the callback is not
  86277. * desired.
  86278. * \param client_data This value will be supplied to callbacks in their
  86279. * \a client_data argument.
  86280. * \assert
  86281. * \code encoder != NULL \endcode
  86282. * \code file != NULL \endcode
  86283. * \retval FLAC__StreamEncoderInitStatus
  86284. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86285. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86286. */
  86287. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  86288. /** Initialize the encoder instance to encode Ogg FLAC files.
  86289. *
  86290. * This flavor of initialization sets up the encoder to encode to a
  86291. * plain Ogg FLAC file. For non-stdio streams, you must use
  86292. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  86293. *
  86294. * This function should be called after FLAC__stream_encoder_new() and
  86295. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86296. * or FLAC__stream_encoder_process_interleaved().
  86297. * initialization succeeded.
  86298. *
  86299. * \param encoder An uninitialized encoder instance.
  86300. * \param file An open file. The file should have been opened
  86301. * with mode \c "w+b" and rewound. The file
  86302. * becomes owned by the encoder and should not be
  86303. * manipulated by the client while encoding.
  86304. * Unless \a file is \c stdout, it will be closed
  86305. * when FLAC__stream_encoder_finish() is called.
  86306. * Note however that a proper SEEKTABLE cannot be
  86307. * created when encoding to \c stdout since it is
  86308. * not seekable.
  86309. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  86310. * pointer may be \c NULL if the callback is not
  86311. * desired.
  86312. * \param client_data This value will be supplied to callbacks in their
  86313. * \a client_data argument.
  86314. * \assert
  86315. * \code encoder != NULL \endcode
  86316. * \code file != NULL \endcode
  86317. * \retval FLAC__StreamEncoderInitStatus
  86318. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86319. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86320. */
  86321. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  86322. /** Initialize the encoder instance to encode native FLAC files.
  86323. *
  86324. * This flavor of initialization sets up the encoder to encode to a plain
  86325. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  86326. * with Unicode filenames on Windows), you must use
  86327. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  86328. * and provide callbacks for the I/O.
  86329. *
  86330. * This function should be called after FLAC__stream_encoder_new() and
  86331. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86332. * or FLAC__stream_encoder_process_interleaved().
  86333. * initialization succeeded.
  86334. *
  86335. * \param encoder An uninitialized encoder instance.
  86336. * \param filename The name of the file to encode to. The file will
  86337. * be opened with fopen(). Use \c NULL to encode to
  86338. * \c stdout. Note however that a proper SEEKTABLE
  86339. * cannot be created when encoding to \c stdout since
  86340. * it is not seekable.
  86341. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  86342. * pointer may be \c NULL if the callback is not
  86343. * desired.
  86344. * \param client_data This value will be supplied to callbacks in their
  86345. * \a client_data argument.
  86346. * \assert
  86347. * \code encoder != NULL \endcode
  86348. * \retval FLAC__StreamEncoderInitStatus
  86349. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86350. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86351. */
  86352. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  86353. /** Initialize the encoder instance to encode Ogg FLAC files.
  86354. *
  86355. * This flavor of initialization sets up the encoder to encode to a plain
  86356. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  86357. * with Unicode filenames on Windows), you must use
  86358. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  86359. * and provide callbacks for the I/O.
  86360. *
  86361. * This function should be called after FLAC__stream_encoder_new() and
  86362. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86363. * or FLAC__stream_encoder_process_interleaved().
  86364. * initialization succeeded.
  86365. *
  86366. * \param encoder An uninitialized encoder instance.
  86367. * \param filename The name of the file to encode to. The file will
  86368. * be opened with fopen(). Use \c NULL to encode to
  86369. * \c stdout. Note however that a proper SEEKTABLE
  86370. * cannot be created when encoding to \c stdout since
  86371. * it is not seekable.
  86372. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  86373. * pointer may be \c NULL if the callback is not
  86374. * desired.
  86375. * \param client_data This value will be supplied to callbacks in their
  86376. * \a client_data argument.
  86377. * \assert
  86378. * \code encoder != NULL \endcode
  86379. * \retval FLAC__StreamEncoderInitStatus
  86380. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86381. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86382. */
  86383. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  86384. /** Finish the encoding process.
  86385. * Flushes the encoding buffer, releases resources, resets the encoder
  86386. * settings to their defaults, and returns the encoder state to
  86387. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  86388. * one or more write callbacks before returning, and will generate
  86389. * a metadata callback.
  86390. *
  86391. * Note that in the course of processing the last frame, errors can
  86392. * occur, so the caller should be sure to check the return value to
  86393. * ensure the file was encoded properly.
  86394. *
  86395. * In the event of a prematurely-terminated encode, it is not strictly
  86396. * necessary to call this immediately before FLAC__stream_encoder_delete()
  86397. * but it is good practice to match every FLAC__stream_encoder_init_*()
  86398. * with a FLAC__stream_encoder_finish().
  86399. *
  86400. * \param encoder An uninitialized encoder instance.
  86401. * \assert
  86402. * \code encoder != NULL \endcode
  86403. * \retval FLAC__bool
  86404. * \c false if an error occurred processing the last frame; or if verify
  86405. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  86406. * verify mismatch; else \c true. If \c false, caller should check the
  86407. * state with FLAC__stream_encoder_get_state() for more information
  86408. * about the error.
  86409. */
  86410. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  86411. /** Submit data for encoding.
  86412. * This version allows you to supply the input data via an array of
  86413. * pointers, each pointer pointing to an array of \a samples samples
  86414. * representing one channel. The samples need not be block-aligned,
  86415. * but each channel should have the same number of samples. Each sample
  86416. * should be a signed integer, right-justified to the resolution set by
  86417. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  86418. * resolution is 16 bits per sample, the samples should all be in the
  86419. * range [-32768,32767].
  86420. *
  86421. * For applications where channel order is important, channels must
  86422. * follow the order as described in the
  86423. * <A HREF="../format.html#frame_header">frame header</A>.
  86424. *
  86425. * \param encoder An initialized encoder instance in the OK state.
  86426. * \param buffer An array of pointers to each channel's signal.
  86427. * \param samples The number of samples in one channel.
  86428. * \assert
  86429. * \code encoder != NULL \endcode
  86430. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  86431. * \retval FLAC__bool
  86432. * \c true if successful, else \c false; in this case, check the
  86433. * encoder state with FLAC__stream_encoder_get_state() to see what
  86434. * went wrong.
  86435. */
  86436. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  86437. /** Submit data for encoding.
  86438. * This version allows you to supply the input data where the channels
  86439. * are interleaved into a single array (i.e. channel0_sample0,
  86440. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  86441. * The samples need not be block-aligned but they must be
  86442. * sample-aligned, i.e. the first value should be channel0_sample0
  86443. * and the last value channelN_sampleM. Each sample should be a signed
  86444. * integer, right-justified to the resolution set by
  86445. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  86446. * resolution is 16 bits per sample, the samples should all be in the
  86447. * range [-32768,32767].
  86448. *
  86449. * For applications where channel order is important, channels must
  86450. * follow the order as described in the
  86451. * <A HREF="../format.html#frame_header">frame header</A>.
  86452. *
  86453. * \param encoder An initialized encoder instance in the OK state.
  86454. * \param buffer An array of channel-interleaved data (see above).
  86455. * \param samples The number of samples in one channel, the same as for
  86456. * FLAC__stream_encoder_process(). For example, if
  86457. * encoding two channels, \c 1000 \a samples corresponds
  86458. * to a \a buffer of 2000 values.
  86459. * \assert
  86460. * \code encoder != NULL \endcode
  86461. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  86462. * \retval FLAC__bool
  86463. * \c true if successful, else \c false; in this case, check the
  86464. * encoder state with FLAC__stream_encoder_get_state() to see what
  86465. * went wrong.
  86466. */
  86467. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  86468. /* \} */
  86469. #ifdef __cplusplus
  86470. }
  86471. #endif
  86472. #endif
  86473. /********* End of inlined file: stream_encoder.h *********/
  86474. #ifdef _MSC_VER
  86475. /* OPT: an MSVC built-in would be better */
  86476. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  86477. {
  86478. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  86479. return (x>>16) | (x<<16);
  86480. }
  86481. #endif
  86482. #if defined(_MSC_VER) && defined(_X86_)
  86483. /* OPT: an MSVC built-in would be better */
  86484. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  86485. {
  86486. __asm {
  86487. mov edx, start
  86488. mov ecx, len
  86489. test ecx, ecx
  86490. loop1:
  86491. jz done1
  86492. mov eax, [edx]
  86493. bswap eax
  86494. mov [edx], eax
  86495. add edx, 4
  86496. dec ecx
  86497. jmp short loop1
  86498. done1:
  86499. }
  86500. }
  86501. #endif
  86502. /** \mainpage
  86503. *
  86504. * \section intro Introduction
  86505. *
  86506. * This is the documentation for the FLAC C and C++ APIs. It is
  86507. * highly interconnected; this introduction should give you a top
  86508. * level idea of the structure and how to find the information you
  86509. * need. As a prerequisite you should have at least a basic
  86510. * knowledge of the FLAC format, documented
  86511. * <A HREF="../format.html">here</A>.
  86512. *
  86513. * \section c_api FLAC C API
  86514. *
  86515. * The FLAC C API is the interface to libFLAC, a set of structures
  86516. * describing the components of FLAC streams, and functions for
  86517. * encoding and decoding streams, as well as manipulating FLAC
  86518. * metadata in files. The public include files will be installed
  86519. * in your include area (for example /usr/include/FLAC/...).
  86520. *
  86521. * By writing a little code and linking against libFLAC, it is
  86522. * relatively easy to add FLAC support to another program. The
  86523. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  86524. * Complete source code of libFLAC as well as the command-line
  86525. * encoder and plugins is available and is a useful source of
  86526. * examples.
  86527. *
  86528. * Aside from encoders and decoders, libFLAC provides a powerful
  86529. * metadata interface for manipulating metadata in FLAC files. It
  86530. * allows the user to add, delete, and modify FLAC metadata blocks
  86531. * and it can automatically take advantage of PADDING blocks to avoid
  86532. * rewriting the entire FLAC file when changing the size of the
  86533. * metadata.
  86534. *
  86535. * libFLAC usually only requires the standard C library and C math
  86536. * library. In particular, threading is not used so there is no
  86537. * dependency on a thread library. However, libFLAC does not use
  86538. * global variables and should be thread-safe.
  86539. *
  86540. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  86541. * However the metadata editing interfaces currently have limited
  86542. * read-only support for Ogg FLAC files.
  86543. *
  86544. * \section cpp_api FLAC C++ API
  86545. *
  86546. * The FLAC C++ API is a set of classes that encapsulate the
  86547. * structures and functions in libFLAC. They provide slightly more
  86548. * functionality with respect to metadata but are otherwise
  86549. * equivalent. For the most part, they share the same usage as
  86550. * their counterparts in libFLAC, and the FLAC C API documentation
  86551. * can be used as a supplement. The public include files
  86552. * for the C++ API will be installed in your include area (for
  86553. * example /usr/include/FLAC++/...).
  86554. *
  86555. * libFLAC++ is also licensed under
  86556. * <A HREF="../license.html">Xiph's BSD license</A>.
  86557. *
  86558. * \section getting_started Getting Started
  86559. *
  86560. * A good starting point for learning the API is to browse through
  86561. * the <A HREF="modules.html">modules</A>. Modules are logical
  86562. * groupings of related functions or classes, which correspond roughly
  86563. * to header files or sections of header files. Each module includes a
  86564. * detailed description of the general usage of its functions or
  86565. * classes.
  86566. *
  86567. * From there you can go on to look at the documentation of
  86568. * individual functions. You can see different views of the individual
  86569. * functions through the links in top bar across this page.
  86570. *
  86571. * If you prefer a more hands-on approach, you can jump right to some
  86572. * <A HREF="../documentation_example_code.html">example code</A>.
  86573. *
  86574. * \section porting_guide Porting Guide
  86575. *
  86576. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  86577. * has been introduced which gives detailed instructions on how to
  86578. * port your code to newer versions of FLAC.
  86579. *
  86580. * \section embedded_developers Embedded Developers
  86581. *
  86582. * libFLAC has grown larger over time as more functionality has been
  86583. * included, but much of it may be unnecessary for a particular embedded
  86584. * implementation. Unused parts may be pruned by some simple editing of
  86585. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  86586. * metadata interface are all independent from each other.
  86587. *
  86588. * It is easiest to just describe the dependencies:
  86589. *
  86590. * - All modules depend on the \link flac_format Format \endlink module.
  86591. * - The decoders and encoders depend on the bitbuffer.
  86592. * - The decoder is independent of the encoder. The encoder uses the
  86593. * decoder because of the verify feature, but this can be removed if
  86594. * not needed.
  86595. * - Parts of the metadata interface require the stream decoder (but not
  86596. * the encoder).
  86597. * - Ogg support is selectable through the compile time macro
  86598. * \c FLAC__HAS_OGG.
  86599. *
  86600. * For example, if your application only requires the stream decoder, no
  86601. * encoder, and no metadata interface, you can remove the stream encoder
  86602. * and the metadata interface, which will greatly reduce the size of the
  86603. * library.
  86604. *
  86605. * Also, there are several places in the libFLAC code with comments marked
  86606. * with "OPT:" where a #define can be changed to enable code that might be
  86607. * faster on a specific platform. Experimenting with these can yield faster
  86608. * binaries.
  86609. */
  86610. /** \defgroup porting Porting Guide for New Versions
  86611. *
  86612. * This module describes differences in the library interfaces from
  86613. * version to version. It assists in the porting of code that uses
  86614. * the libraries to newer versions of FLAC.
  86615. *
  86616. * One simple facility for making porting easier that has been added
  86617. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  86618. * library's includes (e.g. \c include/FLAC/export.h). The
  86619. * \c #defines mirror the libraries'
  86620. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  86621. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  86622. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  86623. * These can be used to support multiple versions of an API during the
  86624. * transition phase, e.g.
  86625. *
  86626. * \code
  86627. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  86628. * legacy code
  86629. * #else
  86630. * new code
  86631. * #endif
  86632. * \endcode
  86633. *
  86634. * The the source will work for multiple versions and the legacy code can
  86635. * easily be removed when the transition is complete.
  86636. *
  86637. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  86638. * include/FLAC/export.h), which can be used to determine whether or not
  86639. * the library has been compiled with support for Ogg FLAC. This is
  86640. * simpler than trying to call an Ogg init function and catching the
  86641. * error.
  86642. */
  86643. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  86644. * \ingroup porting
  86645. *
  86646. * \brief
  86647. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  86648. *
  86649. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  86650. * been simplified. First, libOggFLAC has been merged into libFLAC and
  86651. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  86652. * decoding layers and three encoding layers have been merged into a
  86653. * single stream decoder and stream encoder. That is, the functionality
  86654. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  86655. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  86656. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  86657. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  86658. * is there is now a single API that can be used to encode or decode
  86659. * streams to/from native FLAC or Ogg FLAC and the single API can work
  86660. * on both seekable and non-seekable streams.
  86661. *
  86662. * Instead of creating an encoder or decoder of a certain layer, now the
  86663. * client will always create a FLAC__StreamEncoder or
  86664. * FLAC__StreamDecoder. The old layers are now differentiated by the
  86665. * initialization function. For example, for the decoder,
  86666. * FLAC__stream_decoder_init() has been replaced by
  86667. * FLAC__stream_decoder_init_stream(). This init function takes
  86668. * callbacks for the I/O, and the seeking callbacks are optional. This
  86669. * allows the client to use the same object for seekable and
  86670. * non-seekable streams. For decoding a FLAC file directly, the client
  86671. * can use FLAC__stream_decoder_init_file() and pass just a filename
  86672. * and fewer callbacks; most of the other callbacks are supplied
  86673. * internally. For situations where fopen()ing by filename is not
  86674. * possible (e.g. Unicode filenames on Windows) the client can instead
  86675. * open the file itself and supply the FILE* to
  86676. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  86677. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  86678. * Since the callbacks and client data are now passed to the init
  86679. * function, the FLAC__stream_decoder_set_*_callback() functions and
  86680. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  86681. * rest of the calls to the decoder are the same as before.
  86682. *
  86683. * There are counterpart init functions for Ogg FLAC, e.g.
  86684. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  86685. * and callbacks are the same as for native FLAC.
  86686. *
  86687. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  86688. * been set up like so:
  86689. *
  86690. * \code
  86691. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  86692. * if(decoder == NULL) do_something;
  86693. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  86694. * [... other settings ...]
  86695. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  86696. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  86697. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  86698. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  86699. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  86700. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  86701. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  86702. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  86703. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  86704. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  86705. * \endcode
  86706. *
  86707. * In FLAC 1.1.3 it is like this:
  86708. *
  86709. * \code
  86710. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  86711. * if(decoder == NULL) do_something;
  86712. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  86713. * [... other settings ...]
  86714. * if(FLAC__stream_decoder_init_stream(
  86715. * decoder,
  86716. * my_read_callback,
  86717. * my_seek_callback, // or NULL
  86718. * my_tell_callback, // or NULL
  86719. * my_length_callback, // or NULL
  86720. * my_eof_callback, // or NULL
  86721. * my_write_callback,
  86722. * my_metadata_callback, // or NULL
  86723. * my_error_callback,
  86724. * my_client_data
  86725. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  86726. * \endcode
  86727. *
  86728. * or you could do;
  86729. *
  86730. * \code
  86731. * [...]
  86732. * FILE *file = fopen("somefile.flac","rb");
  86733. * if(file == NULL) do_somthing;
  86734. * if(FLAC__stream_decoder_init_FILE(
  86735. * decoder,
  86736. * file,
  86737. * my_write_callback,
  86738. * my_metadata_callback, // or NULL
  86739. * my_error_callback,
  86740. * my_client_data
  86741. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  86742. * \endcode
  86743. *
  86744. * or just:
  86745. *
  86746. * \code
  86747. * [...]
  86748. * if(FLAC__stream_decoder_init_file(
  86749. * decoder,
  86750. * "somefile.flac",
  86751. * my_write_callback,
  86752. * my_metadata_callback, // or NULL
  86753. * my_error_callback,
  86754. * my_client_data
  86755. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  86756. * \endcode
  86757. *
  86758. * Another small change to the decoder is in how it handles unparseable
  86759. * streams. Before, when the decoder found an unparseable stream
  86760. * (reserved for when the decoder encounters a stream from a future
  86761. * encoder that it can't parse), it changed the state to
  86762. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  86763. * drops sync and calls the error callback with a new error code
  86764. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  86765. * more robust. If your error callback does not discriminate on the the
  86766. * error state, your code does not need to be changed.
  86767. *
  86768. * The encoder now has a new setting:
  86769. * FLAC__stream_encoder_set_apodization(). This is for setting the
  86770. * method used to window the data before LPC analysis. You only need to
  86771. * add a call to this function if the default is not suitable. There
  86772. * are also two new convenience functions that may be useful:
  86773. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  86774. * FLAC__metadata_get_cuesheet().
  86775. *
  86776. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  86777. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  86778. * is now \c size_t instead of \c unsigned.
  86779. */
  86780. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  86781. * \ingroup porting
  86782. *
  86783. * \brief
  86784. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  86785. *
  86786. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  86787. * There was a slight change in the implementation of
  86788. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  86789. * of the \a metadata array of pointers so the client no longer needs
  86790. * to maintain it after the call. The objects themselves that are
  86791. * pointed to by the array are still not copied though and must be
  86792. * maintained until the call to FLAC__stream_encoder_finish().
  86793. */
  86794. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  86795. * \ingroup porting
  86796. *
  86797. * \brief
  86798. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  86799. *
  86800. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  86801. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  86802. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  86803. *
  86804. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  86805. * has changed to reflect the conversion of one of the reserved bits
  86806. * into active use. It used to be \c 2 and now is \c 1. However the
  86807. * FLAC frame header length has not changed, so to skip the proper
  86808. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  86809. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  86810. */
  86811. /** \defgroup flac FLAC C API
  86812. *
  86813. * The FLAC C API is the interface to libFLAC, a set of structures
  86814. * describing the components of FLAC streams, and functions for
  86815. * encoding and decoding streams, as well as manipulating FLAC
  86816. * metadata in files.
  86817. *
  86818. * You should start with the format components as all other modules
  86819. * are dependent on it.
  86820. */
  86821. #endif
  86822. /********* End of inlined file: all.h *********/
  86823. /********* Start of inlined file: bitmath.c *********/
  86824. /********* Start of inlined file: juce_FlacHeader.h *********/
  86825. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  86826. // tasks..
  86827. #define VERSION "1.2.1"
  86828. #define FLAC__NO_DLL 1
  86829. #ifdef _MSC_VER
  86830. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  86831. #endif
  86832. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  86833. #define FLAC__SYS_DARWIN 1
  86834. #endif
  86835. /********* End of inlined file: juce_FlacHeader.h *********/
  86836. #if JUCE_USE_FLAC
  86837. #if HAVE_CONFIG_H
  86838. # include <config.h>
  86839. #endif
  86840. /********* Start of inlined file: bitmath.h *********/
  86841. #ifndef FLAC__PRIVATE__BITMATH_H
  86842. #define FLAC__PRIVATE__BITMATH_H
  86843. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  86844. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  86845. unsigned FLAC__bitmath_silog2(int v);
  86846. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  86847. #endif
  86848. /********* End of inlined file: bitmath.h *********/
  86849. /* An example of what FLAC__bitmath_ilog2() computes:
  86850. *
  86851. * ilog2( 0) = assertion failure
  86852. * ilog2( 1) = 0
  86853. * ilog2( 2) = 1
  86854. * ilog2( 3) = 1
  86855. * ilog2( 4) = 2
  86856. * ilog2( 5) = 2
  86857. * ilog2( 6) = 2
  86858. * ilog2( 7) = 2
  86859. * ilog2( 8) = 3
  86860. * ilog2( 9) = 3
  86861. * ilog2(10) = 3
  86862. * ilog2(11) = 3
  86863. * ilog2(12) = 3
  86864. * ilog2(13) = 3
  86865. * ilog2(14) = 3
  86866. * ilog2(15) = 3
  86867. * ilog2(16) = 4
  86868. * ilog2(17) = 4
  86869. * ilog2(18) = 4
  86870. */
  86871. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  86872. {
  86873. unsigned l = 0;
  86874. FLAC__ASSERT(v > 0);
  86875. while(v >>= 1)
  86876. l++;
  86877. return l;
  86878. }
  86879. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  86880. {
  86881. unsigned l = 0;
  86882. FLAC__ASSERT(v > 0);
  86883. while(v >>= 1)
  86884. l++;
  86885. return l;
  86886. }
  86887. /* An example of what FLAC__bitmath_silog2() computes:
  86888. *
  86889. * silog2(-10) = 5
  86890. * silog2(- 9) = 5
  86891. * silog2(- 8) = 4
  86892. * silog2(- 7) = 4
  86893. * silog2(- 6) = 4
  86894. * silog2(- 5) = 4
  86895. * silog2(- 4) = 3
  86896. * silog2(- 3) = 3
  86897. * silog2(- 2) = 2
  86898. * silog2(- 1) = 2
  86899. * silog2( 0) = 0
  86900. * silog2( 1) = 2
  86901. * silog2( 2) = 3
  86902. * silog2( 3) = 3
  86903. * silog2( 4) = 4
  86904. * silog2( 5) = 4
  86905. * silog2( 6) = 4
  86906. * silog2( 7) = 4
  86907. * silog2( 8) = 5
  86908. * silog2( 9) = 5
  86909. * silog2( 10) = 5
  86910. */
  86911. unsigned FLAC__bitmath_silog2(int v)
  86912. {
  86913. while(1) {
  86914. if(v == 0) {
  86915. return 0;
  86916. }
  86917. else if(v > 0) {
  86918. unsigned l = 0;
  86919. while(v) {
  86920. l++;
  86921. v >>= 1;
  86922. }
  86923. return l+1;
  86924. }
  86925. else if(v == -1) {
  86926. return 2;
  86927. }
  86928. else {
  86929. v++;
  86930. v = -v;
  86931. }
  86932. }
  86933. }
  86934. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  86935. {
  86936. while(1) {
  86937. if(v == 0) {
  86938. return 0;
  86939. }
  86940. else if(v > 0) {
  86941. unsigned l = 0;
  86942. while(v) {
  86943. l++;
  86944. v >>= 1;
  86945. }
  86946. return l+1;
  86947. }
  86948. else if(v == -1) {
  86949. return 2;
  86950. }
  86951. else {
  86952. v++;
  86953. v = -v;
  86954. }
  86955. }
  86956. }
  86957. #endif
  86958. /********* End of inlined file: bitmath.c *********/
  86959. /********* Start of inlined file: bitreader.c *********/
  86960. /********* Start of inlined file: juce_FlacHeader.h *********/
  86961. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  86962. // tasks..
  86963. #define VERSION "1.2.1"
  86964. #define FLAC__NO_DLL 1
  86965. #ifdef _MSC_VER
  86966. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  86967. #endif
  86968. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  86969. #define FLAC__SYS_DARWIN 1
  86970. #endif
  86971. /********* End of inlined file: juce_FlacHeader.h *********/
  86972. #if JUCE_USE_FLAC
  86973. #if HAVE_CONFIG_H
  86974. # include <config.h>
  86975. #endif
  86976. #include <stdlib.h> /* for malloc() */
  86977. #include <string.h> /* for memcpy(), memset() */
  86978. #ifdef _MSC_VER
  86979. #include <winsock.h> /* for ntohl() */
  86980. #elif defined FLAC__SYS_DARWIN
  86981. #include <machine/endian.h> /* for ntohl() */
  86982. #elif defined __MINGW32__
  86983. #include <winsock.h> /* for ntohl() */
  86984. #else
  86985. #include <netinet/in.h> /* for ntohl() */
  86986. #endif
  86987. /********* Start of inlined file: bitreader.h *********/
  86988. #ifndef FLAC__PRIVATE__BITREADER_H
  86989. #define FLAC__PRIVATE__BITREADER_H
  86990. #include <stdio.h> /* for FILE */
  86991. /********* Start of inlined file: cpu.h *********/
  86992. #ifndef FLAC__PRIVATE__CPU_H
  86993. #define FLAC__PRIVATE__CPU_H
  86994. #ifdef HAVE_CONFIG_H
  86995. #include <config.h>
  86996. #endif
  86997. typedef enum {
  86998. FLAC__CPUINFO_TYPE_IA32,
  86999. FLAC__CPUINFO_TYPE_PPC,
  87000. FLAC__CPUINFO_TYPE_UNKNOWN
  87001. } FLAC__CPUInfo_Type;
  87002. typedef struct {
  87003. FLAC__bool cpuid;
  87004. FLAC__bool bswap;
  87005. FLAC__bool cmov;
  87006. FLAC__bool mmx;
  87007. FLAC__bool fxsr;
  87008. FLAC__bool sse;
  87009. FLAC__bool sse2;
  87010. FLAC__bool sse3;
  87011. FLAC__bool ssse3;
  87012. FLAC__bool _3dnow;
  87013. FLAC__bool ext3dnow;
  87014. FLAC__bool extmmx;
  87015. } FLAC__CPUInfo_IA32;
  87016. typedef struct {
  87017. FLAC__bool altivec;
  87018. FLAC__bool ppc64;
  87019. } FLAC__CPUInfo_PPC;
  87020. typedef struct {
  87021. FLAC__bool use_asm;
  87022. FLAC__CPUInfo_Type type;
  87023. union {
  87024. FLAC__CPUInfo_IA32 ia32;
  87025. FLAC__CPUInfo_PPC ppc;
  87026. } data;
  87027. } FLAC__CPUInfo;
  87028. void FLAC__cpu_info(FLAC__CPUInfo *info);
  87029. #ifndef FLAC__NO_ASM
  87030. #ifdef FLAC__CPU_IA32
  87031. #ifdef FLAC__HAS_NASM
  87032. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  87033. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  87034. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  87035. #endif
  87036. #endif
  87037. #endif
  87038. #endif
  87039. /********* End of inlined file: cpu.h *********/
  87040. /*
  87041. * opaque structure definition
  87042. */
  87043. struct FLAC__BitReader;
  87044. typedef struct FLAC__BitReader FLAC__BitReader;
  87045. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  87046. /*
  87047. * construction, deletion, initialization, etc functions
  87048. */
  87049. FLAC__BitReader *FLAC__bitreader_new(void);
  87050. void FLAC__bitreader_delete(FLAC__BitReader *br);
  87051. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  87052. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  87053. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  87054. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  87055. /*
  87056. * CRC functions
  87057. */
  87058. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  87059. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  87060. /*
  87061. * info functions
  87062. */
  87063. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  87064. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  87065. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  87066. /*
  87067. * read functions
  87068. */
  87069. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  87070. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  87071. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  87072. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  87073. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  87074. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  87075. 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! */
  87076. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  87077. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  87078. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  87079. #ifndef FLAC__NO_ASM
  87080. # ifdef FLAC__CPU_IA32
  87081. # ifdef FLAC__HAS_NASM
  87082. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  87083. # endif
  87084. # endif
  87085. #endif
  87086. #if 0 /* UNUSED */
  87087. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  87088. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  87089. #endif
  87090. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  87091. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  87092. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  87093. #endif
  87094. /********* End of inlined file: bitreader.h *********/
  87095. /********* Start of inlined file: crc.h *********/
  87096. #ifndef FLAC__PRIVATE__CRC_H
  87097. #define FLAC__PRIVATE__CRC_H
  87098. /* 8 bit CRC generator, MSB shifted first
  87099. ** polynomial = x^8 + x^2 + x^1 + x^0
  87100. ** init = 0
  87101. */
  87102. extern FLAC__byte const FLAC__crc8_table[256];
  87103. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  87104. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  87105. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  87106. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  87107. /* 16 bit CRC generator, MSB shifted first
  87108. ** polynomial = x^16 + x^15 + x^2 + x^0
  87109. ** init = 0
  87110. */
  87111. extern unsigned FLAC__crc16_table[256];
  87112. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  87113. /* this alternate may be faster on some systems/compilers */
  87114. #if 0
  87115. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  87116. #endif
  87117. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  87118. #endif
  87119. /********* End of inlined file: crc.h *********/
  87120. /* Things should be fastest when this matches the machine word size */
  87121. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  87122. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  87123. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  87124. typedef FLAC__uint32 brword;
  87125. #define FLAC__BYTES_PER_WORD 4
  87126. #define FLAC__BITS_PER_WORD 32
  87127. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  87128. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  87129. #if WORDS_BIGENDIAN
  87130. #define SWAP_BE_WORD_TO_HOST(x) (x)
  87131. #else
  87132. #if defined (_MSC_VER) && defined (_X86_)
  87133. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  87134. #else
  87135. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  87136. #endif
  87137. #endif
  87138. /* counts the # of zero MSBs in a word */
  87139. #define COUNT_ZERO_MSBS(word) ( \
  87140. (word) <= 0xffff ? \
  87141. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  87142. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  87143. )
  87144. /* this alternate might be slightly faster on some systems/compilers: */
  87145. #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])) )
  87146. /*
  87147. * This should be at least twice as large as the largest number of words
  87148. * required to represent any 'number' (in any encoding) you are going to
  87149. * read. With FLAC this is on the order of maybe a few hundred bits.
  87150. * If the buffer is smaller than that, the decoder won't be able to read
  87151. * in a whole number that is in a variable length encoding (e.g. Rice).
  87152. * But to be practical it should be at least 1K bytes.
  87153. *
  87154. * Increase this number to decrease the number of read callbacks, at the
  87155. * expense of using more memory. Or decrease for the reverse effect,
  87156. * keeping in mind the limit from the first paragraph. The optimal size
  87157. * also depends on the CPU cache size and other factors; some twiddling
  87158. * may be necessary to squeeze out the best performance.
  87159. */
  87160. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  87161. static const unsigned char byte_to_unary_table[] = {
  87162. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  87163. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  87164. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  87165. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  87166. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87167. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87168. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87169. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  87178. };
  87179. #ifdef min
  87180. #undef min
  87181. #endif
  87182. #define min(x,y) ((x)<(y)?(x):(y))
  87183. #ifdef max
  87184. #undef max
  87185. #endif
  87186. #define max(x,y) ((x)>(y)?(x):(y))
  87187. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  87188. #ifdef _MSC_VER
  87189. #define FLAC__U64L(x) x
  87190. #else
  87191. #define FLAC__U64L(x) x##LLU
  87192. #endif
  87193. #ifndef FLaC__INLINE
  87194. #define FLaC__INLINE
  87195. #endif
  87196. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  87197. struct FLAC__BitReader {
  87198. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  87199. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  87200. brword *buffer;
  87201. unsigned capacity; /* in words */
  87202. unsigned words; /* # of completed words in buffer */
  87203. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  87204. unsigned consumed_words; /* #words ... */
  87205. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  87206. unsigned read_crc16; /* the running frame CRC */
  87207. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  87208. FLAC__BitReaderReadCallback read_callback;
  87209. void *client_data;
  87210. FLAC__CPUInfo cpu_info;
  87211. };
  87212. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  87213. {
  87214. register unsigned crc = br->read_crc16;
  87215. #if FLAC__BYTES_PER_WORD == 4
  87216. switch(br->crc16_align) {
  87217. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  87218. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  87219. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  87220. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  87221. }
  87222. #elif FLAC__BYTES_PER_WORD == 8
  87223. switch(br->crc16_align) {
  87224. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  87225. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  87226. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  87227. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  87228. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  87229. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  87230. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  87231. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  87232. }
  87233. #else
  87234. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  87235. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  87236. br->read_crc16 = crc;
  87237. #endif
  87238. br->crc16_align = 0;
  87239. }
  87240. /* would be static except it needs to be called by asm routines */
  87241. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  87242. {
  87243. unsigned start, end;
  87244. size_t bytes;
  87245. FLAC__byte *target;
  87246. /* first shift the unconsumed buffer data toward the front as much as possible */
  87247. if(br->consumed_words > 0) {
  87248. start = br->consumed_words;
  87249. end = br->words + (br->bytes? 1:0);
  87250. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  87251. br->words -= start;
  87252. br->consumed_words = 0;
  87253. }
  87254. /*
  87255. * set the target for reading, taking into account word alignment and endianness
  87256. */
  87257. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  87258. if(bytes == 0)
  87259. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  87260. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  87261. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  87262. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  87263. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  87264. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  87265. * ^^-------target, bytes=3
  87266. * on LE machines, have to byteswap the odd tail word so nothing is
  87267. * overwritten:
  87268. */
  87269. #if WORDS_BIGENDIAN
  87270. #else
  87271. if(br->bytes)
  87272. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  87273. #endif
  87274. /* now it looks like:
  87275. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  87276. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  87277. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  87278. * ^^-------target, bytes=3
  87279. */
  87280. /* read in the data; note that the callback may return a smaller number of bytes */
  87281. if(!br->read_callback(target, &bytes, br->client_data))
  87282. return false;
  87283. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  87284. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  87285. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  87286. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  87287. * now have to byteswap on LE machines:
  87288. */
  87289. #if WORDS_BIGENDIAN
  87290. #else
  87291. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  87292. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  87293. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  87294. start = br->words;
  87295. local_swap32_block_(br->buffer + start, end - start);
  87296. }
  87297. else
  87298. # endif
  87299. for(start = br->words; start < end; start++)
  87300. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  87301. #endif
  87302. /* now it looks like:
  87303. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  87304. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  87305. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  87306. * finally we'll update the reader values:
  87307. */
  87308. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  87309. br->words = end / FLAC__BYTES_PER_WORD;
  87310. br->bytes = end % FLAC__BYTES_PER_WORD;
  87311. return true;
  87312. }
  87313. /***********************************************************************
  87314. *
  87315. * Class constructor/destructor
  87316. *
  87317. ***********************************************************************/
  87318. FLAC__BitReader *FLAC__bitreader_new(void)
  87319. {
  87320. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  87321. /* calloc() implies:
  87322. memset(br, 0, sizeof(FLAC__BitReader));
  87323. br->buffer = 0;
  87324. br->capacity = 0;
  87325. br->words = br->bytes = 0;
  87326. br->consumed_words = br->consumed_bits = 0;
  87327. br->read_callback = 0;
  87328. br->client_data = 0;
  87329. */
  87330. return br;
  87331. }
  87332. void FLAC__bitreader_delete(FLAC__BitReader *br)
  87333. {
  87334. FLAC__ASSERT(0 != br);
  87335. FLAC__bitreader_free(br);
  87336. free(br);
  87337. }
  87338. /***********************************************************************
  87339. *
  87340. * Public class methods
  87341. *
  87342. ***********************************************************************/
  87343. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  87344. {
  87345. FLAC__ASSERT(0 != br);
  87346. br->words = br->bytes = 0;
  87347. br->consumed_words = br->consumed_bits = 0;
  87348. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  87349. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  87350. if(br->buffer == 0)
  87351. return false;
  87352. br->read_callback = rcb;
  87353. br->client_data = cd;
  87354. br->cpu_info = cpu;
  87355. return true;
  87356. }
  87357. void FLAC__bitreader_free(FLAC__BitReader *br)
  87358. {
  87359. FLAC__ASSERT(0 != br);
  87360. if(0 != br->buffer)
  87361. free(br->buffer);
  87362. br->buffer = 0;
  87363. br->capacity = 0;
  87364. br->words = br->bytes = 0;
  87365. br->consumed_words = br->consumed_bits = 0;
  87366. br->read_callback = 0;
  87367. br->client_data = 0;
  87368. }
  87369. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  87370. {
  87371. br->words = br->bytes = 0;
  87372. br->consumed_words = br->consumed_bits = 0;
  87373. return true;
  87374. }
  87375. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  87376. {
  87377. unsigned i, j;
  87378. if(br == 0) {
  87379. fprintf(out, "bitreader is NULL\n");
  87380. }
  87381. else {
  87382. 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);
  87383. for(i = 0; i < br->words; i++) {
  87384. fprintf(out, "%08X: ", i);
  87385. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  87386. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  87387. fprintf(out, ".");
  87388. else
  87389. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  87390. fprintf(out, "\n");
  87391. }
  87392. if(br->bytes > 0) {
  87393. fprintf(out, "%08X: ", i);
  87394. for(j = 0; j < br->bytes*8; j++)
  87395. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  87396. fprintf(out, ".");
  87397. else
  87398. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  87399. fprintf(out, "\n");
  87400. }
  87401. }
  87402. }
  87403. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  87404. {
  87405. FLAC__ASSERT(0 != br);
  87406. FLAC__ASSERT(0 != br->buffer);
  87407. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  87408. br->read_crc16 = (unsigned)seed;
  87409. br->crc16_align = br->consumed_bits;
  87410. }
  87411. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  87412. {
  87413. FLAC__ASSERT(0 != br);
  87414. FLAC__ASSERT(0 != br->buffer);
  87415. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  87416. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  87417. /* CRC any tail bytes in a partially-consumed word */
  87418. if(br->consumed_bits) {
  87419. const brword tail = br->buffer[br->consumed_words];
  87420. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  87421. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  87422. }
  87423. return br->read_crc16;
  87424. }
  87425. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  87426. {
  87427. return ((br->consumed_bits & 7) == 0);
  87428. }
  87429. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  87430. {
  87431. return 8 - (br->consumed_bits & 7);
  87432. }
  87433. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  87434. {
  87435. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  87436. }
  87437. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  87438. {
  87439. FLAC__ASSERT(0 != br);
  87440. FLAC__ASSERT(0 != br->buffer);
  87441. FLAC__ASSERT(bits <= 32);
  87442. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  87443. FLAC__ASSERT(br->consumed_words <= br->words);
  87444. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  87445. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  87446. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  87447. *val = 0;
  87448. return true;
  87449. }
  87450. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  87451. if(!bitreader_read_from_client_(br))
  87452. return false;
  87453. }
  87454. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  87455. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  87456. if(br->consumed_bits) {
  87457. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87458. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  87459. const brword word = br->buffer[br->consumed_words];
  87460. if(bits < n) {
  87461. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  87462. br->consumed_bits += bits;
  87463. return true;
  87464. }
  87465. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  87466. bits -= n;
  87467. crc16_update_word_(br, word);
  87468. br->consumed_words++;
  87469. br->consumed_bits = 0;
  87470. 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 */
  87471. *val <<= bits;
  87472. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  87473. br->consumed_bits = bits;
  87474. }
  87475. return true;
  87476. }
  87477. else {
  87478. const brword word = br->buffer[br->consumed_words];
  87479. if(bits < FLAC__BITS_PER_WORD) {
  87480. *val = word >> (FLAC__BITS_PER_WORD-bits);
  87481. br->consumed_bits = bits;
  87482. return true;
  87483. }
  87484. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  87485. *val = word;
  87486. crc16_update_word_(br, word);
  87487. br->consumed_words++;
  87488. return true;
  87489. }
  87490. }
  87491. else {
  87492. /* in this case we're starting our read at a partial tail word;
  87493. * the reader has guaranteed that we have at least 'bits' bits
  87494. * available to read, which makes this case simpler.
  87495. */
  87496. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  87497. if(br->consumed_bits) {
  87498. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87499. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  87500. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  87501. br->consumed_bits += bits;
  87502. return true;
  87503. }
  87504. else {
  87505. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  87506. br->consumed_bits += bits;
  87507. return true;
  87508. }
  87509. }
  87510. }
  87511. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  87512. {
  87513. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  87514. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  87515. return false;
  87516. /* sign-extend: */
  87517. *val <<= (32-bits);
  87518. *val >>= (32-bits);
  87519. return true;
  87520. }
  87521. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  87522. {
  87523. FLAC__uint32 hi, lo;
  87524. if(bits > 32) {
  87525. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  87526. return false;
  87527. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  87528. return false;
  87529. *val = hi;
  87530. *val <<= 32;
  87531. *val |= lo;
  87532. }
  87533. else {
  87534. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  87535. return false;
  87536. *val = lo;
  87537. }
  87538. return true;
  87539. }
  87540. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  87541. {
  87542. FLAC__uint32 x8, x32 = 0;
  87543. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  87544. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  87545. return false;
  87546. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  87547. return false;
  87548. x32 |= (x8 << 8);
  87549. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  87550. return false;
  87551. x32 |= (x8 << 16);
  87552. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  87553. return false;
  87554. x32 |= (x8 << 24);
  87555. *val = x32;
  87556. return true;
  87557. }
  87558. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  87559. {
  87560. /*
  87561. * OPT: a faster implementation is possible but probably not that useful
  87562. * since this is only called a couple of times in the metadata readers.
  87563. */
  87564. FLAC__ASSERT(0 != br);
  87565. FLAC__ASSERT(0 != br->buffer);
  87566. if(bits > 0) {
  87567. const unsigned n = br->consumed_bits & 7;
  87568. unsigned m;
  87569. FLAC__uint32 x;
  87570. if(n != 0) {
  87571. m = min(8-n, bits);
  87572. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  87573. return false;
  87574. bits -= m;
  87575. }
  87576. m = bits / 8;
  87577. if(m > 0) {
  87578. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  87579. return false;
  87580. bits %= 8;
  87581. }
  87582. if(bits > 0) {
  87583. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  87584. return false;
  87585. }
  87586. }
  87587. return true;
  87588. }
  87589. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  87590. {
  87591. FLAC__uint32 x;
  87592. FLAC__ASSERT(0 != br);
  87593. FLAC__ASSERT(0 != br->buffer);
  87594. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  87595. /* step 1: skip over partial head word to get word aligned */
  87596. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  87597. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87598. return false;
  87599. nvals--;
  87600. }
  87601. if(0 == nvals)
  87602. return true;
  87603. /* step 2: skip whole words in chunks */
  87604. while(nvals >= FLAC__BYTES_PER_WORD) {
  87605. if(br->consumed_words < br->words) {
  87606. br->consumed_words++;
  87607. nvals -= FLAC__BYTES_PER_WORD;
  87608. }
  87609. else if(!bitreader_read_from_client_(br))
  87610. return false;
  87611. }
  87612. /* step 3: skip any remainder from partial tail bytes */
  87613. while(nvals) {
  87614. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87615. return false;
  87616. nvals--;
  87617. }
  87618. return true;
  87619. }
  87620. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  87621. {
  87622. FLAC__uint32 x;
  87623. FLAC__ASSERT(0 != br);
  87624. FLAC__ASSERT(0 != br->buffer);
  87625. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  87626. /* step 1: read from partial head word to get word aligned */
  87627. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  87628. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87629. return false;
  87630. *val++ = (FLAC__byte)x;
  87631. nvals--;
  87632. }
  87633. if(0 == nvals)
  87634. return true;
  87635. /* step 2: read whole words in chunks */
  87636. while(nvals >= FLAC__BYTES_PER_WORD) {
  87637. if(br->consumed_words < br->words) {
  87638. const brword word = br->buffer[br->consumed_words++];
  87639. #if FLAC__BYTES_PER_WORD == 4
  87640. val[0] = (FLAC__byte)(word >> 24);
  87641. val[1] = (FLAC__byte)(word >> 16);
  87642. val[2] = (FLAC__byte)(word >> 8);
  87643. val[3] = (FLAC__byte)word;
  87644. #elif FLAC__BYTES_PER_WORD == 8
  87645. val[0] = (FLAC__byte)(word >> 56);
  87646. val[1] = (FLAC__byte)(word >> 48);
  87647. val[2] = (FLAC__byte)(word >> 40);
  87648. val[3] = (FLAC__byte)(word >> 32);
  87649. val[4] = (FLAC__byte)(word >> 24);
  87650. val[5] = (FLAC__byte)(word >> 16);
  87651. val[6] = (FLAC__byte)(word >> 8);
  87652. val[7] = (FLAC__byte)word;
  87653. #else
  87654. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  87655. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  87656. #endif
  87657. val += FLAC__BYTES_PER_WORD;
  87658. nvals -= FLAC__BYTES_PER_WORD;
  87659. }
  87660. else if(!bitreader_read_from_client_(br))
  87661. return false;
  87662. }
  87663. /* step 3: read any remainder from partial tail bytes */
  87664. while(nvals) {
  87665. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87666. return false;
  87667. *val++ = (FLAC__byte)x;
  87668. nvals--;
  87669. }
  87670. return true;
  87671. }
  87672. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  87673. #if 0 /* slow but readable version */
  87674. {
  87675. unsigned bit;
  87676. FLAC__ASSERT(0 != br);
  87677. FLAC__ASSERT(0 != br->buffer);
  87678. *val = 0;
  87679. while(1) {
  87680. if(!FLAC__bitreader_read_bit(br, &bit))
  87681. return false;
  87682. if(bit)
  87683. break;
  87684. else
  87685. *val++;
  87686. }
  87687. return true;
  87688. }
  87689. #else
  87690. {
  87691. unsigned i;
  87692. FLAC__ASSERT(0 != br);
  87693. FLAC__ASSERT(0 != br->buffer);
  87694. *val = 0;
  87695. while(1) {
  87696. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  87697. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  87698. if(b) {
  87699. i = COUNT_ZERO_MSBS(b);
  87700. *val += i;
  87701. i++;
  87702. br->consumed_bits += i;
  87703. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  87704. crc16_update_word_(br, br->buffer[br->consumed_words]);
  87705. br->consumed_words++;
  87706. br->consumed_bits = 0;
  87707. }
  87708. return true;
  87709. }
  87710. else {
  87711. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  87712. crc16_update_word_(br, br->buffer[br->consumed_words]);
  87713. br->consumed_words++;
  87714. br->consumed_bits = 0;
  87715. /* didn't find stop bit yet, have to keep going... */
  87716. }
  87717. }
  87718. /* at this point we've eaten up all the whole words; have to try
  87719. * reading through any tail bytes before calling the read callback.
  87720. * this is a repeat of the above logic adjusted for the fact we
  87721. * don't have a whole word. note though if the client is feeding
  87722. * us data a byte at a time (unlikely), br->consumed_bits may not
  87723. * be zero.
  87724. */
  87725. if(br->bytes) {
  87726. const unsigned end = br->bytes * 8;
  87727. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  87728. if(b) {
  87729. i = COUNT_ZERO_MSBS(b);
  87730. *val += i;
  87731. i++;
  87732. br->consumed_bits += i;
  87733. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  87734. return true;
  87735. }
  87736. else {
  87737. *val += end - br->consumed_bits;
  87738. br->consumed_bits += end;
  87739. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  87740. /* didn't find stop bit yet, have to keep going... */
  87741. }
  87742. }
  87743. if(!bitreader_read_from_client_(br))
  87744. return false;
  87745. }
  87746. }
  87747. #endif
  87748. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  87749. {
  87750. FLAC__uint32 lsbs = 0, msbs = 0;
  87751. unsigned uval;
  87752. FLAC__ASSERT(0 != br);
  87753. FLAC__ASSERT(0 != br->buffer);
  87754. FLAC__ASSERT(parameter <= 31);
  87755. /* read the unary MSBs and end bit */
  87756. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  87757. return false;
  87758. /* read the binary LSBs */
  87759. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  87760. return false;
  87761. /* compose the value */
  87762. uval = (msbs << parameter) | lsbs;
  87763. if(uval & 1)
  87764. *val = -((int)(uval >> 1)) - 1;
  87765. else
  87766. *val = (int)(uval >> 1);
  87767. return true;
  87768. }
  87769. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  87770. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  87771. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  87772. /* OPT: possibly faster version for use with MSVC */
  87773. #ifdef _MSC_VER
  87774. {
  87775. unsigned i;
  87776. unsigned uval = 0;
  87777. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  87778. /* try and get br->consumed_words and br->consumed_bits into register;
  87779. * must remember to flush them back to *br before calling other
  87780. * bitwriter functions that use them, and before returning */
  87781. register unsigned cwords;
  87782. register unsigned cbits;
  87783. FLAC__ASSERT(0 != br);
  87784. FLAC__ASSERT(0 != br->buffer);
  87785. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  87786. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  87787. FLAC__ASSERT(parameter < 32);
  87788. /* 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 */
  87789. if(nvals == 0)
  87790. return true;
  87791. cbits = br->consumed_bits;
  87792. cwords = br->consumed_words;
  87793. while(1) {
  87794. /* read unary part */
  87795. while(1) {
  87796. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87797. brword b = br->buffer[cwords] << cbits;
  87798. if(b) {
  87799. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  87800. __asm {
  87801. bsr eax, b
  87802. not eax
  87803. and eax, 31
  87804. mov i, eax
  87805. }
  87806. #else
  87807. i = COUNT_ZERO_MSBS(b);
  87808. #endif
  87809. uval += i;
  87810. bits = parameter;
  87811. i++;
  87812. cbits += i;
  87813. if(cbits == FLAC__BITS_PER_WORD) {
  87814. crc16_update_word_(br, br->buffer[cwords]);
  87815. cwords++;
  87816. cbits = 0;
  87817. }
  87818. goto break1;
  87819. }
  87820. else {
  87821. uval += FLAC__BITS_PER_WORD - cbits;
  87822. crc16_update_word_(br, br->buffer[cwords]);
  87823. cwords++;
  87824. cbits = 0;
  87825. /* didn't find stop bit yet, have to keep going... */
  87826. }
  87827. }
  87828. /* at this point we've eaten up all the whole words; have to try
  87829. * reading through any tail bytes before calling the read callback.
  87830. * this is a repeat of the above logic adjusted for the fact we
  87831. * don't have a whole word. note though if the client is feeding
  87832. * us data a byte at a time (unlikely), br->consumed_bits may not
  87833. * be zero.
  87834. */
  87835. if(br->bytes) {
  87836. const unsigned end = br->bytes * 8;
  87837. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  87838. if(b) {
  87839. i = COUNT_ZERO_MSBS(b);
  87840. uval += i;
  87841. bits = parameter;
  87842. i++;
  87843. cbits += i;
  87844. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87845. goto break1;
  87846. }
  87847. else {
  87848. uval += end - cbits;
  87849. cbits += end;
  87850. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87851. /* didn't find stop bit yet, have to keep going... */
  87852. }
  87853. }
  87854. /* flush registers and read; bitreader_read_from_client_() does
  87855. * not touch br->consumed_bits at all but we still need to set
  87856. * it in case it fails and we have to return false.
  87857. */
  87858. br->consumed_bits = cbits;
  87859. br->consumed_words = cwords;
  87860. if(!bitreader_read_from_client_(br))
  87861. return false;
  87862. cwords = br->consumed_words;
  87863. }
  87864. break1:
  87865. /* read binary part */
  87866. FLAC__ASSERT(cwords <= br->words);
  87867. if(bits) {
  87868. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  87869. /* flush registers and read; bitreader_read_from_client_() does
  87870. * not touch br->consumed_bits at all but we still need to set
  87871. * it in case it fails and we have to return false.
  87872. */
  87873. br->consumed_bits = cbits;
  87874. br->consumed_words = cwords;
  87875. if(!bitreader_read_from_client_(br))
  87876. return false;
  87877. cwords = br->consumed_words;
  87878. }
  87879. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87880. if(cbits) {
  87881. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87882. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  87883. const brword word = br->buffer[cwords];
  87884. if(bits < n) {
  87885. uval <<= bits;
  87886. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  87887. cbits += bits;
  87888. goto break2;
  87889. }
  87890. uval <<= n;
  87891. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  87892. bits -= n;
  87893. crc16_update_word_(br, word);
  87894. cwords++;
  87895. cbits = 0;
  87896. 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 */
  87897. uval <<= bits;
  87898. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  87899. cbits = bits;
  87900. }
  87901. goto break2;
  87902. }
  87903. else {
  87904. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  87905. uval <<= bits;
  87906. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  87907. cbits = bits;
  87908. goto break2;
  87909. }
  87910. }
  87911. else {
  87912. /* in this case we're starting our read at a partial tail word;
  87913. * the reader has guaranteed that we have at least 'bits' bits
  87914. * available to read, which makes this case simpler.
  87915. */
  87916. uval <<= bits;
  87917. if(cbits) {
  87918. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87919. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  87920. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  87921. cbits += bits;
  87922. goto break2;
  87923. }
  87924. else {
  87925. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  87926. cbits += bits;
  87927. goto break2;
  87928. }
  87929. }
  87930. }
  87931. break2:
  87932. /* compose the value */
  87933. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  87934. /* are we done? */
  87935. --nvals;
  87936. if(nvals == 0) {
  87937. br->consumed_bits = cbits;
  87938. br->consumed_words = cwords;
  87939. return true;
  87940. }
  87941. uval = 0;
  87942. ++vals;
  87943. }
  87944. }
  87945. #else
  87946. {
  87947. unsigned i;
  87948. unsigned uval = 0;
  87949. /* try and get br->consumed_words and br->consumed_bits into register;
  87950. * must remember to flush them back to *br before calling other
  87951. * bitwriter functions that use them, and before returning */
  87952. register unsigned cwords;
  87953. register unsigned cbits;
  87954. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  87955. FLAC__ASSERT(0 != br);
  87956. FLAC__ASSERT(0 != br->buffer);
  87957. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  87958. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  87959. FLAC__ASSERT(parameter < 32);
  87960. /* 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 */
  87961. if(nvals == 0)
  87962. return true;
  87963. cbits = br->consumed_bits;
  87964. cwords = br->consumed_words;
  87965. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  87966. while(1) {
  87967. /* read unary part */
  87968. while(1) {
  87969. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87970. brword b = br->buffer[cwords] << cbits;
  87971. if(b) {
  87972. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  87973. asm volatile (
  87974. "bsrl %1, %0;"
  87975. "notl %0;"
  87976. "andl $31, %0;"
  87977. : "=r"(i)
  87978. : "r"(b)
  87979. );
  87980. #else
  87981. i = COUNT_ZERO_MSBS(b);
  87982. #endif
  87983. uval += i;
  87984. cbits += i;
  87985. cbits++; /* skip over stop bit */
  87986. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  87987. crc16_update_word_(br, br->buffer[cwords]);
  87988. cwords++;
  87989. cbits = 0;
  87990. }
  87991. goto break1;
  87992. }
  87993. else {
  87994. uval += FLAC__BITS_PER_WORD - cbits;
  87995. crc16_update_word_(br, br->buffer[cwords]);
  87996. cwords++;
  87997. cbits = 0;
  87998. /* didn't find stop bit yet, have to keep going... */
  87999. }
  88000. }
  88001. /* at this point we've eaten up all the whole words; have to try
  88002. * reading through any tail bytes before calling the read callback.
  88003. * this is a repeat of the above logic adjusted for the fact we
  88004. * don't have a whole word. note though if the client is feeding
  88005. * us data a byte at a time (unlikely), br->consumed_bits may not
  88006. * be zero.
  88007. */
  88008. if(br->bytes) {
  88009. const unsigned end = br->bytes * 8;
  88010. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  88011. if(b) {
  88012. i = COUNT_ZERO_MSBS(b);
  88013. uval += i;
  88014. cbits += i;
  88015. cbits++; /* skip over stop bit */
  88016. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  88017. goto break1;
  88018. }
  88019. else {
  88020. uval += end - cbits;
  88021. cbits += end;
  88022. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  88023. /* didn't find stop bit yet, have to keep going... */
  88024. }
  88025. }
  88026. /* flush registers and read; bitreader_read_from_client_() does
  88027. * not touch br->consumed_bits at all but we still need to set
  88028. * it in case it fails and we have to return false.
  88029. */
  88030. br->consumed_bits = cbits;
  88031. br->consumed_words = cwords;
  88032. if(!bitreader_read_from_client_(br))
  88033. return false;
  88034. cwords = br->consumed_words;
  88035. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  88036. /* + uval to offset our count by the # of unary bits already
  88037. * consumed before the read, because we will add these back
  88038. * in all at once at break1
  88039. */
  88040. }
  88041. break1:
  88042. ucbits -= uval;
  88043. ucbits--; /* account for stop bit */
  88044. /* read binary part */
  88045. FLAC__ASSERT(cwords <= br->words);
  88046. if(parameter) {
  88047. while(ucbits < parameter) {
  88048. /* flush registers and read; bitreader_read_from_client_() does
  88049. * not touch br->consumed_bits at all but we still need to set
  88050. * it in case it fails and we have to return false.
  88051. */
  88052. br->consumed_bits = cbits;
  88053. br->consumed_words = cwords;
  88054. if(!bitreader_read_from_client_(br))
  88055. return false;
  88056. cwords = br->consumed_words;
  88057. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  88058. }
  88059. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  88060. if(cbits) {
  88061. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  88062. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  88063. const brword word = br->buffer[cwords];
  88064. if(parameter < n) {
  88065. uval <<= parameter;
  88066. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  88067. cbits += parameter;
  88068. }
  88069. else {
  88070. uval <<= n;
  88071. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  88072. crc16_update_word_(br, word);
  88073. cwords++;
  88074. cbits = parameter - n;
  88075. 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 */
  88076. uval <<= cbits;
  88077. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  88078. }
  88079. }
  88080. }
  88081. else {
  88082. cbits = parameter;
  88083. uval <<= parameter;
  88084. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  88085. }
  88086. }
  88087. else {
  88088. /* in this case we're starting our read at a partial tail word;
  88089. * the reader has guaranteed that we have at least 'parameter'
  88090. * bits available to read, which makes this case simpler.
  88091. */
  88092. uval <<= parameter;
  88093. if(cbits) {
  88094. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88095. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  88096. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  88097. cbits += parameter;
  88098. }
  88099. else {
  88100. cbits = parameter;
  88101. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  88102. }
  88103. }
  88104. }
  88105. ucbits -= parameter;
  88106. /* compose the value */
  88107. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  88108. /* are we done? */
  88109. --nvals;
  88110. if(nvals == 0) {
  88111. br->consumed_bits = cbits;
  88112. br->consumed_words = cwords;
  88113. return true;
  88114. }
  88115. uval = 0;
  88116. ++vals;
  88117. }
  88118. }
  88119. #endif
  88120. #if 0 /* UNUSED */
  88121. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  88122. {
  88123. FLAC__uint32 lsbs = 0, msbs = 0;
  88124. unsigned bit, uval, k;
  88125. FLAC__ASSERT(0 != br);
  88126. FLAC__ASSERT(0 != br->buffer);
  88127. k = FLAC__bitmath_ilog2(parameter);
  88128. /* read the unary MSBs and end bit */
  88129. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  88130. return false;
  88131. /* read the binary LSBs */
  88132. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  88133. return false;
  88134. if(parameter == 1u<<k) {
  88135. /* compose the value */
  88136. uval = (msbs << k) | lsbs;
  88137. }
  88138. else {
  88139. unsigned d = (1 << (k+1)) - parameter;
  88140. if(lsbs >= d) {
  88141. if(!FLAC__bitreader_read_bit(br, &bit))
  88142. return false;
  88143. lsbs <<= 1;
  88144. lsbs |= bit;
  88145. lsbs -= d;
  88146. }
  88147. /* compose the value */
  88148. uval = msbs * parameter + lsbs;
  88149. }
  88150. /* unfold unsigned to signed */
  88151. if(uval & 1)
  88152. *val = -((int)(uval >> 1)) - 1;
  88153. else
  88154. *val = (int)(uval >> 1);
  88155. return true;
  88156. }
  88157. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  88158. {
  88159. FLAC__uint32 lsbs, msbs = 0;
  88160. unsigned bit, k;
  88161. FLAC__ASSERT(0 != br);
  88162. FLAC__ASSERT(0 != br->buffer);
  88163. k = FLAC__bitmath_ilog2(parameter);
  88164. /* read the unary MSBs and end bit */
  88165. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  88166. return false;
  88167. /* read the binary LSBs */
  88168. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  88169. return false;
  88170. if(parameter == 1u<<k) {
  88171. /* compose the value */
  88172. *val = (msbs << k) | lsbs;
  88173. }
  88174. else {
  88175. unsigned d = (1 << (k+1)) - parameter;
  88176. if(lsbs >= d) {
  88177. if(!FLAC__bitreader_read_bit(br, &bit))
  88178. return false;
  88179. lsbs <<= 1;
  88180. lsbs |= bit;
  88181. lsbs -= d;
  88182. }
  88183. /* compose the value */
  88184. *val = msbs * parameter + lsbs;
  88185. }
  88186. return true;
  88187. }
  88188. #endif /* UNUSED */
  88189. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  88190. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  88191. {
  88192. FLAC__uint32 v = 0;
  88193. FLAC__uint32 x;
  88194. unsigned i;
  88195. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88196. return false;
  88197. if(raw)
  88198. raw[(*rawlen)++] = (FLAC__byte)x;
  88199. if(!(x & 0x80)) { /* 0xxxxxxx */
  88200. v = x;
  88201. i = 0;
  88202. }
  88203. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  88204. v = x & 0x1F;
  88205. i = 1;
  88206. }
  88207. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  88208. v = x & 0x0F;
  88209. i = 2;
  88210. }
  88211. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  88212. v = x & 0x07;
  88213. i = 3;
  88214. }
  88215. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  88216. v = x & 0x03;
  88217. i = 4;
  88218. }
  88219. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  88220. v = x & 0x01;
  88221. i = 5;
  88222. }
  88223. else {
  88224. *val = 0xffffffff;
  88225. return true;
  88226. }
  88227. for( ; i; i--) {
  88228. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88229. return false;
  88230. if(raw)
  88231. raw[(*rawlen)++] = (FLAC__byte)x;
  88232. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  88233. *val = 0xffffffff;
  88234. return true;
  88235. }
  88236. v <<= 6;
  88237. v |= (x & 0x3F);
  88238. }
  88239. *val = v;
  88240. return true;
  88241. }
  88242. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  88243. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  88244. {
  88245. FLAC__uint64 v = 0;
  88246. FLAC__uint32 x;
  88247. unsigned i;
  88248. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88249. return false;
  88250. if(raw)
  88251. raw[(*rawlen)++] = (FLAC__byte)x;
  88252. if(!(x & 0x80)) { /* 0xxxxxxx */
  88253. v = x;
  88254. i = 0;
  88255. }
  88256. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  88257. v = x & 0x1F;
  88258. i = 1;
  88259. }
  88260. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  88261. v = x & 0x0F;
  88262. i = 2;
  88263. }
  88264. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  88265. v = x & 0x07;
  88266. i = 3;
  88267. }
  88268. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  88269. v = x & 0x03;
  88270. i = 4;
  88271. }
  88272. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  88273. v = x & 0x01;
  88274. i = 5;
  88275. }
  88276. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  88277. v = 0;
  88278. i = 6;
  88279. }
  88280. else {
  88281. *val = FLAC__U64L(0xffffffffffffffff);
  88282. return true;
  88283. }
  88284. for( ; i; i--) {
  88285. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88286. return false;
  88287. if(raw)
  88288. raw[(*rawlen)++] = (FLAC__byte)x;
  88289. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  88290. *val = FLAC__U64L(0xffffffffffffffff);
  88291. return true;
  88292. }
  88293. v <<= 6;
  88294. v |= (x & 0x3F);
  88295. }
  88296. *val = v;
  88297. return true;
  88298. }
  88299. #endif
  88300. /********* End of inlined file: bitreader.c *********/
  88301. /********* Start of inlined file: bitwriter.c *********/
  88302. /********* Start of inlined file: juce_FlacHeader.h *********/
  88303. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  88304. // tasks..
  88305. #define VERSION "1.2.1"
  88306. #define FLAC__NO_DLL 1
  88307. #ifdef _MSC_VER
  88308. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  88309. #endif
  88310. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  88311. #define FLAC__SYS_DARWIN 1
  88312. #endif
  88313. /********* End of inlined file: juce_FlacHeader.h *********/
  88314. #if JUCE_USE_FLAC
  88315. #if HAVE_CONFIG_H
  88316. # include <config.h>
  88317. #endif
  88318. #include <stdlib.h> /* for malloc() */
  88319. #include <string.h> /* for memcpy(), memset() */
  88320. #ifdef _MSC_VER
  88321. #include <winsock.h> /* for ntohl() */
  88322. #elif defined FLAC__SYS_DARWIN
  88323. #include <machine/endian.h> /* for ntohl() */
  88324. #elif defined __MINGW32__
  88325. #include <winsock.h> /* for ntohl() */
  88326. #else
  88327. #include <netinet/in.h> /* for ntohl() */
  88328. #endif
  88329. #if 0 /* UNUSED */
  88330. #endif
  88331. /********* Start of inlined file: bitwriter.h *********/
  88332. #ifndef FLAC__PRIVATE__BITWRITER_H
  88333. #define FLAC__PRIVATE__BITWRITER_H
  88334. #include <stdio.h> /* for FILE */
  88335. /*
  88336. * opaque structure definition
  88337. */
  88338. struct FLAC__BitWriter;
  88339. typedef struct FLAC__BitWriter FLAC__BitWriter;
  88340. /*
  88341. * construction, deletion, initialization, etc functions
  88342. */
  88343. FLAC__BitWriter *FLAC__bitwriter_new(void);
  88344. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  88345. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  88346. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  88347. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  88348. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  88349. /*
  88350. * CRC functions
  88351. *
  88352. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  88353. */
  88354. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  88355. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  88356. /*
  88357. * info functions
  88358. */
  88359. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  88360. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  88361. /*
  88362. * direct buffer access
  88363. *
  88364. * there may be no calls on the bitwriter between get and release.
  88365. * the bitwriter continues to own the returned buffer.
  88366. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  88367. */
  88368. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  88369. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  88370. /*
  88371. * write functions
  88372. */
  88373. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  88374. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  88375. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  88376. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  88377. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  88378. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  88379. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  88380. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  88381. #if 0 /* UNUSED */
  88382. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  88383. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  88384. #endif
  88385. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  88386. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  88387. #if 0 /* UNUSED */
  88388. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  88389. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  88390. #endif
  88391. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  88392. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  88393. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  88394. #endif
  88395. /********* End of inlined file: bitwriter.h *********/
  88396. /********* Start of inlined file: alloc.h *********/
  88397. #ifndef FLAC__SHARE__ALLOC_H
  88398. #define FLAC__SHARE__ALLOC_H
  88399. #if HAVE_CONFIG_H
  88400. # include <config.h>
  88401. #endif
  88402. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  88403. * before #including this file, otherwise SIZE_MAX might not be defined
  88404. */
  88405. #include <limits.h> /* for SIZE_MAX */
  88406. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  88407. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  88408. #endif
  88409. #include <stdlib.h> /* for size_t, malloc(), etc */
  88410. #ifndef SIZE_MAX
  88411. # ifndef SIZE_T_MAX
  88412. # ifdef _MSC_VER
  88413. # define SIZE_T_MAX UINT_MAX
  88414. # else
  88415. # error
  88416. # endif
  88417. # endif
  88418. # define SIZE_MAX SIZE_T_MAX
  88419. #endif
  88420. #ifndef FLaC__INLINE
  88421. #define FLaC__INLINE
  88422. #endif
  88423. /* avoid malloc()ing 0 bytes, see:
  88424. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  88425. */
  88426. static FLaC__INLINE void *safe_malloc_(size_t size)
  88427. {
  88428. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  88429. if(!size)
  88430. size++;
  88431. return malloc(size);
  88432. }
  88433. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  88434. {
  88435. if(!nmemb || !size)
  88436. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  88437. return calloc(nmemb, size);
  88438. }
  88439. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  88440. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  88441. {
  88442. size2 += size1;
  88443. if(size2 < size1)
  88444. return 0;
  88445. return safe_malloc_(size2);
  88446. }
  88447. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  88448. {
  88449. size2 += size1;
  88450. if(size2 < size1)
  88451. return 0;
  88452. size3 += size2;
  88453. if(size3 < size2)
  88454. return 0;
  88455. return safe_malloc_(size3);
  88456. }
  88457. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  88458. {
  88459. size2 += size1;
  88460. if(size2 < size1)
  88461. return 0;
  88462. size3 += size2;
  88463. if(size3 < size2)
  88464. return 0;
  88465. size4 += size3;
  88466. if(size4 < size3)
  88467. return 0;
  88468. return safe_malloc_(size4);
  88469. }
  88470. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  88471. #if 0
  88472. needs support for cases where sizeof(size_t) != 4
  88473. {
  88474. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  88475. if(sizeof(size_t) == 4) {
  88476. if ((double)size1 * (double)size2 < 4294967296.0)
  88477. return malloc(size1*size2);
  88478. }
  88479. return 0;
  88480. }
  88481. #else
  88482. /* better? */
  88483. {
  88484. if(!size1 || !size2)
  88485. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  88486. if(size1 > SIZE_MAX / size2)
  88487. return 0;
  88488. return malloc(size1*size2);
  88489. }
  88490. #endif
  88491. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  88492. {
  88493. if(!size1 || !size2 || !size3)
  88494. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  88495. if(size1 > SIZE_MAX / size2)
  88496. return 0;
  88497. size1 *= size2;
  88498. if(size1 > SIZE_MAX / size3)
  88499. return 0;
  88500. return malloc(size1*size3);
  88501. }
  88502. /* size1*size2 + size3 */
  88503. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  88504. {
  88505. if(!size1 || !size2)
  88506. return safe_malloc_(size3);
  88507. if(size1 > SIZE_MAX / size2)
  88508. return 0;
  88509. return safe_malloc_add_2op_(size1*size2, size3);
  88510. }
  88511. /* size1 * (size2 + size3) */
  88512. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  88513. {
  88514. if(!size1 || (!size2 && !size3))
  88515. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  88516. size2 += size3;
  88517. if(size2 < size3)
  88518. return 0;
  88519. return safe_malloc_mul_2op_(size1, size2);
  88520. }
  88521. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  88522. {
  88523. size2 += size1;
  88524. if(size2 < size1)
  88525. return 0;
  88526. return realloc(ptr, size2);
  88527. }
  88528. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  88529. {
  88530. size2 += size1;
  88531. if(size2 < size1)
  88532. return 0;
  88533. size3 += size2;
  88534. if(size3 < size2)
  88535. return 0;
  88536. return realloc(ptr, size3);
  88537. }
  88538. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  88539. {
  88540. size2 += size1;
  88541. if(size2 < size1)
  88542. return 0;
  88543. size3 += size2;
  88544. if(size3 < size2)
  88545. return 0;
  88546. size4 += size3;
  88547. if(size4 < size3)
  88548. return 0;
  88549. return realloc(ptr, size4);
  88550. }
  88551. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  88552. {
  88553. if(!size1 || !size2)
  88554. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  88555. if(size1 > SIZE_MAX / size2)
  88556. return 0;
  88557. return realloc(ptr, size1*size2);
  88558. }
  88559. /* size1 * (size2 + size3) */
  88560. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  88561. {
  88562. if(!size1 || (!size2 && !size3))
  88563. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  88564. size2 += size3;
  88565. if(size2 < size3)
  88566. return 0;
  88567. return safe_realloc_mul_2op_(ptr, size1, size2);
  88568. }
  88569. #endif
  88570. /********* End of inlined file: alloc.h *********/
  88571. /* Things should be fastest when this matches the machine word size */
  88572. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  88573. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  88574. typedef FLAC__uint32 bwword;
  88575. #define FLAC__BYTES_PER_WORD 4
  88576. #define FLAC__BITS_PER_WORD 32
  88577. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  88578. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  88579. #if WORDS_BIGENDIAN
  88580. #define SWAP_BE_WORD_TO_HOST(x) (x)
  88581. #else
  88582. #ifdef _MSC_VER
  88583. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  88584. #else
  88585. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  88586. #endif
  88587. #endif
  88588. /*
  88589. * The default capacity here doesn't matter too much. The buffer always grows
  88590. * to hold whatever is written to it. Usually the encoder will stop adding at
  88591. * a frame or metadata block, then write that out and clear the buffer for the
  88592. * next one.
  88593. */
  88594. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  88595. /* When growing, increment 4K at a time */
  88596. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  88597. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  88598. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  88599. #ifdef min
  88600. #undef min
  88601. #endif
  88602. #define min(x,y) ((x)<(y)?(x):(y))
  88603. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  88604. #ifdef _MSC_VER
  88605. #define FLAC__U64L(x) x
  88606. #else
  88607. #define FLAC__U64L(x) x##LLU
  88608. #endif
  88609. #ifndef FLaC__INLINE
  88610. #define FLaC__INLINE
  88611. #endif
  88612. struct FLAC__BitWriter {
  88613. bwword *buffer;
  88614. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  88615. unsigned capacity; /* capacity of buffer in words */
  88616. unsigned words; /* # of complete words in buffer */
  88617. unsigned bits; /* # of used bits in accum */
  88618. };
  88619. /* * WATCHOUT: The current implementation only grows the buffer. */
  88620. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  88621. {
  88622. unsigned new_capacity;
  88623. bwword *new_buffer;
  88624. FLAC__ASSERT(0 != bw);
  88625. FLAC__ASSERT(0 != bw->buffer);
  88626. /* calculate total words needed to store 'bits_to_add' additional bits */
  88627. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  88628. /* it's possible (due to pessimism in the growth estimation that
  88629. * leads to this call) that we don't actually need to grow
  88630. */
  88631. if(bw->capacity >= new_capacity)
  88632. return true;
  88633. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  88634. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  88635. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  88636. /* make sure we got everything right */
  88637. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  88638. FLAC__ASSERT(new_capacity > bw->capacity);
  88639. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  88640. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  88641. if(new_buffer == 0)
  88642. return false;
  88643. bw->buffer = new_buffer;
  88644. bw->capacity = new_capacity;
  88645. return true;
  88646. }
  88647. /***********************************************************************
  88648. *
  88649. * Class constructor/destructor
  88650. *
  88651. ***********************************************************************/
  88652. FLAC__BitWriter *FLAC__bitwriter_new(void)
  88653. {
  88654. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  88655. /* note that calloc() sets all members to 0 for us */
  88656. return bw;
  88657. }
  88658. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  88659. {
  88660. FLAC__ASSERT(0 != bw);
  88661. FLAC__bitwriter_free(bw);
  88662. free(bw);
  88663. }
  88664. /***********************************************************************
  88665. *
  88666. * Public class methods
  88667. *
  88668. ***********************************************************************/
  88669. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  88670. {
  88671. FLAC__ASSERT(0 != bw);
  88672. bw->words = bw->bits = 0;
  88673. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  88674. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  88675. if(bw->buffer == 0)
  88676. return false;
  88677. return true;
  88678. }
  88679. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  88680. {
  88681. FLAC__ASSERT(0 != bw);
  88682. if(0 != bw->buffer)
  88683. free(bw->buffer);
  88684. bw->buffer = 0;
  88685. bw->capacity = 0;
  88686. bw->words = bw->bits = 0;
  88687. }
  88688. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  88689. {
  88690. bw->words = bw->bits = 0;
  88691. }
  88692. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  88693. {
  88694. unsigned i, j;
  88695. if(bw == 0) {
  88696. fprintf(out, "bitwriter is NULL\n");
  88697. }
  88698. else {
  88699. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  88700. for(i = 0; i < bw->words; i++) {
  88701. fprintf(out, "%08X: ", i);
  88702. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  88703. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  88704. fprintf(out, "\n");
  88705. }
  88706. if(bw->bits > 0) {
  88707. fprintf(out, "%08X: ", i);
  88708. for(j = 0; j < bw->bits; j++)
  88709. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  88710. fprintf(out, "\n");
  88711. }
  88712. }
  88713. }
  88714. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  88715. {
  88716. const FLAC__byte *buffer;
  88717. size_t bytes;
  88718. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  88719. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  88720. return false;
  88721. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  88722. FLAC__bitwriter_release_buffer(bw);
  88723. return true;
  88724. }
  88725. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  88726. {
  88727. const FLAC__byte *buffer;
  88728. size_t bytes;
  88729. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  88730. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  88731. return false;
  88732. *crc = FLAC__crc8(buffer, bytes);
  88733. FLAC__bitwriter_release_buffer(bw);
  88734. return true;
  88735. }
  88736. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  88737. {
  88738. return ((bw->bits & 7) == 0);
  88739. }
  88740. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  88741. {
  88742. return FLAC__TOTAL_BITS(bw);
  88743. }
  88744. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  88745. {
  88746. FLAC__ASSERT((bw->bits & 7) == 0);
  88747. /* double protection */
  88748. if(bw->bits & 7)
  88749. return false;
  88750. /* if we have bits in the accumulator we have to flush those to the buffer first */
  88751. if(bw->bits) {
  88752. FLAC__ASSERT(bw->words <= bw->capacity);
  88753. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  88754. return false;
  88755. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  88756. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  88757. }
  88758. /* now we can just return what we have */
  88759. *buffer = (FLAC__byte*)bw->buffer;
  88760. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  88761. return true;
  88762. }
  88763. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  88764. {
  88765. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  88766. * get-mode' flag could be added everywhere and then cleared here
  88767. */
  88768. (void)bw;
  88769. }
  88770. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  88771. {
  88772. unsigned n;
  88773. FLAC__ASSERT(0 != bw);
  88774. FLAC__ASSERT(0 != bw->buffer);
  88775. if(bits == 0)
  88776. return true;
  88777. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  88778. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  88779. return false;
  88780. /* first part gets to word alignment */
  88781. if(bw->bits) {
  88782. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  88783. bw->accum <<= n;
  88784. bits -= n;
  88785. bw->bits += n;
  88786. if(bw->bits == FLAC__BITS_PER_WORD) {
  88787. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88788. bw->bits = 0;
  88789. }
  88790. else
  88791. return true;
  88792. }
  88793. /* do whole words */
  88794. while(bits >= FLAC__BITS_PER_WORD) {
  88795. bw->buffer[bw->words++] = 0;
  88796. bits -= FLAC__BITS_PER_WORD;
  88797. }
  88798. /* do any leftovers */
  88799. if(bits > 0) {
  88800. bw->accum = 0;
  88801. bw->bits = bits;
  88802. }
  88803. return true;
  88804. }
  88805. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  88806. {
  88807. register unsigned left;
  88808. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88809. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88810. FLAC__ASSERT(0 != bw);
  88811. FLAC__ASSERT(0 != bw->buffer);
  88812. FLAC__ASSERT(bits <= 32);
  88813. if(bits == 0)
  88814. return true;
  88815. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  88816. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  88817. return false;
  88818. left = FLAC__BITS_PER_WORD - bw->bits;
  88819. if(bits < left) {
  88820. bw->accum <<= bits;
  88821. bw->accum |= val;
  88822. bw->bits += bits;
  88823. }
  88824. 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 */
  88825. bw->accum <<= left;
  88826. bw->accum |= val >> (bw->bits = bits - left);
  88827. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88828. bw->accum = val;
  88829. }
  88830. else {
  88831. bw->accum = val;
  88832. bw->bits = 0;
  88833. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  88834. }
  88835. return true;
  88836. }
  88837. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  88838. {
  88839. /* zero-out unused bits */
  88840. if(bits < 32)
  88841. val &= (~(0xffffffff << bits));
  88842. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  88843. }
  88844. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  88845. {
  88846. /* this could be a little faster but it's not used for much */
  88847. if(bits > 32) {
  88848. return
  88849. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  88850. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  88851. }
  88852. else
  88853. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  88854. }
  88855. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  88856. {
  88857. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  88858. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  88859. return false;
  88860. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  88861. return false;
  88862. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  88863. return false;
  88864. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  88865. return false;
  88866. return true;
  88867. }
  88868. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  88869. {
  88870. unsigned i;
  88871. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  88872. for(i = 0; i < nvals; i++) {
  88873. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  88874. return false;
  88875. }
  88876. return true;
  88877. }
  88878. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  88879. {
  88880. if(val < 32)
  88881. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  88882. else
  88883. return
  88884. FLAC__bitwriter_write_zeroes(bw, val) &&
  88885. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  88886. }
  88887. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  88888. {
  88889. FLAC__uint32 uval;
  88890. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  88891. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  88892. uval = (val<<1) ^ (val>>31);
  88893. return 1 + parameter + (uval >> parameter);
  88894. }
  88895. #if 0 /* UNUSED */
  88896. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  88897. {
  88898. unsigned bits, msbs, uval;
  88899. unsigned k;
  88900. FLAC__ASSERT(parameter > 0);
  88901. /* fold signed to unsigned */
  88902. if(val < 0)
  88903. uval = (unsigned)(((-(++val)) << 1) + 1);
  88904. else
  88905. uval = (unsigned)(val << 1);
  88906. k = FLAC__bitmath_ilog2(parameter);
  88907. if(parameter == 1u<<k) {
  88908. FLAC__ASSERT(k <= 30);
  88909. msbs = uval >> k;
  88910. bits = 1 + k + msbs;
  88911. }
  88912. else {
  88913. unsigned q, r, d;
  88914. d = (1 << (k+1)) - parameter;
  88915. q = uval / parameter;
  88916. r = uval - (q * parameter);
  88917. bits = 1 + q + k;
  88918. if(r >= d)
  88919. bits++;
  88920. }
  88921. return bits;
  88922. }
  88923. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  88924. {
  88925. unsigned bits, msbs;
  88926. unsigned k;
  88927. FLAC__ASSERT(parameter > 0);
  88928. k = FLAC__bitmath_ilog2(parameter);
  88929. if(parameter == 1u<<k) {
  88930. FLAC__ASSERT(k <= 30);
  88931. msbs = uval >> k;
  88932. bits = 1 + k + msbs;
  88933. }
  88934. else {
  88935. unsigned q, r, d;
  88936. d = (1 << (k+1)) - parameter;
  88937. q = uval / parameter;
  88938. r = uval - (q * parameter);
  88939. bits = 1 + q + k;
  88940. if(r >= d)
  88941. bits++;
  88942. }
  88943. return bits;
  88944. }
  88945. #endif /* UNUSED */
  88946. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  88947. {
  88948. unsigned total_bits, interesting_bits, msbs;
  88949. FLAC__uint32 uval, pattern;
  88950. FLAC__ASSERT(0 != bw);
  88951. FLAC__ASSERT(0 != bw->buffer);
  88952. FLAC__ASSERT(parameter < 8*sizeof(uval));
  88953. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  88954. uval = (val<<1) ^ (val>>31);
  88955. msbs = uval >> parameter;
  88956. interesting_bits = 1 + parameter;
  88957. total_bits = interesting_bits + msbs;
  88958. pattern = 1 << parameter; /* the unary end bit */
  88959. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  88960. if(total_bits <= 32)
  88961. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  88962. else
  88963. return
  88964. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  88965. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  88966. }
  88967. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  88968. {
  88969. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  88970. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  88971. FLAC__uint32 uval;
  88972. unsigned left;
  88973. const unsigned lsbits = 1 + parameter;
  88974. unsigned msbits;
  88975. FLAC__ASSERT(0 != bw);
  88976. FLAC__ASSERT(0 != bw->buffer);
  88977. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  88978. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88979. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88980. while(nvals) {
  88981. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  88982. uval = (*vals<<1) ^ (*vals>>31);
  88983. msbits = uval >> parameter;
  88984. #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) */
  88985. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  88986. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  88987. bw->bits = bw->bits + msbits + lsbits;
  88988. uval |= mask1; /* set stop bit */
  88989. uval &= mask2; /* mask off unused top bits */
  88990. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  88991. bw->accum <<= msbits;
  88992. bw->accum <<= lsbits;
  88993. bw->accum |= uval;
  88994. if(bw->bits == FLAC__BITS_PER_WORD) {
  88995. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88996. bw->bits = 0;
  88997. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  88998. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  88999. FLAC__ASSERT(bw->capacity == bw->words);
  89000. return false;
  89001. }
  89002. }
  89003. }
  89004. else {
  89005. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  89006. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  89007. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  89008. bw->bits = bw->bits + msbits + lsbits;
  89009. uval |= mask1; /* set stop bit */
  89010. uval &= mask2; /* mask off unused top bits */
  89011. bw->accum <<= msbits + lsbits;
  89012. bw->accum |= uval;
  89013. }
  89014. else {
  89015. #endif
  89016. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  89017. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  89018. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  89019. return false;
  89020. if(msbits) {
  89021. /* first part gets to word alignment */
  89022. if(bw->bits) {
  89023. left = FLAC__BITS_PER_WORD - bw->bits;
  89024. if(msbits < left) {
  89025. bw->accum <<= msbits;
  89026. bw->bits += msbits;
  89027. goto break1;
  89028. }
  89029. else {
  89030. bw->accum <<= left;
  89031. msbits -= left;
  89032. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89033. bw->bits = 0;
  89034. }
  89035. }
  89036. /* do whole words */
  89037. while(msbits >= FLAC__BITS_PER_WORD) {
  89038. bw->buffer[bw->words++] = 0;
  89039. msbits -= FLAC__BITS_PER_WORD;
  89040. }
  89041. /* do any leftovers */
  89042. if(msbits > 0) {
  89043. bw->accum = 0;
  89044. bw->bits = msbits;
  89045. }
  89046. }
  89047. break1:
  89048. uval |= mask1; /* set stop bit */
  89049. uval &= mask2; /* mask off unused top bits */
  89050. left = FLAC__BITS_PER_WORD - bw->bits;
  89051. if(lsbits < left) {
  89052. bw->accum <<= lsbits;
  89053. bw->accum |= uval;
  89054. bw->bits += lsbits;
  89055. }
  89056. else {
  89057. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  89058. * be > lsbits (because of previous assertions) so it would have
  89059. * triggered the (lsbits<left) case above.
  89060. */
  89061. FLAC__ASSERT(bw->bits);
  89062. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  89063. bw->accum <<= left;
  89064. bw->accum |= uval >> (bw->bits = lsbits - left);
  89065. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89066. bw->accum = uval;
  89067. }
  89068. #if 1
  89069. }
  89070. #endif
  89071. vals++;
  89072. nvals--;
  89073. }
  89074. return true;
  89075. }
  89076. #if 0 /* UNUSED */
  89077. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  89078. {
  89079. unsigned total_bits, msbs, uval;
  89080. unsigned k;
  89081. FLAC__ASSERT(0 != bw);
  89082. FLAC__ASSERT(0 != bw->buffer);
  89083. FLAC__ASSERT(parameter > 0);
  89084. /* fold signed to unsigned */
  89085. if(val < 0)
  89086. uval = (unsigned)(((-(++val)) << 1) + 1);
  89087. else
  89088. uval = (unsigned)(val << 1);
  89089. k = FLAC__bitmath_ilog2(parameter);
  89090. if(parameter == 1u<<k) {
  89091. unsigned pattern;
  89092. FLAC__ASSERT(k <= 30);
  89093. msbs = uval >> k;
  89094. total_bits = 1 + k + msbs;
  89095. pattern = 1 << k; /* the unary end bit */
  89096. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  89097. if(total_bits <= 32) {
  89098. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  89099. return false;
  89100. }
  89101. else {
  89102. /* write the unary MSBs */
  89103. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  89104. return false;
  89105. /* write the unary end bit and binary LSBs */
  89106. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  89107. return false;
  89108. }
  89109. }
  89110. else {
  89111. unsigned q, r, d;
  89112. d = (1 << (k+1)) - parameter;
  89113. q = uval / parameter;
  89114. r = uval - (q * parameter);
  89115. /* write the unary MSBs */
  89116. if(!FLAC__bitwriter_write_zeroes(bw, q))
  89117. return false;
  89118. /* write the unary end bit */
  89119. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  89120. return false;
  89121. /* write the binary LSBs */
  89122. if(r >= d) {
  89123. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  89124. return false;
  89125. }
  89126. else {
  89127. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  89128. return false;
  89129. }
  89130. }
  89131. return true;
  89132. }
  89133. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  89134. {
  89135. unsigned total_bits, msbs;
  89136. unsigned k;
  89137. FLAC__ASSERT(0 != bw);
  89138. FLAC__ASSERT(0 != bw->buffer);
  89139. FLAC__ASSERT(parameter > 0);
  89140. k = FLAC__bitmath_ilog2(parameter);
  89141. if(parameter == 1u<<k) {
  89142. unsigned pattern;
  89143. FLAC__ASSERT(k <= 30);
  89144. msbs = uval >> k;
  89145. total_bits = 1 + k + msbs;
  89146. pattern = 1 << k; /* the unary end bit */
  89147. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  89148. if(total_bits <= 32) {
  89149. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  89150. return false;
  89151. }
  89152. else {
  89153. /* write the unary MSBs */
  89154. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  89155. return false;
  89156. /* write the unary end bit and binary LSBs */
  89157. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  89158. return false;
  89159. }
  89160. }
  89161. else {
  89162. unsigned q, r, d;
  89163. d = (1 << (k+1)) - parameter;
  89164. q = uval / parameter;
  89165. r = uval - (q * parameter);
  89166. /* write the unary MSBs */
  89167. if(!FLAC__bitwriter_write_zeroes(bw, q))
  89168. return false;
  89169. /* write the unary end bit */
  89170. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  89171. return false;
  89172. /* write the binary LSBs */
  89173. if(r >= d) {
  89174. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  89175. return false;
  89176. }
  89177. else {
  89178. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  89179. return false;
  89180. }
  89181. }
  89182. return true;
  89183. }
  89184. #endif /* UNUSED */
  89185. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  89186. {
  89187. FLAC__bool ok = 1;
  89188. FLAC__ASSERT(0 != bw);
  89189. FLAC__ASSERT(0 != bw->buffer);
  89190. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  89191. if(val < 0x80) {
  89192. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  89193. }
  89194. else if(val < 0x800) {
  89195. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  89196. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89197. }
  89198. else if(val < 0x10000) {
  89199. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  89200. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  89201. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89202. }
  89203. else if(val < 0x200000) {
  89204. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  89205. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  89206. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  89207. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89208. }
  89209. else if(val < 0x4000000) {
  89210. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  89211. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  89212. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  89213. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  89214. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89215. }
  89216. else {
  89217. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  89218. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  89219. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  89220. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  89221. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  89222. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  89223. }
  89224. return ok;
  89225. }
  89226. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  89227. {
  89228. FLAC__bool ok = 1;
  89229. FLAC__ASSERT(0 != bw);
  89230. FLAC__ASSERT(0 != bw->buffer);
  89231. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  89232. if(val < 0x80) {
  89233. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  89234. }
  89235. else if(val < 0x800) {
  89236. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  89237. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89238. }
  89239. else if(val < 0x10000) {
  89240. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  89241. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  89242. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89243. }
  89244. else if(val < 0x200000) {
  89245. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  89246. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  89247. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  89248. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89249. }
  89250. else if(val < 0x4000000) {
  89251. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  89252. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  89253. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  89254. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  89255. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89256. }
  89257. else if(val < 0x80000000) {
  89258. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  89259. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  89260. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  89261. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  89262. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  89263. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89264. }
  89265. else {
  89266. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  89267. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  89268. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  89269. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  89270. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  89271. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  89272. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  89273. }
  89274. return ok;
  89275. }
  89276. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  89277. {
  89278. /* 0-pad to byte boundary */
  89279. if(bw->bits & 7u)
  89280. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  89281. else
  89282. return true;
  89283. }
  89284. #endif
  89285. /********* End of inlined file: bitwriter.c *********/
  89286. /********* Start of inlined file: cpu.c *********/
  89287. /********* Start of inlined file: juce_FlacHeader.h *********/
  89288. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89289. // tasks..
  89290. #define VERSION "1.2.1"
  89291. #define FLAC__NO_DLL 1
  89292. #ifdef _MSC_VER
  89293. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89294. #endif
  89295. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89296. #define FLAC__SYS_DARWIN 1
  89297. #endif
  89298. /********* End of inlined file: juce_FlacHeader.h *********/
  89299. #if JUCE_USE_FLAC
  89300. #if HAVE_CONFIG_H
  89301. # include <config.h>
  89302. #endif
  89303. #include <stdlib.h>
  89304. #include <stdio.h>
  89305. #if defined FLAC__CPU_IA32
  89306. # include <signal.h>
  89307. #elif defined FLAC__CPU_PPC
  89308. # if !defined FLAC__NO_ASM
  89309. # if defined FLAC__SYS_DARWIN
  89310. # include <sys/sysctl.h>
  89311. # include <mach/mach.h>
  89312. # include <mach/mach_host.h>
  89313. # include <mach/host_info.h>
  89314. # include <mach/machine.h>
  89315. # ifndef CPU_SUBTYPE_POWERPC_970
  89316. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  89317. # endif
  89318. # else /* FLAC__SYS_DARWIN */
  89319. # include <signal.h>
  89320. # include <setjmp.h>
  89321. static sigjmp_buf jmpbuf;
  89322. static volatile sig_atomic_t canjump = 0;
  89323. static void sigill_handler (int sig)
  89324. {
  89325. if (!canjump) {
  89326. signal (sig, SIG_DFL);
  89327. raise (sig);
  89328. }
  89329. canjump = 0;
  89330. siglongjmp (jmpbuf, 1);
  89331. }
  89332. # endif /* FLAC__SYS_DARWIN */
  89333. # endif /* FLAC__NO_ASM */
  89334. #endif /* FLAC__CPU_PPC */
  89335. #if defined (__NetBSD__) || defined(__OpenBSD__)
  89336. #include <sys/param.h>
  89337. #include <sys/sysctl.h>
  89338. #include <machine/cpu.h>
  89339. #endif
  89340. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  89341. #include <sys/types.h>
  89342. #include <sys/sysctl.h>
  89343. #endif
  89344. #if defined(__APPLE__)
  89345. /* how to get sysctlbyname()? */
  89346. #endif
  89347. /* these are flags in EDX of CPUID AX=00000001 */
  89348. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  89349. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  89350. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  89351. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  89352. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  89353. /* these are flags in ECX of CPUID AX=00000001 */
  89354. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  89355. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  89356. /* these are flags in EDX of CPUID AX=80000001 */
  89357. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  89358. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  89359. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  89360. /*
  89361. * Extra stuff needed for detection of OS support for SSE on IA-32
  89362. */
  89363. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  89364. # if defined(__linux__)
  89365. /*
  89366. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  89367. * modify the return address to jump over the offending SSE instruction
  89368. * and also the operation following it that indicates the instruction
  89369. * executed successfully. In this way we use no global variables and
  89370. * stay thread-safe.
  89371. *
  89372. * 3 + 3 + 6:
  89373. * 3 bytes for "xorps xmm0,xmm0"
  89374. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  89375. * 6 bytes extra in case our estimate is wrong
  89376. * 12 bytes puts us in the NOP "landing zone"
  89377. */
  89378. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  89379. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  89380. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  89381. {
  89382. (void)signal;
  89383. sc.eip += 3 + 3 + 6;
  89384. }
  89385. # else
  89386. # include <sys/ucontext.h>
  89387. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  89388. {
  89389. (void)signal, (void)si;
  89390. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  89391. }
  89392. # endif
  89393. # elif defined(_MSC_VER)
  89394. # include <windows.h>
  89395. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  89396. # ifdef USE_TRY_CATCH_FLAVOR
  89397. # else
  89398. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  89399. {
  89400. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  89401. ep->ContextRecord->Eip += 3 + 3 + 6;
  89402. return EXCEPTION_CONTINUE_EXECUTION;
  89403. }
  89404. return EXCEPTION_CONTINUE_SEARCH;
  89405. }
  89406. # endif
  89407. # endif
  89408. #endif
  89409. void FLAC__cpu_info(FLAC__CPUInfo *info)
  89410. {
  89411. /*
  89412. * IA32-specific
  89413. */
  89414. #ifdef FLAC__CPU_IA32
  89415. info->type = FLAC__CPUINFO_TYPE_IA32;
  89416. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  89417. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  89418. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  89419. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  89420. info->data.ia32.cmov = false;
  89421. info->data.ia32.mmx = false;
  89422. info->data.ia32.fxsr = false;
  89423. info->data.ia32.sse = false;
  89424. info->data.ia32.sse2 = false;
  89425. info->data.ia32.sse3 = false;
  89426. info->data.ia32.ssse3 = false;
  89427. info->data.ia32._3dnow = false;
  89428. info->data.ia32.ext3dnow = false;
  89429. info->data.ia32.extmmx = false;
  89430. if(info->data.ia32.cpuid) {
  89431. /* http://www.sandpile.org/ia32/cpuid.htm */
  89432. FLAC__uint32 flags_edx, flags_ecx;
  89433. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  89434. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  89435. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  89436. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  89437. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  89438. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  89439. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  89440. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  89441. #ifdef FLAC__USE_3DNOW
  89442. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  89443. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  89444. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  89445. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  89446. #else
  89447. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  89448. #endif
  89449. #ifdef DEBUG
  89450. fprintf(stderr, "CPU info (IA-32):\n");
  89451. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  89452. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  89453. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  89454. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  89455. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  89456. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  89457. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  89458. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  89459. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  89460. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  89461. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  89462. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  89463. #endif
  89464. /*
  89465. * now have to check for OS support of SSE/SSE2
  89466. */
  89467. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  89468. #if defined FLAC__NO_SSE_OS
  89469. /* assume user knows better than us; turn it off */
  89470. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89471. #elif defined FLAC__SSE_OS
  89472. /* assume user knows better than us; leave as detected above */
  89473. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  89474. int sse = 0;
  89475. size_t len;
  89476. /* at least one of these must work: */
  89477. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  89478. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  89479. if(!sse)
  89480. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89481. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  89482. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  89483. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  89484. size_t len = sizeof(val);
  89485. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  89486. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89487. else { /* double-check SSE2 */
  89488. mib[1] = CPU_SSE2;
  89489. len = sizeof(val);
  89490. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  89491. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89492. }
  89493. # else
  89494. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89495. # endif
  89496. #elif defined(__linux__)
  89497. int sse = 0;
  89498. struct sigaction sigill_save;
  89499. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  89500. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  89501. #else
  89502. struct sigaction sigill_sse;
  89503. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  89504. __sigemptyset(&sigill_sse.sa_mask);
  89505. 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 */
  89506. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  89507. #endif
  89508. {
  89509. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  89510. /* see sigill_handler_sse_os() for an explanation of the following: */
  89511. asm volatile (
  89512. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  89513. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  89514. "incl %0\n\t" /* SIGILL handler will jump over this */
  89515. /* landing zone */
  89516. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  89517. "nop\n\t"
  89518. "nop\n\t"
  89519. "nop\n\t"
  89520. "nop\n\t"
  89521. "nop\n\t"
  89522. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  89523. "nop\n\t"
  89524. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  89525. : "=r"(sse)
  89526. : "r"(sse)
  89527. );
  89528. sigaction(SIGILL, &sigill_save, NULL);
  89529. }
  89530. if(!sse)
  89531. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89532. #elif defined(_MSC_VER)
  89533. # ifdef USE_TRY_CATCH_FLAVOR
  89534. _try {
  89535. __asm {
  89536. # if _MSC_VER <= 1200
  89537. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  89538. _emit 0x0F
  89539. _emit 0x57
  89540. _emit 0xC0
  89541. # else
  89542. xorps xmm0,xmm0
  89543. # endif
  89544. }
  89545. }
  89546. _except(EXCEPTION_EXECUTE_HANDLER) {
  89547. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  89548. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89549. }
  89550. # else
  89551. int sse = 0;
  89552. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  89553. /* see GCC version above for explanation */
  89554. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  89555. /* http://www.codeproject.com/cpp/gccasm.asp */
  89556. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  89557. __asm {
  89558. # if _MSC_VER <= 1200
  89559. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  89560. _emit 0x0F
  89561. _emit 0x57
  89562. _emit 0xC0
  89563. # else
  89564. xorps xmm0,xmm0
  89565. # endif
  89566. inc sse
  89567. nop
  89568. nop
  89569. nop
  89570. nop
  89571. nop
  89572. nop
  89573. nop
  89574. nop
  89575. nop
  89576. }
  89577. SetUnhandledExceptionFilter(save);
  89578. if(!sse)
  89579. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89580. # endif
  89581. #else
  89582. /* no way to test, disable to be safe */
  89583. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  89584. #endif
  89585. #ifdef DEBUG
  89586. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  89587. #endif
  89588. }
  89589. }
  89590. #else
  89591. info->use_asm = false;
  89592. #endif
  89593. /*
  89594. * PPC-specific
  89595. */
  89596. #elif defined FLAC__CPU_PPC
  89597. info->type = FLAC__CPUINFO_TYPE_PPC;
  89598. # if !defined FLAC__NO_ASM
  89599. info->use_asm = true;
  89600. # ifdef FLAC__USE_ALTIVEC
  89601. # if defined FLAC__SYS_DARWIN
  89602. {
  89603. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  89604. size_t len = sizeof(val);
  89605. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  89606. }
  89607. {
  89608. host_basic_info_data_t hostInfo;
  89609. mach_msg_type_number_t infoCount;
  89610. infoCount = HOST_BASIC_INFO_COUNT;
  89611. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  89612. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  89613. }
  89614. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  89615. {
  89616. /* no Darwin, do it the brute-force way */
  89617. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  89618. info->data.ppc.altivec = 0;
  89619. info->data.ppc.ppc64 = 0;
  89620. signal (SIGILL, sigill_handler);
  89621. canjump = 0;
  89622. if (!sigsetjmp (jmpbuf, 1)) {
  89623. canjump = 1;
  89624. asm volatile (
  89625. "mtspr 256, %0\n\t"
  89626. "vand %%v0, %%v0, %%v0"
  89627. :
  89628. : "r" (-1)
  89629. );
  89630. info->data.ppc.altivec = 1;
  89631. }
  89632. canjump = 0;
  89633. if (!sigsetjmp (jmpbuf, 1)) {
  89634. int x = 0;
  89635. canjump = 1;
  89636. /* PPC64 hardware implements the cntlzd instruction */
  89637. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  89638. info->data.ppc.ppc64 = 1;
  89639. }
  89640. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  89641. }
  89642. # endif
  89643. # else /* !FLAC__USE_ALTIVEC */
  89644. info->data.ppc.altivec = 0;
  89645. info->data.ppc.ppc64 = 0;
  89646. # endif
  89647. # else
  89648. info->use_asm = false;
  89649. # endif
  89650. /*
  89651. * unknown CPI
  89652. */
  89653. #else
  89654. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  89655. info->use_asm = false;
  89656. #endif
  89657. }
  89658. #endif
  89659. /********* End of inlined file: cpu.c *********/
  89660. /********* Start of inlined file: crc.c *********/
  89661. /********* Start of inlined file: juce_FlacHeader.h *********/
  89662. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89663. // tasks..
  89664. #define VERSION "1.2.1"
  89665. #define FLAC__NO_DLL 1
  89666. #ifdef _MSC_VER
  89667. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89668. #endif
  89669. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89670. #define FLAC__SYS_DARWIN 1
  89671. #endif
  89672. /********* End of inlined file: juce_FlacHeader.h *********/
  89673. #if JUCE_USE_FLAC
  89674. #if HAVE_CONFIG_H
  89675. # include <config.h>
  89676. #endif
  89677. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  89678. FLAC__byte const FLAC__crc8_table[256] = {
  89679. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  89680. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  89681. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  89682. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  89683. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  89684. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  89685. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  89686. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  89687. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  89688. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  89689. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  89690. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  89691. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  89692. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  89693. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  89694. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  89695. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  89696. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  89697. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  89698. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  89699. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  89700. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  89701. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  89702. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  89703. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  89704. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  89705. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  89706. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  89707. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  89708. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  89709. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  89710. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  89711. };
  89712. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  89713. unsigned FLAC__crc16_table[256] = {
  89714. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  89715. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  89716. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  89717. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  89718. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  89719. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  89720. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  89721. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  89722. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  89723. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  89724. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  89725. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  89726. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  89727. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  89728. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  89729. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  89730. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  89731. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  89732. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  89733. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  89734. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  89735. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  89736. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  89737. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  89738. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  89739. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  89740. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  89741. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  89742. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  89743. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  89744. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  89745. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  89746. };
  89747. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  89748. {
  89749. *crc = FLAC__crc8_table[*crc ^ data];
  89750. }
  89751. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  89752. {
  89753. while(len--)
  89754. *crc = FLAC__crc8_table[*crc ^ *data++];
  89755. }
  89756. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  89757. {
  89758. FLAC__uint8 crc = 0;
  89759. while(len--)
  89760. crc = FLAC__crc8_table[crc ^ *data++];
  89761. return crc;
  89762. }
  89763. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  89764. {
  89765. unsigned crc = 0;
  89766. while(len--)
  89767. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  89768. return crc;
  89769. }
  89770. #endif
  89771. /********* End of inlined file: crc.c *********/
  89772. /********* Start of inlined file: fixed.c *********/
  89773. /********* Start of inlined file: juce_FlacHeader.h *********/
  89774. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89775. // tasks..
  89776. #define VERSION "1.2.1"
  89777. #define FLAC__NO_DLL 1
  89778. #ifdef _MSC_VER
  89779. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89780. #endif
  89781. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89782. #define FLAC__SYS_DARWIN 1
  89783. #endif
  89784. /********* End of inlined file: juce_FlacHeader.h *********/
  89785. #if JUCE_USE_FLAC
  89786. #if HAVE_CONFIG_H
  89787. # include <config.h>
  89788. #endif
  89789. #include <math.h>
  89790. #include <string.h>
  89791. /********* Start of inlined file: fixed.h *********/
  89792. #ifndef FLAC__PRIVATE__FIXED_H
  89793. #define FLAC__PRIVATE__FIXED_H
  89794. #ifdef HAVE_CONFIG_H
  89795. #include <config.h>
  89796. #endif
  89797. /********* Start of inlined file: float.h *********/
  89798. #ifndef FLAC__PRIVATE__FLOAT_H
  89799. #define FLAC__PRIVATE__FLOAT_H
  89800. #ifdef HAVE_CONFIG_H
  89801. #include <config.h>
  89802. #endif
  89803. /*
  89804. * These typedefs make it easier to ensure that integer versions of
  89805. * the library really only contain integer operations. All the code
  89806. * in libFLAC should use FLAC__float and FLAC__double in place of
  89807. * float and double, and be protected by checks of the macro
  89808. * FLAC__INTEGER_ONLY_LIBRARY.
  89809. *
  89810. * FLAC__real is the basic floating point type used in LPC analysis.
  89811. */
  89812. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89813. typedef double FLAC__double;
  89814. typedef float FLAC__float;
  89815. /*
  89816. * WATCHOUT: changing FLAC__real will change the signatures of many
  89817. * functions that have assembly language equivalents and break them.
  89818. */
  89819. typedef float FLAC__real;
  89820. #else
  89821. /*
  89822. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  89823. * for the integer part and lower 16 bits for the fractional part.
  89824. */
  89825. typedef FLAC__int32 FLAC__fixedpoint;
  89826. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  89827. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  89828. extern const FLAC__fixedpoint FLAC__FP_ONE;
  89829. extern const FLAC__fixedpoint FLAC__FP_LN2;
  89830. extern const FLAC__fixedpoint FLAC__FP_E;
  89831. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  89832. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  89833. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  89834. /*
  89835. * FLAC__fixedpoint_log2()
  89836. * --------------------------------------------------------------------
  89837. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  89838. * algorithm by Knuth for x >= 1.0
  89839. *
  89840. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  89841. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  89842. *
  89843. * 'precision' roughly limits the number of iterations that are done;
  89844. * use (unsigned)(-1) for maximum precision.
  89845. *
  89846. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  89847. * function will punt and return 0.
  89848. *
  89849. * The return value will also have 'fracbits' fractional bits.
  89850. */
  89851. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  89852. #endif
  89853. #endif
  89854. /********* End of inlined file: float.h *********/
  89855. /********* Start of inlined file: format.h *********/
  89856. #ifndef FLAC__PRIVATE__FORMAT_H
  89857. #define FLAC__PRIVATE__FORMAT_H
  89858. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  89859. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  89860. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  89861. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  89862. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  89863. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  89864. #endif
  89865. /********* End of inlined file: format.h *********/
  89866. /*
  89867. * FLAC__fixed_compute_best_predictor()
  89868. * --------------------------------------------------------------------
  89869. * Compute the best fixed predictor and the expected bits-per-sample
  89870. * of the residual signal for each order. The _wide() version uses
  89871. * 64-bit integers which is statistically necessary when bits-per-
  89872. * sample + log2(blocksize) > 30
  89873. *
  89874. * IN data[0,data_len-1]
  89875. * IN data_len
  89876. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  89877. */
  89878. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89879. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  89880. # ifndef FLAC__NO_ASM
  89881. # ifdef FLAC__CPU_IA32
  89882. # ifdef FLAC__HAS_NASM
  89883. 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]);
  89884. # endif
  89885. # endif
  89886. # endif
  89887. 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]);
  89888. #else
  89889. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  89890. 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]);
  89891. #endif
  89892. /*
  89893. * FLAC__fixed_compute_residual()
  89894. * --------------------------------------------------------------------
  89895. * Compute the residual signal obtained from sutracting the predicted
  89896. * signal from the original.
  89897. *
  89898. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  89899. * IN data_len length of original signal
  89900. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  89901. * OUT residual[0,data_len-1] residual signal
  89902. */
  89903. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  89904. /*
  89905. * FLAC__fixed_restore_signal()
  89906. * --------------------------------------------------------------------
  89907. * Restore the original signal by summing the residual and the
  89908. * predictor.
  89909. *
  89910. * IN residual[0,data_len-1] residual signal
  89911. * IN data_len length of original signal
  89912. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  89913. * *** IMPORTANT: the caller must pass in the historical samples:
  89914. * IN data[-order,-1] previously-reconstructed historical samples
  89915. * OUT data[0,data_len-1] original signal
  89916. */
  89917. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  89918. #endif
  89919. /********* End of inlined file: fixed.h *********/
  89920. #ifndef M_LN2
  89921. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  89922. #define M_LN2 0.69314718055994530942
  89923. #endif
  89924. #ifdef min
  89925. #undef min
  89926. #endif
  89927. #define min(x,y) ((x) < (y)? (x) : (y))
  89928. #ifdef local_abs
  89929. #undef local_abs
  89930. #endif
  89931. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  89932. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  89933. /* rbps stands for residual bits per sample
  89934. *
  89935. * (ln(2) * err)
  89936. * rbps = log (-----------)
  89937. * 2 ( n )
  89938. */
  89939. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  89940. {
  89941. FLAC__uint32 rbps;
  89942. unsigned bits; /* the number of bits required to represent a number */
  89943. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  89944. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  89945. FLAC__ASSERT(err > 0);
  89946. FLAC__ASSERT(n > 0);
  89947. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  89948. if(err <= n)
  89949. return 0;
  89950. /*
  89951. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  89952. * These allow us later to know we won't lose too much precision in the
  89953. * fixed-point division (err<<fracbits)/n.
  89954. */
  89955. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  89956. err <<= fracbits;
  89957. err /= n;
  89958. /* err now holds err/n with fracbits fractional bits */
  89959. /*
  89960. * Whittle err down to 16 bits max. 16 significant bits is enough for
  89961. * our purposes.
  89962. */
  89963. FLAC__ASSERT(err > 0);
  89964. bits = FLAC__bitmath_ilog2(err)+1;
  89965. if(bits > 16) {
  89966. err >>= (bits-16);
  89967. fracbits -= (bits-16);
  89968. }
  89969. rbps = (FLAC__uint32)err;
  89970. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  89971. rbps *= FLAC__FP_LN2;
  89972. fracbits += 16;
  89973. FLAC__ASSERT(fracbits >= 0);
  89974. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  89975. {
  89976. const int f = fracbits & 3;
  89977. if(f) {
  89978. rbps >>= f;
  89979. fracbits -= f;
  89980. }
  89981. }
  89982. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  89983. if(rbps == 0)
  89984. return 0;
  89985. /*
  89986. * The return value must have 16 fractional bits. Since the whole part
  89987. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  89988. * must be >= -3, these assertion allows us to be able to shift rbps
  89989. * left if necessary to get 16 fracbits without losing any bits of the
  89990. * whole part of rbps.
  89991. *
  89992. * There is a slight chance due to accumulated error that the whole part
  89993. * will require 6 bits, so we use 6 in the assertion. Really though as
  89994. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  89995. */
  89996. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  89997. FLAC__ASSERT(fracbits >= -3);
  89998. /* now shift the decimal point into place */
  89999. if(fracbits < 16)
  90000. return rbps << (16-fracbits);
  90001. else if(fracbits > 16)
  90002. return rbps >> (fracbits-16);
  90003. else
  90004. return rbps;
  90005. }
  90006. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  90007. {
  90008. FLAC__uint32 rbps;
  90009. unsigned bits; /* the number of bits required to represent a number */
  90010. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  90011. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  90012. FLAC__ASSERT(err > 0);
  90013. FLAC__ASSERT(n > 0);
  90014. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  90015. if(err <= n)
  90016. return 0;
  90017. /*
  90018. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  90019. * These allow us later to know we won't lose too much precision in the
  90020. * fixed-point division (err<<fracbits)/n.
  90021. */
  90022. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  90023. err <<= fracbits;
  90024. err /= n;
  90025. /* err now holds err/n with fracbits fractional bits */
  90026. /*
  90027. * Whittle err down to 16 bits max. 16 significant bits is enough for
  90028. * our purposes.
  90029. */
  90030. FLAC__ASSERT(err > 0);
  90031. bits = FLAC__bitmath_ilog2_wide(err)+1;
  90032. if(bits > 16) {
  90033. err >>= (bits-16);
  90034. fracbits -= (bits-16);
  90035. }
  90036. rbps = (FLAC__uint32)err;
  90037. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  90038. rbps *= FLAC__FP_LN2;
  90039. fracbits += 16;
  90040. FLAC__ASSERT(fracbits >= 0);
  90041. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  90042. {
  90043. const int f = fracbits & 3;
  90044. if(f) {
  90045. rbps >>= f;
  90046. fracbits -= f;
  90047. }
  90048. }
  90049. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  90050. if(rbps == 0)
  90051. return 0;
  90052. /*
  90053. * The return value must have 16 fractional bits. Since the whole part
  90054. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  90055. * must be >= -3, these assertion allows us to be able to shift rbps
  90056. * left if necessary to get 16 fracbits without losing any bits of the
  90057. * whole part of rbps.
  90058. *
  90059. * There is a slight chance due to accumulated error that the whole part
  90060. * will require 6 bits, so we use 6 in the assertion. Really though as
  90061. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  90062. */
  90063. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  90064. FLAC__ASSERT(fracbits >= -3);
  90065. /* now shift the decimal point into place */
  90066. if(fracbits < 16)
  90067. return rbps << (16-fracbits);
  90068. else if(fracbits > 16)
  90069. return rbps >> (fracbits-16);
  90070. else
  90071. return rbps;
  90072. }
  90073. #endif
  90074. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90075. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  90076. #else
  90077. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  90078. #endif
  90079. {
  90080. FLAC__int32 last_error_0 = data[-1];
  90081. FLAC__int32 last_error_1 = data[-1] - data[-2];
  90082. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  90083. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  90084. FLAC__int32 error, save;
  90085. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  90086. unsigned i, order;
  90087. for(i = 0; i < data_len; i++) {
  90088. error = data[i] ; total_error_0 += local_abs(error); save = error;
  90089. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  90090. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  90091. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  90092. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  90093. }
  90094. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  90095. order = 0;
  90096. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  90097. order = 1;
  90098. else if(total_error_2 < min(total_error_3, total_error_4))
  90099. order = 2;
  90100. else if(total_error_3 < total_error_4)
  90101. order = 3;
  90102. else
  90103. order = 4;
  90104. /* Estimate the expected number of bits per residual signal sample. */
  90105. /* 'total_error*' is linearly related to the variance of the residual */
  90106. /* signal, so we use it directly to compute E(|x|) */
  90107. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  90108. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  90109. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  90110. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  90111. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  90112. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90113. 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);
  90114. 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);
  90115. 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);
  90116. 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);
  90117. 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);
  90118. #else
  90119. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  90120. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  90121. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  90122. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  90123. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  90124. #endif
  90125. return order;
  90126. }
  90127. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90128. 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])
  90129. #else
  90130. 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])
  90131. #endif
  90132. {
  90133. FLAC__int32 last_error_0 = data[-1];
  90134. FLAC__int32 last_error_1 = data[-1] - data[-2];
  90135. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  90136. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  90137. FLAC__int32 error, save;
  90138. /* total_error_* are 64-bits to avoid overflow when encoding
  90139. * erratic signals when the bits-per-sample and blocksize are
  90140. * large.
  90141. */
  90142. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  90143. unsigned i, order;
  90144. for(i = 0; i < data_len; i++) {
  90145. error = data[i] ; total_error_0 += local_abs(error); save = error;
  90146. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  90147. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  90148. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  90149. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  90150. }
  90151. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  90152. order = 0;
  90153. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  90154. order = 1;
  90155. else if(total_error_2 < min(total_error_3, total_error_4))
  90156. order = 2;
  90157. else if(total_error_3 < total_error_4)
  90158. order = 3;
  90159. else
  90160. order = 4;
  90161. /* Estimate the expected number of bits per residual signal sample. */
  90162. /* 'total_error*' is linearly related to the variance of the residual */
  90163. /* signal, so we use it directly to compute E(|x|) */
  90164. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  90165. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  90166. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  90167. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  90168. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  90169. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90170. #if defined _MSC_VER || defined __MINGW32__
  90171. /* with MSVC you have to spoon feed it the casting */
  90172. 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);
  90173. 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);
  90174. 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);
  90175. 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);
  90176. 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);
  90177. #else
  90178. 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);
  90179. 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);
  90180. 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);
  90181. 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);
  90182. 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);
  90183. #endif
  90184. #else
  90185. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  90186. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  90187. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  90188. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  90189. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  90190. #endif
  90191. return order;
  90192. }
  90193. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  90194. {
  90195. const int idata_len = (int)data_len;
  90196. int i;
  90197. switch(order) {
  90198. case 0:
  90199. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  90200. memcpy(residual, data, sizeof(residual[0])*data_len);
  90201. break;
  90202. case 1:
  90203. for(i = 0; i < idata_len; i++)
  90204. residual[i] = data[i] - data[i-1];
  90205. break;
  90206. case 2:
  90207. for(i = 0; i < idata_len; i++)
  90208. #if 1 /* OPT: may be faster with some compilers on some systems */
  90209. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  90210. #else
  90211. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  90212. #endif
  90213. break;
  90214. case 3:
  90215. for(i = 0; i < idata_len; i++)
  90216. #if 1 /* OPT: may be faster with some compilers on some systems */
  90217. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  90218. #else
  90219. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  90220. #endif
  90221. break;
  90222. case 4:
  90223. for(i = 0; i < idata_len; i++)
  90224. #if 1 /* OPT: may be faster with some compilers on some systems */
  90225. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  90226. #else
  90227. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  90228. #endif
  90229. break;
  90230. default:
  90231. FLAC__ASSERT(0);
  90232. }
  90233. }
  90234. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  90235. {
  90236. int i, idata_len = (int)data_len;
  90237. switch(order) {
  90238. case 0:
  90239. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  90240. memcpy(data, residual, sizeof(residual[0])*data_len);
  90241. break;
  90242. case 1:
  90243. for(i = 0; i < idata_len; i++)
  90244. data[i] = residual[i] + data[i-1];
  90245. break;
  90246. case 2:
  90247. for(i = 0; i < idata_len; i++)
  90248. #if 1 /* OPT: may be faster with some compilers on some systems */
  90249. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  90250. #else
  90251. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  90252. #endif
  90253. break;
  90254. case 3:
  90255. for(i = 0; i < idata_len; i++)
  90256. #if 1 /* OPT: may be faster with some compilers on some systems */
  90257. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  90258. #else
  90259. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  90260. #endif
  90261. break;
  90262. case 4:
  90263. for(i = 0; i < idata_len; i++)
  90264. #if 1 /* OPT: may be faster with some compilers on some systems */
  90265. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  90266. #else
  90267. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  90268. #endif
  90269. break;
  90270. default:
  90271. FLAC__ASSERT(0);
  90272. }
  90273. }
  90274. #endif
  90275. /********* End of inlined file: fixed.c *********/
  90276. /********* Start of inlined file: float.c *********/
  90277. /********* Start of inlined file: juce_FlacHeader.h *********/
  90278. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90279. // tasks..
  90280. #define VERSION "1.2.1"
  90281. #define FLAC__NO_DLL 1
  90282. #ifdef _MSC_VER
  90283. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90284. #endif
  90285. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90286. #define FLAC__SYS_DARWIN 1
  90287. #endif
  90288. /********* End of inlined file: juce_FlacHeader.h *********/
  90289. #if JUCE_USE_FLAC
  90290. #if HAVE_CONFIG_H
  90291. # include <config.h>
  90292. #endif
  90293. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  90294. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  90295. #ifdef _MSC_VER
  90296. #define FLAC__U64L(x) x
  90297. #else
  90298. #define FLAC__U64L(x) x##LLU
  90299. #endif
  90300. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  90301. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  90302. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  90303. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  90304. const FLAC__fixedpoint FLAC__FP_E = 178145;
  90305. /* Lookup tables for Knuth's logarithm algorithm */
  90306. #define LOG2_LOOKUP_PRECISION 16
  90307. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  90308. {
  90309. /*
  90310. * 0 fraction bits
  90311. */
  90312. /* undefined */ 0x00000000,
  90313. /* lg(2/1) = */ 0x00000001,
  90314. /* lg(4/3) = */ 0x00000000,
  90315. /* lg(8/7) = */ 0x00000000,
  90316. /* lg(16/15) = */ 0x00000000,
  90317. /* lg(32/31) = */ 0x00000000,
  90318. /* lg(64/63) = */ 0x00000000,
  90319. /* lg(128/127) = */ 0x00000000,
  90320. /* lg(256/255) = */ 0x00000000,
  90321. /* lg(512/511) = */ 0x00000000,
  90322. /* lg(1024/1023) = */ 0x00000000,
  90323. /* lg(2048/2047) = */ 0x00000000,
  90324. /* lg(4096/4095) = */ 0x00000000,
  90325. /* lg(8192/8191) = */ 0x00000000,
  90326. /* lg(16384/16383) = */ 0x00000000,
  90327. /* lg(32768/32767) = */ 0x00000000
  90328. },
  90329. {
  90330. /*
  90331. * 4 fraction bits
  90332. */
  90333. /* undefined */ 0x00000000,
  90334. /* lg(2/1) = */ 0x00000010,
  90335. /* lg(4/3) = */ 0x00000007,
  90336. /* lg(8/7) = */ 0x00000003,
  90337. /* lg(16/15) = */ 0x00000001,
  90338. /* lg(32/31) = */ 0x00000001,
  90339. /* lg(64/63) = */ 0x00000000,
  90340. /* lg(128/127) = */ 0x00000000,
  90341. /* lg(256/255) = */ 0x00000000,
  90342. /* lg(512/511) = */ 0x00000000,
  90343. /* lg(1024/1023) = */ 0x00000000,
  90344. /* lg(2048/2047) = */ 0x00000000,
  90345. /* lg(4096/4095) = */ 0x00000000,
  90346. /* lg(8192/8191) = */ 0x00000000,
  90347. /* lg(16384/16383) = */ 0x00000000,
  90348. /* lg(32768/32767) = */ 0x00000000
  90349. },
  90350. {
  90351. /*
  90352. * 8 fraction bits
  90353. */
  90354. /* undefined */ 0x00000000,
  90355. /* lg(2/1) = */ 0x00000100,
  90356. /* lg(4/3) = */ 0x0000006a,
  90357. /* lg(8/7) = */ 0x00000031,
  90358. /* lg(16/15) = */ 0x00000018,
  90359. /* lg(32/31) = */ 0x0000000c,
  90360. /* lg(64/63) = */ 0x00000006,
  90361. /* lg(128/127) = */ 0x00000003,
  90362. /* lg(256/255) = */ 0x00000001,
  90363. /* lg(512/511) = */ 0x00000001,
  90364. /* lg(1024/1023) = */ 0x00000000,
  90365. /* lg(2048/2047) = */ 0x00000000,
  90366. /* lg(4096/4095) = */ 0x00000000,
  90367. /* lg(8192/8191) = */ 0x00000000,
  90368. /* lg(16384/16383) = */ 0x00000000,
  90369. /* lg(32768/32767) = */ 0x00000000
  90370. },
  90371. {
  90372. /*
  90373. * 12 fraction bits
  90374. */
  90375. /* undefined */ 0x00000000,
  90376. /* lg(2/1) = */ 0x00001000,
  90377. /* lg(4/3) = */ 0x000006a4,
  90378. /* lg(8/7) = */ 0x00000315,
  90379. /* lg(16/15) = */ 0x0000017d,
  90380. /* lg(32/31) = */ 0x000000bc,
  90381. /* lg(64/63) = */ 0x0000005d,
  90382. /* lg(128/127) = */ 0x0000002e,
  90383. /* lg(256/255) = */ 0x00000017,
  90384. /* lg(512/511) = */ 0x0000000c,
  90385. /* lg(1024/1023) = */ 0x00000006,
  90386. /* lg(2048/2047) = */ 0x00000003,
  90387. /* lg(4096/4095) = */ 0x00000001,
  90388. /* lg(8192/8191) = */ 0x00000001,
  90389. /* lg(16384/16383) = */ 0x00000000,
  90390. /* lg(32768/32767) = */ 0x00000000
  90391. },
  90392. {
  90393. /*
  90394. * 16 fraction bits
  90395. */
  90396. /* undefined */ 0x00000000,
  90397. /* lg(2/1) = */ 0x00010000,
  90398. /* lg(4/3) = */ 0x00006a40,
  90399. /* lg(8/7) = */ 0x00003151,
  90400. /* lg(16/15) = */ 0x000017d6,
  90401. /* lg(32/31) = */ 0x00000bba,
  90402. /* lg(64/63) = */ 0x000005d1,
  90403. /* lg(128/127) = */ 0x000002e6,
  90404. /* lg(256/255) = */ 0x00000172,
  90405. /* lg(512/511) = */ 0x000000b9,
  90406. /* lg(1024/1023) = */ 0x0000005c,
  90407. /* lg(2048/2047) = */ 0x0000002e,
  90408. /* lg(4096/4095) = */ 0x00000017,
  90409. /* lg(8192/8191) = */ 0x0000000c,
  90410. /* lg(16384/16383) = */ 0x00000006,
  90411. /* lg(32768/32767) = */ 0x00000003
  90412. },
  90413. {
  90414. /*
  90415. * 20 fraction bits
  90416. */
  90417. /* undefined */ 0x00000000,
  90418. /* lg(2/1) = */ 0x00100000,
  90419. /* lg(4/3) = */ 0x0006a3fe,
  90420. /* lg(8/7) = */ 0x00031513,
  90421. /* lg(16/15) = */ 0x00017d60,
  90422. /* lg(32/31) = */ 0x0000bb9d,
  90423. /* lg(64/63) = */ 0x00005d10,
  90424. /* lg(128/127) = */ 0x00002e59,
  90425. /* lg(256/255) = */ 0x00001721,
  90426. /* lg(512/511) = */ 0x00000b8e,
  90427. /* lg(1024/1023) = */ 0x000005c6,
  90428. /* lg(2048/2047) = */ 0x000002e3,
  90429. /* lg(4096/4095) = */ 0x00000171,
  90430. /* lg(8192/8191) = */ 0x000000b9,
  90431. /* lg(16384/16383) = */ 0x0000005c,
  90432. /* lg(32768/32767) = */ 0x0000002e
  90433. },
  90434. {
  90435. /*
  90436. * 24 fraction bits
  90437. */
  90438. /* undefined */ 0x00000000,
  90439. /* lg(2/1) = */ 0x01000000,
  90440. /* lg(4/3) = */ 0x006a3fe6,
  90441. /* lg(8/7) = */ 0x00315130,
  90442. /* lg(16/15) = */ 0x0017d605,
  90443. /* lg(32/31) = */ 0x000bb9ca,
  90444. /* lg(64/63) = */ 0x0005d0fc,
  90445. /* lg(128/127) = */ 0x0002e58f,
  90446. /* lg(256/255) = */ 0x0001720e,
  90447. /* lg(512/511) = */ 0x0000b8d8,
  90448. /* lg(1024/1023) = */ 0x00005c61,
  90449. /* lg(2048/2047) = */ 0x00002e2d,
  90450. /* lg(4096/4095) = */ 0x00001716,
  90451. /* lg(8192/8191) = */ 0x00000b8b,
  90452. /* lg(16384/16383) = */ 0x000005c5,
  90453. /* lg(32768/32767) = */ 0x000002e3
  90454. },
  90455. {
  90456. /*
  90457. * 28 fraction bits
  90458. */
  90459. /* undefined */ 0x00000000,
  90460. /* lg(2/1) = */ 0x10000000,
  90461. /* lg(4/3) = */ 0x06a3fe5c,
  90462. /* lg(8/7) = */ 0x03151301,
  90463. /* lg(16/15) = */ 0x017d6049,
  90464. /* lg(32/31) = */ 0x00bb9ca6,
  90465. /* lg(64/63) = */ 0x005d0fba,
  90466. /* lg(128/127) = */ 0x002e58f7,
  90467. /* lg(256/255) = */ 0x001720da,
  90468. /* lg(512/511) = */ 0x000b8d87,
  90469. /* lg(1024/1023) = */ 0x0005c60b,
  90470. /* lg(2048/2047) = */ 0x0002e2d7,
  90471. /* lg(4096/4095) = */ 0x00017160,
  90472. /* lg(8192/8191) = */ 0x0000b8ad,
  90473. /* lg(16384/16383) = */ 0x00005c56,
  90474. /* lg(32768/32767) = */ 0x00002e2b
  90475. }
  90476. };
  90477. #if 0
  90478. static const FLAC__uint64 log2_lookup_wide[] = {
  90479. {
  90480. /*
  90481. * 32 fraction bits
  90482. */
  90483. /* undefined */ 0x00000000,
  90484. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  90485. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  90486. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  90487. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  90488. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  90489. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  90490. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  90491. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  90492. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  90493. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  90494. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  90495. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  90496. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  90497. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  90498. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  90499. },
  90500. {
  90501. /*
  90502. * 48 fraction bits
  90503. */
  90504. /* undefined */ 0x00000000,
  90505. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  90506. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  90507. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  90508. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  90509. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  90510. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  90511. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  90512. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  90513. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  90514. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  90515. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  90516. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  90517. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  90518. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  90519. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  90520. }
  90521. };
  90522. #endif
  90523. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  90524. {
  90525. const FLAC__uint32 ONE = (1u << fracbits);
  90526. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  90527. FLAC__ASSERT(fracbits < 32);
  90528. FLAC__ASSERT((fracbits & 0x3) == 0);
  90529. if(x < ONE)
  90530. return 0;
  90531. if(precision > LOG2_LOOKUP_PRECISION)
  90532. precision = LOG2_LOOKUP_PRECISION;
  90533. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  90534. {
  90535. FLAC__uint32 y = 0;
  90536. FLAC__uint32 z = x >> 1, k = 1;
  90537. while (x > ONE && k < precision) {
  90538. if (x - z >= ONE) {
  90539. x -= z;
  90540. z = x >> k;
  90541. y += table[k];
  90542. }
  90543. else {
  90544. z >>= 1;
  90545. k++;
  90546. }
  90547. }
  90548. return y;
  90549. }
  90550. }
  90551. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  90552. #endif
  90553. /********* End of inlined file: float.c *********/
  90554. /********* Start of inlined file: format.c *********/
  90555. /********* Start of inlined file: juce_FlacHeader.h *********/
  90556. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90557. // tasks..
  90558. #define VERSION "1.2.1"
  90559. #define FLAC__NO_DLL 1
  90560. #ifdef _MSC_VER
  90561. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90562. #endif
  90563. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90564. #define FLAC__SYS_DARWIN 1
  90565. #endif
  90566. /********* End of inlined file: juce_FlacHeader.h *********/
  90567. #if JUCE_USE_FLAC
  90568. #if HAVE_CONFIG_H
  90569. # include <config.h>
  90570. #endif
  90571. #include <stdio.h>
  90572. #include <stdlib.h> /* for qsort() */
  90573. #include <string.h> /* for memset() */
  90574. #ifndef FLaC__INLINE
  90575. #define FLaC__INLINE
  90576. #endif
  90577. #ifdef min
  90578. #undef min
  90579. #endif
  90580. #define min(a,b) ((a)<(b)?(a):(b))
  90581. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  90582. #ifdef _MSC_VER
  90583. #define FLAC__U64L(x) x
  90584. #else
  90585. #define FLAC__U64L(x) x##LLU
  90586. #endif
  90587. /* VERSION should come from configure */
  90588. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  90589. ;
  90590. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  90591. /* yet one more hack because of MSVC6: */
  90592. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  90593. #else
  90594. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  90595. #endif
  90596. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  90597. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  90598. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  90599. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  90600. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  90601. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  90602. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  90603. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  90604. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  90605. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  90606. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  90607. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  90608. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  90609. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  90610. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  90611. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  90612. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  90613. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  90614. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  90615. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  90616. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  90617. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  90618. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  90619. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  90620. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  90621. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  90622. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  90623. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  90624. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  90625. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  90626. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  90627. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  90628. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  90629. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  90630. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  90631. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  90632. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  90633. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  90634. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  90635. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  90636. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  90637. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  90638. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  90639. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  90640. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  90641. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  90642. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  90643. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  90644. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  90645. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  90646. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  90647. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  90648. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  90649. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  90650. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  90651. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  90652. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  90653. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  90654. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  90655. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  90656. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  90657. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  90658. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  90659. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  90660. "PARTITIONED_RICE",
  90661. "PARTITIONED_RICE2"
  90662. };
  90663. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  90664. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  90665. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  90666. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  90667. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  90668. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  90669. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  90670. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  90671. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  90672. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  90673. "CONSTANT",
  90674. "VERBATIM",
  90675. "FIXED",
  90676. "LPC"
  90677. };
  90678. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  90679. "INDEPENDENT",
  90680. "LEFT_SIDE",
  90681. "RIGHT_SIDE",
  90682. "MID_SIDE"
  90683. };
  90684. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  90685. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  90686. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  90687. };
  90688. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  90689. "STREAMINFO",
  90690. "PADDING",
  90691. "APPLICATION",
  90692. "SEEKTABLE",
  90693. "VORBIS_COMMENT",
  90694. "CUESHEET",
  90695. "PICTURE"
  90696. };
  90697. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  90698. "Other",
  90699. "32x32 pixels 'file icon' (PNG only)",
  90700. "Other file icon",
  90701. "Cover (front)",
  90702. "Cover (back)",
  90703. "Leaflet page",
  90704. "Media (e.g. label side of CD)",
  90705. "Lead artist/lead performer/soloist",
  90706. "Artist/performer",
  90707. "Conductor",
  90708. "Band/Orchestra",
  90709. "Composer",
  90710. "Lyricist/text writer",
  90711. "Recording Location",
  90712. "During recording",
  90713. "During performance",
  90714. "Movie/video screen capture",
  90715. "A bright coloured fish",
  90716. "Illustration",
  90717. "Band/artist logotype",
  90718. "Publisher/Studio logotype"
  90719. };
  90720. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  90721. {
  90722. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  90723. return false;
  90724. }
  90725. else
  90726. return true;
  90727. }
  90728. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  90729. {
  90730. if(
  90731. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  90732. (
  90733. sample_rate >= (1u << 16) &&
  90734. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  90735. )
  90736. ) {
  90737. return false;
  90738. }
  90739. else
  90740. return true;
  90741. }
  90742. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90743. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  90744. {
  90745. unsigned i;
  90746. FLAC__uint64 prev_sample_number = 0;
  90747. FLAC__bool got_prev = false;
  90748. FLAC__ASSERT(0 != seek_table);
  90749. for(i = 0; i < seek_table->num_points; i++) {
  90750. if(got_prev) {
  90751. if(
  90752. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  90753. seek_table->points[i].sample_number <= prev_sample_number
  90754. )
  90755. return false;
  90756. }
  90757. prev_sample_number = seek_table->points[i].sample_number;
  90758. got_prev = true;
  90759. }
  90760. return true;
  90761. }
  90762. /* used as the sort predicate for qsort() */
  90763. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  90764. {
  90765. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  90766. if(l->sample_number == r->sample_number)
  90767. return 0;
  90768. else if(l->sample_number < r->sample_number)
  90769. return -1;
  90770. else
  90771. return 1;
  90772. }
  90773. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90774. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  90775. {
  90776. unsigned i, j;
  90777. FLAC__bool first;
  90778. FLAC__ASSERT(0 != seek_table);
  90779. /* sort the seekpoints */
  90780. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  90781. /* uniquify the seekpoints */
  90782. first = true;
  90783. for(i = j = 0; i < seek_table->num_points; i++) {
  90784. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  90785. if(!first) {
  90786. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  90787. continue;
  90788. }
  90789. }
  90790. first = false;
  90791. seek_table->points[j++] = seek_table->points[i];
  90792. }
  90793. for(i = j; i < seek_table->num_points; i++) {
  90794. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  90795. seek_table->points[i].stream_offset = 0;
  90796. seek_table->points[i].frame_samples = 0;
  90797. }
  90798. return j;
  90799. }
  90800. /*
  90801. * also disallows non-shortest-form encodings, c.f.
  90802. * http://www.unicode.org/versions/corrigendum1.html
  90803. * and a more clear explanation at the end of this section:
  90804. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  90805. */
  90806. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  90807. {
  90808. FLAC__ASSERT(0 != utf8);
  90809. if ((utf8[0] & 0x80) == 0) {
  90810. return 1;
  90811. }
  90812. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  90813. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  90814. return 0;
  90815. return 2;
  90816. }
  90817. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  90818. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  90819. return 0;
  90820. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  90821. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  90822. return 0;
  90823. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  90824. return 0;
  90825. return 3;
  90826. }
  90827. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  90828. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  90829. return 0;
  90830. return 4;
  90831. }
  90832. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  90833. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  90834. return 0;
  90835. return 5;
  90836. }
  90837. 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) {
  90838. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  90839. return 0;
  90840. return 6;
  90841. }
  90842. else {
  90843. return 0;
  90844. }
  90845. }
  90846. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  90847. {
  90848. char c;
  90849. for(c = *name; c; c = *(++name))
  90850. if(c < 0x20 || c == 0x3d || c > 0x7d)
  90851. return false;
  90852. return true;
  90853. }
  90854. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  90855. {
  90856. if(length == (unsigned)(-1)) {
  90857. while(*value) {
  90858. unsigned n = utf8len_(value);
  90859. if(n == 0)
  90860. return false;
  90861. value += n;
  90862. }
  90863. }
  90864. else {
  90865. const FLAC__byte *end = value + length;
  90866. while(value < end) {
  90867. unsigned n = utf8len_(value);
  90868. if(n == 0)
  90869. return false;
  90870. value += n;
  90871. }
  90872. if(value != end)
  90873. return false;
  90874. }
  90875. return true;
  90876. }
  90877. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  90878. {
  90879. const FLAC__byte *s, *end;
  90880. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  90881. if(*s < 0x20 || *s > 0x7D)
  90882. return false;
  90883. }
  90884. if(s == end)
  90885. return false;
  90886. s++; /* skip '=' */
  90887. while(s < end) {
  90888. unsigned n = utf8len_(s);
  90889. if(n == 0)
  90890. return false;
  90891. s += n;
  90892. }
  90893. if(s != end)
  90894. return false;
  90895. return true;
  90896. }
  90897. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90898. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  90899. {
  90900. unsigned i, j;
  90901. if(check_cd_da_subset) {
  90902. if(cue_sheet->lead_in < 2 * 44100) {
  90903. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  90904. return false;
  90905. }
  90906. if(cue_sheet->lead_in % 588 != 0) {
  90907. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  90908. return false;
  90909. }
  90910. }
  90911. if(cue_sheet->num_tracks == 0) {
  90912. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  90913. return false;
  90914. }
  90915. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  90916. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  90917. return false;
  90918. }
  90919. for(i = 0; i < cue_sheet->num_tracks; i++) {
  90920. if(cue_sheet->tracks[i].number == 0) {
  90921. if(violation) *violation = "cue sheet may not have a track number 0";
  90922. return false;
  90923. }
  90924. if(check_cd_da_subset) {
  90925. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  90926. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  90927. return false;
  90928. }
  90929. }
  90930. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  90931. if(violation) {
  90932. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  90933. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  90934. else
  90935. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  90936. }
  90937. return false;
  90938. }
  90939. if(i < cue_sheet->num_tracks - 1) {
  90940. if(cue_sheet->tracks[i].num_indices == 0) {
  90941. if(violation) *violation = "cue sheet track must have at least one index point";
  90942. return false;
  90943. }
  90944. if(cue_sheet->tracks[i].indices[0].number > 1) {
  90945. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  90946. return false;
  90947. }
  90948. }
  90949. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  90950. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  90951. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  90952. return false;
  90953. }
  90954. if(j > 0) {
  90955. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  90956. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  90957. return false;
  90958. }
  90959. }
  90960. }
  90961. }
  90962. return true;
  90963. }
  90964. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90965. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  90966. {
  90967. char *p;
  90968. FLAC__byte *b;
  90969. for(p = picture->mime_type; *p; p++) {
  90970. if(*p < 0x20 || *p > 0x7e) {
  90971. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  90972. return false;
  90973. }
  90974. }
  90975. for(b = picture->description; *b; ) {
  90976. unsigned n = utf8len_(b);
  90977. if(n == 0) {
  90978. if(violation) *violation = "description string must be valid UTF-8";
  90979. return false;
  90980. }
  90981. b += n;
  90982. }
  90983. return true;
  90984. }
  90985. /*
  90986. * These routines are private to libFLAC
  90987. */
  90988. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  90989. {
  90990. return
  90991. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  90992. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  90993. blocksize,
  90994. predictor_order
  90995. );
  90996. }
  90997. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  90998. {
  90999. unsigned max_rice_partition_order = 0;
  91000. while(!(blocksize & 1)) {
  91001. max_rice_partition_order++;
  91002. blocksize >>= 1;
  91003. }
  91004. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  91005. }
  91006. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  91007. {
  91008. unsigned max_rice_partition_order = limit;
  91009. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  91010. max_rice_partition_order--;
  91011. FLAC__ASSERT(
  91012. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  91013. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  91014. );
  91015. return max_rice_partition_order;
  91016. }
  91017. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  91018. {
  91019. FLAC__ASSERT(0 != object);
  91020. object->parameters = 0;
  91021. object->raw_bits = 0;
  91022. object->capacity_by_order = 0;
  91023. }
  91024. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  91025. {
  91026. FLAC__ASSERT(0 != object);
  91027. if(0 != object->parameters)
  91028. free(object->parameters);
  91029. if(0 != object->raw_bits)
  91030. free(object->raw_bits);
  91031. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  91032. }
  91033. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  91034. {
  91035. FLAC__ASSERT(0 != object);
  91036. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  91037. if(object->capacity_by_order < max_partition_order) {
  91038. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  91039. return false;
  91040. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  91041. return false;
  91042. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  91043. object->capacity_by_order = max_partition_order;
  91044. }
  91045. return true;
  91046. }
  91047. #endif
  91048. /********* End of inlined file: format.c *********/
  91049. /********* Start of inlined file: lpc_flac.c *********/
  91050. /********* Start of inlined file: juce_FlacHeader.h *********/
  91051. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91052. // tasks..
  91053. #define VERSION "1.2.1"
  91054. #define FLAC__NO_DLL 1
  91055. #ifdef _MSC_VER
  91056. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91057. #endif
  91058. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  91059. #define FLAC__SYS_DARWIN 1
  91060. #endif
  91061. /********* End of inlined file: juce_FlacHeader.h *********/
  91062. #if JUCE_USE_FLAC
  91063. #if HAVE_CONFIG_H
  91064. # include <config.h>
  91065. #endif
  91066. #include <math.h>
  91067. /********* Start of inlined file: lpc.h *********/
  91068. #ifndef FLAC__PRIVATE__LPC_H
  91069. #define FLAC__PRIVATE__LPC_H
  91070. #ifdef HAVE_CONFIG_H
  91071. #include <config.h>
  91072. #endif
  91073. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91074. /*
  91075. * FLAC__lpc_window_data()
  91076. * --------------------------------------------------------------------
  91077. * Applies the given window to the data.
  91078. * OPT: asm implementation
  91079. *
  91080. * IN in[0,data_len-1]
  91081. * IN window[0,data_len-1]
  91082. * OUT out[0,lag-1]
  91083. * IN data_len
  91084. */
  91085. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  91086. /*
  91087. * FLAC__lpc_compute_autocorrelation()
  91088. * --------------------------------------------------------------------
  91089. * Compute the autocorrelation for lags between 0 and lag-1.
  91090. * Assumes data[] outside of [0,data_len-1] == 0.
  91091. * Asserts that lag > 0.
  91092. *
  91093. * IN data[0,data_len-1]
  91094. * IN data_len
  91095. * IN 0 < lag <= data_len
  91096. * OUT autoc[0,lag-1]
  91097. */
  91098. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91099. #ifndef FLAC__NO_ASM
  91100. # ifdef FLAC__CPU_IA32
  91101. # ifdef FLAC__HAS_NASM
  91102. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91103. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91104. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91105. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91106. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  91107. # endif
  91108. # endif
  91109. #endif
  91110. /*
  91111. * FLAC__lpc_compute_lp_coefficients()
  91112. * --------------------------------------------------------------------
  91113. * Computes LP coefficients for orders 1..max_order.
  91114. * Do not call if autoc[0] == 0.0. This means the signal is zero
  91115. * and there is no point in calculating a predictor.
  91116. *
  91117. * IN autoc[0,max_order] autocorrelation values
  91118. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  91119. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  91120. * *** IMPORTANT:
  91121. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  91122. * OUT error[0,max_order-1] error for each order (more
  91123. * specifically, the variance of
  91124. * the error signal times # of
  91125. * samples in the signal)
  91126. *
  91127. * Example: if max_order is 9, the LP coefficients for order 9 will be
  91128. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  91129. * in lp_coeff[7][0,7], etc.
  91130. */
  91131. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  91132. /*
  91133. * FLAC__lpc_quantize_coefficients()
  91134. * --------------------------------------------------------------------
  91135. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  91136. * must be less than 32 (sizeof(FLAC__int32)*8).
  91137. *
  91138. * IN lp_coeff[0,order-1] LP coefficients
  91139. * IN order LP order
  91140. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  91141. * desired precision (in bits, including sign
  91142. * bit) of largest coefficient
  91143. * OUT qlp_coeff[0,order-1] quantized coefficients
  91144. * OUT shift # of bits to shift right to get approximated
  91145. * LP coefficients. NOTE: could be negative.
  91146. * RETURN 0 => quantization OK
  91147. * 1 => coefficients require too much shifting for *shift to
  91148. * fit in the LPC subframe header. 'shift' is unset.
  91149. * 2 => coefficients are all zero, which is bad. 'shift' is
  91150. * unset.
  91151. */
  91152. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  91153. /*
  91154. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  91155. * --------------------------------------------------------------------
  91156. * Compute the residual signal obtained from sutracting the predicted
  91157. * signal from the original.
  91158. *
  91159. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  91160. * IN data_len length of original signal
  91161. * IN qlp_coeff[0,order-1] quantized LP coefficients
  91162. * IN order > 0 LP order
  91163. * IN lp_quantization quantization of LP coefficients in bits
  91164. * OUT residual[0,data_len-1] residual signal
  91165. */
  91166. 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[]);
  91167. 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[]);
  91168. #ifndef FLAC__NO_ASM
  91169. # ifdef FLAC__CPU_IA32
  91170. # ifdef FLAC__HAS_NASM
  91171. 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[]);
  91172. 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[]);
  91173. # endif
  91174. # endif
  91175. #endif
  91176. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  91177. /*
  91178. * FLAC__lpc_restore_signal()
  91179. * --------------------------------------------------------------------
  91180. * Restore the original signal by summing the residual and the
  91181. * predictor.
  91182. *
  91183. * IN residual[0,data_len-1] residual signal
  91184. * IN data_len length of original signal
  91185. * IN qlp_coeff[0,order-1] quantized LP coefficients
  91186. * IN order > 0 LP order
  91187. * IN lp_quantization quantization of LP coefficients in bits
  91188. * *** IMPORTANT: the caller must pass in the historical samples:
  91189. * IN data[-order,-1] previously-reconstructed historical samples
  91190. * OUT data[0,data_len-1] original signal
  91191. */
  91192. 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[]);
  91193. 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[]);
  91194. #ifndef FLAC__NO_ASM
  91195. # ifdef FLAC__CPU_IA32
  91196. # ifdef FLAC__HAS_NASM
  91197. 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[]);
  91198. 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[]);
  91199. # endif /* FLAC__HAS_NASM */
  91200. # elif defined FLAC__CPU_PPC
  91201. 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[]);
  91202. 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[]);
  91203. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  91204. #endif /* FLAC__NO_ASM */
  91205. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91206. /*
  91207. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  91208. * --------------------------------------------------------------------
  91209. * Compute the expected number of bits per residual signal sample
  91210. * based on the LP error (which is related to the residual variance).
  91211. *
  91212. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  91213. * IN total_samples > 0 # of samples in residual signal
  91214. * RETURN expected bits per sample
  91215. */
  91216. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  91217. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  91218. /*
  91219. * FLAC__lpc_compute_best_order()
  91220. * --------------------------------------------------------------------
  91221. * Compute the best order from the array of signal errors returned
  91222. * during coefficient computation.
  91223. *
  91224. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  91225. * IN max_order > 0 max LP order
  91226. * IN total_samples > 0 # of samples in residual signal
  91227. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  91228. * (includes warmup sample size and quantized LP coefficient)
  91229. * RETURN [1,max_order] best order
  91230. */
  91231. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  91232. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  91233. #endif
  91234. /********* End of inlined file: lpc.h *********/
  91235. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  91236. #include <stdio.h>
  91237. #endif
  91238. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91239. #ifndef M_LN2
  91240. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  91241. #define M_LN2 0.69314718055994530942
  91242. #endif
  91243. /* OPT: #undef'ing this may improve the speed on some architectures */
  91244. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  91245. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  91246. {
  91247. unsigned i;
  91248. for(i = 0; i < data_len; i++)
  91249. out[i] = in[i] * window[i];
  91250. }
  91251. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  91252. {
  91253. /* a readable, but slower, version */
  91254. #if 0
  91255. FLAC__real d;
  91256. unsigned i;
  91257. FLAC__ASSERT(lag > 0);
  91258. FLAC__ASSERT(lag <= data_len);
  91259. /*
  91260. * Technically we should subtract the mean first like so:
  91261. * for(i = 0; i < data_len; i++)
  91262. * data[i] -= mean;
  91263. * but it appears not to make enough of a difference to matter, and
  91264. * most signals are already closely centered around zero
  91265. */
  91266. while(lag--) {
  91267. for(i = lag, d = 0.0; i < data_len; i++)
  91268. d += data[i] * data[i - lag];
  91269. autoc[lag] = d;
  91270. }
  91271. #endif
  91272. /*
  91273. * this version tends to run faster because of better data locality
  91274. * ('data_len' is usually much larger than 'lag')
  91275. */
  91276. FLAC__real d;
  91277. unsigned sample, coeff;
  91278. const unsigned limit = data_len - lag;
  91279. FLAC__ASSERT(lag > 0);
  91280. FLAC__ASSERT(lag <= data_len);
  91281. for(coeff = 0; coeff < lag; coeff++)
  91282. autoc[coeff] = 0.0;
  91283. for(sample = 0; sample <= limit; sample++) {
  91284. d = data[sample];
  91285. for(coeff = 0; coeff < lag; coeff++)
  91286. autoc[coeff] += d * data[sample+coeff];
  91287. }
  91288. for(; sample < data_len; sample++) {
  91289. d = data[sample];
  91290. for(coeff = 0; coeff < data_len - sample; coeff++)
  91291. autoc[coeff] += d * data[sample+coeff];
  91292. }
  91293. }
  91294. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  91295. {
  91296. unsigned i, j;
  91297. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  91298. FLAC__ASSERT(0 != max_order);
  91299. FLAC__ASSERT(0 < *max_order);
  91300. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  91301. FLAC__ASSERT(autoc[0] != 0.0);
  91302. err = autoc[0];
  91303. for(i = 0; i < *max_order; i++) {
  91304. /* Sum up this iteration's reflection coefficient. */
  91305. r = -autoc[i+1];
  91306. for(j = 0; j < i; j++)
  91307. r -= lpc[j] * autoc[i-j];
  91308. ref[i] = (r/=err);
  91309. /* Update LPC coefficients and total error. */
  91310. lpc[i]=r;
  91311. for(j = 0; j < (i>>1); j++) {
  91312. FLAC__double tmp = lpc[j];
  91313. lpc[j] += r * lpc[i-1-j];
  91314. lpc[i-1-j] += r * tmp;
  91315. }
  91316. if(i & 1)
  91317. lpc[j] += lpc[j] * r;
  91318. err *= (1.0 - r * r);
  91319. /* save this order */
  91320. for(j = 0; j <= i; j++)
  91321. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  91322. error[i] = err;
  91323. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  91324. if(err == 0.0) {
  91325. *max_order = i+1;
  91326. return;
  91327. }
  91328. }
  91329. }
  91330. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  91331. {
  91332. unsigned i;
  91333. FLAC__double cmax;
  91334. FLAC__int32 qmax, qmin;
  91335. FLAC__ASSERT(precision > 0);
  91336. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  91337. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  91338. precision--;
  91339. qmax = 1 << precision;
  91340. qmin = -qmax;
  91341. qmax--;
  91342. /* calc cmax = max( |lp_coeff[i]| ) */
  91343. cmax = 0.0;
  91344. for(i = 0; i < order; i++) {
  91345. const FLAC__double d = fabs(lp_coeff[i]);
  91346. if(d > cmax)
  91347. cmax = d;
  91348. }
  91349. if(cmax <= 0.0) {
  91350. /* => coefficients are all 0, which means our constant-detect didn't work */
  91351. return 2;
  91352. }
  91353. else {
  91354. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  91355. const int min_shiftlimit = -max_shiftlimit - 1;
  91356. int log2cmax;
  91357. (void)frexp(cmax, &log2cmax);
  91358. log2cmax--;
  91359. *shift = (int)precision - log2cmax - 1;
  91360. if(*shift > max_shiftlimit)
  91361. *shift = max_shiftlimit;
  91362. else if(*shift < min_shiftlimit)
  91363. return 1;
  91364. }
  91365. if(*shift >= 0) {
  91366. FLAC__double error = 0.0;
  91367. FLAC__int32 q;
  91368. for(i = 0; i < order; i++) {
  91369. error += lp_coeff[i] * (1 << *shift);
  91370. #if 1 /* unfortunately lround() is C99 */
  91371. if(error >= 0.0)
  91372. q = (FLAC__int32)(error + 0.5);
  91373. else
  91374. q = (FLAC__int32)(error - 0.5);
  91375. #else
  91376. q = lround(error);
  91377. #endif
  91378. #ifdef FLAC__OVERFLOW_DETECT
  91379. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  91380. 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]);
  91381. else if(q < qmin)
  91382. 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]);
  91383. #endif
  91384. if(q > qmax)
  91385. q = qmax;
  91386. else if(q < qmin)
  91387. q = qmin;
  91388. error -= q;
  91389. qlp_coeff[i] = q;
  91390. }
  91391. }
  91392. /* negative shift is very rare but due to design flaw, negative shift is
  91393. * a NOP in the decoder, so it must be handled specially by scaling down
  91394. * coeffs
  91395. */
  91396. else {
  91397. const int nshift = -(*shift);
  91398. FLAC__double error = 0.0;
  91399. FLAC__int32 q;
  91400. #ifdef DEBUG
  91401. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  91402. #endif
  91403. for(i = 0; i < order; i++) {
  91404. error += lp_coeff[i] / (1 << nshift);
  91405. #if 1 /* unfortunately lround() is C99 */
  91406. if(error >= 0.0)
  91407. q = (FLAC__int32)(error + 0.5);
  91408. else
  91409. q = (FLAC__int32)(error - 0.5);
  91410. #else
  91411. q = lround(error);
  91412. #endif
  91413. #ifdef FLAC__OVERFLOW_DETECT
  91414. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  91415. 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]);
  91416. else if(q < qmin)
  91417. 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]);
  91418. #endif
  91419. if(q > qmax)
  91420. q = qmax;
  91421. else if(q < qmin)
  91422. q = qmin;
  91423. error -= q;
  91424. qlp_coeff[i] = q;
  91425. }
  91426. *shift = 0;
  91427. }
  91428. return 0;
  91429. }
  91430. 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[])
  91431. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  91432. {
  91433. FLAC__int64 sumo;
  91434. unsigned i, j;
  91435. FLAC__int32 sum;
  91436. const FLAC__int32 *history;
  91437. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  91438. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  91439. for(i=0;i<order;i++)
  91440. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  91441. fprintf(stderr,"\n");
  91442. #endif
  91443. FLAC__ASSERT(order > 0);
  91444. for(i = 0; i < data_len; i++) {
  91445. sumo = 0;
  91446. sum = 0;
  91447. history = data;
  91448. for(j = 0; j < order; j++) {
  91449. sum += qlp_coeff[j] * (*(--history));
  91450. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  91451. #if defined _MSC_VER
  91452. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  91453. 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);
  91454. #else
  91455. if(sumo > 2147483647ll || sumo < -2147483648ll)
  91456. 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);
  91457. #endif
  91458. }
  91459. *(residual++) = *(data++) - (sum >> lp_quantization);
  91460. }
  91461. /* Here's a slower but clearer version:
  91462. for(i = 0; i < data_len; i++) {
  91463. sum = 0;
  91464. for(j = 0; j < order; j++)
  91465. sum += qlp_coeff[j] * data[i-j-1];
  91466. residual[i] = data[i] - (sum >> lp_quantization);
  91467. }
  91468. */
  91469. }
  91470. #else /* fully unrolled version for normal use */
  91471. {
  91472. int i;
  91473. FLAC__int32 sum;
  91474. FLAC__ASSERT(order > 0);
  91475. FLAC__ASSERT(order <= 32);
  91476. /*
  91477. * We do unique versions up to 12th order since that's the subset limit.
  91478. * Also they are roughly ordered to match frequency of occurrence to
  91479. * minimize branching.
  91480. */
  91481. if(order <= 12) {
  91482. if(order > 8) {
  91483. if(order > 10) {
  91484. if(order == 12) {
  91485. for(i = 0; i < (int)data_len; i++) {
  91486. sum = 0;
  91487. sum += qlp_coeff[11] * data[i-12];
  91488. sum += qlp_coeff[10] * data[i-11];
  91489. sum += qlp_coeff[9] * data[i-10];
  91490. sum += qlp_coeff[8] * data[i-9];
  91491. sum += qlp_coeff[7] * data[i-8];
  91492. sum += qlp_coeff[6] * data[i-7];
  91493. sum += qlp_coeff[5] * data[i-6];
  91494. sum += qlp_coeff[4] * data[i-5];
  91495. sum += qlp_coeff[3] * data[i-4];
  91496. sum += qlp_coeff[2] * data[i-3];
  91497. sum += qlp_coeff[1] * data[i-2];
  91498. sum += qlp_coeff[0] * data[i-1];
  91499. residual[i] = data[i] - (sum >> lp_quantization);
  91500. }
  91501. }
  91502. else { /* order == 11 */
  91503. for(i = 0; i < (int)data_len; i++) {
  91504. sum = 0;
  91505. sum += qlp_coeff[10] * data[i-11];
  91506. sum += qlp_coeff[9] * data[i-10];
  91507. sum += qlp_coeff[8] * data[i-9];
  91508. sum += qlp_coeff[7] * data[i-8];
  91509. sum += qlp_coeff[6] * data[i-7];
  91510. sum += qlp_coeff[5] * data[i-6];
  91511. sum += qlp_coeff[4] * data[i-5];
  91512. sum += qlp_coeff[3] * data[i-4];
  91513. sum += qlp_coeff[2] * data[i-3];
  91514. sum += qlp_coeff[1] * data[i-2];
  91515. sum += qlp_coeff[0] * data[i-1];
  91516. residual[i] = data[i] - (sum >> lp_quantization);
  91517. }
  91518. }
  91519. }
  91520. else {
  91521. if(order == 10) {
  91522. for(i = 0; i < (int)data_len; i++) {
  91523. sum = 0;
  91524. sum += qlp_coeff[9] * data[i-10];
  91525. sum += qlp_coeff[8] * data[i-9];
  91526. sum += qlp_coeff[7] * data[i-8];
  91527. sum += qlp_coeff[6] * data[i-7];
  91528. sum += qlp_coeff[5] * data[i-6];
  91529. sum += qlp_coeff[4] * data[i-5];
  91530. sum += qlp_coeff[3] * data[i-4];
  91531. sum += qlp_coeff[2] * data[i-3];
  91532. sum += qlp_coeff[1] * data[i-2];
  91533. sum += qlp_coeff[0] * data[i-1];
  91534. residual[i] = data[i] - (sum >> lp_quantization);
  91535. }
  91536. }
  91537. else { /* order == 9 */
  91538. for(i = 0; i < (int)data_len; i++) {
  91539. sum = 0;
  91540. sum += qlp_coeff[8] * data[i-9];
  91541. sum += qlp_coeff[7] * data[i-8];
  91542. sum += qlp_coeff[6] * data[i-7];
  91543. sum += qlp_coeff[5] * data[i-6];
  91544. sum += qlp_coeff[4] * data[i-5];
  91545. sum += qlp_coeff[3] * data[i-4];
  91546. sum += qlp_coeff[2] * data[i-3];
  91547. sum += qlp_coeff[1] * data[i-2];
  91548. sum += qlp_coeff[0] * data[i-1];
  91549. residual[i] = data[i] - (sum >> lp_quantization);
  91550. }
  91551. }
  91552. }
  91553. }
  91554. else if(order > 4) {
  91555. if(order > 6) {
  91556. if(order == 8) {
  91557. for(i = 0; i < (int)data_len; i++) {
  91558. sum = 0;
  91559. sum += qlp_coeff[7] * data[i-8];
  91560. sum += qlp_coeff[6] * data[i-7];
  91561. sum += qlp_coeff[5] * data[i-6];
  91562. sum += qlp_coeff[4] * data[i-5];
  91563. sum += qlp_coeff[3] * data[i-4];
  91564. sum += qlp_coeff[2] * data[i-3];
  91565. sum += qlp_coeff[1] * data[i-2];
  91566. sum += qlp_coeff[0] * data[i-1];
  91567. residual[i] = data[i] - (sum >> lp_quantization);
  91568. }
  91569. }
  91570. else { /* order == 7 */
  91571. for(i = 0; i < (int)data_len; i++) {
  91572. sum = 0;
  91573. sum += qlp_coeff[6] * data[i-7];
  91574. sum += qlp_coeff[5] * data[i-6];
  91575. sum += qlp_coeff[4] * data[i-5];
  91576. sum += qlp_coeff[3] * data[i-4];
  91577. sum += qlp_coeff[2] * data[i-3];
  91578. sum += qlp_coeff[1] * data[i-2];
  91579. sum += qlp_coeff[0] * data[i-1];
  91580. residual[i] = data[i] - (sum >> lp_quantization);
  91581. }
  91582. }
  91583. }
  91584. else {
  91585. if(order == 6) {
  91586. for(i = 0; i < (int)data_len; i++) {
  91587. sum = 0;
  91588. sum += qlp_coeff[5] * data[i-6];
  91589. sum += qlp_coeff[4] * data[i-5];
  91590. sum += qlp_coeff[3] * data[i-4];
  91591. sum += qlp_coeff[2] * data[i-3];
  91592. sum += qlp_coeff[1] * data[i-2];
  91593. sum += qlp_coeff[0] * data[i-1];
  91594. residual[i] = data[i] - (sum >> lp_quantization);
  91595. }
  91596. }
  91597. else { /* order == 5 */
  91598. for(i = 0; i < (int)data_len; i++) {
  91599. sum = 0;
  91600. sum += qlp_coeff[4] * data[i-5];
  91601. sum += qlp_coeff[3] * data[i-4];
  91602. sum += qlp_coeff[2] * data[i-3];
  91603. sum += qlp_coeff[1] * data[i-2];
  91604. sum += qlp_coeff[0] * data[i-1];
  91605. residual[i] = data[i] - (sum >> lp_quantization);
  91606. }
  91607. }
  91608. }
  91609. }
  91610. else {
  91611. if(order > 2) {
  91612. if(order == 4) {
  91613. for(i = 0; i < (int)data_len; i++) {
  91614. sum = 0;
  91615. sum += qlp_coeff[3] * data[i-4];
  91616. sum += qlp_coeff[2] * data[i-3];
  91617. sum += qlp_coeff[1] * data[i-2];
  91618. sum += qlp_coeff[0] * data[i-1];
  91619. residual[i] = data[i] - (sum >> lp_quantization);
  91620. }
  91621. }
  91622. else { /* order == 3 */
  91623. for(i = 0; i < (int)data_len; i++) {
  91624. sum = 0;
  91625. sum += qlp_coeff[2] * data[i-3];
  91626. sum += qlp_coeff[1] * data[i-2];
  91627. sum += qlp_coeff[0] * data[i-1];
  91628. residual[i] = data[i] - (sum >> lp_quantization);
  91629. }
  91630. }
  91631. }
  91632. else {
  91633. if(order == 2) {
  91634. for(i = 0; i < (int)data_len; i++) {
  91635. sum = 0;
  91636. sum += qlp_coeff[1] * data[i-2];
  91637. sum += qlp_coeff[0] * data[i-1];
  91638. residual[i] = data[i] - (sum >> lp_quantization);
  91639. }
  91640. }
  91641. else { /* order == 1 */
  91642. for(i = 0; i < (int)data_len; i++)
  91643. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  91644. }
  91645. }
  91646. }
  91647. }
  91648. else { /* order > 12 */
  91649. for(i = 0; i < (int)data_len; i++) {
  91650. sum = 0;
  91651. switch(order) {
  91652. case 32: sum += qlp_coeff[31] * data[i-32];
  91653. case 31: sum += qlp_coeff[30] * data[i-31];
  91654. case 30: sum += qlp_coeff[29] * data[i-30];
  91655. case 29: sum += qlp_coeff[28] * data[i-29];
  91656. case 28: sum += qlp_coeff[27] * data[i-28];
  91657. case 27: sum += qlp_coeff[26] * data[i-27];
  91658. case 26: sum += qlp_coeff[25] * data[i-26];
  91659. case 25: sum += qlp_coeff[24] * data[i-25];
  91660. case 24: sum += qlp_coeff[23] * data[i-24];
  91661. case 23: sum += qlp_coeff[22] * data[i-23];
  91662. case 22: sum += qlp_coeff[21] * data[i-22];
  91663. case 21: sum += qlp_coeff[20] * data[i-21];
  91664. case 20: sum += qlp_coeff[19] * data[i-20];
  91665. case 19: sum += qlp_coeff[18] * data[i-19];
  91666. case 18: sum += qlp_coeff[17] * data[i-18];
  91667. case 17: sum += qlp_coeff[16] * data[i-17];
  91668. case 16: sum += qlp_coeff[15] * data[i-16];
  91669. case 15: sum += qlp_coeff[14] * data[i-15];
  91670. case 14: sum += qlp_coeff[13] * data[i-14];
  91671. case 13: sum += qlp_coeff[12] * data[i-13];
  91672. sum += qlp_coeff[11] * data[i-12];
  91673. sum += qlp_coeff[10] * data[i-11];
  91674. sum += qlp_coeff[ 9] * data[i-10];
  91675. sum += qlp_coeff[ 8] * data[i- 9];
  91676. sum += qlp_coeff[ 7] * data[i- 8];
  91677. sum += qlp_coeff[ 6] * data[i- 7];
  91678. sum += qlp_coeff[ 5] * data[i- 6];
  91679. sum += qlp_coeff[ 4] * data[i- 5];
  91680. sum += qlp_coeff[ 3] * data[i- 4];
  91681. sum += qlp_coeff[ 2] * data[i- 3];
  91682. sum += qlp_coeff[ 1] * data[i- 2];
  91683. sum += qlp_coeff[ 0] * data[i- 1];
  91684. }
  91685. residual[i] = data[i] - (sum >> lp_quantization);
  91686. }
  91687. }
  91688. }
  91689. #endif
  91690. 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[])
  91691. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  91692. {
  91693. unsigned i, j;
  91694. FLAC__int64 sum;
  91695. const FLAC__int32 *history;
  91696. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  91697. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  91698. for(i=0;i<order;i++)
  91699. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  91700. fprintf(stderr,"\n");
  91701. #endif
  91702. FLAC__ASSERT(order > 0);
  91703. for(i = 0; i < data_len; i++) {
  91704. sum = 0;
  91705. history = data;
  91706. for(j = 0; j < order; j++)
  91707. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  91708. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  91709. #if defined _MSC_VER
  91710. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  91711. #else
  91712. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  91713. #endif
  91714. break;
  91715. }
  91716. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  91717. #if defined _MSC_VER
  91718. 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));
  91719. #else
  91720. 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)));
  91721. #endif
  91722. break;
  91723. }
  91724. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  91725. }
  91726. }
  91727. #else /* fully unrolled version for normal use */
  91728. {
  91729. int i;
  91730. FLAC__int64 sum;
  91731. FLAC__ASSERT(order > 0);
  91732. FLAC__ASSERT(order <= 32);
  91733. /*
  91734. * We do unique versions up to 12th order since that's the subset limit.
  91735. * Also they are roughly ordered to match frequency of occurrence to
  91736. * minimize branching.
  91737. */
  91738. if(order <= 12) {
  91739. if(order > 8) {
  91740. if(order > 10) {
  91741. if(order == 12) {
  91742. for(i = 0; i < (int)data_len; i++) {
  91743. sum = 0;
  91744. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  91745. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91746. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91747. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91748. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91749. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91750. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91751. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91752. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91753. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91754. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91755. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91756. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91757. }
  91758. }
  91759. else { /* order == 11 */
  91760. for(i = 0; i < (int)data_len; i++) {
  91761. sum = 0;
  91762. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91763. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91764. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91765. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91766. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91767. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91768. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91769. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91770. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91771. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91772. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91773. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91774. }
  91775. }
  91776. }
  91777. else {
  91778. if(order == 10) {
  91779. for(i = 0; i < (int)data_len; i++) {
  91780. sum = 0;
  91781. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91782. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91783. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91784. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91785. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91786. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91787. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91788. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91789. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91790. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91791. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91792. }
  91793. }
  91794. else { /* order == 9 */
  91795. for(i = 0; i < (int)data_len; i++) {
  91796. sum = 0;
  91797. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91798. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91799. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91800. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91801. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91802. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91803. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91804. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91805. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91806. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91807. }
  91808. }
  91809. }
  91810. }
  91811. else if(order > 4) {
  91812. if(order > 6) {
  91813. if(order == 8) {
  91814. for(i = 0; i < (int)data_len; i++) {
  91815. sum = 0;
  91816. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91817. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91818. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91819. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91820. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91821. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91822. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91823. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91824. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91825. }
  91826. }
  91827. else { /* order == 7 */
  91828. for(i = 0; i < (int)data_len; i++) {
  91829. sum = 0;
  91830. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91831. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91832. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91833. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91834. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91835. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91836. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91837. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91838. }
  91839. }
  91840. }
  91841. else {
  91842. if(order == 6) {
  91843. for(i = 0; i < (int)data_len; i++) {
  91844. sum = 0;
  91845. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91846. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91847. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91848. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91849. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91850. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91851. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91852. }
  91853. }
  91854. else { /* order == 5 */
  91855. for(i = 0; i < (int)data_len; i++) {
  91856. sum = 0;
  91857. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91858. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91859. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91860. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91861. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91862. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91863. }
  91864. }
  91865. }
  91866. }
  91867. else {
  91868. if(order > 2) {
  91869. if(order == 4) {
  91870. for(i = 0; i < (int)data_len; i++) {
  91871. sum = 0;
  91872. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91873. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91874. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91875. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91876. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91877. }
  91878. }
  91879. else { /* order == 3 */
  91880. for(i = 0; i < (int)data_len; i++) {
  91881. sum = 0;
  91882. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91883. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91884. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91885. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91886. }
  91887. }
  91888. }
  91889. else {
  91890. if(order == 2) {
  91891. for(i = 0; i < (int)data_len; i++) {
  91892. sum = 0;
  91893. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91894. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91895. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91896. }
  91897. }
  91898. else { /* order == 1 */
  91899. for(i = 0; i < (int)data_len; i++)
  91900. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  91901. }
  91902. }
  91903. }
  91904. }
  91905. else { /* order > 12 */
  91906. for(i = 0; i < (int)data_len; i++) {
  91907. sum = 0;
  91908. switch(order) {
  91909. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  91910. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  91911. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  91912. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  91913. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  91914. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  91915. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  91916. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  91917. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  91918. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  91919. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  91920. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  91921. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  91922. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  91923. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  91924. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  91925. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  91926. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  91927. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  91928. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  91929. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  91930. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91931. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  91932. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  91933. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  91934. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  91935. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  91936. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  91937. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  91938. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  91939. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  91940. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  91941. }
  91942. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91943. }
  91944. }
  91945. }
  91946. #endif
  91947. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  91948. 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[])
  91949. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  91950. {
  91951. FLAC__int64 sumo;
  91952. unsigned i, j;
  91953. FLAC__int32 sum;
  91954. const FLAC__int32 *r = residual, *history;
  91955. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  91956. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  91957. for(i=0;i<order;i++)
  91958. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  91959. fprintf(stderr,"\n");
  91960. #endif
  91961. FLAC__ASSERT(order > 0);
  91962. for(i = 0; i < data_len; i++) {
  91963. sumo = 0;
  91964. sum = 0;
  91965. history = data;
  91966. for(j = 0; j < order; j++) {
  91967. sum += qlp_coeff[j] * (*(--history));
  91968. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  91969. #if defined _MSC_VER
  91970. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  91971. 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);
  91972. #else
  91973. if(sumo > 2147483647ll || sumo < -2147483648ll)
  91974. 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);
  91975. #endif
  91976. }
  91977. *(data++) = *(r++) + (sum >> lp_quantization);
  91978. }
  91979. /* Here's a slower but clearer version:
  91980. for(i = 0; i < data_len; i++) {
  91981. sum = 0;
  91982. for(j = 0; j < order; j++)
  91983. sum += qlp_coeff[j] * data[i-j-1];
  91984. data[i] = residual[i] + (sum >> lp_quantization);
  91985. }
  91986. */
  91987. }
  91988. #else /* fully unrolled version for normal use */
  91989. {
  91990. int i;
  91991. FLAC__int32 sum;
  91992. FLAC__ASSERT(order > 0);
  91993. FLAC__ASSERT(order <= 32);
  91994. /*
  91995. * We do unique versions up to 12th order since that's the subset limit.
  91996. * Also they are roughly ordered to match frequency of occurrence to
  91997. * minimize branching.
  91998. */
  91999. if(order <= 12) {
  92000. if(order > 8) {
  92001. if(order > 10) {
  92002. if(order == 12) {
  92003. for(i = 0; i < (int)data_len; i++) {
  92004. sum = 0;
  92005. sum += qlp_coeff[11] * data[i-12];
  92006. sum += qlp_coeff[10] * data[i-11];
  92007. sum += qlp_coeff[9] * data[i-10];
  92008. sum += qlp_coeff[8] * data[i-9];
  92009. sum += qlp_coeff[7] * data[i-8];
  92010. sum += qlp_coeff[6] * data[i-7];
  92011. sum += qlp_coeff[5] * data[i-6];
  92012. sum += qlp_coeff[4] * data[i-5];
  92013. sum += qlp_coeff[3] * data[i-4];
  92014. sum += qlp_coeff[2] * data[i-3];
  92015. sum += qlp_coeff[1] * data[i-2];
  92016. sum += qlp_coeff[0] * data[i-1];
  92017. data[i] = residual[i] + (sum >> lp_quantization);
  92018. }
  92019. }
  92020. else { /* order == 11 */
  92021. for(i = 0; i < (int)data_len; i++) {
  92022. sum = 0;
  92023. sum += qlp_coeff[10] * data[i-11];
  92024. sum += qlp_coeff[9] * data[i-10];
  92025. sum += qlp_coeff[8] * data[i-9];
  92026. sum += qlp_coeff[7] * data[i-8];
  92027. sum += qlp_coeff[6] * data[i-7];
  92028. sum += qlp_coeff[5] * data[i-6];
  92029. sum += qlp_coeff[4] * data[i-5];
  92030. sum += qlp_coeff[3] * data[i-4];
  92031. sum += qlp_coeff[2] * data[i-3];
  92032. sum += qlp_coeff[1] * data[i-2];
  92033. sum += qlp_coeff[0] * data[i-1];
  92034. data[i] = residual[i] + (sum >> lp_quantization);
  92035. }
  92036. }
  92037. }
  92038. else {
  92039. if(order == 10) {
  92040. for(i = 0; i < (int)data_len; i++) {
  92041. sum = 0;
  92042. sum += qlp_coeff[9] * data[i-10];
  92043. sum += qlp_coeff[8] * data[i-9];
  92044. sum += qlp_coeff[7] * data[i-8];
  92045. sum += qlp_coeff[6] * data[i-7];
  92046. sum += qlp_coeff[5] * data[i-6];
  92047. sum += qlp_coeff[4] * data[i-5];
  92048. sum += qlp_coeff[3] * data[i-4];
  92049. sum += qlp_coeff[2] * data[i-3];
  92050. sum += qlp_coeff[1] * data[i-2];
  92051. sum += qlp_coeff[0] * data[i-1];
  92052. data[i] = residual[i] + (sum >> lp_quantization);
  92053. }
  92054. }
  92055. else { /* order == 9 */
  92056. for(i = 0; i < (int)data_len; i++) {
  92057. sum = 0;
  92058. sum += qlp_coeff[8] * data[i-9];
  92059. sum += qlp_coeff[7] * data[i-8];
  92060. sum += qlp_coeff[6] * data[i-7];
  92061. sum += qlp_coeff[5] * data[i-6];
  92062. sum += qlp_coeff[4] * data[i-5];
  92063. sum += qlp_coeff[3] * data[i-4];
  92064. sum += qlp_coeff[2] * data[i-3];
  92065. sum += qlp_coeff[1] * data[i-2];
  92066. sum += qlp_coeff[0] * data[i-1];
  92067. data[i] = residual[i] + (sum >> lp_quantization);
  92068. }
  92069. }
  92070. }
  92071. }
  92072. else if(order > 4) {
  92073. if(order > 6) {
  92074. if(order == 8) {
  92075. for(i = 0; i < (int)data_len; i++) {
  92076. sum = 0;
  92077. sum += qlp_coeff[7] * data[i-8];
  92078. sum += qlp_coeff[6] * data[i-7];
  92079. sum += qlp_coeff[5] * data[i-6];
  92080. sum += qlp_coeff[4] * data[i-5];
  92081. sum += qlp_coeff[3] * data[i-4];
  92082. sum += qlp_coeff[2] * data[i-3];
  92083. sum += qlp_coeff[1] * data[i-2];
  92084. sum += qlp_coeff[0] * data[i-1];
  92085. data[i] = residual[i] + (sum >> lp_quantization);
  92086. }
  92087. }
  92088. else { /* order == 7 */
  92089. for(i = 0; i < (int)data_len; i++) {
  92090. sum = 0;
  92091. sum += qlp_coeff[6] * data[i-7];
  92092. sum += qlp_coeff[5] * data[i-6];
  92093. sum += qlp_coeff[4] * data[i-5];
  92094. sum += qlp_coeff[3] * data[i-4];
  92095. sum += qlp_coeff[2] * data[i-3];
  92096. sum += qlp_coeff[1] * data[i-2];
  92097. sum += qlp_coeff[0] * data[i-1];
  92098. data[i] = residual[i] + (sum >> lp_quantization);
  92099. }
  92100. }
  92101. }
  92102. else {
  92103. if(order == 6) {
  92104. for(i = 0; i < (int)data_len; i++) {
  92105. sum = 0;
  92106. sum += qlp_coeff[5] * data[i-6];
  92107. sum += qlp_coeff[4] * data[i-5];
  92108. sum += qlp_coeff[3] * data[i-4];
  92109. sum += qlp_coeff[2] * data[i-3];
  92110. sum += qlp_coeff[1] * data[i-2];
  92111. sum += qlp_coeff[0] * data[i-1];
  92112. data[i] = residual[i] + (sum >> lp_quantization);
  92113. }
  92114. }
  92115. else { /* order == 5 */
  92116. for(i = 0; i < (int)data_len; i++) {
  92117. sum = 0;
  92118. sum += qlp_coeff[4] * data[i-5];
  92119. sum += qlp_coeff[3] * data[i-4];
  92120. sum += qlp_coeff[2] * data[i-3];
  92121. sum += qlp_coeff[1] * data[i-2];
  92122. sum += qlp_coeff[0] * data[i-1];
  92123. data[i] = residual[i] + (sum >> lp_quantization);
  92124. }
  92125. }
  92126. }
  92127. }
  92128. else {
  92129. if(order > 2) {
  92130. if(order == 4) {
  92131. for(i = 0; i < (int)data_len; i++) {
  92132. sum = 0;
  92133. sum += qlp_coeff[3] * data[i-4];
  92134. sum += qlp_coeff[2] * data[i-3];
  92135. sum += qlp_coeff[1] * data[i-2];
  92136. sum += qlp_coeff[0] * data[i-1];
  92137. data[i] = residual[i] + (sum >> lp_quantization);
  92138. }
  92139. }
  92140. else { /* order == 3 */
  92141. for(i = 0; i < (int)data_len; i++) {
  92142. sum = 0;
  92143. sum += qlp_coeff[2] * data[i-3];
  92144. sum += qlp_coeff[1] * data[i-2];
  92145. sum += qlp_coeff[0] * data[i-1];
  92146. data[i] = residual[i] + (sum >> lp_quantization);
  92147. }
  92148. }
  92149. }
  92150. else {
  92151. if(order == 2) {
  92152. for(i = 0; i < (int)data_len; i++) {
  92153. sum = 0;
  92154. sum += qlp_coeff[1] * data[i-2];
  92155. sum += qlp_coeff[0] * data[i-1];
  92156. data[i] = residual[i] + (sum >> lp_quantization);
  92157. }
  92158. }
  92159. else { /* order == 1 */
  92160. for(i = 0; i < (int)data_len; i++)
  92161. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  92162. }
  92163. }
  92164. }
  92165. }
  92166. else { /* order > 12 */
  92167. for(i = 0; i < (int)data_len; i++) {
  92168. sum = 0;
  92169. switch(order) {
  92170. case 32: sum += qlp_coeff[31] * data[i-32];
  92171. case 31: sum += qlp_coeff[30] * data[i-31];
  92172. case 30: sum += qlp_coeff[29] * data[i-30];
  92173. case 29: sum += qlp_coeff[28] * data[i-29];
  92174. case 28: sum += qlp_coeff[27] * data[i-28];
  92175. case 27: sum += qlp_coeff[26] * data[i-27];
  92176. case 26: sum += qlp_coeff[25] * data[i-26];
  92177. case 25: sum += qlp_coeff[24] * data[i-25];
  92178. case 24: sum += qlp_coeff[23] * data[i-24];
  92179. case 23: sum += qlp_coeff[22] * data[i-23];
  92180. case 22: sum += qlp_coeff[21] * data[i-22];
  92181. case 21: sum += qlp_coeff[20] * data[i-21];
  92182. case 20: sum += qlp_coeff[19] * data[i-20];
  92183. case 19: sum += qlp_coeff[18] * data[i-19];
  92184. case 18: sum += qlp_coeff[17] * data[i-18];
  92185. case 17: sum += qlp_coeff[16] * data[i-17];
  92186. case 16: sum += qlp_coeff[15] * data[i-16];
  92187. case 15: sum += qlp_coeff[14] * data[i-15];
  92188. case 14: sum += qlp_coeff[13] * data[i-14];
  92189. case 13: sum += qlp_coeff[12] * data[i-13];
  92190. sum += qlp_coeff[11] * data[i-12];
  92191. sum += qlp_coeff[10] * data[i-11];
  92192. sum += qlp_coeff[ 9] * data[i-10];
  92193. sum += qlp_coeff[ 8] * data[i- 9];
  92194. sum += qlp_coeff[ 7] * data[i- 8];
  92195. sum += qlp_coeff[ 6] * data[i- 7];
  92196. sum += qlp_coeff[ 5] * data[i- 6];
  92197. sum += qlp_coeff[ 4] * data[i- 5];
  92198. sum += qlp_coeff[ 3] * data[i- 4];
  92199. sum += qlp_coeff[ 2] * data[i- 3];
  92200. sum += qlp_coeff[ 1] * data[i- 2];
  92201. sum += qlp_coeff[ 0] * data[i- 1];
  92202. }
  92203. data[i] = residual[i] + (sum >> lp_quantization);
  92204. }
  92205. }
  92206. }
  92207. #endif
  92208. 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[])
  92209. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  92210. {
  92211. unsigned i, j;
  92212. FLAC__int64 sum;
  92213. const FLAC__int32 *r = residual, *history;
  92214. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  92215. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  92216. for(i=0;i<order;i++)
  92217. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  92218. fprintf(stderr,"\n");
  92219. #endif
  92220. FLAC__ASSERT(order > 0);
  92221. for(i = 0; i < data_len; i++) {
  92222. sum = 0;
  92223. history = data;
  92224. for(j = 0; j < order; j++)
  92225. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  92226. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  92227. #ifdef _MSC_VER
  92228. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  92229. #else
  92230. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  92231. #endif
  92232. break;
  92233. }
  92234. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  92235. #ifdef _MSC_VER
  92236. 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));
  92237. #else
  92238. 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)));
  92239. #endif
  92240. break;
  92241. }
  92242. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  92243. }
  92244. }
  92245. #else /* fully unrolled version for normal use */
  92246. {
  92247. int i;
  92248. FLAC__int64 sum;
  92249. FLAC__ASSERT(order > 0);
  92250. FLAC__ASSERT(order <= 32);
  92251. /*
  92252. * We do unique versions up to 12th order since that's the subset limit.
  92253. * Also they are roughly ordered to match frequency of occurrence to
  92254. * minimize branching.
  92255. */
  92256. if(order <= 12) {
  92257. if(order > 8) {
  92258. if(order > 10) {
  92259. if(order == 12) {
  92260. for(i = 0; i < (int)data_len; i++) {
  92261. sum = 0;
  92262. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  92263. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  92264. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  92265. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92266. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92267. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92268. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92269. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92270. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92271. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92272. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92273. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92274. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92275. }
  92276. }
  92277. else { /* order == 11 */
  92278. for(i = 0; i < (int)data_len; i++) {
  92279. sum = 0;
  92280. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  92281. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  92282. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92283. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92284. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92285. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92286. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92287. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92288. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92289. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92290. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92291. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92292. }
  92293. }
  92294. }
  92295. else {
  92296. if(order == 10) {
  92297. for(i = 0; i < (int)data_len; i++) {
  92298. sum = 0;
  92299. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  92300. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92301. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92302. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92303. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92304. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92305. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92306. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92307. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92308. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92309. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92310. }
  92311. }
  92312. else { /* order == 9 */
  92313. for(i = 0; i < (int)data_len; i++) {
  92314. sum = 0;
  92315. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  92316. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92317. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92318. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92319. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92320. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92321. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92322. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92323. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92324. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92325. }
  92326. }
  92327. }
  92328. }
  92329. else if(order > 4) {
  92330. if(order > 6) {
  92331. if(order == 8) {
  92332. for(i = 0; i < (int)data_len; i++) {
  92333. sum = 0;
  92334. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  92335. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92336. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92337. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92338. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92339. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92340. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92341. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92342. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92343. }
  92344. }
  92345. else { /* order == 7 */
  92346. for(i = 0; i < (int)data_len; i++) {
  92347. sum = 0;
  92348. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  92349. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92350. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92351. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92352. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92353. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92354. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92355. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92356. }
  92357. }
  92358. }
  92359. else {
  92360. if(order == 6) {
  92361. for(i = 0; i < (int)data_len; i++) {
  92362. sum = 0;
  92363. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  92364. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92365. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92366. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92367. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92368. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92369. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92370. }
  92371. }
  92372. else { /* order == 5 */
  92373. for(i = 0; i < (int)data_len; i++) {
  92374. sum = 0;
  92375. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  92376. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92377. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92378. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92379. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92380. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92381. }
  92382. }
  92383. }
  92384. }
  92385. else {
  92386. if(order > 2) {
  92387. if(order == 4) {
  92388. for(i = 0; i < (int)data_len; i++) {
  92389. sum = 0;
  92390. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  92391. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92392. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92393. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92394. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92395. }
  92396. }
  92397. else { /* order == 3 */
  92398. for(i = 0; i < (int)data_len; i++) {
  92399. sum = 0;
  92400. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  92401. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92402. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92403. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92404. }
  92405. }
  92406. }
  92407. else {
  92408. if(order == 2) {
  92409. for(i = 0; i < (int)data_len; i++) {
  92410. sum = 0;
  92411. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  92412. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  92413. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92414. }
  92415. }
  92416. else { /* order == 1 */
  92417. for(i = 0; i < (int)data_len; i++)
  92418. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  92419. }
  92420. }
  92421. }
  92422. }
  92423. else { /* order > 12 */
  92424. for(i = 0; i < (int)data_len; i++) {
  92425. sum = 0;
  92426. switch(order) {
  92427. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  92428. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  92429. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  92430. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  92431. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  92432. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  92433. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  92434. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  92435. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  92436. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  92437. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  92438. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  92439. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  92440. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  92441. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  92442. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  92443. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  92444. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  92445. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  92446. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  92447. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  92448. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  92449. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  92450. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  92451. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  92452. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  92453. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  92454. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  92455. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  92456. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  92457. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  92458. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  92459. }
  92460. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  92461. }
  92462. }
  92463. }
  92464. #endif
  92465. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92466. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  92467. {
  92468. FLAC__double error_scale;
  92469. FLAC__ASSERT(total_samples > 0);
  92470. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  92471. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  92472. }
  92473. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  92474. {
  92475. if(lpc_error > 0.0) {
  92476. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  92477. if(bps >= 0.0)
  92478. return bps;
  92479. else
  92480. return 0.0;
  92481. }
  92482. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  92483. return 1e32;
  92484. }
  92485. else {
  92486. return 0.0;
  92487. }
  92488. }
  92489. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  92490. {
  92491. 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 */
  92492. FLAC__double bits, best_bits, error_scale;
  92493. FLAC__ASSERT(max_order > 0);
  92494. FLAC__ASSERT(total_samples > 0);
  92495. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  92496. best_index = 0;
  92497. best_bits = (unsigned)(-1);
  92498. for(index = 0, order = 1; index < max_order; index++, order++) {
  92499. 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);
  92500. if(bits < best_bits) {
  92501. best_index = index;
  92502. best_bits = bits;
  92503. }
  92504. }
  92505. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  92506. }
  92507. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92508. #endif
  92509. /********* End of inlined file: lpc_flac.c *********/
  92510. /********* Start of inlined file: md5.c *********/
  92511. /********* Start of inlined file: juce_FlacHeader.h *********/
  92512. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92513. // tasks..
  92514. #define VERSION "1.2.1"
  92515. #define FLAC__NO_DLL 1
  92516. #ifdef _MSC_VER
  92517. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92518. #endif
  92519. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92520. #define FLAC__SYS_DARWIN 1
  92521. #endif
  92522. /********* End of inlined file: juce_FlacHeader.h *********/
  92523. #if JUCE_USE_FLAC
  92524. #if HAVE_CONFIG_H
  92525. # include <config.h>
  92526. #endif
  92527. #include <stdlib.h> /* for malloc() */
  92528. #include <string.h> /* for memcpy() */
  92529. /********* Start of inlined file: md5.h *********/
  92530. #ifndef FLAC__PRIVATE__MD5_H
  92531. #define FLAC__PRIVATE__MD5_H
  92532. /*
  92533. * This is the header file for the MD5 message-digest algorithm.
  92534. * The algorithm is due to Ron Rivest. This code was
  92535. * written by Colin Plumb in 1993, no copyright is claimed.
  92536. * This code is in the public domain; do with it what you wish.
  92537. *
  92538. * Equivalent code is available from RSA Data Security, Inc.
  92539. * This code has been tested against that, and is equivalent,
  92540. * except that you don't need to include two pages of legalese
  92541. * with every copy.
  92542. *
  92543. * To compute the message digest of a chunk of bytes, declare an
  92544. * MD5Context structure, pass it to MD5Init, call MD5Update as
  92545. * needed on buffers full of bytes, and then call MD5Final, which
  92546. * will fill a supplied 16-byte array with the digest.
  92547. *
  92548. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  92549. * header definitions; now uses stuff from dpkg's config.h
  92550. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  92551. * Still in the public domain.
  92552. *
  92553. * Josh Coalson: made some changes to integrate with libFLAC.
  92554. * Still in the public domain, with no warranty.
  92555. */
  92556. typedef struct {
  92557. FLAC__uint32 in[16];
  92558. FLAC__uint32 buf[4];
  92559. FLAC__uint32 bytes[2];
  92560. FLAC__byte *internal_buf;
  92561. size_t capacity;
  92562. } FLAC__MD5Context;
  92563. void FLAC__MD5Init(FLAC__MD5Context *context);
  92564. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  92565. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  92566. #endif
  92567. /********* End of inlined file: md5.h *********/
  92568. #ifndef FLaC__INLINE
  92569. #define FLaC__INLINE
  92570. #endif
  92571. /*
  92572. * This code implements the MD5 message-digest algorithm.
  92573. * The algorithm is due to Ron Rivest. This code was
  92574. * written by Colin Plumb in 1993, no copyright is claimed.
  92575. * This code is in the public domain; do with it what you wish.
  92576. *
  92577. * Equivalent code is available from RSA Data Security, Inc.
  92578. * This code has been tested against that, and is equivalent,
  92579. * except that you don't need to include two pages of legalese
  92580. * with every copy.
  92581. *
  92582. * To compute the message digest of a chunk of bytes, declare an
  92583. * MD5Context structure, pass it to MD5Init, call MD5Update as
  92584. * needed on buffers full of bytes, and then call MD5Final, which
  92585. * will fill a supplied 16-byte array with the digest.
  92586. *
  92587. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  92588. * definitions; now uses stuff from dpkg's config.h.
  92589. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  92590. * Still in the public domain.
  92591. *
  92592. * Josh Coalson: made some changes to integrate with libFLAC.
  92593. * Still in the public domain.
  92594. */
  92595. /* The four core functions - F1 is optimized somewhat */
  92596. /* #define F1(x, y, z) (x & y | ~x & z) */
  92597. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  92598. #define F2(x, y, z) F1(z, x, y)
  92599. #define F3(x, y, z) (x ^ y ^ z)
  92600. #define F4(x, y, z) (y ^ (x | ~z))
  92601. /* This is the central step in the MD5 algorithm. */
  92602. #define MD5STEP(f,w,x,y,z,in,s) \
  92603. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  92604. /*
  92605. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  92606. * reflect the addition of 16 longwords of new data. MD5Update blocks
  92607. * the data and converts bytes into longwords for this routine.
  92608. */
  92609. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  92610. {
  92611. register FLAC__uint32 a, b, c, d;
  92612. a = buf[0];
  92613. b = buf[1];
  92614. c = buf[2];
  92615. d = buf[3];
  92616. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  92617. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  92618. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  92619. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  92620. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  92621. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  92622. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  92623. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  92624. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  92625. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  92626. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  92627. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  92628. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  92629. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  92630. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  92631. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  92632. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  92633. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  92634. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  92635. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  92636. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  92637. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  92638. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  92639. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  92640. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  92641. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  92642. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  92643. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  92644. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  92645. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  92646. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  92647. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  92648. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  92649. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  92650. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  92651. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  92652. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  92653. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  92654. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  92655. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  92656. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  92657. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  92658. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  92659. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  92660. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  92661. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  92662. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  92663. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  92664. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  92665. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  92666. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  92667. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  92668. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  92669. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  92670. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  92671. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  92672. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  92673. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  92674. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  92675. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  92676. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  92677. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  92678. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  92679. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  92680. buf[0] += a;
  92681. buf[1] += b;
  92682. buf[2] += c;
  92683. buf[3] += d;
  92684. }
  92685. #if WORDS_BIGENDIAN
  92686. //@@@@@@ OPT: use bswap/intrinsics
  92687. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  92688. {
  92689. register FLAC__uint32 x;
  92690. do {
  92691. x = *buf;
  92692. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  92693. *buf++ = (x >> 16) | (x << 16);
  92694. } while (--words);
  92695. }
  92696. static void byteSwapX16(FLAC__uint32 *buf)
  92697. {
  92698. register FLAC__uint32 x;
  92699. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92700. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92701. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92702. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92703. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92704. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92705. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92706. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92707. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92708. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92709. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92710. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92711. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92712. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92713. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  92714. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  92715. }
  92716. #else
  92717. #define byteSwap(buf, words)
  92718. #define byteSwapX16(buf)
  92719. #endif
  92720. /*
  92721. * Update context to reflect the concatenation of another buffer full
  92722. * of bytes.
  92723. */
  92724. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  92725. {
  92726. FLAC__uint32 t;
  92727. /* Update byte count */
  92728. t = ctx->bytes[0];
  92729. if ((ctx->bytes[0] = t + len) < t)
  92730. ctx->bytes[1]++; /* Carry from low to high */
  92731. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  92732. if (t > len) {
  92733. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  92734. return;
  92735. }
  92736. /* First chunk is an odd size */
  92737. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  92738. byteSwapX16(ctx->in);
  92739. FLAC__MD5Transform(ctx->buf, ctx->in);
  92740. buf += t;
  92741. len -= t;
  92742. /* Process data in 64-byte chunks */
  92743. while (len >= 64) {
  92744. memcpy(ctx->in, buf, 64);
  92745. byteSwapX16(ctx->in);
  92746. FLAC__MD5Transform(ctx->buf, ctx->in);
  92747. buf += 64;
  92748. len -= 64;
  92749. }
  92750. /* Handle any remaining bytes of data. */
  92751. memcpy(ctx->in, buf, len);
  92752. }
  92753. /*
  92754. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  92755. * initialization constants.
  92756. */
  92757. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  92758. {
  92759. ctx->buf[0] = 0x67452301;
  92760. ctx->buf[1] = 0xefcdab89;
  92761. ctx->buf[2] = 0x98badcfe;
  92762. ctx->buf[3] = 0x10325476;
  92763. ctx->bytes[0] = 0;
  92764. ctx->bytes[1] = 0;
  92765. ctx->internal_buf = 0;
  92766. ctx->capacity = 0;
  92767. }
  92768. /*
  92769. * Final wrapup - pad to 64-byte boundary with the bit pattern
  92770. * 1 0* (64-bit count of bits processed, MSB-first)
  92771. */
  92772. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  92773. {
  92774. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  92775. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  92776. /* Set the first char of padding to 0x80. There is always room. */
  92777. *p++ = 0x80;
  92778. /* Bytes of padding needed to make 56 bytes (-8..55) */
  92779. count = 56 - 1 - count;
  92780. if (count < 0) { /* Padding forces an extra block */
  92781. memset(p, 0, count + 8);
  92782. byteSwapX16(ctx->in);
  92783. FLAC__MD5Transform(ctx->buf, ctx->in);
  92784. p = (FLAC__byte *)ctx->in;
  92785. count = 56;
  92786. }
  92787. memset(p, 0, count);
  92788. byteSwap(ctx->in, 14);
  92789. /* Append length in bits and transform */
  92790. ctx->in[14] = ctx->bytes[0] << 3;
  92791. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  92792. FLAC__MD5Transform(ctx->buf, ctx->in);
  92793. byteSwap(ctx->buf, 4);
  92794. memcpy(digest, ctx->buf, 16);
  92795. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  92796. if(0 != ctx->internal_buf) {
  92797. free(ctx->internal_buf);
  92798. ctx->internal_buf = 0;
  92799. ctx->capacity = 0;
  92800. }
  92801. }
  92802. /*
  92803. * Convert the incoming audio signal to a byte stream
  92804. */
  92805. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  92806. {
  92807. unsigned channel, sample;
  92808. register FLAC__int32 a_word;
  92809. register FLAC__byte *buf_ = buf;
  92810. #if WORDS_BIGENDIAN
  92811. #else
  92812. if(channels == 2 && bytes_per_sample == 2) {
  92813. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  92814. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  92815. for(sample = 0; sample < samples; sample++, buf1_+=2)
  92816. *buf1_ = (FLAC__int16)signal[1][sample];
  92817. }
  92818. else if(channels == 1 && bytes_per_sample == 2) {
  92819. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  92820. for(sample = 0; sample < samples; sample++)
  92821. *buf1_++ = (FLAC__int16)signal[0][sample];
  92822. }
  92823. else
  92824. #endif
  92825. if(bytes_per_sample == 2) {
  92826. if(channels == 2) {
  92827. for(sample = 0; sample < samples; sample++) {
  92828. a_word = signal[0][sample];
  92829. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92830. *buf_++ = (FLAC__byte)a_word;
  92831. a_word = signal[1][sample];
  92832. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92833. *buf_++ = (FLAC__byte)a_word;
  92834. }
  92835. }
  92836. else if(channels == 1) {
  92837. for(sample = 0; sample < samples; sample++) {
  92838. a_word = signal[0][sample];
  92839. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92840. *buf_++ = (FLAC__byte)a_word;
  92841. }
  92842. }
  92843. else {
  92844. for(sample = 0; sample < samples; sample++) {
  92845. for(channel = 0; channel < channels; channel++) {
  92846. a_word = signal[channel][sample];
  92847. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92848. *buf_++ = (FLAC__byte)a_word;
  92849. }
  92850. }
  92851. }
  92852. }
  92853. else if(bytes_per_sample == 3) {
  92854. if(channels == 2) {
  92855. for(sample = 0; sample < samples; sample++) {
  92856. a_word = signal[0][sample];
  92857. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92858. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92859. *buf_++ = (FLAC__byte)a_word;
  92860. a_word = signal[1][sample];
  92861. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92862. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92863. *buf_++ = (FLAC__byte)a_word;
  92864. }
  92865. }
  92866. else if(channels == 1) {
  92867. for(sample = 0; sample < samples; sample++) {
  92868. a_word = signal[0][sample];
  92869. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92870. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92871. *buf_++ = (FLAC__byte)a_word;
  92872. }
  92873. }
  92874. else {
  92875. for(sample = 0; sample < samples; sample++) {
  92876. for(channel = 0; channel < channels; channel++) {
  92877. a_word = signal[channel][sample];
  92878. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92879. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92880. *buf_++ = (FLAC__byte)a_word;
  92881. }
  92882. }
  92883. }
  92884. }
  92885. else if(bytes_per_sample == 1) {
  92886. if(channels == 2) {
  92887. for(sample = 0; sample < samples; sample++) {
  92888. a_word = signal[0][sample];
  92889. *buf_++ = (FLAC__byte)a_word;
  92890. a_word = signal[1][sample];
  92891. *buf_++ = (FLAC__byte)a_word;
  92892. }
  92893. }
  92894. else if(channels == 1) {
  92895. for(sample = 0; sample < samples; sample++) {
  92896. a_word = signal[0][sample];
  92897. *buf_++ = (FLAC__byte)a_word;
  92898. }
  92899. }
  92900. else {
  92901. for(sample = 0; sample < samples; sample++) {
  92902. for(channel = 0; channel < channels; channel++) {
  92903. a_word = signal[channel][sample];
  92904. *buf_++ = (FLAC__byte)a_word;
  92905. }
  92906. }
  92907. }
  92908. }
  92909. else { /* bytes_per_sample == 4, maybe optimize more later */
  92910. for(sample = 0; sample < samples; sample++) {
  92911. for(channel = 0; channel < channels; channel++) {
  92912. a_word = signal[channel][sample];
  92913. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92914. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92915. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92916. *buf_++ = (FLAC__byte)a_word;
  92917. }
  92918. }
  92919. }
  92920. }
  92921. /*
  92922. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  92923. */
  92924. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  92925. {
  92926. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  92927. /* overflow check */
  92928. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  92929. return false;
  92930. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  92931. return false;
  92932. if(ctx->capacity < bytes_needed) {
  92933. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  92934. if(0 == tmp) {
  92935. free(ctx->internal_buf);
  92936. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  92937. return false;
  92938. }
  92939. ctx->internal_buf = tmp;
  92940. ctx->capacity = bytes_needed;
  92941. }
  92942. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  92943. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  92944. return true;
  92945. }
  92946. #endif
  92947. /********* End of inlined file: md5.c *********/
  92948. /********* Start of inlined file: memory.c *********/
  92949. /********* Start of inlined file: juce_FlacHeader.h *********/
  92950. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92951. // tasks..
  92952. #define VERSION "1.2.1"
  92953. #define FLAC__NO_DLL 1
  92954. #ifdef _MSC_VER
  92955. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92956. #endif
  92957. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92958. #define FLAC__SYS_DARWIN 1
  92959. #endif
  92960. /********* End of inlined file: juce_FlacHeader.h *********/
  92961. #if JUCE_USE_FLAC
  92962. #if HAVE_CONFIG_H
  92963. # include <config.h>
  92964. #endif
  92965. /********* Start of inlined file: memory.h *********/
  92966. #ifndef FLAC__PRIVATE__MEMORY_H
  92967. #define FLAC__PRIVATE__MEMORY_H
  92968. #ifdef HAVE_CONFIG_H
  92969. #include <config.h>
  92970. #endif
  92971. #include <stdlib.h> /* for size_t */
  92972. /* Returns the unaligned address returned by malloc.
  92973. * Use free() on this address to deallocate.
  92974. */
  92975. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  92976. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  92977. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  92978. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  92979. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  92980. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92981. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  92982. #endif
  92983. #endif
  92984. /********* End of inlined file: memory.h *********/
  92985. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  92986. {
  92987. void *x;
  92988. FLAC__ASSERT(0 != aligned_address);
  92989. #ifdef FLAC__ALIGN_MALLOC_DATA
  92990. /* align on 32-byte (256-bit) boundary */
  92991. x = safe_malloc_add_2op_(bytes, /*+*/31);
  92992. #ifdef SIZEOF_VOIDP
  92993. #if SIZEOF_VOIDP == 4
  92994. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  92995. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  92996. #elif SIZEOF_VOIDP == 8
  92997. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  92998. #else
  92999. # error Unsupported sizeof(void*)
  93000. #endif
  93001. #else
  93002. /* there's got to be a better way to do this right for all archs */
  93003. if(sizeof(void*) == sizeof(unsigned))
  93004. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  93005. else if(sizeof(void*) == sizeof(FLAC__uint64))
  93006. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  93007. else
  93008. return 0;
  93009. #endif
  93010. #else
  93011. x = safe_malloc_(bytes);
  93012. *aligned_address = x;
  93013. #endif
  93014. return x;
  93015. }
  93016. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  93017. {
  93018. FLAC__int32 *pu; /* unaligned pointer */
  93019. union { /* union needed to comply with C99 pointer aliasing rules */
  93020. FLAC__int32 *pa; /* aligned pointer */
  93021. void *pv; /* aligned pointer alias */
  93022. } u;
  93023. FLAC__ASSERT(elements > 0);
  93024. FLAC__ASSERT(0 != unaligned_pointer);
  93025. FLAC__ASSERT(0 != aligned_pointer);
  93026. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  93027. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  93028. return false;
  93029. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  93030. if(0 == pu) {
  93031. return false;
  93032. }
  93033. else {
  93034. if(*unaligned_pointer != 0)
  93035. free(*unaligned_pointer);
  93036. *unaligned_pointer = pu;
  93037. *aligned_pointer = u.pa;
  93038. return true;
  93039. }
  93040. }
  93041. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  93042. {
  93043. FLAC__uint32 *pu; /* unaligned pointer */
  93044. union { /* union needed to comply with C99 pointer aliasing rules */
  93045. FLAC__uint32 *pa; /* aligned pointer */
  93046. void *pv; /* aligned pointer alias */
  93047. } u;
  93048. FLAC__ASSERT(elements > 0);
  93049. FLAC__ASSERT(0 != unaligned_pointer);
  93050. FLAC__ASSERT(0 != aligned_pointer);
  93051. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  93052. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  93053. return false;
  93054. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  93055. if(0 == pu) {
  93056. return false;
  93057. }
  93058. else {
  93059. if(*unaligned_pointer != 0)
  93060. free(*unaligned_pointer);
  93061. *unaligned_pointer = pu;
  93062. *aligned_pointer = u.pa;
  93063. return true;
  93064. }
  93065. }
  93066. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  93067. {
  93068. FLAC__uint64 *pu; /* unaligned pointer */
  93069. union { /* union needed to comply with C99 pointer aliasing rules */
  93070. FLAC__uint64 *pa; /* aligned pointer */
  93071. void *pv; /* aligned pointer alias */
  93072. } u;
  93073. FLAC__ASSERT(elements > 0);
  93074. FLAC__ASSERT(0 != unaligned_pointer);
  93075. FLAC__ASSERT(0 != aligned_pointer);
  93076. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  93077. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  93078. return false;
  93079. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  93080. if(0 == pu) {
  93081. return false;
  93082. }
  93083. else {
  93084. if(*unaligned_pointer != 0)
  93085. free(*unaligned_pointer);
  93086. *unaligned_pointer = pu;
  93087. *aligned_pointer = u.pa;
  93088. return true;
  93089. }
  93090. }
  93091. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  93092. {
  93093. unsigned *pu; /* unaligned pointer */
  93094. union { /* union needed to comply with C99 pointer aliasing rules */
  93095. unsigned *pa; /* aligned pointer */
  93096. void *pv; /* aligned pointer alias */
  93097. } u;
  93098. FLAC__ASSERT(elements > 0);
  93099. FLAC__ASSERT(0 != unaligned_pointer);
  93100. FLAC__ASSERT(0 != aligned_pointer);
  93101. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  93102. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  93103. return false;
  93104. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  93105. if(0 == pu) {
  93106. return false;
  93107. }
  93108. else {
  93109. if(*unaligned_pointer != 0)
  93110. free(*unaligned_pointer);
  93111. *unaligned_pointer = pu;
  93112. *aligned_pointer = u.pa;
  93113. return true;
  93114. }
  93115. }
  93116. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93117. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  93118. {
  93119. FLAC__real *pu; /* unaligned pointer */
  93120. union { /* union needed to comply with C99 pointer aliasing rules */
  93121. FLAC__real *pa; /* aligned pointer */
  93122. void *pv; /* aligned pointer alias */
  93123. } u;
  93124. FLAC__ASSERT(elements > 0);
  93125. FLAC__ASSERT(0 != unaligned_pointer);
  93126. FLAC__ASSERT(0 != aligned_pointer);
  93127. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  93128. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  93129. return false;
  93130. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  93131. if(0 == pu) {
  93132. return false;
  93133. }
  93134. else {
  93135. if(*unaligned_pointer != 0)
  93136. free(*unaligned_pointer);
  93137. *unaligned_pointer = pu;
  93138. *aligned_pointer = u.pa;
  93139. return true;
  93140. }
  93141. }
  93142. #endif
  93143. #endif
  93144. /********* End of inlined file: memory.c *********/
  93145. /********* Start of inlined file: stream_decoder.c *********/
  93146. /********* Start of inlined file: juce_FlacHeader.h *********/
  93147. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93148. // tasks..
  93149. #define VERSION "1.2.1"
  93150. #define FLAC__NO_DLL 1
  93151. #ifdef _MSC_VER
  93152. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93153. #endif
  93154. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  93155. #define FLAC__SYS_DARWIN 1
  93156. #endif
  93157. /********* End of inlined file: juce_FlacHeader.h *********/
  93158. #if JUCE_USE_FLAC
  93159. #if HAVE_CONFIG_H
  93160. # include <config.h>
  93161. #endif
  93162. #if defined _MSC_VER || defined __MINGW32__
  93163. #include <io.h> /* for _setmode() */
  93164. #include <fcntl.h> /* for _O_BINARY */
  93165. #endif
  93166. #if defined __CYGWIN__ || defined __EMX__
  93167. #include <io.h> /* for setmode(), O_BINARY */
  93168. #include <fcntl.h> /* for _O_BINARY */
  93169. #endif
  93170. #include <stdio.h>
  93171. #include <stdlib.h> /* for malloc() */
  93172. #include <string.h> /* for memset/memcpy() */
  93173. #include <sys/stat.h> /* for stat() */
  93174. #include <sys/types.h> /* for off_t */
  93175. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  93176. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  93177. #define fseeko fseek
  93178. #define ftello ftell
  93179. #endif
  93180. #endif
  93181. /********* Start of inlined file: stream_decoder.h *********/
  93182. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  93183. #define FLAC__PROTECTED__STREAM_DECODER_H
  93184. #if FLAC__HAS_OGG
  93185. #include "include/private/ogg_decoder_aspect.h"
  93186. #endif
  93187. typedef struct FLAC__StreamDecoderProtected {
  93188. FLAC__StreamDecoderState state;
  93189. unsigned channels;
  93190. FLAC__ChannelAssignment channel_assignment;
  93191. unsigned bits_per_sample;
  93192. unsigned sample_rate; /* in Hz */
  93193. unsigned blocksize; /* in samples (per channel) */
  93194. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  93195. #if FLAC__HAS_OGG
  93196. FLAC__OggDecoderAspect ogg_decoder_aspect;
  93197. #endif
  93198. } FLAC__StreamDecoderProtected;
  93199. /*
  93200. * return the number of input bytes consumed
  93201. */
  93202. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  93203. #endif
  93204. /********* End of inlined file: stream_decoder.h *********/
  93205. #ifdef max
  93206. #undef max
  93207. #endif
  93208. #define max(a,b) ((a)>(b)?(a):(b))
  93209. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93210. #ifdef _MSC_VER
  93211. #define FLAC__U64L(x) x
  93212. #else
  93213. #define FLAC__U64L(x) x##LLU
  93214. #endif
  93215. /* technically this should be in an "export.c" but this is convenient enough */
  93216. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  93217. #if FLAC__HAS_OGG
  93218. 1
  93219. #else
  93220. 0
  93221. #endif
  93222. ;
  93223. /***********************************************************************
  93224. *
  93225. * Private static data
  93226. *
  93227. ***********************************************************************/
  93228. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  93229. /***********************************************************************
  93230. *
  93231. * Private class method prototypes
  93232. *
  93233. ***********************************************************************/
  93234. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  93235. static FILE *get_binary_stdin_(void);
  93236. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  93237. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  93238. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  93239. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  93240. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  93241. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  93242. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  93243. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  93244. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  93245. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  93246. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  93247. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  93248. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  93249. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  93250. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  93251. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  93252. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  93253. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  93254. 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);
  93255. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  93256. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  93257. #if FLAC__HAS_OGG
  93258. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  93259. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  93260. #endif
  93261. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  93262. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  93263. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  93264. #if FLAC__HAS_OGG
  93265. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  93266. #endif
  93267. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  93268. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  93269. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  93270. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  93271. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  93272. /***********************************************************************
  93273. *
  93274. * Private class data
  93275. *
  93276. ***********************************************************************/
  93277. typedef struct FLAC__StreamDecoderPrivate {
  93278. #if FLAC__HAS_OGG
  93279. FLAC__bool is_ogg;
  93280. #endif
  93281. FLAC__StreamDecoderReadCallback read_callback;
  93282. FLAC__StreamDecoderSeekCallback seek_callback;
  93283. FLAC__StreamDecoderTellCallback tell_callback;
  93284. FLAC__StreamDecoderLengthCallback length_callback;
  93285. FLAC__StreamDecoderEofCallback eof_callback;
  93286. FLAC__StreamDecoderWriteCallback write_callback;
  93287. FLAC__StreamDecoderMetadataCallback metadata_callback;
  93288. FLAC__StreamDecoderErrorCallback error_callback;
  93289. /* generic 32-bit datapath: */
  93290. 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[]);
  93291. /* generic 64-bit datapath: */
  93292. 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[]);
  93293. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  93294. 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[]);
  93295. /* 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: */
  93296. 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[]);
  93297. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  93298. void *client_data;
  93299. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  93300. FLAC__BitReader *input;
  93301. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  93302. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  93303. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  93304. unsigned output_capacity, output_channels;
  93305. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  93306. FLAC__uint64 samples_decoded;
  93307. FLAC__bool has_stream_info, has_seek_table;
  93308. FLAC__StreamMetadata stream_info;
  93309. FLAC__StreamMetadata seek_table;
  93310. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  93311. FLAC__byte *metadata_filter_ids;
  93312. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  93313. FLAC__Frame frame;
  93314. FLAC__bool cached; /* true if there is a byte in lookahead */
  93315. FLAC__CPUInfo cpuinfo;
  93316. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  93317. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  93318. /* unaligned (original) pointers to allocated data */
  93319. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  93320. 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 */
  93321. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  93322. FLAC__bool is_seeking;
  93323. FLAC__MD5Context md5context;
  93324. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  93325. /* (the rest of these are only used for seeking) */
  93326. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  93327. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  93328. FLAC__uint64 target_sample;
  93329. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  93330. #if FLAC__HAS_OGG
  93331. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  93332. #endif
  93333. } FLAC__StreamDecoderPrivate;
  93334. /***********************************************************************
  93335. *
  93336. * Public static class data
  93337. *
  93338. ***********************************************************************/
  93339. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  93340. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  93341. "FLAC__STREAM_DECODER_READ_METADATA",
  93342. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  93343. "FLAC__STREAM_DECODER_READ_FRAME",
  93344. "FLAC__STREAM_DECODER_END_OF_STREAM",
  93345. "FLAC__STREAM_DECODER_OGG_ERROR",
  93346. "FLAC__STREAM_DECODER_SEEK_ERROR",
  93347. "FLAC__STREAM_DECODER_ABORTED",
  93348. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  93349. "FLAC__STREAM_DECODER_UNINITIALIZED"
  93350. };
  93351. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  93352. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  93353. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  93354. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  93355. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  93356. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  93357. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  93358. };
  93359. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  93360. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  93361. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  93362. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  93363. };
  93364. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  93365. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  93366. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  93367. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  93368. };
  93369. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  93370. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  93371. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  93372. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  93373. };
  93374. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  93375. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  93376. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  93377. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  93378. };
  93379. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  93380. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  93381. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  93382. };
  93383. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  93384. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  93385. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  93386. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  93387. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  93388. };
  93389. /***********************************************************************
  93390. *
  93391. * Class constructor/destructor
  93392. *
  93393. ***********************************************************************/
  93394. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  93395. {
  93396. FLAC__StreamDecoder *decoder;
  93397. unsigned i;
  93398. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  93399. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  93400. if(decoder == 0) {
  93401. return 0;
  93402. }
  93403. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  93404. if(decoder->protected_ == 0) {
  93405. free(decoder);
  93406. return 0;
  93407. }
  93408. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  93409. if(decoder->private_ == 0) {
  93410. free(decoder->protected_);
  93411. free(decoder);
  93412. return 0;
  93413. }
  93414. decoder->private_->input = FLAC__bitreader_new();
  93415. if(decoder->private_->input == 0) {
  93416. free(decoder->private_);
  93417. free(decoder->protected_);
  93418. free(decoder);
  93419. return 0;
  93420. }
  93421. decoder->private_->metadata_filter_ids_capacity = 16;
  93422. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  93423. FLAC__bitreader_delete(decoder->private_->input);
  93424. free(decoder->private_);
  93425. free(decoder->protected_);
  93426. free(decoder);
  93427. return 0;
  93428. }
  93429. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  93430. decoder->private_->output[i] = 0;
  93431. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  93432. }
  93433. decoder->private_->output_capacity = 0;
  93434. decoder->private_->output_channels = 0;
  93435. decoder->private_->has_seek_table = false;
  93436. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  93437. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  93438. decoder->private_->file = 0;
  93439. set_defaults_dec(decoder);
  93440. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  93441. return decoder;
  93442. }
  93443. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  93444. {
  93445. unsigned i;
  93446. FLAC__ASSERT(0 != decoder);
  93447. FLAC__ASSERT(0 != decoder->protected_);
  93448. FLAC__ASSERT(0 != decoder->private_);
  93449. FLAC__ASSERT(0 != decoder->private_->input);
  93450. (void)FLAC__stream_decoder_finish(decoder);
  93451. if(0 != decoder->private_->metadata_filter_ids)
  93452. free(decoder->private_->metadata_filter_ids);
  93453. FLAC__bitreader_delete(decoder->private_->input);
  93454. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  93455. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  93456. free(decoder->private_);
  93457. free(decoder->protected_);
  93458. free(decoder);
  93459. }
  93460. /***********************************************************************
  93461. *
  93462. * Public class methods
  93463. *
  93464. ***********************************************************************/
  93465. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  93466. FLAC__StreamDecoder *decoder,
  93467. FLAC__StreamDecoderReadCallback read_callback,
  93468. FLAC__StreamDecoderSeekCallback seek_callback,
  93469. FLAC__StreamDecoderTellCallback tell_callback,
  93470. FLAC__StreamDecoderLengthCallback length_callback,
  93471. FLAC__StreamDecoderEofCallback eof_callback,
  93472. FLAC__StreamDecoderWriteCallback write_callback,
  93473. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93474. FLAC__StreamDecoderErrorCallback error_callback,
  93475. void *client_data,
  93476. FLAC__bool is_ogg
  93477. )
  93478. {
  93479. FLAC__ASSERT(0 != decoder);
  93480. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93481. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  93482. #if !FLAC__HAS_OGG
  93483. if(is_ogg)
  93484. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  93485. #endif
  93486. if(
  93487. 0 == read_callback ||
  93488. 0 == write_callback ||
  93489. 0 == error_callback ||
  93490. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  93491. )
  93492. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  93493. #if FLAC__HAS_OGG
  93494. decoder->private_->is_ogg = is_ogg;
  93495. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  93496. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  93497. #endif
  93498. /*
  93499. * get the CPU info and set the function pointers
  93500. */
  93501. FLAC__cpu_info(&decoder->private_->cpuinfo);
  93502. /* first default to the non-asm routines */
  93503. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  93504. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  93505. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  93506. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  93507. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  93508. /* now override with asm where appropriate */
  93509. #ifndef FLAC__NO_ASM
  93510. if(decoder->private_->cpuinfo.use_asm) {
  93511. #ifdef FLAC__CPU_IA32
  93512. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  93513. #ifdef FLAC__HAS_NASM
  93514. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  93515. if(decoder->private_->cpuinfo.data.ia32.bswap)
  93516. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  93517. #endif
  93518. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  93519. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  93520. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  93521. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  93522. }
  93523. else {
  93524. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  93525. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  93526. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  93527. }
  93528. #endif
  93529. #elif defined FLAC__CPU_PPC
  93530. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  93531. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  93532. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  93533. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  93534. }
  93535. #endif
  93536. }
  93537. #endif
  93538. /* from here on, errors are fatal */
  93539. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  93540. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93541. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  93542. }
  93543. decoder->private_->read_callback = read_callback;
  93544. decoder->private_->seek_callback = seek_callback;
  93545. decoder->private_->tell_callback = tell_callback;
  93546. decoder->private_->length_callback = length_callback;
  93547. decoder->private_->eof_callback = eof_callback;
  93548. decoder->private_->write_callback = write_callback;
  93549. decoder->private_->metadata_callback = metadata_callback;
  93550. decoder->private_->error_callback = error_callback;
  93551. decoder->private_->client_data = client_data;
  93552. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  93553. decoder->private_->samples_decoded = 0;
  93554. decoder->private_->has_stream_info = false;
  93555. decoder->private_->cached = false;
  93556. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  93557. decoder->private_->is_seeking = false;
  93558. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  93559. if(!FLAC__stream_decoder_reset(decoder)) {
  93560. /* above call sets the state for us */
  93561. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  93562. }
  93563. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  93564. }
  93565. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  93566. FLAC__StreamDecoder *decoder,
  93567. FLAC__StreamDecoderReadCallback read_callback,
  93568. FLAC__StreamDecoderSeekCallback seek_callback,
  93569. FLAC__StreamDecoderTellCallback tell_callback,
  93570. FLAC__StreamDecoderLengthCallback length_callback,
  93571. FLAC__StreamDecoderEofCallback eof_callback,
  93572. FLAC__StreamDecoderWriteCallback write_callback,
  93573. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93574. FLAC__StreamDecoderErrorCallback error_callback,
  93575. void *client_data
  93576. )
  93577. {
  93578. return init_stream_internal_dec(
  93579. decoder,
  93580. read_callback,
  93581. seek_callback,
  93582. tell_callback,
  93583. length_callback,
  93584. eof_callback,
  93585. write_callback,
  93586. metadata_callback,
  93587. error_callback,
  93588. client_data,
  93589. /*is_ogg=*/false
  93590. );
  93591. }
  93592. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  93593. FLAC__StreamDecoder *decoder,
  93594. FLAC__StreamDecoderReadCallback read_callback,
  93595. FLAC__StreamDecoderSeekCallback seek_callback,
  93596. FLAC__StreamDecoderTellCallback tell_callback,
  93597. FLAC__StreamDecoderLengthCallback length_callback,
  93598. FLAC__StreamDecoderEofCallback eof_callback,
  93599. FLAC__StreamDecoderWriteCallback write_callback,
  93600. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93601. FLAC__StreamDecoderErrorCallback error_callback,
  93602. void *client_data
  93603. )
  93604. {
  93605. return init_stream_internal_dec(
  93606. decoder,
  93607. read_callback,
  93608. seek_callback,
  93609. tell_callback,
  93610. length_callback,
  93611. eof_callback,
  93612. write_callback,
  93613. metadata_callback,
  93614. error_callback,
  93615. client_data,
  93616. /*is_ogg=*/true
  93617. );
  93618. }
  93619. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  93620. FLAC__StreamDecoder *decoder,
  93621. FILE *file,
  93622. FLAC__StreamDecoderWriteCallback write_callback,
  93623. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93624. FLAC__StreamDecoderErrorCallback error_callback,
  93625. void *client_data,
  93626. FLAC__bool is_ogg
  93627. )
  93628. {
  93629. FLAC__ASSERT(0 != decoder);
  93630. FLAC__ASSERT(0 != file);
  93631. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93632. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  93633. if(0 == write_callback || 0 == error_callback)
  93634. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  93635. /*
  93636. * To make sure that our file does not go unclosed after an error, we
  93637. * must assign the FILE pointer before any further error can occur in
  93638. * this routine.
  93639. */
  93640. if(file == stdin)
  93641. file = get_binary_stdin_(); /* just to be safe */
  93642. decoder->private_->file = file;
  93643. return init_stream_internal_dec(
  93644. decoder,
  93645. file_read_callback_dec,
  93646. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  93647. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  93648. decoder->private_->file == stdin? 0: file_length_callback_,
  93649. file_eof_callback_,
  93650. write_callback,
  93651. metadata_callback,
  93652. error_callback,
  93653. client_data,
  93654. is_ogg
  93655. );
  93656. }
  93657. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  93658. FLAC__StreamDecoder *decoder,
  93659. FILE *file,
  93660. FLAC__StreamDecoderWriteCallback write_callback,
  93661. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93662. FLAC__StreamDecoderErrorCallback error_callback,
  93663. void *client_data
  93664. )
  93665. {
  93666. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  93667. }
  93668. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  93669. FLAC__StreamDecoder *decoder,
  93670. FILE *file,
  93671. FLAC__StreamDecoderWriteCallback write_callback,
  93672. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93673. FLAC__StreamDecoderErrorCallback error_callback,
  93674. void *client_data
  93675. )
  93676. {
  93677. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  93678. }
  93679. static FLAC__StreamDecoderInitStatus init_file_internal_(
  93680. FLAC__StreamDecoder *decoder,
  93681. const char *filename,
  93682. FLAC__StreamDecoderWriteCallback write_callback,
  93683. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93684. FLAC__StreamDecoderErrorCallback error_callback,
  93685. void *client_data,
  93686. FLAC__bool is_ogg
  93687. )
  93688. {
  93689. FILE *file;
  93690. FLAC__ASSERT(0 != decoder);
  93691. /*
  93692. * To make sure that our file does not go unclosed after an error, we
  93693. * have to do the same entrance checks here that are later performed
  93694. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  93695. */
  93696. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93697. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  93698. if(0 == write_callback || 0 == error_callback)
  93699. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  93700. file = filename? fopen(filename, "rb") : stdin;
  93701. if(0 == file)
  93702. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  93703. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  93704. }
  93705. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  93706. FLAC__StreamDecoder *decoder,
  93707. const char *filename,
  93708. FLAC__StreamDecoderWriteCallback write_callback,
  93709. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93710. FLAC__StreamDecoderErrorCallback error_callback,
  93711. void *client_data
  93712. )
  93713. {
  93714. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  93715. }
  93716. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  93717. FLAC__StreamDecoder *decoder,
  93718. const char *filename,
  93719. FLAC__StreamDecoderWriteCallback write_callback,
  93720. FLAC__StreamDecoderMetadataCallback metadata_callback,
  93721. FLAC__StreamDecoderErrorCallback error_callback,
  93722. void *client_data
  93723. )
  93724. {
  93725. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  93726. }
  93727. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  93728. {
  93729. FLAC__bool md5_failed = false;
  93730. unsigned i;
  93731. FLAC__ASSERT(0 != decoder);
  93732. FLAC__ASSERT(0 != decoder->private_);
  93733. FLAC__ASSERT(0 != decoder->protected_);
  93734. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  93735. return true;
  93736. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  93737. * always call FLAC__MD5Final()
  93738. */
  93739. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  93740. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  93741. free(decoder->private_->seek_table.data.seek_table.points);
  93742. decoder->private_->seek_table.data.seek_table.points = 0;
  93743. decoder->private_->has_seek_table = false;
  93744. }
  93745. FLAC__bitreader_free(decoder->private_->input);
  93746. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  93747. /* WATCHOUT:
  93748. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  93749. * output arrays have a buffer of up to 3 zeroes in front
  93750. * (at negative indices) for alignment purposes; we use 4
  93751. * to keep the data well-aligned.
  93752. */
  93753. if(0 != decoder->private_->output[i]) {
  93754. free(decoder->private_->output[i]-4);
  93755. decoder->private_->output[i] = 0;
  93756. }
  93757. if(0 != decoder->private_->residual_unaligned[i]) {
  93758. free(decoder->private_->residual_unaligned[i]);
  93759. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  93760. }
  93761. }
  93762. decoder->private_->output_capacity = 0;
  93763. decoder->private_->output_channels = 0;
  93764. #if FLAC__HAS_OGG
  93765. if(decoder->private_->is_ogg)
  93766. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  93767. #endif
  93768. if(0 != decoder->private_->file) {
  93769. if(decoder->private_->file != stdin)
  93770. fclose(decoder->private_->file);
  93771. decoder->private_->file = 0;
  93772. }
  93773. if(decoder->private_->do_md5_checking) {
  93774. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  93775. md5_failed = true;
  93776. }
  93777. decoder->private_->is_seeking = false;
  93778. set_defaults_dec(decoder);
  93779. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  93780. return !md5_failed;
  93781. }
  93782. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  93783. {
  93784. FLAC__ASSERT(0 != decoder);
  93785. FLAC__ASSERT(0 != decoder->private_);
  93786. FLAC__ASSERT(0 != decoder->protected_);
  93787. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93788. return false;
  93789. #if FLAC__HAS_OGG
  93790. /* can't check decoder->private_->is_ogg since that's not set until init time */
  93791. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  93792. return true;
  93793. #else
  93794. (void)value;
  93795. return false;
  93796. #endif
  93797. }
  93798. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  93799. {
  93800. FLAC__ASSERT(0 != decoder);
  93801. FLAC__ASSERT(0 != decoder->protected_);
  93802. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93803. return false;
  93804. decoder->protected_->md5_checking = value;
  93805. return true;
  93806. }
  93807. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  93808. {
  93809. FLAC__ASSERT(0 != decoder);
  93810. FLAC__ASSERT(0 != decoder->private_);
  93811. FLAC__ASSERT(0 != decoder->protected_);
  93812. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  93813. /* double protection */
  93814. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  93815. return false;
  93816. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93817. return false;
  93818. decoder->private_->metadata_filter[type] = true;
  93819. if(type == FLAC__METADATA_TYPE_APPLICATION)
  93820. decoder->private_->metadata_filter_ids_count = 0;
  93821. return true;
  93822. }
  93823. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  93824. {
  93825. FLAC__ASSERT(0 != decoder);
  93826. FLAC__ASSERT(0 != decoder->private_);
  93827. FLAC__ASSERT(0 != decoder->protected_);
  93828. FLAC__ASSERT(0 != id);
  93829. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93830. return false;
  93831. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  93832. return true;
  93833. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  93834. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  93835. 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))) {
  93836. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93837. return false;
  93838. }
  93839. decoder->private_->metadata_filter_ids_capacity *= 2;
  93840. }
  93841. 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));
  93842. decoder->private_->metadata_filter_ids_count++;
  93843. return true;
  93844. }
  93845. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  93846. {
  93847. unsigned i;
  93848. FLAC__ASSERT(0 != decoder);
  93849. FLAC__ASSERT(0 != decoder->private_);
  93850. FLAC__ASSERT(0 != decoder->protected_);
  93851. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93852. return false;
  93853. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  93854. decoder->private_->metadata_filter[i] = true;
  93855. decoder->private_->metadata_filter_ids_count = 0;
  93856. return true;
  93857. }
  93858. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  93859. {
  93860. FLAC__ASSERT(0 != decoder);
  93861. FLAC__ASSERT(0 != decoder->private_);
  93862. FLAC__ASSERT(0 != decoder->protected_);
  93863. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  93864. /* double protection */
  93865. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  93866. return false;
  93867. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93868. return false;
  93869. decoder->private_->metadata_filter[type] = false;
  93870. if(type == FLAC__METADATA_TYPE_APPLICATION)
  93871. decoder->private_->metadata_filter_ids_count = 0;
  93872. return true;
  93873. }
  93874. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  93875. {
  93876. FLAC__ASSERT(0 != decoder);
  93877. FLAC__ASSERT(0 != decoder->private_);
  93878. FLAC__ASSERT(0 != decoder->protected_);
  93879. FLAC__ASSERT(0 != id);
  93880. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93881. return false;
  93882. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  93883. return true;
  93884. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  93885. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  93886. 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))) {
  93887. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93888. return false;
  93889. }
  93890. decoder->private_->metadata_filter_ids_capacity *= 2;
  93891. }
  93892. 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));
  93893. decoder->private_->metadata_filter_ids_count++;
  93894. return true;
  93895. }
  93896. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  93897. {
  93898. FLAC__ASSERT(0 != decoder);
  93899. FLAC__ASSERT(0 != decoder->private_);
  93900. FLAC__ASSERT(0 != decoder->protected_);
  93901. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93902. return false;
  93903. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  93904. decoder->private_->metadata_filter_ids_count = 0;
  93905. return true;
  93906. }
  93907. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  93908. {
  93909. FLAC__ASSERT(0 != decoder);
  93910. FLAC__ASSERT(0 != decoder->protected_);
  93911. return decoder->protected_->state;
  93912. }
  93913. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  93914. {
  93915. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  93916. }
  93917. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  93918. {
  93919. FLAC__ASSERT(0 != decoder);
  93920. FLAC__ASSERT(0 != decoder->protected_);
  93921. return decoder->protected_->md5_checking;
  93922. }
  93923. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  93924. {
  93925. FLAC__ASSERT(0 != decoder);
  93926. FLAC__ASSERT(0 != decoder->protected_);
  93927. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  93928. }
  93929. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  93930. {
  93931. FLAC__ASSERT(0 != decoder);
  93932. FLAC__ASSERT(0 != decoder->protected_);
  93933. return decoder->protected_->channels;
  93934. }
  93935. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  93936. {
  93937. FLAC__ASSERT(0 != decoder);
  93938. FLAC__ASSERT(0 != decoder->protected_);
  93939. return decoder->protected_->channel_assignment;
  93940. }
  93941. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  93942. {
  93943. FLAC__ASSERT(0 != decoder);
  93944. FLAC__ASSERT(0 != decoder->protected_);
  93945. return decoder->protected_->bits_per_sample;
  93946. }
  93947. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  93948. {
  93949. FLAC__ASSERT(0 != decoder);
  93950. FLAC__ASSERT(0 != decoder->protected_);
  93951. return decoder->protected_->sample_rate;
  93952. }
  93953. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  93954. {
  93955. FLAC__ASSERT(0 != decoder);
  93956. FLAC__ASSERT(0 != decoder->protected_);
  93957. return decoder->protected_->blocksize;
  93958. }
  93959. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  93960. {
  93961. FLAC__ASSERT(0 != decoder);
  93962. FLAC__ASSERT(0 != decoder->private_);
  93963. FLAC__ASSERT(0 != position);
  93964. #if FLAC__HAS_OGG
  93965. if(decoder->private_->is_ogg)
  93966. return false;
  93967. #endif
  93968. if(0 == decoder->private_->tell_callback)
  93969. return false;
  93970. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  93971. return false;
  93972. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  93973. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  93974. return false;
  93975. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  93976. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  93977. return true;
  93978. }
  93979. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  93980. {
  93981. FLAC__ASSERT(0 != decoder);
  93982. FLAC__ASSERT(0 != decoder->private_);
  93983. FLAC__ASSERT(0 != decoder->protected_);
  93984. decoder->private_->samples_decoded = 0;
  93985. decoder->private_->do_md5_checking = false;
  93986. #if FLAC__HAS_OGG
  93987. if(decoder->private_->is_ogg)
  93988. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  93989. #endif
  93990. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  93991. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93992. return false;
  93993. }
  93994. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  93995. return true;
  93996. }
  93997. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  93998. {
  93999. FLAC__ASSERT(0 != decoder);
  94000. FLAC__ASSERT(0 != decoder->private_);
  94001. FLAC__ASSERT(0 != decoder->protected_);
  94002. if(!FLAC__stream_decoder_flush(decoder)) {
  94003. /* above call sets the state for us */
  94004. return false;
  94005. }
  94006. #if FLAC__HAS_OGG
  94007. /*@@@ could go in !internal_reset_hack block below */
  94008. if(decoder->private_->is_ogg)
  94009. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  94010. #endif
  94011. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  94012. * (internal_reset_hack) don't try to rewind since we are already at
  94013. * the beginning of the stream and don't want to fail if the input is
  94014. * not seekable.
  94015. */
  94016. if(!decoder->private_->internal_reset_hack) {
  94017. if(decoder->private_->file == stdin)
  94018. return false; /* can't rewind stdin, reset fails */
  94019. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  94020. return false; /* seekable and seek fails, reset fails */
  94021. }
  94022. else
  94023. decoder->private_->internal_reset_hack = false;
  94024. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  94025. decoder->private_->has_stream_info = false;
  94026. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  94027. free(decoder->private_->seek_table.data.seek_table.points);
  94028. decoder->private_->seek_table.data.seek_table.points = 0;
  94029. decoder->private_->has_seek_table = false;
  94030. }
  94031. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  94032. /*
  94033. * This goes in reset() and not flush() because according to the spec, a
  94034. * fixed-blocksize stream must stay that way through the whole stream.
  94035. */
  94036. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  94037. /* We initialize the FLAC__MD5Context even though we may never use it. This
  94038. * is because md5 checking may be turned on to start and then turned off if
  94039. * a seek occurs. So we init the context here and finalize it in
  94040. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  94041. * properly.
  94042. */
  94043. FLAC__MD5Init(&decoder->private_->md5context);
  94044. decoder->private_->first_frame_offset = 0;
  94045. decoder->private_->unparseable_frame_count = 0;
  94046. return true;
  94047. }
  94048. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  94049. {
  94050. FLAC__bool got_a_frame;
  94051. FLAC__ASSERT(0 != decoder);
  94052. FLAC__ASSERT(0 != decoder->protected_);
  94053. while(1) {
  94054. switch(decoder->protected_->state) {
  94055. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  94056. if(!find_metadata_(decoder))
  94057. return false; /* above function sets the status for us */
  94058. break;
  94059. case FLAC__STREAM_DECODER_READ_METADATA:
  94060. if(!read_metadata_(decoder))
  94061. return false; /* above function sets the status for us */
  94062. else
  94063. return true;
  94064. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  94065. if(!frame_sync_(decoder))
  94066. return true; /* above function sets the status for us */
  94067. break;
  94068. case FLAC__STREAM_DECODER_READ_FRAME:
  94069. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  94070. return false; /* above function sets the status for us */
  94071. if(got_a_frame)
  94072. return true; /* above function sets the status for us */
  94073. break;
  94074. case FLAC__STREAM_DECODER_END_OF_STREAM:
  94075. case FLAC__STREAM_DECODER_ABORTED:
  94076. return true;
  94077. default:
  94078. FLAC__ASSERT(0);
  94079. return false;
  94080. }
  94081. }
  94082. }
  94083. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  94084. {
  94085. FLAC__ASSERT(0 != decoder);
  94086. FLAC__ASSERT(0 != decoder->protected_);
  94087. while(1) {
  94088. switch(decoder->protected_->state) {
  94089. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  94090. if(!find_metadata_(decoder))
  94091. return false; /* above function sets the status for us */
  94092. break;
  94093. case FLAC__STREAM_DECODER_READ_METADATA:
  94094. if(!read_metadata_(decoder))
  94095. return false; /* above function sets the status for us */
  94096. break;
  94097. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  94098. case FLAC__STREAM_DECODER_READ_FRAME:
  94099. case FLAC__STREAM_DECODER_END_OF_STREAM:
  94100. case FLAC__STREAM_DECODER_ABORTED:
  94101. return true;
  94102. default:
  94103. FLAC__ASSERT(0);
  94104. return false;
  94105. }
  94106. }
  94107. }
  94108. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  94109. {
  94110. FLAC__bool dummy;
  94111. FLAC__ASSERT(0 != decoder);
  94112. FLAC__ASSERT(0 != decoder->protected_);
  94113. while(1) {
  94114. switch(decoder->protected_->state) {
  94115. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  94116. if(!find_metadata_(decoder))
  94117. return false; /* above function sets the status for us */
  94118. break;
  94119. case FLAC__STREAM_DECODER_READ_METADATA:
  94120. if(!read_metadata_(decoder))
  94121. return false; /* above function sets the status for us */
  94122. break;
  94123. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  94124. if(!frame_sync_(decoder))
  94125. return true; /* above function sets the status for us */
  94126. break;
  94127. case FLAC__STREAM_DECODER_READ_FRAME:
  94128. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  94129. return false; /* above function sets the status for us */
  94130. break;
  94131. case FLAC__STREAM_DECODER_END_OF_STREAM:
  94132. case FLAC__STREAM_DECODER_ABORTED:
  94133. return true;
  94134. default:
  94135. FLAC__ASSERT(0);
  94136. return false;
  94137. }
  94138. }
  94139. }
  94140. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  94141. {
  94142. FLAC__bool got_a_frame;
  94143. FLAC__ASSERT(0 != decoder);
  94144. FLAC__ASSERT(0 != decoder->protected_);
  94145. while(1) {
  94146. switch(decoder->protected_->state) {
  94147. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  94148. case FLAC__STREAM_DECODER_READ_METADATA:
  94149. return false; /* above function sets the status for us */
  94150. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  94151. if(!frame_sync_(decoder))
  94152. return true; /* above function sets the status for us */
  94153. break;
  94154. case FLAC__STREAM_DECODER_READ_FRAME:
  94155. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  94156. return false; /* above function sets the status for us */
  94157. if(got_a_frame)
  94158. return true; /* above function sets the status for us */
  94159. break;
  94160. case FLAC__STREAM_DECODER_END_OF_STREAM:
  94161. case FLAC__STREAM_DECODER_ABORTED:
  94162. return true;
  94163. default:
  94164. FLAC__ASSERT(0);
  94165. return false;
  94166. }
  94167. }
  94168. }
  94169. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  94170. {
  94171. FLAC__uint64 length;
  94172. FLAC__ASSERT(0 != decoder);
  94173. if(
  94174. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  94175. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  94176. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  94177. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  94178. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  94179. )
  94180. return false;
  94181. if(0 == decoder->private_->seek_callback)
  94182. return false;
  94183. FLAC__ASSERT(decoder->private_->seek_callback);
  94184. FLAC__ASSERT(decoder->private_->tell_callback);
  94185. FLAC__ASSERT(decoder->private_->length_callback);
  94186. FLAC__ASSERT(decoder->private_->eof_callback);
  94187. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  94188. return false;
  94189. decoder->private_->is_seeking = true;
  94190. /* turn off md5 checking if a seek is attempted */
  94191. decoder->private_->do_md5_checking = false;
  94192. /* 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) */
  94193. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  94194. decoder->private_->is_seeking = false;
  94195. return false;
  94196. }
  94197. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  94198. if(
  94199. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  94200. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  94201. ) {
  94202. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  94203. /* above call sets the state for us */
  94204. decoder->private_->is_seeking = false;
  94205. return false;
  94206. }
  94207. /* check this again in case we didn't know total_samples the first time */
  94208. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  94209. decoder->private_->is_seeking = false;
  94210. return false;
  94211. }
  94212. }
  94213. {
  94214. const FLAC__bool ok =
  94215. #if FLAC__HAS_OGG
  94216. decoder->private_->is_ogg?
  94217. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  94218. #endif
  94219. seek_to_absolute_sample_(decoder, length, sample)
  94220. ;
  94221. decoder->private_->is_seeking = false;
  94222. return ok;
  94223. }
  94224. }
  94225. /***********************************************************************
  94226. *
  94227. * Protected class methods
  94228. *
  94229. ***********************************************************************/
  94230. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  94231. {
  94232. FLAC__ASSERT(0 != decoder);
  94233. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94234. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  94235. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  94236. }
  94237. /***********************************************************************
  94238. *
  94239. * Private class methods
  94240. *
  94241. ***********************************************************************/
  94242. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  94243. {
  94244. #if FLAC__HAS_OGG
  94245. decoder->private_->is_ogg = false;
  94246. #endif
  94247. decoder->private_->read_callback = 0;
  94248. decoder->private_->seek_callback = 0;
  94249. decoder->private_->tell_callback = 0;
  94250. decoder->private_->length_callback = 0;
  94251. decoder->private_->eof_callback = 0;
  94252. decoder->private_->write_callback = 0;
  94253. decoder->private_->metadata_callback = 0;
  94254. decoder->private_->error_callback = 0;
  94255. decoder->private_->client_data = 0;
  94256. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  94257. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  94258. decoder->private_->metadata_filter_ids_count = 0;
  94259. decoder->protected_->md5_checking = false;
  94260. #if FLAC__HAS_OGG
  94261. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  94262. #endif
  94263. }
  94264. /*
  94265. * This will forcibly set stdin to binary mode (for OSes that require it)
  94266. */
  94267. FILE *get_binary_stdin_(void)
  94268. {
  94269. /* if something breaks here it is probably due to the presence or
  94270. * absence of an underscore before the identifiers 'setmode',
  94271. * 'fileno', and/or 'O_BINARY'; check your system header files.
  94272. */
  94273. #if defined _MSC_VER || defined __MINGW32__
  94274. _setmode(_fileno(stdin), _O_BINARY);
  94275. #elif defined __CYGWIN__
  94276. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  94277. setmode(_fileno(stdin), _O_BINARY);
  94278. #elif defined __EMX__
  94279. setmode(fileno(stdin), O_BINARY);
  94280. #endif
  94281. return stdin;
  94282. }
  94283. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  94284. {
  94285. unsigned i;
  94286. FLAC__int32 *tmp;
  94287. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  94288. return true;
  94289. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  94290. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  94291. if(0 != decoder->private_->output[i]) {
  94292. free(decoder->private_->output[i]-4);
  94293. decoder->private_->output[i] = 0;
  94294. }
  94295. if(0 != decoder->private_->residual_unaligned[i]) {
  94296. free(decoder->private_->residual_unaligned[i]);
  94297. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  94298. }
  94299. }
  94300. for(i = 0; i < channels; i++) {
  94301. /* WATCHOUT:
  94302. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  94303. * output arrays have a buffer of up to 3 zeroes in front
  94304. * (at negative indices) for alignment purposes; we use 4
  94305. * to keep the data well-aligned.
  94306. */
  94307. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  94308. if(tmp == 0) {
  94309. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94310. return false;
  94311. }
  94312. memset(tmp, 0, sizeof(FLAC__int32)*4);
  94313. decoder->private_->output[i] = tmp + 4;
  94314. /* WATCHOUT:
  94315. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  94316. */
  94317. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  94318. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94319. return false;
  94320. }
  94321. }
  94322. decoder->private_->output_capacity = size;
  94323. decoder->private_->output_channels = channels;
  94324. return true;
  94325. }
  94326. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  94327. {
  94328. size_t i;
  94329. FLAC__ASSERT(0 != decoder);
  94330. FLAC__ASSERT(0 != decoder->private_);
  94331. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  94332. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  94333. return true;
  94334. return false;
  94335. }
  94336. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  94337. {
  94338. FLAC__uint32 x;
  94339. unsigned i, id_;
  94340. FLAC__bool first = true;
  94341. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94342. for(i = id_ = 0; i < 4; ) {
  94343. if(decoder->private_->cached) {
  94344. x = (FLAC__uint32)decoder->private_->lookahead;
  94345. decoder->private_->cached = false;
  94346. }
  94347. else {
  94348. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94349. return false; /* read_callback_ sets the state for us */
  94350. }
  94351. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  94352. first = true;
  94353. i++;
  94354. id_ = 0;
  94355. continue;
  94356. }
  94357. if(x == ID3V2_TAG_[id_]) {
  94358. id_++;
  94359. i = 0;
  94360. if(id_ == 3) {
  94361. if(!skip_id3v2_tag_(decoder))
  94362. return false; /* skip_id3v2_tag_ sets the state for us */
  94363. }
  94364. continue;
  94365. }
  94366. id_ = 0;
  94367. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94368. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  94369. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94370. return false; /* read_callback_ sets the state for us */
  94371. /* 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 */
  94372. /* else we have to check if the second byte is the end of a sync code */
  94373. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94374. decoder->private_->lookahead = (FLAC__byte)x;
  94375. decoder->private_->cached = true;
  94376. }
  94377. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  94378. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  94379. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  94380. return true;
  94381. }
  94382. }
  94383. i = 0;
  94384. if(first) {
  94385. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94386. first = false;
  94387. }
  94388. }
  94389. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  94390. return true;
  94391. }
  94392. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  94393. {
  94394. FLAC__bool is_last;
  94395. FLAC__uint32 i, x, type, length;
  94396. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94397. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  94398. return false; /* read_callback_ sets the state for us */
  94399. is_last = x? true : false;
  94400. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  94401. return false; /* read_callback_ sets the state for us */
  94402. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  94403. return false; /* read_callback_ sets the state for us */
  94404. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  94405. if(!read_metadata_streaminfo_(decoder, is_last, length))
  94406. return false;
  94407. decoder->private_->has_stream_info = true;
  94408. 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))
  94409. decoder->private_->do_md5_checking = false;
  94410. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  94411. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  94412. }
  94413. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  94414. if(!read_metadata_seektable_(decoder, is_last, length))
  94415. return false;
  94416. decoder->private_->has_seek_table = true;
  94417. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  94418. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  94419. }
  94420. else {
  94421. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  94422. unsigned real_length = length;
  94423. FLAC__StreamMetadata block;
  94424. block.is_last = is_last;
  94425. block.type = (FLAC__MetadataType)type;
  94426. block.length = length;
  94427. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  94428. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  94429. return false; /* read_callback_ sets the state for us */
  94430. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  94431. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  94432. return false;
  94433. }
  94434. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  94435. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  94436. skip_it = !skip_it;
  94437. }
  94438. if(skip_it) {
  94439. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  94440. return false; /* read_callback_ sets the state for us */
  94441. }
  94442. else {
  94443. switch(type) {
  94444. case FLAC__METADATA_TYPE_PADDING:
  94445. /* skip the padding bytes */
  94446. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  94447. return false; /* read_callback_ sets the state for us */
  94448. break;
  94449. case FLAC__METADATA_TYPE_APPLICATION:
  94450. /* remember, we read the ID already */
  94451. if(real_length > 0) {
  94452. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  94453. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94454. return false;
  94455. }
  94456. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  94457. return false; /* read_callback_ sets the state for us */
  94458. }
  94459. else
  94460. block.data.application.data = 0;
  94461. break;
  94462. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  94463. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  94464. return false;
  94465. break;
  94466. case FLAC__METADATA_TYPE_CUESHEET:
  94467. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  94468. return false;
  94469. break;
  94470. case FLAC__METADATA_TYPE_PICTURE:
  94471. if(!read_metadata_picture_(decoder, &block.data.picture))
  94472. return false;
  94473. break;
  94474. case FLAC__METADATA_TYPE_STREAMINFO:
  94475. case FLAC__METADATA_TYPE_SEEKTABLE:
  94476. FLAC__ASSERT(0);
  94477. break;
  94478. default:
  94479. if(real_length > 0) {
  94480. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  94481. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94482. return false;
  94483. }
  94484. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  94485. return false; /* read_callback_ sets the state for us */
  94486. }
  94487. else
  94488. block.data.unknown.data = 0;
  94489. break;
  94490. }
  94491. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  94492. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  94493. /* now we have to free any malloc()ed data in the block */
  94494. switch(type) {
  94495. case FLAC__METADATA_TYPE_PADDING:
  94496. break;
  94497. case FLAC__METADATA_TYPE_APPLICATION:
  94498. if(0 != block.data.application.data)
  94499. free(block.data.application.data);
  94500. break;
  94501. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  94502. if(0 != block.data.vorbis_comment.vendor_string.entry)
  94503. free(block.data.vorbis_comment.vendor_string.entry);
  94504. if(block.data.vorbis_comment.num_comments > 0)
  94505. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  94506. if(0 != block.data.vorbis_comment.comments[i].entry)
  94507. free(block.data.vorbis_comment.comments[i].entry);
  94508. if(0 != block.data.vorbis_comment.comments)
  94509. free(block.data.vorbis_comment.comments);
  94510. break;
  94511. case FLAC__METADATA_TYPE_CUESHEET:
  94512. if(block.data.cue_sheet.num_tracks > 0)
  94513. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  94514. if(0 != block.data.cue_sheet.tracks[i].indices)
  94515. free(block.data.cue_sheet.tracks[i].indices);
  94516. if(0 != block.data.cue_sheet.tracks)
  94517. free(block.data.cue_sheet.tracks);
  94518. break;
  94519. case FLAC__METADATA_TYPE_PICTURE:
  94520. if(0 != block.data.picture.mime_type)
  94521. free(block.data.picture.mime_type);
  94522. if(0 != block.data.picture.description)
  94523. free(block.data.picture.description);
  94524. if(0 != block.data.picture.data)
  94525. free(block.data.picture.data);
  94526. break;
  94527. case FLAC__METADATA_TYPE_STREAMINFO:
  94528. case FLAC__METADATA_TYPE_SEEKTABLE:
  94529. FLAC__ASSERT(0);
  94530. default:
  94531. if(0 != block.data.unknown.data)
  94532. free(block.data.unknown.data);
  94533. break;
  94534. }
  94535. }
  94536. }
  94537. if(is_last) {
  94538. /* if this fails, it's OK, it's just a hint for the seek routine */
  94539. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  94540. decoder->private_->first_frame_offset = 0;
  94541. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94542. }
  94543. return true;
  94544. }
  94545. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  94546. {
  94547. FLAC__uint32 x;
  94548. unsigned bits, used_bits = 0;
  94549. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94550. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  94551. decoder->private_->stream_info.is_last = is_last;
  94552. decoder->private_->stream_info.length = length;
  94553. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  94554. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  94555. return false; /* read_callback_ sets the state for us */
  94556. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  94557. used_bits += bits;
  94558. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  94559. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  94560. return false; /* read_callback_ sets the state for us */
  94561. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  94562. used_bits += bits;
  94563. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  94564. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  94565. return false; /* read_callback_ sets the state for us */
  94566. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  94567. used_bits += bits;
  94568. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  94569. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  94570. return false; /* read_callback_ sets the state for us */
  94571. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  94572. used_bits += bits;
  94573. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  94574. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  94575. return false; /* read_callback_ sets the state for us */
  94576. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  94577. used_bits += bits;
  94578. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  94579. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  94580. return false; /* read_callback_ sets the state for us */
  94581. decoder->private_->stream_info.data.stream_info.channels = x+1;
  94582. used_bits += bits;
  94583. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  94584. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  94585. return false; /* read_callback_ sets the state for us */
  94586. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  94587. used_bits += bits;
  94588. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  94589. 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))
  94590. return false; /* read_callback_ sets the state for us */
  94591. used_bits += bits;
  94592. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  94593. return false; /* read_callback_ sets the state for us */
  94594. used_bits += 16*8;
  94595. /* skip the rest of the block */
  94596. FLAC__ASSERT(used_bits % 8 == 0);
  94597. length -= (used_bits / 8);
  94598. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  94599. return false; /* read_callback_ sets the state for us */
  94600. return true;
  94601. }
  94602. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  94603. {
  94604. FLAC__uint32 i, x;
  94605. FLAC__uint64 xx;
  94606. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94607. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  94608. decoder->private_->seek_table.is_last = is_last;
  94609. decoder->private_->seek_table.length = length;
  94610. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  94611. /* use realloc since we may pass through here several times (e.g. after seeking) */
  94612. 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)))) {
  94613. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94614. return false;
  94615. }
  94616. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  94617. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  94618. return false; /* read_callback_ sets the state for us */
  94619. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  94620. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  94621. return false; /* read_callback_ sets the state for us */
  94622. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  94623. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  94624. return false; /* read_callback_ sets the state for us */
  94625. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  94626. }
  94627. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  94628. /* if there is a partial point left, skip over it */
  94629. if(length > 0) {
  94630. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  94631. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  94632. return false; /* read_callback_ sets the state for us */
  94633. }
  94634. return true;
  94635. }
  94636. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  94637. {
  94638. FLAC__uint32 i;
  94639. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94640. /* read vendor string */
  94641. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  94642. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  94643. return false; /* read_callback_ sets the state for us */
  94644. if(obj->vendor_string.length > 0) {
  94645. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  94646. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94647. return false;
  94648. }
  94649. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  94650. return false; /* read_callback_ sets the state for us */
  94651. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  94652. }
  94653. else
  94654. obj->vendor_string.entry = 0;
  94655. /* read num comments */
  94656. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  94657. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  94658. return false; /* read_callback_ sets the state for us */
  94659. /* read comments */
  94660. if(obj->num_comments > 0) {
  94661. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  94662. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94663. return false;
  94664. }
  94665. for(i = 0; i < obj->num_comments; i++) {
  94666. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  94667. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  94668. return false; /* read_callback_ sets the state for us */
  94669. if(obj->comments[i].length > 0) {
  94670. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  94671. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94672. return false;
  94673. }
  94674. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  94675. return false; /* read_callback_ sets the state for us */
  94676. obj->comments[i].entry[obj->comments[i].length] = '\0';
  94677. }
  94678. else
  94679. obj->comments[i].entry = 0;
  94680. }
  94681. }
  94682. else {
  94683. obj->comments = 0;
  94684. }
  94685. return true;
  94686. }
  94687. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  94688. {
  94689. FLAC__uint32 i, j, x;
  94690. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94691. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  94692. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  94693. 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))
  94694. return false; /* read_callback_ sets the state for us */
  94695. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  94696. return false; /* read_callback_ sets the state for us */
  94697. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  94698. return false; /* read_callback_ sets the state for us */
  94699. obj->is_cd = x? true : false;
  94700. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  94701. return false; /* read_callback_ sets the state for us */
  94702. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  94703. return false; /* read_callback_ sets the state for us */
  94704. obj->num_tracks = x;
  94705. if(obj->num_tracks > 0) {
  94706. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  94707. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94708. return false;
  94709. }
  94710. for(i = 0; i < obj->num_tracks; i++) {
  94711. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  94712. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  94713. return false; /* read_callback_ sets the state for us */
  94714. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  94715. return false; /* read_callback_ sets the state for us */
  94716. track->number = (FLAC__byte)x;
  94717. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  94718. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  94719. return false; /* read_callback_ sets the state for us */
  94720. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  94721. return false; /* read_callback_ sets the state for us */
  94722. track->type = x;
  94723. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  94724. return false; /* read_callback_ sets the state for us */
  94725. track->pre_emphasis = x;
  94726. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  94727. return false; /* read_callback_ sets the state for us */
  94728. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  94729. return false; /* read_callback_ sets the state for us */
  94730. track->num_indices = (FLAC__byte)x;
  94731. if(track->num_indices > 0) {
  94732. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  94733. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94734. return false;
  94735. }
  94736. for(j = 0; j < track->num_indices; j++) {
  94737. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  94738. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  94739. return false; /* read_callback_ sets the state for us */
  94740. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  94741. return false; /* read_callback_ sets the state for us */
  94742. index->number = (FLAC__byte)x;
  94743. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  94744. return false; /* read_callback_ sets the state for us */
  94745. }
  94746. }
  94747. }
  94748. }
  94749. return true;
  94750. }
  94751. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  94752. {
  94753. FLAC__uint32 x;
  94754. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94755. /* read type */
  94756. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  94757. return false; /* read_callback_ sets the state for us */
  94758. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  94759. /* read MIME type */
  94760. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  94761. return false; /* read_callback_ sets the state for us */
  94762. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  94763. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94764. return false;
  94765. }
  94766. if(x > 0) {
  94767. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  94768. return false; /* read_callback_ sets the state for us */
  94769. }
  94770. obj->mime_type[x] = '\0';
  94771. /* read description */
  94772. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  94773. return false; /* read_callback_ sets the state for us */
  94774. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  94775. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94776. return false;
  94777. }
  94778. if(x > 0) {
  94779. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  94780. return false; /* read_callback_ sets the state for us */
  94781. }
  94782. obj->description[x] = '\0';
  94783. /* read width */
  94784. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  94785. return false; /* read_callback_ sets the state for us */
  94786. /* read height */
  94787. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  94788. return false; /* read_callback_ sets the state for us */
  94789. /* read depth */
  94790. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  94791. return false; /* read_callback_ sets the state for us */
  94792. /* read colors */
  94793. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  94794. return false; /* read_callback_ sets the state for us */
  94795. /* read data */
  94796. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  94797. return false; /* read_callback_ sets the state for us */
  94798. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  94799. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94800. return false;
  94801. }
  94802. if(obj->data_length > 0) {
  94803. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  94804. return false; /* read_callback_ sets the state for us */
  94805. }
  94806. return true;
  94807. }
  94808. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  94809. {
  94810. FLAC__uint32 x;
  94811. unsigned i, skip;
  94812. /* skip the version and flags bytes */
  94813. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  94814. return false; /* read_callback_ sets the state for us */
  94815. /* get the size (in bytes) to skip */
  94816. skip = 0;
  94817. for(i = 0; i < 4; i++) {
  94818. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94819. return false; /* read_callback_ sets the state for us */
  94820. skip <<= 7;
  94821. skip |= (x & 0x7f);
  94822. }
  94823. /* skip the rest of the tag */
  94824. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  94825. return false; /* read_callback_ sets the state for us */
  94826. return true;
  94827. }
  94828. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  94829. {
  94830. FLAC__uint32 x;
  94831. FLAC__bool first = true;
  94832. /* If we know the total number of samples in the stream, stop if we've read that many. */
  94833. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  94834. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  94835. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  94836. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  94837. return true;
  94838. }
  94839. }
  94840. /* make sure we're byte aligned */
  94841. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  94842. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  94843. return false; /* read_callback_ sets the state for us */
  94844. }
  94845. while(1) {
  94846. if(decoder->private_->cached) {
  94847. x = (FLAC__uint32)decoder->private_->lookahead;
  94848. decoder->private_->cached = false;
  94849. }
  94850. else {
  94851. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94852. return false; /* read_callback_ sets the state for us */
  94853. }
  94854. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94855. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  94856. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94857. return false; /* read_callback_ sets the state for us */
  94858. /* 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 */
  94859. /* else we have to check if the second byte is the end of a sync code */
  94860. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94861. decoder->private_->lookahead = (FLAC__byte)x;
  94862. decoder->private_->cached = true;
  94863. }
  94864. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  94865. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  94866. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  94867. return true;
  94868. }
  94869. }
  94870. if(first) {
  94871. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94872. first = false;
  94873. }
  94874. }
  94875. return true;
  94876. }
  94877. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  94878. {
  94879. unsigned channel;
  94880. unsigned i;
  94881. FLAC__int32 mid, side;
  94882. unsigned frame_crc; /* the one we calculate from the input stream */
  94883. FLAC__uint32 x;
  94884. *got_a_frame = false;
  94885. /* init the CRC */
  94886. frame_crc = 0;
  94887. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  94888. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  94889. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  94890. if(!read_frame_header_(decoder))
  94891. return false;
  94892. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  94893. return true;
  94894. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  94895. return false;
  94896. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  94897. /*
  94898. * first figure the correct bits-per-sample of the subframe
  94899. */
  94900. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  94901. switch(decoder->private_->frame.header.channel_assignment) {
  94902. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  94903. /* no adjustment needed */
  94904. break;
  94905. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  94906. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94907. if(channel == 1)
  94908. bps++;
  94909. break;
  94910. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  94911. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94912. if(channel == 0)
  94913. bps++;
  94914. break;
  94915. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  94916. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94917. if(channel == 1)
  94918. bps++;
  94919. break;
  94920. default:
  94921. FLAC__ASSERT(0);
  94922. }
  94923. /*
  94924. * now read it
  94925. */
  94926. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  94927. return false;
  94928. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  94929. return true;
  94930. }
  94931. if(!read_zero_padding_(decoder))
  94932. return false;
  94933. 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) */
  94934. return true;
  94935. /*
  94936. * Read the frame CRC-16 from the footer and check
  94937. */
  94938. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  94939. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  94940. return false; /* read_callback_ sets the state for us */
  94941. if(frame_crc == x) {
  94942. if(do_full_decode) {
  94943. /* Undo any special channel coding */
  94944. switch(decoder->private_->frame.header.channel_assignment) {
  94945. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  94946. /* do nothing */
  94947. break;
  94948. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  94949. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94950. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  94951. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  94952. break;
  94953. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  94954. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94955. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  94956. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  94957. break;
  94958. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  94959. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94960. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  94961. #if 1
  94962. mid = decoder->private_->output[0][i];
  94963. side = decoder->private_->output[1][i];
  94964. mid <<= 1;
  94965. mid |= (side & 1); /* i.e. if 'side' is odd... */
  94966. decoder->private_->output[0][i] = (mid + side) >> 1;
  94967. decoder->private_->output[1][i] = (mid - side) >> 1;
  94968. #else
  94969. /* OPT: without 'side' temp variable */
  94970. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  94971. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  94972. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  94973. #endif
  94974. }
  94975. break;
  94976. default:
  94977. FLAC__ASSERT(0);
  94978. break;
  94979. }
  94980. }
  94981. }
  94982. else {
  94983. /* Bad frame, emit error and zero the output signal */
  94984. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  94985. if(do_full_decode) {
  94986. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  94987. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  94988. }
  94989. }
  94990. }
  94991. *got_a_frame = true;
  94992. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  94993. if(decoder->private_->next_fixed_block_size)
  94994. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  94995. /* put the latest values into the public section of the decoder instance */
  94996. decoder->protected_->channels = decoder->private_->frame.header.channels;
  94997. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  94998. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  94999. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  95000. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  95001. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  95002. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  95003. /* write it */
  95004. if(do_full_decode) {
  95005. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  95006. return false;
  95007. }
  95008. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95009. return true;
  95010. }
  95011. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  95012. {
  95013. FLAC__uint32 x;
  95014. FLAC__uint64 xx;
  95015. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  95016. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  95017. unsigned raw_header_len;
  95018. FLAC__bool is_unparseable = false;
  95019. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95020. /* init the raw header with the saved bits from synchronization */
  95021. raw_header[0] = decoder->private_->header_warmup[0];
  95022. raw_header[1] = decoder->private_->header_warmup[1];
  95023. raw_header_len = 2;
  95024. /* check to make sure that reserved bit is 0 */
  95025. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  95026. is_unparseable = true;
  95027. /*
  95028. * Note that along the way as we read the header, we look for a sync
  95029. * code inside. If we find one it would indicate that our original
  95030. * sync was bad since there cannot be a sync code in a valid header.
  95031. *
  95032. * Three kinds of things can go wrong when reading the frame header:
  95033. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  95034. * If we don't find a sync code, it can end up looking like we read
  95035. * a valid but unparseable header, until getting to the frame header
  95036. * CRC. Even then we could get a false positive on the CRC.
  95037. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  95038. * future encoder).
  95039. * 3) We may be on a damaged frame which appears valid but unparseable.
  95040. *
  95041. * For all these reasons, we try and read a complete frame header as
  95042. * long as it seems valid, even if unparseable, up until the frame
  95043. * header CRC.
  95044. */
  95045. /*
  95046. * read in the raw header as bytes so we can CRC it, and parse it on the way
  95047. */
  95048. for(i = 0; i < 2; i++) {
  95049. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95050. return false; /* read_callback_ sets the state for us */
  95051. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  95052. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  95053. decoder->private_->lookahead = (FLAC__byte)x;
  95054. decoder->private_->cached = true;
  95055. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95056. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95057. return true;
  95058. }
  95059. raw_header[raw_header_len++] = (FLAC__byte)x;
  95060. }
  95061. switch(x = raw_header[2] >> 4) {
  95062. case 0:
  95063. is_unparseable = true;
  95064. break;
  95065. case 1:
  95066. decoder->private_->frame.header.blocksize = 192;
  95067. break;
  95068. case 2:
  95069. case 3:
  95070. case 4:
  95071. case 5:
  95072. decoder->private_->frame.header.blocksize = 576 << (x-2);
  95073. break;
  95074. case 6:
  95075. case 7:
  95076. blocksize_hint = x;
  95077. break;
  95078. case 8:
  95079. case 9:
  95080. case 10:
  95081. case 11:
  95082. case 12:
  95083. case 13:
  95084. case 14:
  95085. case 15:
  95086. decoder->private_->frame.header.blocksize = 256 << (x-8);
  95087. break;
  95088. default:
  95089. FLAC__ASSERT(0);
  95090. break;
  95091. }
  95092. switch(x = raw_header[2] & 0x0f) {
  95093. case 0:
  95094. if(decoder->private_->has_stream_info)
  95095. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  95096. else
  95097. is_unparseable = true;
  95098. break;
  95099. case 1:
  95100. decoder->private_->frame.header.sample_rate = 88200;
  95101. break;
  95102. case 2:
  95103. decoder->private_->frame.header.sample_rate = 176400;
  95104. break;
  95105. case 3:
  95106. decoder->private_->frame.header.sample_rate = 192000;
  95107. break;
  95108. case 4:
  95109. decoder->private_->frame.header.sample_rate = 8000;
  95110. break;
  95111. case 5:
  95112. decoder->private_->frame.header.sample_rate = 16000;
  95113. break;
  95114. case 6:
  95115. decoder->private_->frame.header.sample_rate = 22050;
  95116. break;
  95117. case 7:
  95118. decoder->private_->frame.header.sample_rate = 24000;
  95119. break;
  95120. case 8:
  95121. decoder->private_->frame.header.sample_rate = 32000;
  95122. break;
  95123. case 9:
  95124. decoder->private_->frame.header.sample_rate = 44100;
  95125. break;
  95126. case 10:
  95127. decoder->private_->frame.header.sample_rate = 48000;
  95128. break;
  95129. case 11:
  95130. decoder->private_->frame.header.sample_rate = 96000;
  95131. break;
  95132. case 12:
  95133. case 13:
  95134. case 14:
  95135. sample_rate_hint = x;
  95136. break;
  95137. case 15:
  95138. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95139. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95140. return true;
  95141. default:
  95142. FLAC__ASSERT(0);
  95143. }
  95144. x = (unsigned)(raw_header[3] >> 4);
  95145. if(x & 8) {
  95146. decoder->private_->frame.header.channels = 2;
  95147. switch(x & 7) {
  95148. case 0:
  95149. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  95150. break;
  95151. case 1:
  95152. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  95153. break;
  95154. case 2:
  95155. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  95156. break;
  95157. default:
  95158. is_unparseable = true;
  95159. break;
  95160. }
  95161. }
  95162. else {
  95163. decoder->private_->frame.header.channels = (unsigned)x + 1;
  95164. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  95165. }
  95166. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  95167. case 0:
  95168. if(decoder->private_->has_stream_info)
  95169. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  95170. else
  95171. is_unparseable = true;
  95172. break;
  95173. case 1:
  95174. decoder->private_->frame.header.bits_per_sample = 8;
  95175. break;
  95176. case 2:
  95177. decoder->private_->frame.header.bits_per_sample = 12;
  95178. break;
  95179. case 4:
  95180. decoder->private_->frame.header.bits_per_sample = 16;
  95181. break;
  95182. case 5:
  95183. decoder->private_->frame.header.bits_per_sample = 20;
  95184. break;
  95185. case 6:
  95186. decoder->private_->frame.header.bits_per_sample = 24;
  95187. break;
  95188. case 3:
  95189. case 7:
  95190. is_unparseable = true;
  95191. break;
  95192. default:
  95193. FLAC__ASSERT(0);
  95194. break;
  95195. }
  95196. /* check to make sure that reserved bit is 0 */
  95197. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  95198. is_unparseable = true;
  95199. /* read the frame's starting sample number (or frame number as the case may be) */
  95200. if(
  95201. raw_header[1] & 0x01 ||
  95202. /*@@@ 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 */
  95203. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  95204. ) { /* variable blocksize */
  95205. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  95206. return false; /* read_callback_ sets the state for us */
  95207. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  95208. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  95209. decoder->private_->cached = true;
  95210. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95211. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95212. return true;
  95213. }
  95214. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  95215. decoder->private_->frame.header.number.sample_number = xx;
  95216. }
  95217. else { /* fixed blocksize */
  95218. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  95219. return false; /* read_callback_ sets the state for us */
  95220. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  95221. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  95222. decoder->private_->cached = true;
  95223. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95224. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95225. return true;
  95226. }
  95227. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  95228. decoder->private_->frame.header.number.frame_number = x;
  95229. }
  95230. if(blocksize_hint) {
  95231. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95232. return false; /* read_callback_ sets the state for us */
  95233. raw_header[raw_header_len++] = (FLAC__byte)x;
  95234. if(blocksize_hint == 7) {
  95235. FLAC__uint32 _x;
  95236. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  95237. return false; /* read_callback_ sets the state for us */
  95238. raw_header[raw_header_len++] = (FLAC__byte)_x;
  95239. x = (x << 8) | _x;
  95240. }
  95241. decoder->private_->frame.header.blocksize = x+1;
  95242. }
  95243. if(sample_rate_hint) {
  95244. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95245. return false; /* read_callback_ sets the state for us */
  95246. raw_header[raw_header_len++] = (FLAC__byte)x;
  95247. if(sample_rate_hint != 12) {
  95248. FLAC__uint32 _x;
  95249. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  95250. return false; /* read_callback_ sets the state for us */
  95251. raw_header[raw_header_len++] = (FLAC__byte)_x;
  95252. x = (x << 8) | _x;
  95253. }
  95254. if(sample_rate_hint == 12)
  95255. decoder->private_->frame.header.sample_rate = x*1000;
  95256. else if(sample_rate_hint == 13)
  95257. decoder->private_->frame.header.sample_rate = x;
  95258. else
  95259. decoder->private_->frame.header.sample_rate = x*10;
  95260. }
  95261. /* read the CRC-8 byte */
  95262. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95263. return false; /* read_callback_ sets the state for us */
  95264. crc8 = (FLAC__byte)x;
  95265. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  95266. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  95267. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95268. return true;
  95269. }
  95270. /* calculate the sample number from the frame number if needed */
  95271. decoder->private_->next_fixed_block_size = 0;
  95272. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  95273. x = decoder->private_->frame.header.number.frame_number;
  95274. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  95275. if(decoder->private_->fixed_block_size)
  95276. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  95277. else if(decoder->private_->has_stream_info) {
  95278. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  95279. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  95280. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  95281. }
  95282. else
  95283. is_unparseable = true;
  95284. }
  95285. else if(x == 0) {
  95286. decoder->private_->frame.header.number.sample_number = 0;
  95287. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  95288. }
  95289. else {
  95290. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  95291. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  95292. }
  95293. }
  95294. if(is_unparseable) {
  95295. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  95296. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95297. return true;
  95298. }
  95299. return true;
  95300. }
  95301. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  95302. {
  95303. FLAC__uint32 x;
  95304. FLAC__bool wasted_bits;
  95305. unsigned i;
  95306. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  95307. return false; /* read_callback_ sets the state for us */
  95308. wasted_bits = (x & 1);
  95309. x &= 0xfe;
  95310. if(wasted_bits) {
  95311. unsigned u;
  95312. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  95313. return false; /* read_callback_ sets the state for us */
  95314. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  95315. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  95316. }
  95317. else
  95318. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  95319. /*
  95320. * Lots of magic numbers here
  95321. */
  95322. if(x & 0x80) {
  95323. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95324. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95325. return true;
  95326. }
  95327. else if(x == 0) {
  95328. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  95329. return false;
  95330. }
  95331. else if(x == 2) {
  95332. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  95333. return false;
  95334. }
  95335. else if(x < 16) {
  95336. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  95337. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95338. return true;
  95339. }
  95340. else if(x <= 24) {
  95341. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  95342. return false;
  95343. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  95344. return true;
  95345. }
  95346. else if(x < 64) {
  95347. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  95348. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95349. return true;
  95350. }
  95351. else {
  95352. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  95353. return false;
  95354. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  95355. return true;
  95356. }
  95357. if(wasted_bits && do_full_decode) {
  95358. x = decoder->private_->frame.subframes[channel].wasted_bits;
  95359. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  95360. decoder->private_->output[channel][i] <<= x;
  95361. }
  95362. return true;
  95363. }
  95364. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  95365. {
  95366. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  95367. FLAC__int32 x;
  95368. unsigned i;
  95369. FLAC__int32 *output = decoder->private_->output[channel];
  95370. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  95371. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  95372. return false; /* read_callback_ sets the state for us */
  95373. subframe->value = x;
  95374. /* decode the subframe */
  95375. if(do_full_decode) {
  95376. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  95377. output[i] = x;
  95378. }
  95379. return true;
  95380. }
  95381. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  95382. {
  95383. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  95384. FLAC__int32 i32;
  95385. FLAC__uint32 u32;
  95386. unsigned u;
  95387. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  95388. subframe->residual = decoder->private_->residual[channel];
  95389. subframe->order = order;
  95390. /* read warm-up samples */
  95391. for(u = 0; u < order; u++) {
  95392. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  95393. return false; /* read_callback_ sets the state for us */
  95394. subframe->warmup[u] = i32;
  95395. }
  95396. /* read entropy coding method info */
  95397. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  95398. return false; /* read_callback_ sets the state for us */
  95399. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  95400. switch(subframe->entropy_coding_method.type) {
  95401. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  95402. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  95403. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  95404. return false; /* read_callback_ sets the state for us */
  95405. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  95406. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  95407. break;
  95408. default:
  95409. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  95410. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95411. return true;
  95412. }
  95413. /* read residual */
  95414. switch(subframe->entropy_coding_method.type) {
  95415. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  95416. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  95417. 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))
  95418. return false;
  95419. break;
  95420. default:
  95421. FLAC__ASSERT(0);
  95422. }
  95423. /* decode the subframe */
  95424. if(do_full_decode) {
  95425. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  95426. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  95427. }
  95428. return true;
  95429. }
  95430. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  95431. {
  95432. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  95433. FLAC__int32 i32;
  95434. FLAC__uint32 u32;
  95435. unsigned u;
  95436. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  95437. subframe->residual = decoder->private_->residual[channel];
  95438. subframe->order = order;
  95439. /* read warm-up samples */
  95440. for(u = 0; u < order; u++) {
  95441. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  95442. return false; /* read_callback_ sets the state for us */
  95443. subframe->warmup[u] = i32;
  95444. }
  95445. /* read qlp coeff precision */
  95446. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  95447. return false; /* read_callback_ sets the state for us */
  95448. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  95449. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95450. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95451. return true;
  95452. }
  95453. subframe->qlp_coeff_precision = u32+1;
  95454. /* read qlp shift */
  95455. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  95456. return false; /* read_callback_ sets the state for us */
  95457. subframe->quantization_level = i32;
  95458. /* read quantized lp coefficiencts */
  95459. for(u = 0; u < order; u++) {
  95460. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  95461. return false; /* read_callback_ sets the state for us */
  95462. subframe->qlp_coeff[u] = i32;
  95463. }
  95464. /* read entropy coding method info */
  95465. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  95466. return false; /* read_callback_ sets the state for us */
  95467. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  95468. switch(subframe->entropy_coding_method.type) {
  95469. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  95470. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  95471. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  95472. return false; /* read_callback_ sets the state for us */
  95473. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  95474. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  95475. break;
  95476. default:
  95477. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  95478. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95479. return true;
  95480. }
  95481. /* read residual */
  95482. switch(subframe->entropy_coding_method.type) {
  95483. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  95484. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  95485. 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))
  95486. return false;
  95487. break;
  95488. default:
  95489. FLAC__ASSERT(0);
  95490. }
  95491. /* decode the subframe */
  95492. if(do_full_decode) {
  95493. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  95494. /*@@@@@@ technically not pessimistic enough, should be more like
  95495. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  95496. */
  95497. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  95498. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  95499. if(order <= 8)
  95500. 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);
  95501. else
  95502. 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);
  95503. }
  95504. else
  95505. 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);
  95506. else
  95507. 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);
  95508. }
  95509. return true;
  95510. }
  95511. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  95512. {
  95513. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  95514. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  95515. unsigned i;
  95516. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  95517. subframe->data = residual;
  95518. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  95519. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  95520. return false; /* read_callback_ sets the state for us */
  95521. residual[i] = x;
  95522. }
  95523. /* decode the subframe */
  95524. if(do_full_decode)
  95525. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  95526. return true;
  95527. }
  95528. 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)
  95529. {
  95530. FLAC__uint32 rice_parameter;
  95531. int i;
  95532. unsigned partition, sample, u;
  95533. const unsigned partitions = 1u << partition_order;
  95534. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  95535. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  95536. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  95537. /* sanity checks */
  95538. if(partition_order == 0) {
  95539. if(decoder->private_->frame.header.blocksize < predictor_order) {
  95540. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95541. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95542. return true;
  95543. }
  95544. }
  95545. else {
  95546. if(partition_samples < predictor_order) {
  95547. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95548. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95549. return true;
  95550. }
  95551. }
  95552. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  95553. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95554. return false;
  95555. }
  95556. sample = 0;
  95557. for(partition = 0; partition < partitions; partition++) {
  95558. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  95559. return false; /* read_callback_ sets the state for us */
  95560. partitioned_rice_contents->parameters[partition] = rice_parameter;
  95561. if(rice_parameter < pesc) {
  95562. partitioned_rice_contents->raw_bits[partition] = 0;
  95563. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  95564. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  95565. return false; /* read_callback_ sets the state for us */
  95566. sample += u;
  95567. }
  95568. else {
  95569. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  95570. return false; /* read_callback_ sets the state for us */
  95571. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  95572. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  95573. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  95574. return false; /* read_callback_ sets the state for us */
  95575. residual[sample] = i;
  95576. }
  95577. }
  95578. }
  95579. return true;
  95580. }
  95581. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  95582. {
  95583. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  95584. FLAC__uint32 zero = 0;
  95585. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  95586. return false; /* read_callback_ sets the state for us */
  95587. if(zero != 0) {
  95588. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95589. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95590. }
  95591. }
  95592. return true;
  95593. }
  95594. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  95595. {
  95596. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  95597. if(
  95598. #if FLAC__HAS_OGG
  95599. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  95600. !decoder->private_->is_ogg &&
  95601. #endif
  95602. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  95603. ) {
  95604. *bytes = 0;
  95605. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  95606. return false;
  95607. }
  95608. else if(*bytes > 0) {
  95609. /* While seeking, it is possible for our seek to land in the
  95610. * middle of audio data that looks exactly like a frame header
  95611. * from a future version of an encoder. When that happens, our
  95612. * error callback will get an
  95613. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  95614. * unparseable_frame_count. But there is a remote possibility
  95615. * that it is properly synced at such a "future-codec frame",
  95616. * so to make sure, we wait to see many "unparseable" errors in
  95617. * a row before bailing out.
  95618. */
  95619. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  95620. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  95621. return false;
  95622. }
  95623. else {
  95624. const FLAC__StreamDecoderReadStatus status =
  95625. #if FLAC__HAS_OGG
  95626. decoder->private_->is_ogg?
  95627. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  95628. #endif
  95629. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  95630. ;
  95631. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  95632. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  95633. return false;
  95634. }
  95635. else if(*bytes == 0) {
  95636. if(
  95637. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  95638. (
  95639. #if FLAC__HAS_OGG
  95640. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  95641. !decoder->private_->is_ogg &&
  95642. #endif
  95643. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  95644. )
  95645. ) {
  95646. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  95647. return false;
  95648. }
  95649. else
  95650. return true;
  95651. }
  95652. else
  95653. return true;
  95654. }
  95655. }
  95656. else {
  95657. /* abort to avoid a deadlock */
  95658. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  95659. return false;
  95660. }
  95661. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  95662. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  95663. * and at the same time hit the end of the stream (for example, seeking
  95664. * to a point that is after the beginning of the last Ogg page). There
  95665. * is no way to report an Ogg sync loss through the callbacks (see note
  95666. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  95667. * So to keep the decoder from stopping at this point we gate the call
  95668. * to the eof_callback and let the Ogg decoder aspect set the
  95669. * end-of-stream state when it is needed.
  95670. */
  95671. }
  95672. #if FLAC__HAS_OGG
  95673. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  95674. {
  95675. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  95676. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  95677. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  95678. /* we don't really have a way to handle lost sync via read
  95679. * callback so we'll let it pass and let the underlying
  95680. * FLAC decoder catch the error
  95681. */
  95682. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  95683. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  95684. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  95685. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  95686. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  95687. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  95688. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  95689. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  95690. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  95691. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  95692. default:
  95693. FLAC__ASSERT(0);
  95694. /* double protection */
  95695. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  95696. }
  95697. }
  95698. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  95699. {
  95700. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  95701. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  95702. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  95703. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  95704. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  95705. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  95706. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  95707. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  95708. default:
  95709. /* double protection: */
  95710. FLAC__ASSERT(0);
  95711. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  95712. }
  95713. }
  95714. #endif
  95715. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  95716. {
  95717. if(decoder->private_->is_seeking) {
  95718. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  95719. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  95720. FLAC__uint64 target_sample = decoder->private_->target_sample;
  95721. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  95722. #if FLAC__HAS_OGG
  95723. decoder->private_->got_a_frame = true;
  95724. #endif
  95725. decoder->private_->last_frame = *frame; /* save the frame */
  95726. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  95727. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  95728. /* kick out of seek mode */
  95729. decoder->private_->is_seeking = false;
  95730. /* shift out the samples before target_sample */
  95731. if(delta > 0) {
  95732. unsigned channel;
  95733. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  95734. for(channel = 0; channel < frame->header.channels; channel++)
  95735. newbuffer[channel] = buffer[channel] + delta;
  95736. decoder->private_->last_frame.header.blocksize -= delta;
  95737. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  95738. /* write the relevant samples */
  95739. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  95740. }
  95741. else {
  95742. /* write the relevant samples */
  95743. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  95744. }
  95745. }
  95746. else {
  95747. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  95748. }
  95749. }
  95750. else {
  95751. /*
  95752. * If we never got STREAMINFO, turn off MD5 checking to save
  95753. * cycles since we don't have a sum to compare to anyway
  95754. */
  95755. if(!decoder->private_->has_stream_info)
  95756. decoder->private_->do_md5_checking = false;
  95757. if(decoder->private_->do_md5_checking) {
  95758. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  95759. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  95760. }
  95761. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  95762. }
  95763. }
  95764. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  95765. {
  95766. if(!decoder->private_->is_seeking)
  95767. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  95768. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  95769. decoder->private_->unparseable_frame_count++;
  95770. }
  95771. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  95772. {
  95773. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  95774. FLAC__int64 pos = -1;
  95775. int i;
  95776. unsigned approx_bytes_per_frame;
  95777. FLAC__bool first_seek = true;
  95778. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  95779. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  95780. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  95781. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  95782. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  95783. /* take these from the current frame in case they've changed mid-stream */
  95784. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  95785. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  95786. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  95787. /* use values from stream info if we didn't decode a frame */
  95788. if(channels == 0)
  95789. channels = decoder->private_->stream_info.data.stream_info.channels;
  95790. if(bps == 0)
  95791. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  95792. /* we are just guessing here */
  95793. if(max_framesize > 0)
  95794. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  95795. /*
  95796. * Check if it's a known fixed-blocksize stream. Note that though
  95797. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  95798. * never get a STREAMINFO block when decoding so the value of
  95799. * min_blocksize might be zero.
  95800. */
  95801. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  95802. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  95803. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  95804. }
  95805. else
  95806. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  95807. /*
  95808. * First, we set an upper and lower bound on where in the
  95809. * stream we will search. For now we assume the worst case
  95810. * scenario, which is our best guess at the beginning of
  95811. * the first frame and end of the stream.
  95812. */
  95813. lower_bound = first_frame_offset;
  95814. lower_bound_sample = 0;
  95815. upper_bound = stream_length;
  95816. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  95817. /*
  95818. * Now we refine the bounds if we have a seektable with
  95819. * suitable points. Note that according to the spec they
  95820. * must be ordered by ascending sample number.
  95821. *
  95822. * Note: to protect against invalid seek tables we will ignore points
  95823. * that have frame_samples==0 or sample_number>=total_samples
  95824. */
  95825. if(seek_table) {
  95826. FLAC__uint64 new_lower_bound = lower_bound;
  95827. FLAC__uint64 new_upper_bound = upper_bound;
  95828. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  95829. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  95830. /* find the closest seek point <= target_sample, if it exists */
  95831. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  95832. if(
  95833. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  95834. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  95835. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  95836. seek_table->points[i].sample_number <= target_sample
  95837. )
  95838. break;
  95839. }
  95840. if(i >= 0) { /* i.e. we found a suitable seek point... */
  95841. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  95842. new_lower_bound_sample = seek_table->points[i].sample_number;
  95843. }
  95844. /* find the closest seek point > target_sample, if it exists */
  95845. for(i = 0; i < (int)seek_table->num_points; i++) {
  95846. if(
  95847. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  95848. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  95849. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  95850. seek_table->points[i].sample_number > target_sample
  95851. )
  95852. break;
  95853. }
  95854. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  95855. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  95856. new_upper_bound_sample = seek_table->points[i].sample_number;
  95857. }
  95858. /* final protection against unsorted seek tables; keep original values if bogus */
  95859. if(new_upper_bound >= new_lower_bound) {
  95860. lower_bound = new_lower_bound;
  95861. upper_bound = new_upper_bound;
  95862. lower_bound_sample = new_lower_bound_sample;
  95863. upper_bound_sample = new_upper_bound_sample;
  95864. }
  95865. }
  95866. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  95867. /* there are 2 insidious ways that the following equality occurs, which
  95868. * we need to fix:
  95869. * 1) total_samples is 0 (unknown) and target_sample is 0
  95870. * 2) total_samples is 0 (unknown) and target_sample happens to be
  95871. * exactly equal to the last seek point in the seek table; this
  95872. * means there is no seek point above it, and upper_bound_samples
  95873. * remains equal to the estimate (of target_samples) we made above
  95874. * in either case it does not hurt to move upper_bound_sample up by 1
  95875. */
  95876. if(upper_bound_sample == lower_bound_sample)
  95877. upper_bound_sample++;
  95878. decoder->private_->target_sample = target_sample;
  95879. while(1) {
  95880. /* check if the bounds are still ok */
  95881. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  95882. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95883. return false;
  95884. }
  95885. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95886. #if defined _MSC_VER || defined __MINGW32__
  95887. /* with VC++ you have to spoon feed it the casting */
  95888. 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;
  95889. #else
  95890. 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;
  95891. #endif
  95892. #else
  95893. /* a little less accurate: */
  95894. if(upper_bound - lower_bound < 0xffffffff)
  95895. 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;
  95896. else /* @@@ WATCHOUT, ~2TB limit */
  95897. 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;
  95898. #endif
  95899. if(pos >= (FLAC__int64)upper_bound)
  95900. pos = (FLAC__int64)upper_bound - 1;
  95901. if(pos < (FLAC__int64)lower_bound)
  95902. pos = (FLAC__int64)lower_bound;
  95903. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  95904. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95905. return false;
  95906. }
  95907. if(!FLAC__stream_decoder_flush(decoder)) {
  95908. /* above call sets the state for us */
  95909. return false;
  95910. }
  95911. /* Now we need to get a frame. First we need to reset our
  95912. * unparseable_frame_count; if we get too many unparseable
  95913. * frames in a row, the read callback will return
  95914. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  95915. * FLAC__stream_decoder_process_single() to return false.
  95916. */
  95917. decoder->private_->unparseable_frame_count = 0;
  95918. if(!FLAC__stream_decoder_process_single(decoder)) {
  95919. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95920. return false;
  95921. }
  95922. /* our write callback will change the state when it gets to the target frame */
  95923. /* 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 */
  95924. #if 0
  95925. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  95926. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  95927. break;
  95928. #endif
  95929. if(!decoder->private_->is_seeking)
  95930. break;
  95931. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  95932. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  95933. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  95934. if (pos == (FLAC__int64)lower_bound) {
  95935. /* can't move back any more than the first frame, something is fatally wrong */
  95936. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95937. return false;
  95938. }
  95939. /* our last move backwards wasn't big enough, try again */
  95940. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  95941. continue;
  95942. }
  95943. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  95944. first_seek = false;
  95945. /* make sure we are not seeking in corrupted stream */
  95946. if (this_frame_sample < lower_bound_sample) {
  95947. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95948. return false;
  95949. }
  95950. /* we need to narrow the search */
  95951. if(target_sample < this_frame_sample) {
  95952. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  95953. /*@@@@@@ what will decode position be if at end of stream? */
  95954. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  95955. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95956. return false;
  95957. }
  95958. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  95959. }
  95960. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  95961. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  95962. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  95963. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95964. return false;
  95965. }
  95966. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  95967. }
  95968. }
  95969. return true;
  95970. }
  95971. #if FLAC__HAS_OGG
  95972. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  95973. {
  95974. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  95975. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  95976. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  95977. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  95978. FLAC__bool did_a_seek;
  95979. unsigned iteration = 0;
  95980. /* In the first iterations, we will calculate the target byte position
  95981. * by the distance from the target sample to left_sample and
  95982. * right_sample (let's call it "proportional search"). After that, we
  95983. * will switch to binary search.
  95984. */
  95985. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  95986. /* We will switch to a linear search once our current sample is less
  95987. * than this number of samples ahead of the target sample
  95988. */
  95989. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  95990. /* If the total number of samples is unknown, use a large value, and
  95991. * force binary search immediately.
  95992. */
  95993. if(right_sample == 0) {
  95994. right_sample = (FLAC__uint64)(-1);
  95995. BINARY_SEARCH_AFTER_ITERATION = 0;
  95996. }
  95997. decoder->private_->target_sample = target_sample;
  95998. for( ; ; iteration++) {
  95999. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  96000. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  96001. pos = (right_pos + left_pos) / 2;
  96002. }
  96003. else {
  96004. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96005. #if defined _MSC_VER || defined __MINGW32__
  96006. /* with MSVC you have to spoon feed it the casting */
  96007. 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));
  96008. #else
  96009. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  96010. #endif
  96011. #else
  96012. /* a little less accurate: */
  96013. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  96014. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  96015. else /* @@@ WATCHOUT, ~2TB limit */
  96016. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  96017. #endif
  96018. /* @@@ TODO: might want to limit pos to some distance
  96019. * before EOF, to make sure we land before the last frame,
  96020. * thereby getting a this_frame_sample and so having a better
  96021. * estimate.
  96022. */
  96023. }
  96024. /* physical seek */
  96025. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  96026. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96027. return false;
  96028. }
  96029. if(!FLAC__stream_decoder_flush(decoder)) {
  96030. /* above call sets the state for us */
  96031. return false;
  96032. }
  96033. did_a_seek = true;
  96034. }
  96035. else
  96036. did_a_seek = false;
  96037. decoder->private_->got_a_frame = false;
  96038. if(!FLAC__stream_decoder_process_single(decoder)) {
  96039. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96040. return false;
  96041. }
  96042. if(!decoder->private_->got_a_frame) {
  96043. if(did_a_seek) {
  96044. /* this can happen if we seek to a point after the last frame; we drop
  96045. * to binary search right away in this case to avoid any wasted
  96046. * iterations of proportional search.
  96047. */
  96048. right_pos = pos;
  96049. BINARY_SEARCH_AFTER_ITERATION = 0;
  96050. }
  96051. else {
  96052. /* this can probably only happen if total_samples is unknown and the
  96053. * target_sample is past the end of the stream
  96054. */
  96055. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96056. return false;
  96057. }
  96058. }
  96059. /* our write callback will change the state when it gets to the target frame */
  96060. else if(!decoder->private_->is_seeking) {
  96061. break;
  96062. }
  96063. else {
  96064. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  96065. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  96066. if (did_a_seek) {
  96067. if (this_frame_sample <= target_sample) {
  96068. /* The 'equal' case should not happen, since
  96069. * FLAC__stream_decoder_process_single()
  96070. * should recognize that it has hit the
  96071. * target sample and we would exit through
  96072. * the 'break' above.
  96073. */
  96074. FLAC__ASSERT(this_frame_sample != target_sample);
  96075. left_sample = this_frame_sample;
  96076. /* sanity check to avoid infinite loop */
  96077. if (left_pos == pos) {
  96078. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96079. return false;
  96080. }
  96081. left_pos = pos;
  96082. }
  96083. else if(this_frame_sample > target_sample) {
  96084. right_sample = this_frame_sample;
  96085. /* sanity check to avoid infinite loop */
  96086. if (right_pos == pos) {
  96087. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  96088. return false;
  96089. }
  96090. right_pos = pos;
  96091. }
  96092. }
  96093. }
  96094. }
  96095. return true;
  96096. }
  96097. #endif
  96098. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  96099. {
  96100. (void)client_data;
  96101. if(*bytes > 0) {
  96102. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  96103. if(ferror(decoder->private_->file))
  96104. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  96105. else if(*bytes == 0)
  96106. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  96107. else
  96108. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  96109. }
  96110. else
  96111. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  96112. }
  96113. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  96114. {
  96115. (void)client_data;
  96116. if(decoder->private_->file == stdin)
  96117. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  96118. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  96119. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  96120. else
  96121. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  96122. }
  96123. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  96124. {
  96125. off_t pos;
  96126. (void)client_data;
  96127. if(decoder->private_->file == stdin)
  96128. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  96129. else if((pos = ftello(decoder->private_->file)) < 0)
  96130. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  96131. else {
  96132. *absolute_byte_offset = (FLAC__uint64)pos;
  96133. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  96134. }
  96135. }
  96136. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  96137. {
  96138. struct stat filestats;
  96139. (void)client_data;
  96140. if(decoder->private_->file == stdin)
  96141. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  96142. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  96143. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  96144. else {
  96145. *stream_length = (FLAC__uint64)filestats.st_size;
  96146. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  96147. }
  96148. }
  96149. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  96150. {
  96151. (void)client_data;
  96152. return feof(decoder->private_->file)? true : false;
  96153. }
  96154. #endif
  96155. /********* End of inlined file: stream_decoder.c *********/
  96156. /********* Start of inlined file: stream_encoder.c *********/
  96157. /********* Start of inlined file: juce_FlacHeader.h *********/
  96158. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96159. // tasks..
  96160. #define VERSION "1.2.1"
  96161. #define FLAC__NO_DLL 1
  96162. #ifdef _MSC_VER
  96163. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96164. #endif
  96165. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  96166. #define FLAC__SYS_DARWIN 1
  96167. #endif
  96168. /********* End of inlined file: juce_FlacHeader.h *********/
  96169. #if JUCE_USE_FLAC
  96170. #if HAVE_CONFIG_H
  96171. # include <config.h>
  96172. #endif
  96173. #if defined _MSC_VER || defined __MINGW32__
  96174. #include <io.h> /* for _setmode() */
  96175. #include <fcntl.h> /* for _O_BINARY */
  96176. #endif
  96177. #if defined __CYGWIN__ || defined __EMX__
  96178. #include <io.h> /* for setmode(), O_BINARY */
  96179. #include <fcntl.h> /* for _O_BINARY */
  96180. #endif
  96181. #include <limits.h>
  96182. #include <stdio.h>
  96183. #include <stdlib.h> /* for malloc() */
  96184. #include <string.h> /* for memcpy() */
  96185. #include <sys/types.h> /* for off_t */
  96186. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  96187. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  96188. #define fseeko fseek
  96189. #define ftello ftell
  96190. #endif
  96191. #endif
  96192. /********* Start of inlined file: stream_encoder.h *********/
  96193. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  96194. #define FLAC__PROTECTED__STREAM_ENCODER_H
  96195. #if FLAC__HAS_OGG
  96196. #include "private/ogg_encoder_aspect.h"
  96197. #endif
  96198. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96199. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  96200. typedef enum {
  96201. FLAC__APODIZATION_BARTLETT,
  96202. FLAC__APODIZATION_BARTLETT_HANN,
  96203. FLAC__APODIZATION_BLACKMAN,
  96204. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  96205. FLAC__APODIZATION_CONNES,
  96206. FLAC__APODIZATION_FLATTOP,
  96207. FLAC__APODIZATION_GAUSS,
  96208. FLAC__APODIZATION_HAMMING,
  96209. FLAC__APODIZATION_HANN,
  96210. FLAC__APODIZATION_KAISER_BESSEL,
  96211. FLAC__APODIZATION_NUTTALL,
  96212. FLAC__APODIZATION_RECTANGLE,
  96213. FLAC__APODIZATION_TRIANGLE,
  96214. FLAC__APODIZATION_TUKEY,
  96215. FLAC__APODIZATION_WELCH
  96216. } FLAC__ApodizationFunction;
  96217. typedef struct {
  96218. FLAC__ApodizationFunction type;
  96219. union {
  96220. struct {
  96221. FLAC__real stddev;
  96222. } gauss;
  96223. struct {
  96224. FLAC__real p;
  96225. } tukey;
  96226. } parameters;
  96227. } FLAC__ApodizationSpecification;
  96228. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96229. typedef struct FLAC__StreamEncoderProtected {
  96230. FLAC__StreamEncoderState state;
  96231. FLAC__bool verify;
  96232. FLAC__bool streamable_subset;
  96233. FLAC__bool do_md5;
  96234. FLAC__bool do_mid_side_stereo;
  96235. FLAC__bool loose_mid_side_stereo;
  96236. unsigned channels;
  96237. unsigned bits_per_sample;
  96238. unsigned sample_rate;
  96239. unsigned blocksize;
  96240. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96241. unsigned num_apodizations;
  96242. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  96243. #endif
  96244. unsigned max_lpc_order;
  96245. unsigned qlp_coeff_precision;
  96246. FLAC__bool do_qlp_coeff_prec_search;
  96247. FLAC__bool do_exhaustive_model_search;
  96248. FLAC__bool do_escape_coding;
  96249. unsigned min_residual_partition_order;
  96250. unsigned max_residual_partition_order;
  96251. unsigned rice_parameter_search_dist;
  96252. FLAC__uint64 total_samples_estimate;
  96253. FLAC__StreamMetadata **metadata;
  96254. unsigned num_metadata_blocks;
  96255. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  96256. #if FLAC__HAS_OGG
  96257. FLAC__OggEncoderAspect ogg_encoder_aspect;
  96258. #endif
  96259. } FLAC__StreamEncoderProtected;
  96260. #endif
  96261. /********* End of inlined file: stream_encoder.h *********/
  96262. #if FLAC__HAS_OGG
  96263. #include "include/private/ogg_helper.h"
  96264. #include "include/private/ogg_mapping.h"
  96265. #endif
  96266. /********* Start of inlined file: stream_encoder_framing.h *********/
  96267. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  96268. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  96269. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  96270. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  96271. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  96272. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  96273. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  96274. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  96275. #endif
  96276. /********* End of inlined file: stream_encoder_framing.h *********/
  96277. /********* Start of inlined file: window.h *********/
  96278. #ifndef FLAC__PRIVATE__WINDOW_H
  96279. #define FLAC__PRIVATE__WINDOW_H
  96280. #ifdef HAVE_CONFIG_H
  96281. #include <config.h>
  96282. #endif
  96283. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96284. /*
  96285. * FLAC__window_*()
  96286. * --------------------------------------------------------------------
  96287. * Calculates window coefficients according to different apodization
  96288. * functions.
  96289. *
  96290. * OUT window[0,L-1]
  96291. * IN L (number of points in window)
  96292. */
  96293. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  96294. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  96295. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  96296. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  96297. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  96298. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  96299. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  96300. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  96301. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  96302. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  96303. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  96304. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  96305. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  96306. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  96307. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  96308. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96309. #endif
  96310. /********* End of inlined file: window.h *********/
  96311. #ifndef FLaC__INLINE
  96312. #define FLaC__INLINE
  96313. #endif
  96314. #ifdef min
  96315. #undef min
  96316. #endif
  96317. #define min(x,y) ((x)<(y)?(x):(y))
  96318. #ifdef max
  96319. #undef max
  96320. #endif
  96321. #define max(x,y) ((x)>(y)?(x):(y))
  96322. /* Exact Rice codeword length calculation is off by default. The simple
  96323. * (and fast) estimation (of how many bits a residual value will be
  96324. * encoded with) in this encoder is very good, almost always yielding
  96325. * compression within 0.1% of exact calculation.
  96326. */
  96327. #undef EXACT_RICE_BITS_CALCULATION
  96328. /* Rice parameter searching is off by default. The simple (and fast)
  96329. * parameter estimation in this encoder is very good, almost always
  96330. * yielding compression within 0.1% of the optimal parameters.
  96331. */
  96332. #undef ENABLE_RICE_PARAMETER_SEARCH
  96333. typedef struct {
  96334. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  96335. unsigned size; /* of each data[] in samples */
  96336. unsigned tail;
  96337. } verify_input_fifo;
  96338. typedef struct {
  96339. const FLAC__byte *data;
  96340. unsigned capacity;
  96341. unsigned bytes;
  96342. } verify_output;
  96343. typedef enum {
  96344. ENCODER_IN_MAGIC = 0,
  96345. ENCODER_IN_METADATA = 1,
  96346. ENCODER_IN_AUDIO = 2
  96347. } EncoderStateHint;
  96348. static struct CompressionLevels {
  96349. FLAC__bool do_mid_side_stereo;
  96350. FLAC__bool loose_mid_side_stereo;
  96351. unsigned max_lpc_order;
  96352. unsigned qlp_coeff_precision;
  96353. FLAC__bool do_qlp_coeff_prec_search;
  96354. FLAC__bool do_escape_coding;
  96355. FLAC__bool do_exhaustive_model_search;
  96356. unsigned min_residual_partition_order;
  96357. unsigned max_residual_partition_order;
  96358. unsigned rice_parameter_search_dist;
  96359. } compression_levels_[] = {
  96360. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  96361. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  96362. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  96363. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  96364. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  96365. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  96366. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  96367. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  96368. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  96369. };
  96370. /***********************************************************************
  96371. *
  96372. * Private class method prototypes
  96373. *
  96374. ***********************************************************************/
  96375. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  96376. static void free_(FLAC__StreamEncoder *encoder);
  96377. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  96378. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  96379. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  96380. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  96381. #if FLAC__HAS_OGG
  96382. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  96383. #endif
  96384. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  96385. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  96386. static FLAC__bool process_subframe_(
  96387. FLAC__StreamEncoder *encoder,
  96388. unsigned min_partition_order,
  96389. unsigned max_partition_order,
  96390. const FLAC__FrameHeader *frame_header,
  96391. unsigned subframe_bps,
  96392. const FLAC__int32 integer_signal[],
  96393. FLAC__Subframe *subframe[2],
  96394. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  96395. FLAC__int32 *residual[2],
  96396. unsigned *best_subframe,
  96397. unsigned *best_bits
  96398. );
  96399. static FLAC__bool add_subframe_(
  96400. FLAC__StreamEncoder *encoder,
  96401. unsigned blocksize,
  96402. unsigned subframe_bps,
  96403. const FLAC__Subframe *subframe,
  96404. FLAC__BitWriter *frame
  96405. );
  96406. static unsigned evaluate_constant_subframe_(
  96407. FLAC__StreamEncoder *encoder,
  96408. const FLAC__int32 signal,
  96409. unsigned blocksize,
  96410. unsigned subframe_bps,
  96411. FLAC__Subframe *subframe
  96412. );
  96413. static unsigned evaluate_fixed_subframe_(
  96414. FLAC__StreamEncoder *encoder,
  96415. const FLAC__int32 signal[],
  96416. FLAC__int32 residual[],
  96417. FLAC__uint64 abs_residual_partition_sums[],
  96418. unsigned raw_bits_per_partition[],
  96419. unsigned blocksize,
  96420. unsigned subframe_bps,
  96421. unsigned order,
  96422. unsigned rice_parameter,
  96423. unsigned rice_parameter_limit,
  96424. unsigned min_partition_order,
  96425. unsigned max_partition_order,
  96426. FLAC__bool do_escape_coding,
  96427. unsigned rice_parameter_search_dist,
  96428. FLAC__Subframe *subframe,
  96429. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  96430. );
  96431. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96432. static unsigned evaluate_lpc_subframe_(
  96433. FLAC__StreamEncoder *encoder,
  96434. const FLAC__int32 signal[],
  96435. FLAC__int32 residual[],
  96436. FLAC__uint64 abs_residual_partition_sums[],
  96437. unsigned raw_bits_per_partition[],
  96438. const FLAC__real lp_coeff[],
  96439. unsigned blocksize,
  96440. unsigned subframe_bps,
  96441. unsigned order,
  96442. unsigned qlp_coeff_precision,
  96443. unsigned rice_parameter,
  96444. unsigned rice_parameter_limit,
  96445. unsigned min_partition_order,
  96446. unsigned max_partition_order,
  96447. FLAC__bool do_escape_coding,
  96448. unsigned rice_parameter_search_dist,
  96449. FLAC__Subframe *subframe,
  96450. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  96451. );
  96452. #endif
  96453. static unsigned evaluate_verbatim_subframe_(
  96454. FLAC__StreamEncoder *encoder,
  96455. const FLAC__int32 signal[],
  96456. unsigned blocksize,
  96457. unsigned subframe_bps,
  96458. FLAC__Subframe *subframe
  96459. );
  96460. static unsigned find_best_partition_order_(
  96461. struct FLAC__StreamEncoderPrivate *private_,
  96462. const FLAC__int32 residual[],
  96463. FLAC__uint64 abs_residual_partition_sums[],
  96464. unsigned raw_bits_per_partition[],
  96465. unsigned residual_samples,
  96466. unsigned predictor_order,
  96467. unsigned rice_parameter,
  96468. unsigned rice_parameter_limit,
  96469. unsigned min_partition_order,
  96470. unsigned max_partition_order,
  96471. unsigned bps,
  96472. FLAC__bool do_escape_coding,
  96473. unsigned rice_parameter_search_dist,
  96474. FLAC__EntropyCodingMethod *best_ecm
  96475. );
  96476. static void precompute_partition_info_sums_(
  96477. const FLAC__int32 residual[],
  96478. FLAC__uint64 abs_residual_partition_sums[],
  96479. unsigned residual_samples,
  96480. unsigned predictor_order,
  96481. unsigned min_partition_order,
  96482. unsigned max_partition_order,
  96483. unsigned bps
  96484. );
  96485. static void precompute_partition_info_escapes_(
  96486. const FLAC__int32 residual[],
  96487. unsigned raw_bits_per_partition[],
  96488. unsigned residual_samples,
  96489. unsigned predictor_order,
  96490. unsigned min_partition_order,
  96491. unsigned max_partition_order
  96492. );
  96493. static FLAC__bool set_partitioned_rice_(
  96494. #ifdef EXACT_RICE_BITS_CALCULATION
  96495. const FLAC__int32 residual[],
  96496. #endif
  96497. const FLAC__uint64 abs_residual_partition_sums[],
  96498. const unsigned raw_bits_per_partition[],
  96499. const unsigned residual_samples,
  96500. const unsigned predictor_order,
  96501. const unsigned suggested_rice_parameter,
  96502. const unsigned rice_parameter_limit,
  96503. const unsigned rice_parameter_search_dist,
  96504. const unsigned partition_order,
  96505. const FLAC__bool search_for_escapes,
  96506. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  96507. unsigned *bits
  96508. );
  96509. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  96510. /* verify-related routines: */
  96511. static void append_to_verify_fifo_(
  96512. verify_input_fifo *fifo,
  96513. const FLAC__int32 * const input[],
  96514. unsigned input_offset,
  96515. unsigned channels,
  96516. unsigned wide_samples
  96517. );
  96518. static void append_to_verify_fifo_interleaved_(
  96519. verify_input_fifo *fifo,
  96520. const FLAC__int32 input[],
  96521. unsigned input_offset,
  96522. unsigned channels,
  96523. unsigned wide_samples
  96524. );
  96525. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  96526. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  96527. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  96528. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  96529. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  96530. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  96531. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  96532. 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);
  96533. static FILE *get_binary_stdout_(void);
  96534. /***********************************************************************
  96535. *
  96536. * Private class data
  96537. *
  96538. ***********************************************************************/
  96539. typedef struct FLAC__StreamEncoderPrivate {
  96540. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  96541. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  96542. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  96543. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96544. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  96545. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  96546. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  96547. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  96548. #endif
  96549. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  96550. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  96551. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  96552. FLAC__int32 *residual_workspace_mid_side[2][2];
  96553. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  96554. FLAC__Subframe subframe_workspace_mid_side[2][2];
  96555. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  96556. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  96557. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  96558. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  96559. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  96560. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  96561. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  96562. unsigned best_subframe_mid_side[2];
  96563. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  96564. unsigned best_subframe_bits_mid_side[2];
  96565. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  96566. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  96567. FLAC__BitWriter *frame; /* the current frame being worked on */
  96568. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  96569. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  96570. FLAC__ChannelAssignment last_channel_assignment;
  96571. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  96572. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  96573. unsigned current_sample_number;
  96574. unsigned current_frame_number;
  96575. FLAC__MD5Context md5context;
  96576. FLAC__CPUInfo cpuinfo;
  96577. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96578. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96579. #else
  96580. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96581. #endif
  96582. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96583. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96584. 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[]);
  96585. 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[]);
  96586. 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[]);
  96587. #endif
  96588. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  96589. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  96590. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  96591. FLAC__bool disable_constant_subframes;
  96592. FLAC__bool disable_fixed_subframes;
  96593. FLAC__bool disable_verbatim_subframes;
  96594. #if FLAC__HAS_OGG
  96595. FLAC__bool is_ogg;
  96596. #endif
  96597. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  96598. FLAC__StreamEncoderSeekCallback seek_callback;
  96599. FLAC__StreamEncoderTellCallback tell_callback;
  96600. FLAC__StreamEncoderWriteCallback write_callback;
  96601. FLAC__StreamEncoderMetadataCallback metadata_callback;
  96602. FLAC__StreamEncoderProgressCallback progress_callback;
  96603. void *client_data;
  96604. unsigned first_seekpoint_to_check;
  96605. FILE *file; /* only used when encoding to a file */
  96606. FLAC__uint64 bytes_written;
  96607. FLAC__uint64 samples_written;
  96608. unsigned frames_written;
  96609. unsigned total_frames_estimate;
  96610. /* unaligned (original) pointers to allocated data */
  96611. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  96612. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  96613. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96614. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  96615. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  96616. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  96617. FLAC__real *windowed_signal_unaligned;
  96618. #endif
  96619. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  96620. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  96621. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  96622. unsigned *raw_bits_per_partition_unaligned;
  96623. /*
  96624. * These fields have been moved here from private function local
  96625. * declarations merely to save stack space during encoding.
  96626. */
  96627. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96628. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  96629. #endif
  96630. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  96631. /*
  96632. * The data for the verify section
  96633. */
  96634. struct {
  96635. FLAC__StreamDecoder *decoder;
  96636. EncoderStateHint state_hint;
  96637. FLAC__bool needs_magic_hack;
  96638. verify_input_fifo input_fifo;
  96639. verify_output output;
  96640. struct {
  96641. FLAC__uint64 absolute_sample;
  96642. unsigned frame_number;
  96643. unsigned channel;
  96644. unsigned sample;
  96645. FLAC__int32 expected;
  96646. FLAC__int32 got;
  96647. } error_stats;
  96648. } verify;
  96649. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  96650. } FLAC__StreamEncoderPrivate;
  96651. /***********************************************************************
  96652. *
  96653. * Public static class data
  96654. *
  96655. ***********************************************************************/
  96656. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  96657. "FLAC__STREAM_ENCODER_OK",
  96658. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  96659. "FLAC__STREAM_ENCODER_OGG_ERROR",
  96660. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  96661. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  96662. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  96663. "FLAC__STREAM_ENCODER_IO_ERROR",
  96664. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  96665. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  96666. };
  96667. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  96668. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  96669. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  96670. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  96671. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  96672. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  96673. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  96674. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  96675. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  96676. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  96677. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  96678. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  96679. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  96680. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  96681. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  96682. };
  96683. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  96684. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  96685. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  96686. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  96687. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  96688. };
  96689. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  96690. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  96691. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  96692. };
  96693. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  96694. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  96695. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  96696. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  96697. };
  96698. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  96699. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  96700. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  96701. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  96702. };
  96703. /* Number of samples that will be overread to watch for end of stream. By
  96704. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  96705. * always try to read blocksize+1 samples before encoding a block, so that
  96706. * even if the stream has a total sample count that is an integral multiple
  96707. * of the blocksize, we will still notice when we are encoding the last
  96708. * block. This is needed, for example, to correctly set the end-of-stream
  96709. * marker in Ogg FLAC.
  96710. *
  96711. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  96712. * not really any reason to change it.
  96713. */
  96714. static const unsigned OVERREAD_ = 1;
  96715. /***********************************************************************
  96716. *
  96717. * Class constructor/destructor
  96718. *
  96719. */
  96720. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  96721. {
  96722. FLAC__StreamEncoder *encoder;
  96723. unsigned i;
  96724. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  96725. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  96726. if(encoder == 0) {
  96727. return 0;
  96728. }
  96729. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  96730. if(encoder->protected_ == 0) {
  96731. free(encoder);
  96732. return 0;
  96733. }
  96734. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  96735. if(encoder->private_ == 0) {
  96736. free(encoder->protected_);
  96737. free(encoder);
  96738. return 0;
  96739. }
  96740. encoder->private_->frame = FLAC__bitwriter_new();
  96741. if(encoder->private_->frame == 0) {
  96742. free(encoder->private_);
  96743. free(encoder->protected_);
  96744. free(encoder);
  96745. return 0;
  96746. }
  96747. encoder->private_->file = 0;
  96748. set_defaults_enc(encoder);
  96749. encoder->private_->is_being_deleted = false;
  96750. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96751. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  96752. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  96753. }
  96754. for(i = 0; i < 2; i++) {
  96755. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  96756. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  96757. }
  96758. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96759. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  96760. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  96761. }
  96762. for(i = 0; i < 2; i++) {
  96763. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  96764. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  96765. }
  96766. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96767. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  96768. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  96769. }
  96770. for(i = 0; i < 2; i++) {
  96771. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  96772. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  96773. }
  96774. for(i = 0; i < 2; i++)
  96775. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  96776. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  96777. return encoder;
  96778. }
  96779. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  96780. {
  96781. unsigned i;
  96782. FLAC__ASSERT(0 != encoder);
  96783. FLAC__ASSERT(0 != encoder->protected_);
  96784. FLAC__ASSERT(0 != encoder->private_);
  96785. FLAC__ASSERT(0 != encoder->private_->frame);
  96786. encoder->private_->is_being_deleted = true;
  96787. (void)FLAC__stream_encoder_finish(encoder);
  96788. if(0 != encoder->private_->verify.decoder)
  96789. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  96790. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96791. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  96792. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  96793. }
  96794. for(i = 0; i < 2; i++) {
  96795. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  96796. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  96797. }
  96798. for(i = 0; i < 2; i++)
  96799. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  96800. FLAC__bitwriter_delete(encoder->private_->frame);
  96801. free(encoder->private_);
  96802. free(encoder->protected_);
  96803. free(encoder);
  96804. }
  96805. /***********************************************************************
  96806. *
  96807. * Public class methods
  96808. *
  96809. ***********************************************************************/
  96810. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  96811. FLAC__StreamEncoder *encoder,
  96812. FLAC__StreamEncoderReadCallback read_callback,
  96813. FLAC__StreamEncoderWriteCallback write_callback,
  96814. FLAC__StreamEncoderSeekCallback seek_callback,
  96815. FLAC__StreamEncoderTellCallback tell_callback,
  96816. FLAC__StreamEncoderMetadataCallback metadata_callback,
  96817. void *client_data,
  96818. FLAC__bool is_ogg
  96819. )
  96820. {
  96821. unsigned i;
  96822. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  96823. FLAC__ASSERT(0 != encoder);
  96824. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96825. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  96826. #if !FLAC__HAS_OGG
  96827. if(is_ogg)
  96828. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  96829. #endif
  96830. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  96831. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  96832. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  96833. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  96834. if(encoder->protected_->channels != 2) {
  96835. encoder->protected_->do_mid_side_stereo = false;
  96836. encoder->protected_->loose_mid_side_stereo = false;
  96837. }
  96838. else if(!encoder->protected_->do_mid_side_stereo)
  96839. encoder->protected_->loose_mid_side_stereo = false;
  96840. if(encoder->protected_->bits_per_sample >= 32)
  96841. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  96842. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  96843. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  96844. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  96845. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  96846. if(encoder->protected_->blocksize == 0) {
  96847. if(encoder->protected_->max_lpc_order == 0)
  96848. encoder->protected_->blocksize = 1152;
  96849. else
  96850. encoder->protected_->blocksize = 4096;
  96851. }
  96852. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  96853. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  96854. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  96855. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  96856. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  96857. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  96858. if(encoder->protected_->qlp_coeff_precision == 0) {
  96859. if(encoder->protected_->bits_per_sample < 16) {
  96860. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  96861. /* @@@ until then we'll make a guess */
  96862. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  96863. }
  96864. else if(encoder->protected_->bits_per_sample == 16) {
  96865. if(encoder->protected_->blocksize <= 192)
  96866. encoder->protected_->qlp_coeff_precision = 7;
  96867. else if(encoder->protected_->blocksize <= 384)
  96868. encoder->protected_->qlp_coeff_precision = 8;
  96869. else if(encoder->protected_->blocksize <= 576)
  96870. encoder->protected_->qlp_coeff_precision = 9;
  96871. else if(encoder->protected_->blocksize <= 1152)
  96872. encoder->protected_->qlp_coeff_precision = 10;
  96873. else if(encoder->protected_->blocksize <= 2304)
  96874. encoder->protected_->qlp_coeff_precision = 11;
  96875. else if(encoder->protected_->blocksize <= 4608)
  96876. encoder->protected_->qlp_coeff_precision = 12;
  96877. else
  96878. encoder->protected_->qlp_coeff_precision = 13;
  96879. }
  96880. else {
  96881. if(encoder->protected_->blocksize <= 384)
  96882. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  96883. else if(encoder->protected_->blocksize <= 1152)
  96884. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  96885. else
  96886. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  96887. }
  96888. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  96889. }
  96890. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  96891. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  96892. if(encoder->protected_->streamable_subset) {
  96893. if(
  96894. encoder->protected_->blocksize != 192 &&
  96895. encoder->protected_->blocksize != 576 &&
  96896. encoder->protected_->blocksize != 1152 &&
  96897. encoder->protected_->blocksize != 2304 &&
  96898. encoder->protected_->blocksize != 4608 &&
  96899. encoder->protected_->blocksize != 256 &&
  96900. encoder->protected_->blocksize != 512 &&
  96901. encoder->protected_->blocksize != 1024 &&
  96902. encoder->protected_->blocksize != 2048 &&
  96903. encoder->protected_->blocksize != 4096 &&
  96904. encoder->protected_->blocksize != 8192 &&
  96905. encoder->protected_->blocksize != 16384
  96906. )
  96907. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96908. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  96909. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96910. if(
  96911. encoder->protected_->bits_per_sample != 8 &&
  96912. encoder->protected_->bits_per_sample != 12 &&
  96913. encoder->protected_->bits_per_sample != 16 &&
  96914. encoder->protected_->bits_per_sample != 20 &&
  96915. encoder->protected_->bits_per_sample != 24
  96916. )
  96917. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96918. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  96919. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96920. if(
  96921. encoder->protected_->sample_rate <= 48000 &&
  96922. (
  96923. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  96924. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  96925. )
  96926. ) {
  96927. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96928. }
  96929. }
  96930. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  96931. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  96932. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  96933. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  96934. #if FLAC__HAS_OGG
  96935. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  96936. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  96937. unsigned i;
  96938. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  96939. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  96940. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  96941. for( ; i > 0; i--)
  96942. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  96943. encoder->protected_->metadata[0] = vc;
  96944. break;
  96945. }
  96946. }
  96947. }
  96948. #endif
  96949. /* keep track of any SEEKTABLE block */
  96950. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  96951. unsigned i;
  96952. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  96953. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  96954. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  96955. break; /* take only the first one */
  96956. }
  96957. }
  96958. }
  96959. /* validate metadata */
  96960. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  96961. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96962. metadata_has_seektable = false;
  96963. metadata_has_vorbis_comment = false;
  96964. metadata_picture_has_type1 = false;
  96965. metadata_picture_has_type2 = false;
  96966. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  96967. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  96968. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  96969. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96970. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  96971. if(metadata_has_seektable) /* only one is allowed */
  96972. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96973. metadata_has_seektable = true;
  96974. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  96975. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96976. }
  96977. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  96978. if(metadata_has_vorbis_comment) /* only one is allowed */
  96979. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96980. metadata_has_vorbis_comment = true;
  96981. }
  96982. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  96983. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  96984. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96985. }
  96986. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  96987. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  96988. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96989. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  96990. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  96991. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96992. metadata_picture_has_type1 = true;
  96993. /* standard icon must be 32x32 pixel PNG */
  96994. if(
  96995. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  96996. (
  96997. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  96998. m->data.picture.width != 32 ||
  96999. m->data.picture.height != 32
  97000. )
  97001. )
  97002. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97003. }
  97004. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  97005. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  97006. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  97007. metadata_picture_has_type2 = true;
  97008. }
  97009. }
  97010. }
  97011. encoder->private_->input_capacity = 0;
  97012. for(i = 0; i < encoder->protected_->channels; i++) {
  97013. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  97014. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97015. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  97016. #endif
  97017. }
  97018. for(i = 0; i < 2; i++) {
  97019. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  97020. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97021. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  97022. #endif
  97023. }
  97024. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97025. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  97026. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  97027. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  97028. #endif
  97029. for(i = 0; i < encoder->protected_->channels; i++) {
  97030. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  97031. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  97032. encoder->private_->best_subframe[i] = 0;
  97033. }
  97034. for(i = 0; i < 2; i++) {
  97035. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  97036. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  97037. encoder->private_->best_subframe_mid_side[i] = 0;
  97038. }
  97039. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  97040. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  97041. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97042. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  97043. #else
  97044. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  97045. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  97046. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  97047. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  97048. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  97049. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  97050. 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);
  97051. #endif
  97052. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  97053. encoder->private_->loose_mid_side_stereo_frames = 1;
  97054. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  97055. encoder->private_->current_sample_number = 0;
  97056. encoder->private_->current_frame_number = 0;
  97057. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  97058. 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? */
  97059. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  97060. /*
  97061. * get the CPU info and set the function pointers
  97062. */
  97063. FLAC__cpu_info(&encoder->private_->cpuinfo);
  97064. /* first default to the non-asm routines */
  97065. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97066. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  97067. #endif
  97068. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  97069. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97070. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  97071. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  97072. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  97073. #endif
  97074. /* now override with asm where appropriate */
  97075. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97076. # ifndef FLAC__NO_ASM
  97077. if(encoder->private_->cpuinfo.use_asm) {
  97078. # ifdef FLAC__CPU_IA32
  97079. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  97080. # ifdef FLAC__HAS_NASM
  97081. if(encoder->private_->cpuinfo.data.ia32.sse) {
  97082. if(encoder->protected_->max_lpc_order < 4)
  97083. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  97084. else if(encoder->protected_->max_lpc_order < 8)
  97085. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  97086. else if(encoder->protected_->max_lpc_order < 12)
  97087. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  97088. else
  97089. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  97090. }
  97091. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  97092. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  97093. else
  97094. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  97095. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  97096. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  97097. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  97098. }
  97099. else {
  97100. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  97101. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  97102. }
  97103. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  97104. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  97105. # endif /* FLAC__HAS_NASM */
  97106. # endif /* FLAC__CPU_IA32 */
  97107. }
  97108. # endif /* !FLAC__NO_ASM */
  97109. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  97110. /* finally override based on wide-ness if necessary */
  97111. if(encoder->private_->use_wide_by_block) {
  97112. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  97113. }
  97114. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  97115. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  97116. #if FLAC__HAS_OGG
  97117. encoder->private_->is_ogg = is_ogg;
  97118. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  97119. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  97120. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97121. }
  97122. #endif
  97123. encoder->private_->read_callback = read_callback;
  97124. encoder->private_->write_callback = write_callback;
  97125. encoder->private_->seek_callback = seek_callback;
  97126. encoder->private_->tell_callback = tell_callback;
  97127. encoder->private_->metadata_callback = metadata_callback;
  97128. encoder->private_->client_data = client_data;
  97129. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  97130. /* the above function sets the state for us in case of an error */
  97131. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97132. }
  97133. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  97134. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  97135. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97136. }
  97137. /*
  97138. * Set up the verify stuff if necessary
  97139. */
  97140. if(encoder->protected_->verify) {
  97141. /*
  97142. * First, set up the fifo which will hold the
  97143. * original signal to compare against
  97144. */
  97145. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  97146. for(i = 0; i < encoder->protected_->channels; i++) {
  97147. 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))) {
  97148. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  97149. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97150. }
  97151. }
  97152. encoder->private_->verify.input_fifo.tail = 0;
  97153. /*
  97154. * Now set up a stream decoder for verification
  97155. */
  97156. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  97157. if(0 == encoder->private_->verify.decoder) {
  97158. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  97159. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97160. }
  97161. 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) {
  97162. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  97163. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97164. }
  97165. }
  97166. encoder->private_->verify.error_stats.absolute_sample = 0;
  97167. encoder->private_->verify.error_stats.frame_number = 0;
  97168. encoder->private_->verify.error_stats.channel = 0;
  97169. encoder->private_->verify.error_stats.sample = 0;
  97170. encoder->private_->verify.error_stats.expected = 0;
  97171. encoder->private_->verify.error_stats.got = 0;
  97172. /*
  97173. * These must be done before we write any metadata, because that
  97174. * calls the write_callback, which uses these values.
  97175. */
  97176. encoder->private_->first_seekpoint_to_check = 0;
  97177. encoder->private_->samples_written = 0;
  97178. encoder->protected_->streaminfo_offset = 0;
  97179. encoder->protected_->seektable_offset = 0;
  97180. encoder->protected_->audio_offset = 0;
  97181. /*
  97182. * write the stream header
  97183. */
  97184. if(encoder->protected_->verify)
  97185. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  97186. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  97187. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  97188. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97189. }
  97190. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  97191. /* the above function sets the state for us in case of an error */
  97192. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97193. }
  97194. /*
  97195. * write the STREAMINFO metadata block
  97196. */
  97197. if(encoder->protected_->verify)
  97198. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  97199. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  97200. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  97201. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  97202. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  97203. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  97204. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  97205. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  97206. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  97207. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  97208. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  97209. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  97210. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  97211. if(encoder->protected_->do_md5)
  97212. FLAC__MD5Init(&encoder->private_->md5context);
  97213. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  97214. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  97215. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97216. }
  97217. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  97218. /* the above function sets the state for us in case of an error */
  97219. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97220. }
  97221. /*
  97222. * Now that the STREAMINFO block is written, we can init this to an
  97223. * absurdly-high value...
  97224. */
  97225. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  97226. /* ... and clear this to 0 */
  97227. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  97228. /*
  97229. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  97230. * if not, we will write an empty one (FLAC__add_metadata_block()
  97231. * automatically supplies the vendor string).
  97232. *
  97233. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  97234. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  97235. * true it will have already insured that the metadata list is properly
  97236. * ordered.)
  97237. */
  97238. if(!metadata_has_vorbis_comment) {
  97239. FLAC__StreamMetadata vorbis_comment;
  97240. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  97241. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  97242. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  97243. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  97244. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  97245. vorbis_comment.data.vorbis_comment.num_comments = 0;
  97246. vorbis_comment.data.vorbis_comment.comments = 0;
  97247. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  97248. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  97249. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97250. }
  97251. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  97252. /* the above function sets the state for us in case of an error */
  97253. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97254. }
  97255. }
  97256. /*
  97257. * write the user's metadata blocks
  97258. */
  97259. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  97260. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  97261. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  97262. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  97263. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97264. }
  97265. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  97266. /* the above function sets the state for us in case of an error */
  97267. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97268. }
  97269. }
  97270. /* now that all the metadata is written, we save the stream offset */
  97271. 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 */
  97272. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97273. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97274. }
  97275. if(encoder->protected_->verify)
  97276. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  97277. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  97278. }
  97279. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  97280. FLAC__StreamEncoder *encoder,
  97281. FLAC__StreamEncoderWriteCallback write_callback,
  97282. FLAC__StreamEncoderSeekCallback seek_callback,
  97283. FLAC__StreamEncoderTellCallback tell_callback,
  97284. FLAC__StreamEncoderMetadataCallback metadata_callback,
  97285. void *client_data
  97286. )
  97287. {
  97288. return init_stream_internal_enc(
  97289. encoder,
  97290. /*read_callback=*/0,
  97291. write_callback,
  97292. seek_callback,
  97293. tell_callback,
  97294. metadata_callback,
  97295. client_data,
  97296. /*is_ogg=*/false
  97297. );
  97298. }
  97299. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  97300. FLAC__StreamEncoder *encoder,
  97301. FLAC__StreamEncoderReadCallback read_callback,
  97302. FLAC__StreamEncoderWriteCallback write_callback,
  97303. FLAC__StreamEncoderSeekCallback seek_callback,
  97304. FLAC__StreamEncoderTellCallback tell_callback,
  97305. FLAC__StreamEncoderMetadataCallback metadata_callback,
  97306. void *client_data
  97307. )
  97308. {
  97309. return init_stream_internal_enc(
  97310. encoder,
  97311. read_callback,
  97312. write_callback,
  97313. seek_callback,
  97314. tell_callback,
  97315. metadata_callback,
  97316. client_data,
  97317. /*is_ogg=*/true
  97318. );
  97319. }
  97320. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  97321. FLAC__StreamEncoder *encoder,
  97322. FILE *file,
  97323. FLAC__StreamEncoderProgressCallback progress_callback,
  97324. void *client_data,
  97325. FLAC__bool is_ogg
  97326. )
  97327. {
  97328. FLAC__StreamEncoderInitStatus init_status;
  97329. FLAC__ASSERT(0 != encoder);
  97330. FLAC__ASSERT(0 != file);
  97331. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97332. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  97333. /* double protection */
  97334. if(file == 0) {
  97335. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  97336. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97337. }
  97338. /*
  97339. * To make sure that our file does not go unclosed after an error, we
  97340. * must assign the FILE pointer before any further error can occur in
  97341. * this routine.
  97342. */
  97343. if(file == stdout)
  97344. file = get_binary_stdout_(); /* just to be safe */
  97345. encoder->private_->file = file;
  97346. encoder->private_->progress_callback = progress_callback;
  97347. encoder->private_->bytes_written = 0;
  97348. encoder->private_->samples_written = 0;
  97349. encoder->private_->frames_written = 0;
  97350. init_status = init_stream_internal_enc(
  97351. encoder,
  97352. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  97353. file_write_callback_,
  97354. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  97355. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  97356. /*metadata_callback=*/0,
  97357. client_data,
  97358. is_ogg
  97359. );
  97360. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  97361. /* the above function sets the state for us in case of an error */
  97362. return init_status;
  97363. }
  97364. {
  97365. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  97366. FLAC__ASSERT(blocksize != 0);
  97367. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  97368. }
  97369. return init_status;
  97370. }
  97371. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  97372. FLAC__StreamEncoder *encoder,
  97373. FILE *file,
  97374. FLAC__StreamEncoderProgressCallback progress_callback,
  97375. void *client_data
  97376. )
  97377. {
  97378. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  97379. }
  97380. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  97381. FLAC__StreamEncoder *encoder,
  97382. FILE *file,
  97383. FLAC__StreamEncoderProgressCallback progress_callback,
  97384. void *client_data
  97385. )
  97386. {
  97387. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  97388. }
  97389. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  97390. FLAC__StreamEncoder *encoder,
  97391. const char *filename,
  97392. FLAC__StreamEncoderProgressCallback progress_callback,
  97393. void *client_data,
  97394. FLAC__bool is_ogg
  97395. )
  97396. {
  97397. FILE *file;
  97398. FLAC__ASSERT(0 != encoder);
  97399. /*
  97400. * To make sure that our file does not go unclosed after an error, we
  97401. * have to do the same entrance checks here that are later performed
  97402. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  97403. */
  97404. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97405. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  97406. file = filename? fopen(filename, "w+b") : stdout;
  97407. if(file == 0) {
  97408. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  97409. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  97410. }
  97411. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  97412. }
  97413. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  97414. FLAC__StreamEncoder *encoder,
  97415. const char *filename,
  97416. FLAC__StreamEncoderProgressCallback progress_callback,
  97417. void *client_data
  97418. )
  97419. {
  97420. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  97421. }
  97422. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  97423. FLAC__StreamEncoder *encoder,
  97424. const char *filename,
  97425. FLAC__StreamEncoderProgressCallback progress_callback,
  97426. void *client_data
  97427. )
  97428. {
  97429. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  97430. }
  97431. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  97432. {
  97433. FLAC__bool error = false;
  97434. FLAC__ASSERT(0 != encoder);
  97435. FLAC__ASSERT(0 != encoder->private_);
  97436. FLAC__ASSERT(0 != encoder->protected_);
  97437. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  97438. return true;
  97439. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  97440. if(encoder->private_->current_sample_number != 0) {
  97441. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  97442. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  97443. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  97444. error = true;
  97445. }
  97446. }
  97447. if(encoder->protected_->do_md5)
  97448. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  97449. if(!encoder->private_->is_being_deleted) {
  97450. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  97451. if(encoder->private_->seek_callback) {
  97452. #if FLAC__HAS_OGG
  97453. if(encoder->private_->is_ogg)
  97454. update_ogg_metadata_(encoder);
  97455. else
  97456. #endif
  97457. update_metadata_(encoder);
  97458. /* check if an error occurred while updating metadata */
  97459. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  97460. error = true;
  97461. }
  97462. if(encoder->private_->metadata_callback)
  97463. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  97464. }
  97465. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  97466. if(!error)
  97467. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  97468. error = true;
  97469. }
  97470. }
  97471. if(0 != encoder->private_->file) {
  97472. if(encoder->private_->file != stdout)
  97473. fclose(encoder->private_->file);
  97474. encoder->private_->file = 0;
  97475. }
  97476. #if FLAC__HAS_OGG
  97477. if(encoder->private_->is_ogg)
  97478. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  97479. #endif
  97480. free_(encoder);
  97481. set_defaults_enc(encoder);
  97482. if(!error)
  97483. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  97484. return !error;
  97485. }
  97486. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  97487. {
  97488. FLAC__ASSERT(0 != encoder);
  97489. FLAC__ASSERT(0 != encoder->private_);
  97490. FLAC__ASSERT(0 != encoder->protected_);
  97491. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97492. return false;
  97493. #if FLAC__HAS_OGG
  97494. /* can't check encoder->private_->is_ogg since that's not set until init time */
  97495. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  97496. return true;
  97497. #else
  97498. (void)value;
  97499. return false;
  97500. #endif
  97501. }
  97502. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97503. {
  97504. FLAC__ASSERT(0 != encoder);
  97505. FLAC__ASSERT(0 != encoder->private_);
  97506. FLAC__ASSERT(0 != encoder->protected_);
  97507. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97508. return false;
  97509. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  97510. encoder->protected_->verify = value;
  97511. #endif
  97512. return true;
  97513. }
  97514. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97515. {
  97516. FLAC__ASSERT(0 != encoder);
  97517. FLAC__ASSERT(0 != encoder->private_);
  97518. FLAC__ASSERT(0 != encoder->protected_);
  97519. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97520. return false;
  97521. encoder->protected_->streamable_subset = value;
  97522. return true;
  97523. }
  97524. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97525. {
  97526. FLAC__ASSERT(0 != encoder);
  97527. FLAC__ASSERT(0 != encoder->private_);
  97528. FLAC__ASSERT(0 != encoder->protected_);
  97529. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97530. return false;
  97531. encoder->protected_->do_md5 = value;
  97532. return true;
  97533. }
  97534. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  97535. {
  97536. FLAC__ASSERT(0 != encoder);
  97537. FLAC__ASSERT(0 != encoder->private_);
  97538. FLAC__ASSERT(0 != encoder->protected_);
  97539. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97540. return false;
  97541. encoder->protected_->channels = value;
  97542. return true;
  97543. }
  97544. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  97545. {
  97546. FLAC__ASSERT(0 != encoder);
  97547. FLAC__ASSERT(0 != encoder->private_);
  97548. FLAC__ASSERT(0 != encoder->protected_);
  97549. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97550. return false;
  97551. encoder->protected_->bits_per_sample = value;
  97552. return true;
  97553. }
  97554. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  97555. {
  97556. FLAC__ASSERT(0 != encoder);
  97557. FLAC__ASSERT(0 != encoder->private_);
  97558. FLAC__ASSERT(0 != encoder->protected_);
  97559. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97560. return false;
  97561. encoder->protected_->sample_rate = value;
  97562. return true;
  97563. }
  97564. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  97565. {
  97566. FLAC__bool ok = true;
  97567. FLAC__ASSERT(0 != encoder);
  97568. FLAC__ASSERT(0 != encoder->private_);
  97569. FLAC__ASSERT(0 != encoder->protected_);
  97570. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97571. return false;
  97572. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  97573. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  97574. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  97575. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  97576. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97577. #if 0
  97578. /* was: */
  97579. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  97580. /* but it's too hard to specify the string in a locale-specific way */
  97581. #else
  97582. encoder->protected_->num_apodizations = 1;
  97583. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  97584. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  97585. #endif
  97586. #endif
  97587. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  97588. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  97589. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  97590. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  97591. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  97592. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  97593. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  97594. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  97595. return ok;
  97596. }
  97597. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  97598. {
  97599. FLAC__ASSERT(0 != encoder);
  97600. FLAC__ASSERT(0 != encoder->private_);
  97601. FLAC__ASSERT(0 != encoder->protected_);
  97602. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97603. return false;
  97604. encoder->protected_->blocksize = value;
  97605. return true;
  97606. }
  97607. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97608. {
  97609. FLAC__ASSERT(0 != encoder);
  97610. FLAC__ASSERT(0 != encoder->private_);
  97611. FLAC__ASSERT(0 != encoder->protected_);
  97612. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97613. return false;
  97614. encoder->protected_->do_mid_side_stereo = value;
  97615. return true;
  97616. }
  97617. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97618. {
  97619. FLAC__ASSERT(0 != encoder);
  97620. FLAC__ASSERT(0 != encoder->private_);
  97621. FLAC__ASSERT(0 != encoder->protected_);
  97622. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97623. return false;
  97624. encoder->protected_->loose_mid_side_stereo = value;
  97625. return true;
  97626. }
  97627. /*@@@@add to tests*/
  97628. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  97629. {
  97630. FLAC__ASSERT(0 != encoder);
  97631. FLAC__ASSERT(0 != encoder->private_);
  97632. FLAC__ASSERT(0 != encoder->protected_);
  97633. FLAC__ASSERT(0 != specification);
  97634. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97635. return false;
  97636. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  97637. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  97638. #else
  97639. encoder->protected_->num_apodizations = 0;
  97640. while(1) {
  97641. const char *s = strchr(specification, ';');
  97642. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  97643. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  97644. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  97645. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  97646. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  97647. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  97648. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  97649. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  97650. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  97651. else if(n==6 && 0 == strncmp("connes" , specification, n))
  97652. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  97653. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  97654. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  97655. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  97656. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  97657. if (stddev > 0.0 && stddev <= 0.5) {
  97658. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  97659. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  97660. }
  97661. }
  97662. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  97663. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  97664. else if(n==4 && 0 == strncmp("hann" , specification, n))
  97665. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  97666. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  97667. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  97668. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  97669. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  97670. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  97671. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  97672. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  97673. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  97674. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  97675. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  97676. if (p >= 0.0 && p <= 1.0) {
  97677. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  97678. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  97679. }
  97680. }
  97681. else if(n==5 && 0 == strncmp("welch" , specification, n))
  97682. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  97683. if (encoder->protected_->num_apodizations == 32)
  97684. break;
  97685. if (s)
  97686. specification = s+1;
  97687. else
  97688. break;
  97689. }
  97690. if(encoder->protected_->num_apodizations == 0) {
  97691. encoder->protected_->num_apodizations = 1;
  97692. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  97693. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  97694. }
  97695. #endif
  97696. return true;
  97697. }
  97698. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  97699. {
  97700. FLAC__ASSERT(0 != encoder);
  97701. FLAC__ASSERT(0 != encoder->private_);
  97702. FLAC__ASSERT(0 != encoder->protected_);
  97703. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97704. return false;
  97705. encoder->protected_->max_lpc_order = value;
  97706. return true;
  97707. }
  97708. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  97709. {
  97710. FLAC__ASSERT(0 != encoder);
  97711. FLAC__ASSERT(0 != encoder->private_);
  97712. FLAC__ASSERT(0 != encoder->protected_);
  97713. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97714. return false;
  97715. encoder->protected_->qlp_coeff_precision = value;
  97716. return true;
  97717. }
  97718. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97719. {
  97720. FLAC__ASSERT(0 != encoder);
  97721. FLAC__ASSERT(0 != encoder->private_);
  97722. FLAC__ASSERT(0 != encoder->protected_);
  97723. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97724. return false;
  97725. encoder->protected_->do_qlp_coeff_prec_search = value;
  97726. return true;
  97727. }
  97728. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97729. {
  97730. FLAC__ASSERT(0 != encoder);
  97731. FLAC__ASSERT(0 != encoder->private_);
  97732. FLAC__ASSERT(0 != encoder->protected_);
  97733. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97734. return false;
  97735. #if 0
  97736. /*@@@ deprecated: */
  97737. encoder->protected_->do_escape_coding = value;
  97738. #else
  97739. (void)value;
  97740. #endif
  97741. return true;
  97742. }
  97743. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97744. {
  97745. FLAC__ASSERT(0 != encoder);
  97746. FLAC__ASSERT(0 != encoder->private_);
  97747. FLAC__ASSERT(0 != encoder->protected_);
  97748. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97749. return false;
  97750. encoder->protected_->do_exhaustive_model_search = value;
  97751. return true;
  97752. }
  97753. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  97754. {
  97755. FLAC__ASSERT(0 != encoder);
  97756. FLAC__ASSERT(0 != encoder->private_);
  97757. FLAC__ASSERT(0 != encoder->protected_);
  97758. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97759. return false;
  97760. encoder->protected_->min_residual_partition_order = value;
  97761. return true;
  97762. }
  97763. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  97764. {
  97765. FLAC__ASSERT(0 != encoder);
  97766. FLAC__ASSERT(0 != encoder->private_);
  97767. FLAC__ASSERT(0 != encoder->protected_);
  97768. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97769. return false;
  97770. encoder->protected_->max_residual_partition_order = value;
  97771. return true;
  97772. }
  97773. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  97774. {
  97775. FLAC__ASSERT(0 != encoder);
  97776. FLAC__ASSERT(0 != encoder->private_);
  97777. FLAC__ASSERT(0 != encoder->protected_);
  97778. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97779. return false;
  97780. #if 0
  97781. /*@@@ deprecated: */
  97782. encoder->protected_->rice_parameter_search_dist = value;
  97783. #else
  97784. (void)value;
  97785. #endif
  97786. return true;
  97787. }
  97788. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  97789. {
  97790. FLAC__ASSERT(0 != encoder);
  97791. FLAC__ASSERT(0 != encoder->private_);
  97792. FLAC__ASSERT(0 != encoder->protected_);
  97793. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97794. return false;
  97795. encoder->protected_->total_samples_estimate = value;
  97796. return true;
  97797. }
  97798. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  97799. {
  97800. FLAC__ASSERT(0 != encoder);
  97801. FLAC__ASSERT(0 != encoder->private_);
  97802. FLAC__ASSERT(0 != encoder->protected_);
  97803. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97804. return false;
  97805. if(0 == metadata)
  97806. num_blocks = 0;
  97807. if(0 == num_blocks)
  97808. metadata = 0;
  97809. /* realloc() does not do exactly what we want so... */
  97810. if(encoder->protected_->metadata) {
  97811. free(encoder->protected_->metadata);
  97812. encoder->protected_->metadata = 0;
  97813. encoder->protected_->num_metadata_blocks = 0;
  97814. }
  97815. if(num_blocks) {
  97816. FLAC__StreamMetadata **m;
  97817. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  97818. return false;
  97819. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  97820. encoder->protected_->metadata = m;
  97821. encoder->protected_->num_metadata_blocks = num_blocks;
  97822. }
  97823. #if FLAC__HAS_OGG
  97824. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  97825. return false;
  97826. #endif
  97827. return true;
  97828. }
  97829. /*
  97830. * These three functions are not static, but not publically exposed in
  97831. * include/FLAC/ either. They are used by the test suite.
  97832. */
  97833. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97834. {
  97835. FLAC__ASSERT(0 != encoder);
  97836. FLAC__ASSERT(0 != encoder->private_);
  97837. FLAC__ASSERT(0 != encoder->protected_);
  97838. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97839. return false;
  97840. encoder->private_->disable_constant_subframes = value;
  97841. return true;
  97842. }
  97843. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97844. {
  97845. FLAC__ASSERT(0 != encoder);
  97846. FLAC__ASSERT(0 != encoder->private_);
  97847. FLAC__ASSERT(0 != encoder->protected_);
  97848. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97849. return false;
  97850. encoder->private_->disable_fixed_subframes = value;
  97851. return true;
  97852. }
  97853. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97854. {
  97855. FLAC__ASSERT(0 != encoder);
  97856. FLAC__ASSERT(0 != encoder->private_);
  97857. FLAC__ASSERT(0 != encoder->protected_);
  97858. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97859. return false;
  97860. encoder->private_->disable_verbatim_subframes = value;
  97861. return true;
  97862. }
  97863. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  97864. {
  97865. FLAC__ASSERT(0 != encoder);
  97866. FLAC__ASSERT(0 != encoder->private_);
  97867. FLAC__ASSERT(0 != encoder->protected_);
  97868. return encoder->protected_->state;
  97869. }
  97870. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  97871. {
  97872. FLAC__ASSERT(0 != encoder);
  97873. FLAC__ASSERT(0 != encoder->private_);
  97874. FLAC__ASSERT(0 != encoder->protected_);
  97875. if(encoder->protected_->verify)
  97876. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  97877. else
  97878. return FLAC__STREAM_DECODER_UNINITIALIZED;
  97879. }
  97880. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  97881. {
  97882. FLAC__ASSERT(0 != encoder);
  97883. FLAC__ASSERT(0 != encoder->private_);
  97884. FLAC__ASSERT(0 != encoder->protected_);
  97885. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  97886. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  97887. else
  97888. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  97889. }
  97890. 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)
  97891. {
  97892. FLAC__ASSERT(0 != encoder);
  97893. FLAC__ASSERT(0 != encoder->private_);
  97894. FLAC__ASSERT(0 != encoder->protected_);
  97895. if(0 != absolute_sample)
  97896. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  97897. if(0 != frame_number)
  97898. *frame_number = encoder->private_->verify.error_stats.frame_number;
  97899. if(0 != channel)
  97900. *channel = encoder->private_->verify.error_stats.channel;
  97901. if(0 != sample)
  97902. *sample = encoder->private_->verify.error_stats.sample;
  97903. if(0 != expected)
  97904. *expected = encoder->private_->verify.error_stats.expected;
  97905. if(0 != got)
  97906. *got = encoder->private_->verify.error_stats.got;
  97907. }
  97908. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(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_->verify;
  97914. }
  97915. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(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_->streamable_subset;
  97921. }
  97922. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(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_->do_md5;
  97928. }
  97929. FLAC_API unsigned FLAC__stream_encoder_get_channels(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_->channels;
  97935. }
  97936. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(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_->bits_per_sample;
  97942. }
  97943. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(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_->sample_rate;
  97949. }
  97950. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  97951. {
  97952. FLAC__ASSERT(0 != encoder);
  97953. FLAC__ASSERT(0 != encoder->private_);
  97954. FLAC__ASSERT(0 != encoder->protected_);
  97955. return encoder->protected_->blocksize;
  97956. }
  97957. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  97958. {
  97959. FLAC__ASSERT(0 != encoder);
  97960. FLAC__ASSERT(0 != encoder->private_);
  97961. FLAC__ASSERT(0 != encoder->protected_);
  97962. return encoder->protected_->do_mid_side_stereo;
  97963. }
  97964. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  97965. {
  97966. FLAC__ASSERT(0 != encoder);
  97967. FLAC__ASSERT(0 != encoder->private_);
  97968. FLAC__ASSERT(0 != encoder->protected_);
  97969. return encoder->protected_->loose_mid_side_stereo;
  97970. }
  97971. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  97972. {
  97973. FLAC__ASSERT(0 != encoder);
  97974. FLAC__ASSERT(0 != encoder->private_);
  97975. FLAC__ASSERT(0 != encoder->protected_);
  97976. return encoder->protected_->max_lpc_order;
  97977. }
  97978. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  97979. {
  97980. FLAC__ASSERT(0 != encoder);
  97981. FLAC__ASSERT(0 != encoder->private_);
  97982. FLAC__ASSERT(0 != encoder->protected_);
  97983. return encoder->protected_->qlp_coeff_precision;
  97984. }
  97985. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  97986. {
  97987. FLAC__ASSERT(0 != encoder);
  97988. FLAC__ASSERT(0 != encoder->private_);
  97989. FLAC__ASSERT(0 != encoder->protected_);
  97990. return encoder->protected_->do_qlp_coeff_prec_search;
  97991. }
  97992. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  97993. {
  97994. FLAC__ASSERT(0 != encoder);
  97995. FLAC__ASSERT(0 != encoder->private_);
  97996. FLAC__ASSERT(0 != encoder->protected_);
  97997. return encoder->protected_->do_escape_coding;
  97998. }
  97999. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  98000. {
  98001. FLAC__ASSERT(0 != encoder);
  98002. FLAC__ASSERT(0 != encoder->private_);
  98003. FLAC__ASSERT(0 != encoder->protected_);
  98004. return encoder->protected_->do_exhaustive_model_search;
  98005. }
  98006. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  98007. {
  98008. FLAC__ASSERT(0 != encoder);
  98009. FLAC__ASSERT(0 != encoder->private_);
  98010. FLAC__ASSERT(0 != encoder->protected_);
  98011. return encoder->protected_->min_residual_partition_order;
  98012. }
  98013. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  98014. {
  98015. FLAC__ASSERT(0 != encoder);
  98016. FLAC__ASSERT(0 != encoder->private_);
  98017. FLAC__ASSERT(0 != encoder->protected_);
  98018. return encoder->protected_->max_residual_partition_order;
  98019. }
  98020. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  98021. {
  98022. FLAC__ASSERT(0 != encoder);
  98023. FLAC__ASSERT(0 != encoder->private_);
  98024. FLAC__ASSERT(0 != encoder->protected_);
  98025. return encoder->protected_->rice_parameter_search_dist;
  98026. }
  98027. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  98028. {
  98029. FLAC__ASSERT(0 != encoder);
  98030. FLAC__ASSERT(0 != encoder->private_);
  98031. FLAC__ASSERT(0 != encoder->protected_);
  98032. return encoder->protected_->total_samples_estimate;
  98033. }
  98034. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  98035. {
  98036. unsigned i, j = 0, channel;
  98037. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  98038. FLAC__ASSERT(0 != encoder);
  98039. FLAC__ASSERT(0 != encoder->private_);
  98040. FLAC__ASSERT(0 != encoder->protected_);
  98041. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  98042. do {
  98043. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  98044. if(encoder->protected_->verify)
  98045. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  98046. for(channel = 0; channel < channels; channel++)
  98047. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  98048. if(encoder->protected_->do_mid_side_stereo) {
  98049. FLAC__ASSERT(channels == 2);
  98050. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  98051. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  98052. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  98053. 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' ! */
  98054. }
  98055. }
  98056. else
  98057. j += n;
  98058. encoder->private_->current_sample_number += n;
  98059. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  98060. if(encoder->private_->current_sample_number > blocksize) {
  98061. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  98062. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  98063. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  98064. return false;
  98065. /* move unprocessed overread samples to beginnings of arrays */
  98066. for(channel = 0; channel < channels; channel++)
  98067. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  98068. if(encoder->protected_->do_mid_side_stereo) {
  98069. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  98070. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  98071. }
  98072. encoder->private_->current_sample_number = 1;
  98073. }
  98074. } while(j < samples);
  98075. return true;
  98076. }
  98077. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  98078. {
  98079. unsigned i, j, k, channel;
  98080. FLAC__int32 x, mid, side;
  98081. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  98082. FLAC__ASSERT(0 != encoder);
  98083. FLAC__ASSERT(0 != encoder->private_);
  98084. FLAC__ASSERT(0 != encoder->protected_);
  98085. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  98086. j = k = 0;
  98087. /*
  98088. * we have several flavors of the same basic loop, optimized for
  98089. * different conditions:
  98090. */
  98091. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  98092. /*
  98093. * stereo coding: unroll channel loop
  98094. */
  98095. do {
  98096. if(encoder->protected_->verify)
  98097. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  98098. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  98099. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  98100. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  98101. x = buffer[k++];
  98102. encoder->private_->integer_signal[1][i] = x;
  98103. mid += x;
  98104. side -= x;
  98105. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  98106. encoder->private_->integer_signal_mid_side[1][i] = side;
  98107. encoder->private_->integer_signal_mid_side[0][i] = mid;
  98108. }
  98109. encoder->private_->current_sample_number = i;
  98110. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  98111. if(i > blocksize) {
  98112. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  98113. return false;
  98114. /* move unprocessed overread samples to beginnings of arrays */
  98115. FLAC__ASSERT(i == blocksize+OVERREAD_);
  98116. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  98117. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  98118. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  98119. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  98120. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  98121. encoder->private_->current_sample_number = 1;
  98122. }
  98123. } while(j < samples);
  98124. }
  98125. else {
  98126. /*
  98127. * independent channel coding: buffer each channel in inner loop
  98128. */
  98129. do {
  98130. if(encoder->protected_->verify)
  98131. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  98132. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  98133. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  98134. for(channel = 0; channel < channels; channel++)
  98135. encoder->private_->integer_signal[channel][i] = buffer[k++];
  98136. }
  98137. encoder->private_->current_sample_number = i;
  98138. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  98139. if(i > blocksize) {
  98140. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  98141. return false;
  98142. /* move unprocessed overread samples to beginnings of arrays */
  98143. FLAC__ASSERT(i == blocksize+OVERREAD_);
  98144. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  98145. for(channel = 0; channel < channels; channel++)
  98146. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  98147. encoder->private_->current_sample_number = 1;
  98148. }
  98149. } while(j < samples);
  98150. }
  98151. return true;
  98152. }
  98153. /***********************************************************************
  98154. *
  98155. * Private class methods
  98156. *
  98157. ***********************************************************************/
  98158. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  98159. {
  98160. FLAC__ASSERT(0 != encoder);
  98161. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  98162. encoder->protected_->verify = true;
  98163. #else
  98164. encoder->protected_->verify = false;
  98165. #endif
  98166. encoder->protected_->streamable_subset = true;
  98167. encoder->protected_->do_md5 = true;
  98168. encoder->protected_->do_mid_side_stereo = false;
  98169. encoder->protected_->loose_mid_side_stereo = false;
  98170. encoder->protected_->channels = 2;
  98171. encoder->protected_->bits_per_sample = 16;
  98172. encoder->protected_->sample_rate = 44100;
  98173. encoder->protected_->blocksize = 0;
  98174. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98175. encoder->protected_->num_apodizations = 1;
  98176. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  98177. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  98178. #endif
  98179. encoder->protected_->max_lpc_order = 0;
  98180. encoder->protected_->qlp_coeff_precision = 0;
  98181. encoder->protected_->do_qlp_coeff_prec_search = false;
  98182. encoder->protected_->do_exhaustive_model_search = false;
  98183. encoder->protected_->do_escape_coding = false;
  98184. encoder->protected_->min_residual_partition_order = 0;
  98185. encoder->protected_->max_residual_partition_order = 0;
  98186. encoder->protected_->rice_parameter_search_dist = 0;
  98187. encoder->protected_->total_samples_estimate = 0;
  98188. encoder->protected_->metadata = 0;
  98189. encoder->protected_->num_metadata_blocks = 0;
  98190. encoder->private_->seek_table = 0;
  98191. encoder->private_->disable_constant_subframes = false;
  98192. encoder->private_->disable_fixed_subframes = false;
  98193. encoder->private_->disable_verbatim_subframes = false;
  98194. #if FLAC__HAS_OGG
  98195. encoder->private_->is_ogg = false;
  98196. #endif
  98197. encoder->private_->read_callback = 0;
  98198. encoder->private_->write_callback = 0;
  98199. encoder->private_->seek_callback = 0;
  98200. encoder->private_->tell_callback = 0;
  98201. encoder->private_->metadata_callback = 0;
  98202. encoder->private_->progress_callback = 0;
  98203. encoder->private_->client_data = 0;
  98204. #if FLAC__HAS_OGG
  98205. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  98206. #endif
  98207. }
  98208. void free_(FLAC__StreamEncoder *encoder)
  98209. {
  98210. unsigned i, channel;
  98211. FLAC__ASSERT(0 != encoder);
  98212. if(encoder->protected_->metadata) {
  98213. free(encoder->protected_->metadata);
  98214. encoder->protected_->metadata = 0;
  98215. encoder->protected_->num_metadata_blocks = 0;
  98216. }
  98217. for(i = 0; i < encoder->protected_->channels; i++) {
  98218. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  98219. free(encoder->private_->integer_signal_unaligned[i]);
  98220. encoder->private_->integer_signal_unaligned[i] = 0;
  98221. }
  98222. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98223. if(0 != encoder->private_->real_signal_unaligned[i]) {
  98224. free(encoder->private_->real_signal_unaligned[i]);
  98225. encoder->private_->real_signal_unaligned[i] = 0;
  98226. }
  98227. #endif
  98228. }
  98229. for(i = 0; i < 2; i++) {
  98230. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  98231. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  98232. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  98233. }
  98234. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98235. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  98236. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  98237. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  98238. }
  98239. #endif
  98240. }
  98241. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98242. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  98243. if(0 != encoder->private_->window_unaligned[i]) {
  98244. free(encoder->private_->window_unaligned[i]);
  98245. encoder->private_->window_unaligned[i] = 0;
  98246. }
  98247. }
  98248. if(0 != encoder->private_->windowed_signal_unaligned) {
  98249. free(encoder->private_->windowed_signal_unaligned);
  98250. encoder->private_->windowed_signal_unaligned = 0;
  98251. }
  98252. #endif
  98253. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  98254. for(i = 0; i < 2; i++) {
  98255. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  98256. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  98257. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  98258. }
  98259. }
  98260. }
  98261. for(channel = 0; channel < 2; channel++) {
  98262. for(i = 0; i < 2; i++) {
  98263. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  98264. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  98265. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  98266. }
  98267. }
  98268. }
  98269. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  98270. free(encoder->private_->abs_residual_partition_sums_unaligned);
  98271. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  98272. }
  98273. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  98274. free(encoder->private_->raw_bits_per_partition_unaligned);
  98275. encoder->private_->raw_bits_per_partition_unaligned = 0;
  98276. }
  98277. if(encoder->protected_->verify) {
  98278. for(i = 0; i < encoder->protected_->channels; i++) {
  98279. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  98280. free(encoder->private_->verify.input_fifo.data[i]);
  98281. encoder->private_->verify.input_fifo.data[i] = 0;
  98282. }
  98283. }
  98284. }
  98285. FLAC__bitwriter_free(encoder->private_->frame);
  98286. }
  98287. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  98288. {
  98289. FLAC__bool ok;
  98290. unsigned i, channel;
  98291. FLAC__ASSERT(new_blocksize > 0);
  98292. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  98293. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  98294. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  98295. if(new_blocksize <= encoder->private_->input_capacity)
  98296. return true;
  98297. ok = true;
  98298. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  98299. * requires that the input arrays (in our case the integer signals)
  98300. * have a buffer of up to 3 zeroes in front (at negative indices) for
  98301. * alignment purposes; we use 4 in front to keep the data well-aligned.
  98302. */
  98303. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  98304. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  98305. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  98306. encoder->private_->integer_signal[i] += 4;
  98307. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98308. #if 0 /* @@@ currently unused */
  98309. if(encoder->protected_->max_lpc_order > 0)
  98310. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  98311. #endif
  98312. #endif
  98313. }
  98314. for(i = 0; ok && i < 2; i++) {
  98315. 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]);
  98316. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  98317. encoder->private_->integer_signal_mid_side[i] += 4;
  98318. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98319. #if 0 /* @@@ currently unused */
  98320. if(encoder->protected_->max_lpc_order > 0)
  98321. 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]);
  98322. #endif
  98323. #endif
  98324. }
  98325. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98326. if(ok && encoder->protected_->max_lpc_order > 0) {
  98327. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  98328. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  98329. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  98330. }
  98331. #endif
  98332. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  98333. for(i = 0; ok && i < 2; i++) {
  98334. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  98335. }
  98336. }
  98337. for(channel = 0; ok && channel < 2; channel++) {
  98338. for(i = 0; ok && i < 2; i++) {
  98339. 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]);
  98340. }
  98341. }
  98342. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  98343. /*@@@ 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) */
  98344. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  98345. if(encoder->protected_->do_escape_coding)
  98346. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  98347. /* now adjust the windows if the blocksize has changed */
  98348. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98349. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  98350. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  98351. switch(encoder->protected_->apodizations[i].type) {
  98352. case FLAC__APODIZATION_BARTLETT:
  98353. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  98354. break;
  98355. case FLAC__APODIZATION_BARTLETT_HANN:
  98356. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  98357. break;
  98358. case FLAC__APODIZATION_BLACKMAN:
  98359. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  98360. break;
  98361. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  98362. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  98363. break;
  98364. case FLAC__APODIZATION_CONNES:
  98365. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  98366. break;
  98367. case FLAC__APODIZATION_FLATTOP:
  98368. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  98369. break;
  98370. case FLAC__APODIZATION_GAUSS:
  98371. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  98372. break;
  98373. case FLAC__APODIZATION_HAMMING:
  98374. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  98375. break;
  98376. case FLAC__APODIZATION_HANN:
  98377. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  98378. break;
  98379. case FLAC__APODIZATION_KAISER_BESSEL:
  98380. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  98381. break;
  98382. case FLAC__APODIZATION_NUTTALL:
  98383. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  98384. break;
  98385. case FLAC__APODIZATION_RECTANGLE:
  98386. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  98387. break;
  98388. case FLAC__APODIZATION_TRIANGLE:
  98389. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  98390. break;
  98391. case FLAC__APODIZATION_TUKEY:
  98392. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  98393. break;
  98394. case FLAC__APODIZATION_WELCH:
  98395. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  98396. break;
  98397. default:
  98398. FLAC__ASSERT(0);
  98399. /* double protection */
  98400. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  98401. break;
  98402. }
  98403. }
  98404. }
  98405. #endif
  98406. if(ok)
  98407. encoder->private_->input_capacity = new_blocksize;
  98408. else
  98409. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98410. return ok;
  98411. }
  98412. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  98413. {
  98414. const FLAC__byte *buffer;
  98415. size_t bytes;
  98416. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  98417. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  98418. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98419. return false;
  98420. }
  98421. if(encoder->protected_->verify) {
  98422. encoder->private_->verify.output.data = buffer;
  98423. encoder->private_->verify.output.bytes = bytes;
  98424. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  98425. encoder->private_->verify.needs_magic_hack = true;
  98426. }
  98427. else {
  98428. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  98429. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  98430. FLAC__bitwriter_clear(encoder->private_->frame);
  98431. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  98432. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  98433. return false;
  98434. }
  98435. }
  98436. }
  98437. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98438. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  98439. FLAC__bitwriter_clear(encoder->private_->frame);
  98440. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98441. return false;
  98442. }
  98443. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  98444. FLAC__bitwriter_clear(encoder->private_->frame);
  98445. if(samples > 0) {
  98446. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  98447. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  98448. }
  98449. return true;
  98450. }
  98451. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  98452. {
  98453. FLAC__StreamEncoderWriteStatus status;
  98454. FLAC__uint64 output_position = 0;
  98455. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  98456. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  98457. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98458. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  98459. }
  98460. /*
  98461. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  98462. */
  98463. if(samples == 0) {
  98464. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  98465. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  98466. encoder->protected_->streaminfo_offset = output_position;
  98467. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  98468. encoder->protected_->seektable_offset = output_position;
  98469. }
  98470. /*
  98471. * Mark the current seek point if hit (if audio_offset == 0 that
  98472. * means we're still writing metadata and haven't hit the first
  98473. * frame yet)
  98474. */
  98475. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  98476. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  98477. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  98478. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  98479. FLAC__uint64 test_sample;
  98480. unsigned i;
  98481. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  98482. test_sample = encoder->private_->seek_table->points[i].sample_number;
  98483. if(test_sample > frame_last_sample) {
  98484. break;
  98485. }
  98486. else if(test_sample >= frame_first_sample) {
  98487. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  98488. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  98489. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  98490. encoder->private_->first_seekpoint_to_check++;
  98491. /* DO NOT: "break;" and here's why:
  98492. * The seektable template may contain more than one target
  98493. * sample for any given frame; we will keep looping, generating
  98494. * duplicate seekpoints for them, and we'll clean it up later,
  98495. * just before writing the seektable back to the metadata.
  98496. */
  98497. }
  98498. else {
  98499. encoder->private_->first_seekpoint_to_check++;
  98500. }
  98501. }
  98502. }
  98503. #if FLAC__HAS_OGG
  98504. if(encoder->private_->is_ogg) {
  98505. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  98506. &encoder->protected_->ogg_encoder_aspect,
  98507. buffer,
  98508. bytes,
  98509. samples,
  98510. encoder->private_->current_frame_number,
  98511. is_last_block,
  98512. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  98513. encoder,
  98514. encoder->private_->client_data
  98515. );
  98516. }
  98517. else
  98518. #endif
  98519. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  98520. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98521. encoder->private_->bytes_written += bytes;
  98522. encoder->private_->samples_written += samples;
  98523. /* we keep a high watermark on the number of frames written because
  98524. * when the encoder goes back to write metadata, 'current_frame'
  98525. * will drop back to 0.
  98526. */
  98527. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  98528. }
  98529. else
  98530. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98531. return status;
  98532. }
  98533. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  98534. void update_metadata_(const FLAC__StreamEncoder *encoder)
  98535. {
  98536. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  98537. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  98538. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  98539. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  98540. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  98541. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  98542. FLAC__StreamEncoderSeekStatus seek_status;
  98543. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  98544. /* All this is based on intimate knowledge of the stream header
  98545. * layout, but a change to the header format that would break this
  98546. * would also break all streams encoded in the previous format.
  98547. */
  98548. /*
  98549. * Write MD5 signature
  98550. */
  98551. {
  98552. const unsigned md5_offset =
  98553. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98554. (
  98555. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98556. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  98557. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  98558. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  98559. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  98560. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  98561. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  98562. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  98563. ) / 8;
  98564. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  98565. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  98566. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98567. return;
  98568. }
  98569. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98570. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98571. return;
  98572. }
  98573. }
  98574. /*
  98575. * Write total samples
  98576. */
  98577. {
  98578. const unsigned total_samples_byte_offset =
  98579. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98580. (
  98581. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98582. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  98583. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  98584. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  98585. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  98586. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  98587. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  98588. - 4
  98589. ) / 8;
  98590. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  98591. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  98592. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  98593. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  98594. b[4] = (FLAC__byte)(samples & 0xFF);
  98595. 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) {
  98596. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  98597. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98598. return;
  98599. }
  98600. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98601. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98602. return;
  98603. }
  98604. }
  98605. /*
  98606. * Write min/max framesize
  98607. */
  98608. {
  98609. const unsigned min_framesize_offset =
  98610. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98611. (
  98612. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98613. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  98614. ) / 8;
  98615. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  98616. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  98617. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  98618. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  98619. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  98620. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  98621. 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) {
  98622. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  98623. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98624. return;
  98625. }
  98626. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98627. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98628. return;
  98629. }
  98630. }
  98631. /*
  98632. * Write seektable
  98633. */
  98634. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  98635. unsigned i;
  98636. FLAC__format_seektable_sort(encoder->private_->seek_table);
  98637. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  98638. 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) {
  98639. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  98640. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98641. return;
  98642. }
  98643. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  98644. FLAC__uint64 xx;
  98645. unsigned x;
  98646. xx = encoder->private_->seek_table->points[i].sample_number;
  98647. b[7] = (FLAC__byte)xx; xx >>= 8;
  98648. b[6] = (FLAC__byte)xx; xx >>= 8;
  98649. b[5] = (FLAC__byte)xx; xx >>= 8;
  98650. b[4] = (FLAC__byte)xx; xx >>= 8;
  98651. b[3] = (FLAC__byte)xx; xx >>= 8;
  98652. b[2] = (FLAC__byte)xx; xx >>= 8;
  98653. b[1] = (FLAC__byte)xx; xx >>= 8;
  98654. b[0] = (FLAC__byte)xx; xx >>= 8;
  98655. xx = encoder->private_->seek_table->points[i].stream_offset;
  98656. b[15] = (FLAC__byte)xx; xx >>= 8;
  98657. b[14] = (FLAC__byte)xx; xx >>= 8;
  98658. b[13] = (FLAC__byte)xx; xx >>= 8;
  98659. b[12] = (FLAC__byte)xx; xx >>= 8;
  98660. b[11] = (FLAC__byte)xx; xx >>= 8;
  98661. b[10] = (FLAC__byte)xx; xx >>= 8;
  98662. b[9] = (FLAC__byte)xx; xx >>= 8;
  98663. b[8] = (FLAC__byte)xx; xx >>= 8;
  98664. x = encoder->private_->seek_table->points[i].frame_samples;
  98665. b[17] = (FLAC__byte)x; x >>= 8;
  98666. b[16] = (FLAC__byte)x; x >>= 8;
  98667. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  98668. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98669. return;
  98670. }
  98671. }
  98672. }
  98673. }
  98674. #if FLAC__HAS_OGG
  98675. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  98676. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  98677. {
  98678. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  98679. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  98680. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  98681. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  98682. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  98683. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  98684. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  98685. FLAC__STREAM_SYNC_LENGTH
  98686. ;
  98687. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  98688. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  98689. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  98690. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  98691. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  98692. ogg_page page;
  98693. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  98694. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  98695. /* Pre-check that client supports seeking, since we don't want the
  98696. * ogg_helper code to ever have to deal with this condition.
  98697. */
  98698. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  98699. return;
  98700. /* All this is based on intimate knowledge of the stream header
  98701. * layout, but a change to the header format that would break this
  98702. * would also break all streams encoded in the previous format.
  98703. */
  98704. /**
  98705. ** Write STREAMINFO stats
  98706. **/
  98707. simple_ogg_page__init(&page);
  98708. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  98709. simple_ogg_page__clear(&page);
  98710. return; /* state already set */
  98711. }
  98712. /*
  98713. * Write MD5 signature
  98714. */
  98715. {
  98716. const unsigned md5_offset =
  98717. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  98718. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98719. (
  98720. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98721. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  98722. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  98723. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  98724. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  98725. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  98726. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  98727. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  98728. ) / 8;
  98729. if(md5_offset + 16 > (unsigned)page.body_len) {
  98730. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98731. simple_ogg_page__clear(&page);
  98732. return;
  98733. }
  98734. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  98735. }
  98736. /*
  98737. * Write total samples
  98738. */
  98739. {
  98740. const unsigned total_samples_byte_offset =
  98741. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  98742. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98743. (
  98744. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98745. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  98746. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  98747. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  98748. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  98749. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  98750. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  98751. - 4
  98752. ) / 8;
  98753. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  98754. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98755. simple_ogg_page__clear(&page);
  98756. return;
  98757. }
  98758. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  98759. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  98760. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  98761. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  98762. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  98763. b[4] = (FLAC__byte)(samples & 0xFF);
  98764. memcpy(page.body + total_samples_byte_offset, b, 5);
  98765. }
  98766. /*
  98767. * Write min/max framesize
  98768. */
  98769. {
  98770. const unsigned min_framesize_offset =
  98771. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  98772. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98773. (
  98774. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98775. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  98776. ) / 8;
  98777. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  98778. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98779. simple_ogg_page__clear(&page);
  98780. return;
  98781. }
  98782. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  98783. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  98784. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  98785. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  98786. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  98787. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  98788. memcpy(page.body + min_framesize_offset, b, 6);
  98789. }
  98790. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  98791. simple_ogg_page__clear(&page);
  98792. return; /* state already set */
  98793. }
  98794. simple_ogg_page__clear(&page);
  98795. /*
  98796. * Write seektable
  98797. */
  98798. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  98799. unsigned i;
  98800. FLAC__byte *p;
  98801. FLAC__format_seektable_sort(encoder->private_->seek_table);
  98802. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  98803. simple_ogg_page__init(&page);
  98804. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  98805. simple_ogg_page__clear(&page);
  98806. return; /* state already set */
  98807. }
  98808. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  98809. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98810. simple_ogg_page__clear(&page);
  98811. return;
  98812. }
  98813. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  98814. FLAC__uint64 xx;
  98815. unsigned x;
  98816. xx = encoder->private_->seek_table->points[i].sample_number;
  98817. b[7] = (FLAC__byte)xx; xx >>= 8;
  98818. b[6] = (FLAC__byte)xx; xx >>= 8;
  98819. b[5] = (FLAC__byte)xx; xx >>= 8;
  98820. b[4] = (FLAC__byte)xx; xx >>= 8;
  98821. b[3] = (FLAC__byte)xx; xx >>= 8;
  98822. b[2] = (FLAC__byte)xx; xx >>= 8;
  98823. b[1] = (FLAC__byte)xx; xx >>= 8;
  98824. b[0] = (FLAC__byte)xx; xx >>= 8;
  98825. xx = encoder->private_->seek_table->points[i].stream_offset;
  98826. b[15] = (FLAC__byte)xx; xx >>= 8;
  98827. b[14] = (FLAC__byte)xx; xx >>= 8;
  98828. b[13] = (FLAC__byte)xx; xx >>= 8;
  98829. b[12] = (FLAC__byte)xx; xx >>= 8;
  98830. b[11] = (FLAC__byte)xx; xx >>= 8;
  98831. b[10] = (FLAC__byte)xx; xx >>= 8;
  98832. b[9] = (FLAC__byte)xx; xx >>= 8;
  98833. b[8] = (FLAC__byte)xx; xx >>= 8;
  98834. x = encoder->private_->seek_table->points[i].frame_samples;
  98835. b[17] = (FLAC__byte)x; x >>= 8;
  98836. b[16] = (FLAC__byte)x; x >>= 8;
  98837. memcpy(p, b, 18);
  98838. }
  98839. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  98840. simple_ogg_page__clear(&page);
  98841. return; /* state already set */
  98842. }
  98843. simple_ogg_page__clear(&page);
  98844. }
  98845. }
  98846. #endif
  98847. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  98848. {
  98849. FLAC__uint16 crc;
  98850. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  98851. /*
  98852. * Accumulate raw signal to the MD5 signature
  98853. */
  98854. 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)) {
  98855. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98856. return false;
  98857. }
  98858. /*
  98859. * Process the frame header and subframes into the frame bitbuffer
  98860. */
  98861. if(!process_subframes_(encoder, is_fractional_block)) {
  98862. /* the above function sets the state for us in case of an error */
  98863. return false;
  98864. }
  98865. /*
  98866. * Zero-pad the frame to a byte_boundary
  98867. */
  98868. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  98869. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98870. return false;
  98871. }
  98872. /*
  98873. * CRC-16 the whole thing
  98874. */
  98875. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  98876. if(
  98877. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  98878. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  98879. ) {
  98880. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98881. return false;
  98882. }
  98883. /*
  98884. * Write it
  98885. */
  98886. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  98887. /* the above function sets the state for us in case of an error */
  98888. return false;
  98889. }
  98890. /*
  98891. * Get ready for the next frame
  98892. */
  98893. encoder->private_->current_sample_number = 0;
  98894. encoder->private_->current_frame_number++;
  98895. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  98896. return true;
  98897. }
  98898. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  98899. {
  98900. FLAC__FrameHeader frame_header;
  98901. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  98902. FLAC__bool do_independent, do_mid_side;
  98903. /*
  98904. * Calculate the min,max Rice partition orders
  98905. */
  98906. if(is_fractional_block) {
  98907. max_partition_order = 0;
  98908. }
  98909. else {
  98910. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  98911. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  98912. }
  98913. min_partition_order = min(min_partition_order, max_partition_order);
  98914. /*
  98915. * Setup the frame
  98916. */
  98917. frame_header.blocksize = encoder->protected_->blocksize;
  98918. frame_header.sample_rate = encoder->protected_->sample_rate;
  98919. frame_header.channels = encoder->protected_->channels;
  98920. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  98921. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  98922. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  98923. frame_header.number.frame_number = encoder->private_->current_frame_number;
  98924. /*
  98925. * Figure out what channel assignments to try
  98926. */
  98927. if(encoder->protected_->do_mid_side_stereo) {
  98928. if(encoder->protected_->loose_mid_side_stereo) {
  98929. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  98930. do_independent = true;
  98931. do_mid_side = true;
  98932. }
  98933. else {
  98934. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  98935. do_mid_side = !do_independent;
  98936. }
  98937. }
  98938. else {
  98939. do_independent = true;
  98940. do_mid_side = true;
  98941. }
  98942. }
  98943. else {
  98944. do_independent = true;
  98945. do_mid_side = false;
  98946. }
  98947. FLAC__ASSERT(do_independent || do_mid_side);
  98948. /*
  98949. * Check for wasted bits; set effective bps for each subframe
  98950. */
  98951. if(do_independent) {
  98952. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  98953. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  98954. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  98955. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  98956. }
  98957. }
  98958. if(do_mid_side) {
  98959. FLAC__ASSERT(encoder->protected_->channels == 2);
  98960. for(channel = 0; channel < 2; channel++) {
  98961. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  98962. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  98963. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  98964. }
  98965. }
  98966. /*
  98967. * First do a normal encoding pass of each independent channel
  98968. */
  98969. if(do_independent) {
  98970. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  98971. if(!
  98972. process_subframe_(
  98973. encoder,
  98974. min_partition_order,
  98975. max_partition_order,
  98976. &frame_header,
  98977. encoder->private_->subframe_bps[channel],
  98978. encoder->private_->integer_signal[channel],
  98979. encoder->private_->subframe_workspace_ptr[channel],
  98980. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  98981. encoder->private_->residual_workspace[channel],
  98982. encoder->private_->best_subframe+channel,
  98983. encoder->private_->best_subframe_bits+channel
  98984. )
  98985. )
  98986. return false;
  98987. }
  98988. }
  98989. /*
  98990. * Now do mid and side channels if requested
  98991. */
  98992. if(do_mid_side) {
  98993. FLAC__ASSERT(encoder->protected_->channels == 2);
  98994. for(channel = 0; channel < 2; channel++) {
  98995. if(!
  98996. process_subframe_(
  98997. encoder,
  98998. min_partition_order,
  98999. max_partition_order,
  99000. &frame_header,
  99001. encoder->private_->subframe_bps_mid_side[channel],
  99002. encoder->private_->integer_signal_mid_side[channel],
  99003. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  99004. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  99005. encoder->private_->residual_workspace_mid_side[channel],
  99006. encoder->private_->best_subframe_mid_side+channel,
  99007. encoder->private_->best_subframe_bits_mid_side+channel
  99008. )
  99009. )
  99010. return false;
  99011. }
  99012. }
  99013. /*
  99014. * Compose the frame bitbuffer
  99015. */
  99016. if(do_mid_side) {
  99017. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  99018. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  99019. FLAC__ChannelAssignment channel_assignment;
  99020. FLAC__ASSERT(encoder->protected_->channels == 2);
  99021. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  99022. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  99023. }
  99024. else {
  99025. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  99026. unsigned min_bits;
  99027. int ca;
  99028. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  99029. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  99030. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  99031. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  99032. FLAC__ASSERT(do_independent && do_mid_side);
  99033. /* We have to figure out which channel assignent results in the smallest frame */
  99034. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  99035. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  99036. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  99037. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  99038. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  99039. min_bits = bits[channel_assignment];
  99040. for(ca = 1; ca <= 3; ca++) {
  99041. if(bits[ca] < min_bits) {
  99042. min_bits = bits[ca];
  99043. channel_assignment = (FLAC__ChannelAssignment)ca;
  99044. }
  99045. }
  99046. }
  99047. frame_header.channel_assignment = channel_assignment;
  99048. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  99049. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99050. return false;
  99051. }
  99052. switch(channel_assignment) {
  99053. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  99054. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  99055. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  99056. break;
  99057. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  99058. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  99059. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  99060. break;
  99061. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  99062. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  99063. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  99064. break;
  99065. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99066. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  99067. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  99068. break;
  99069. default:
  99070. FLAC__ASSERT(0);
  99071. }
  99072. switch(channel_assignment) {
  99073. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  99074. left_bps = encoder->private_->subframe_bps [0];
  99075. right_bps = encoder->private_->subframe_bps [1];
  99076. break;
  99077. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  99078. left_bps = encoder->private_->subframe_bps [0];
  99079. right_bps = encoder->private_->subframe_bps_mid_side[1];
  99080. break;
  99081. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  99082. left_bps = encoder->private_->subframe_bps_mid_side[1];
  99083. right_bps = encoder->private_->subframe_bps [1];
  99084. break;
  99085. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99086. left_bps = encoder->private_->subframe_bps_mid_side[0];
  99087. right_bps = encoder->private_->subframe_bps_mid_side[1];
  99088. break;
  99089. default:
  99090. FLAC__ASSERT(0);
  99091. }
  99092. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  99093. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  99094. return false;
  99095. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  99096. return false;
  99097. }
  99098. else {
  99099. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  99100. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99101. return false;
  99102. }
  99103. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  99104. 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)) {
  99105. /* the above function sets the state for us in case of an error */
  99106. return false;
  99107. }
  99108. }
  99109. }
  99110. if(encoder->protected_->loose_mid_side_stereo) {
  99111. encoder->private_->loose_mid_side_stereo_frame_count++;
  99112. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  99113. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  99114. }
  99115. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  99116. return true;
  99117. }
  99118. FLAC__bool process_subframe_(
  99119. FLAC__StreamEncoder *encoder,
  99120. unsigned min_partition_order,
  99121. unsigned max_partition_order,
  99122. const FLAC__FrameHeader *frame_header,
  99123. unsigned subframe_bps,
  99124. const FLAC__int32 integer_signal[],
  99125. FLAC__Subframe *subframe[2],
  99126. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  99127. FLAC__int32 *residual[2],
  99128. unsigned *best_subframe,
  99129. unsigned *best_bits
  99130. )
  99131. {
  99132. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99133. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  99134. #else
  99135. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  99136. #endif
  99137. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99138. FLAC__double lpc_residual_bits_per_sample;
  99139. 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 */
  99140. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  99141. unsigned min_lpc_order, max_lpc_order, lpc_order;
  99142. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  99143. #endif
  99144. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  99145. unsigned rice_parameter;
  99146. unsigned _candidate_bits, _best_bits;
  99147. unsigned _best_subframe;
  99148. /* only use RICE2 partitions if stream bps > 16 */
  99149. 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;
  99150. FLAC__ASSERT(frame_header->blocksize > 0);
  99151. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  99152. _best_subframe = 0;
  99153. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  99154. _best_bits = UINT_MAX;
  99155. else
  99156. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  99157. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  99158. unsigned signal_is_constant = false;
  99159. 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);
  99160. /* check for constant subframe */
  99161. if(
  99162. !encoder->private_->disable_constant_subframes &&
  99163. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99164. fixed_residual_bits_per_sample[1] == 0.0
  99165. #else
  99166. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  99167. #endif
  99168. ) {
  99169. /* the above means it's possible all samples are the same value; now double-check it: */
  99170. unsigned i;
  99171. signal_is_constant = true;
  99172. for(i = 1; i < frame_header->blocksize; i++) {
  99173. if(integer_signal[0] != integer_signal[i]) {
  99174. signal_is_constant = false;
  99175. break;
  99176. }
  99177. }
  99178. }
  99179. if(signal_is_constant) {
  99180. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  99181. if(_candidate_bits < _best_bits) {
  99182. _best_subframe = !_best_subframe;
  99183. _best_bits = _candidate_bits;
  99184. }
  99185. }
  99186. else {
  99187. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  99188. /* encode fixed */
  99189. if(encoder->protected_->do_exhaustive_model_search) {
  99190. min_fixed_order = 0;
  99191. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  99192. }
  99193. else {
  99194. min_fixed_order = max_fixed_order = guess_fixed_order;
  99195. }
  99196. if(max_fixed_order >= frame_header->blocksize)
  99197. max_fixed_order = frame_header->blocksize - 1;
  99198. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  99199. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99200. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  99201. continue; /* don't even try */
  99202. 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 */
  99203. #else
  99204. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  99205. continue; /* don't even try */
  99206. 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 */
  99207. #endif
  99208. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  99209. if(rice_parameter >= rice_parameter_limit) {
  99210. #ifdef DEBUG_VERBOSE
  99211. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  99212. #endif
  99213. rice_parameter = rice_parameter_limit - 1;
  99214. }
  99215. _candidate_bits =
  99216. evaluate_fixed_subframe_(
  99217. encoder,
  99218. integer_signal,
  99219. residual[!_best_subframe],
  99220. encoder->private_->abs_residual_partition_sums,
  99221. encoder->private_->raw_bits_per_partition,
  99222. frame_header->blocksize,
  99223. subframe_bps,
  99224. fixed_order,
  99225. rice_parameter,
  99226. rice_parameter_limit,
  99227. min_partition_order,
  99228. max_partition_order,
  99229. encoder->protected_->do_escape_coding,
  99230. encoder->protected_->rice_parameter_search_dist,
  99231. subframe[!_best_subframe],
  99232. partitioned_rice_contents[!_best_subframe]
  99233. );
  99234. if(_candidate_bits < _best_bits) {
  99235. _best_subframe = !_best_subframe;
  99236. _best_bits = _candidate_bits;
  99237. }
  99238. }
  99239. }
  99240. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99241. /* encode lpc */
  99242. if(encoder->protected_->max_lpc_order > 0) {
  99243. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  99244. max_lpc_order = frame_header->blocksize-1;
  99245. else
  99246. max_lpc_order = encoder->protected_->max_lpc_order;
  99247. if(max_lpc_order > 0) {
  99248. unsigned a;
  99249. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  99250. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  99251. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  99252. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  99253. if(autoc[0] != 0.0) {
  99254. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  99255. if(encoder->protected_->do_exhaustive_model_search) {
  99256. min_lpc_order = 1;
  99257. }
  99258. else {
  99259. const unsigned guess_lpc_order =
  99260. FLAC__lpc_compute_best_order(
  99261. lpc_error,
  99262. max_lpc_order,
  99263. frame_header->blocksize,
  99264. subframe_bps + (
  99265. encoder->protected_->do_qlp_coeff_prec_search?
  99266. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  99267. encoder->protected_->qlp_coeff_precision
  99268. )
  99269. );
  99270. min_lpc_order = max_lpc_order = guess_lpc_order;
  99271. }
  99272. if(max_lpc_order >= frame_header->blocksize)
  99273. max_lpc_order = frame_header->blocksize - 1;
  99274. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  99275. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  99276. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  99277. continue; /* don't even try */
  99278. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  99279. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  99280. if(rice_parameter >= rice_parameter_limit) {
  99281. #ifdef DEBUG_VERBOSE
  99282. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  99283. #endif
  99284. rice_parameter = rice_parameter_limit - 1;
  99285. }
  99286. if(encoder->protected_->do_qlp_coeff_prec_search) {
  99287. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  99288. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  99289. if(subframe_bps <= 17) {
  99290. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  99291. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  99292. }
  99293. else
  99294. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  99295. }
  99296. else {
  99297. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  99298. }
  99299. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  99300. _candidate_bits =
  99301. evaluate_lpc_subframe_(
  99302. encoder,
  99303. integer_signal,
  99304. residual[!_best_subframe],
  99305. encoder->private_->abs_residual_partition_sums,
  99306. encoder->private_->raw_bits_per_partition,
  99307. encoder->private_->lp_coeff[lpc_order-1],
  99308. frame_header->blocksize,
  99309. subframe_bps,
  99310. lpc_order,
  99311. qlp_coeff_precision,
  99312. rice_parameter,
  99313. rice_parameter_limit,
  99314. min_partition_order,
  99315. max_partition_order,
  99316. encoder->protected_->do_escape_coding,
  99317. encoder->protected_->rice_parameter_search_dist,
  99318. subframe[!_best_subframe],
  99319. partitioned_rice_contents[!_best_subframe]
  99320. );
  99321. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  99322. if(_candidate_bits < _best_bits) {
  99323. _best_subframe = !_best_subframe;
  99324. _best_bits = _candidate_bits;
  99325. }
  99326. }
  99327. }
  99328. }
  99329. }
  99330. }
  99331. }
  99332. }
  99333. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  99334. }
  99335. }
  99336. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  99337. if(_best_bits == UINT_MAX) {
  99338. FLAC__ASSERT(_best_subframe == 0);
  99339. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  99340. }
  99341. *best_subframe = _best_subframe;
  99342. *best_bits = _best_bits;
  99343. return true;
  99344. }
  99345. FLAC__bool add_subframe_(
  99346. FLAC__StreamEncoder *encoder,
  99347. unsigned blocksize,
  99348. unsigned subframe_bps,
  99349. const FLAC__Subframe *subframe,
  99350. FLAC__BitWriter *frame
  99351. )
  99352. {
  99353. switch(subframe->type) {
  99354. case FLAC__SUBFRAME_TYPE_CONSTANT:
  99355. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  99356. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99357. return false;
  99358. }
  99359. break;
  99360. case FLAC__SUBFRAME_TYPE_FIXED:
  99361. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  99362. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99363. return false;
  99364. }
  99365. break;
  99366. case FLAC__SUBFRAME_TYPE_LPC:
  99367. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  99368. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99369. return false;
  99370. }
  99371. break;
  99372. case FLAC__SUBFRAME_TYPE_VERBATIM:
  99373. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  99374. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99375. return false;
  99376. }
  99377. break;
  99378. default:
  99379. FLAC__ASSERT(0);
  99380. }
  99381. return true;
  99382. }
  99383. #define SPOTCHECK_ESTIMATE 0
  99384. #if SPOTCHECK_ESTIMATE
  99385. static void spotcheck_subframe_estimate_(
  99386. FLAC__StreamEncoder *encoder,
  99387. unsigned blocksize,
  99388. unsigned subframe_bps,
  99389. const FLAC__Subframe *subframe,
  99390. unsigned estimate
  99391. )
  99392. {
  99393. FLAC__bool ret;
  99394. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  99395. if(frame == 0) {
  99396. fprintf(stderr, "EST: can't allocate frame\n");
  99397. return;
  99398. }
  99399. if(!FLAC__bitwriter_init(frame)) {
  99400. fprintf(stderr, "EST: can't init frame\n");
  99401. return;
  99402. }
  99403. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  99404. FLAC__ASSERT(ret);
  99405. {
  99406. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  99407. if(estimate != actual)
  99408. 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);
  99409. }
  99410. FLAC__bitwriter_delete(frame);
  99411. }
  99412. #endif
  99413. unsigned evaluate_constant_subframe_(
  99414. FLAC__StreamEncoder *encoder,
  99415. const FLAC__int32 signal,
  99416. unsigned blocksize,
  99417. unsigned subframe_bps,
  99418. FLAC__Subframe *subframe
  99419. )
  99420. {
  99421. unsigned estimate;
  99422. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  99423. subframe->data.constant.value = signal;
  99424. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  99425. #if SPOTCHECK_ESTIMATE
  99426. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  99427. #else
  99428. (void)encoder, (void)blocksize;
  99429. #endif
  99430. return estimate;
  99431. }
  99432. unsigned evaluate_fixed_subframe_(
  99433. FLAC__StreamEncoder *encoder,
  99434. const FLAC__int32 signal[],
  99435. FLAC__int32 residual[],
  99436. FLAC__uint64 abs_residual_partition_sums[],
  99437. unsigned raw_bits_per_partition[],
  99438. unsigned blocksize,
  99439. unsigned subframe_bps,
  99440. unsigned order,
  99441. unsigned rice_parameter,
  99442. unsigned rice_parameter_limit,
  99443. unsigned min_partition_order,
  99444. unsigned max_partition_order,
  99445. FLAC__bool do_escape_coding,
  99446. unsigned rice_parameter_search_dist,
  99447. FLAC__Subframe *subframe,
  99448. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  99449. )
  99450. {
  99451. unsigned i, residual_bits, estimate;
  99452. const unsigned residual_samples = blocksize - order;
  99453. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  99454. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  99455. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  99456. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  99457. subframe->data.fixed.residual = residual;
  99458. residual_bits =
  99459. find_best_partition_order_(
  99460. encoder->private_,
  99461. residual,
  99462. abs_residual_partition_sums,
  99463. raw_bits_per_partition,
  99464. residual_samples,
  99465. order,
  99466. rice_parameter,
  99467. rice_parameter_limit,
  99468. min_partition_order,
  99469. max_partition_order,
  99470. subframe_bps,
  99471. do_escape_coding,
  99472. rice_parameter_search_dist,
  99473. &subframe->data.fixed.entropy_coding_method
  99474. );
  99475. subframe->data.fixed.order = order;
  99476. for(i = 0; i < order; i++)
  99477. subframe->data.fixed.warmup[i] = signal[i];
  99478. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  99479. #if SPOTCHECK_ESTIMATE
  99480. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  99481. #endif
  99482. return estimate;
  99483. }
  99484. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99485. unsigned evaluate_lpc_subframe_(
  99486. FLAC__StreamEncoder *encoder,
  99487. const FLAC__int32 signal[],
  99488. FLAC__int32 residual[],
  99489. FLAC__uint64 abs_residual_partition_sums[],
  99490. unsigned raw_bits_per_partition[],
  99491. const FLAC__real lp_coeff[],
  99492. unsigned blocksize,
  99493. unsigned subframe_bps,
  99494. unsigned order,
  99495. unsigned qlp_coeff_precision,
  99496. unsigned rice_parameter,
  99497. unsigned rice_parameter_limit,
  99498. unsigned min_partition_order,
  99499. unsigned max_partition_order,
  99500. FLAC__bool do_escape_coding,
  99501. unsigned rice_parameter_search_dist,
  99502. FLAC__Subframe *subframe,
  99503. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  99504. )
  99505. {
  99506. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  99507. unsigned i, residual_bits, estimate;
  99508. int quantization, ret;
  99509. const unsigned residual_samples = blocksize - order;
  99510. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  99511. if(subframe_bps <= 16) {
  99512. FLAC__ASSERT(order > 0);
  99513. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  99514. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  99515. }
  99516. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  99517. if(ret != 0)
  99518. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  99519. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  99520. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  99521. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  99522. else
  99523. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  99524. else
  99525. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  99526. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  99527. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  99528. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  99529. subframe->data.lpc.residual = residual;
  99530. residual_bits =
  99531. find_best_partition_order_(
  99532. encoder->private_,
  99533. residual,
  99534. abs_residual_partition_sums,
  99535. raw_bits_per_partition,
  99536. residual_samples,
  99537. order,
  99538. rice_parameter,
  99539. rice_parameter_limit,
  99540. min_partition_order,
  99541. max_partition_order,
  99542. subframe_bps,
  99543. do_escape_coding,
  99544. rice_parameter_search_dist,
  99545. &subframe->data.lpc.entropy_coding_method
  99546. );
  99547. subframe->data.lpc.order = order;
  99548. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  99549. subframe->data.lpc.quantization_level = quantization;
  99550. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  99551. for(i = 0; i < order; i++)
  99552. subframe->data.lpc.warmup[i] = signal[i];
  99553. 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;
  99554. #if SPOTCHECK_ESTIMATE
  99555. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  99556. #endif
  99557. return estimate;
  99558. }
  99559. #endif
  99560. unsigned evaluate_verbatim_subframe_(
  99561. FLAC__StreamEncoder *encoder,
  99562. const FLAC__int32 signal[],
  99563. unsigned blocksize,
  99564. unsigned subframe_bps,
  99565. FLAC__Subframe *subframe
  99566. )
  99567. {
  99568. unsigned estimate;
  99569. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  99570. subframe->data.verbatim.data = signal;
  99571. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  99572. #if SPOTCHECK_ESTIMATE
  99573. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  99574. #else
  99575. (void)encoder;
  99576. #endif
  99577. return estimate;
  99578. }
  99579. unsigned find_best_partition_order_(
  99580. FLAC__StreamEncoderPrivate *private_,
  99581. const FLAC__int32 residual[],
  99582. FLAC__uint64 abs_residual_partition_sums[],
  99583. unsigned raw_bits_per_partition[],
  99584. unsigned residual_samples,
  99585. unsigned predictor_order,
  99586. unsigned rice_parameter,
  99587. unsigned rice_parameter_limit,
  99588. unsigned min_partition_order,
  99589. unsigned max_partition_order,
  99590. unsigned bps,
  99591. FLAC__bool do_escape_coding,
  99592. unsigned rice_parameter_search_dist,
  99593. FLAC__EntropyCodingMethod *best_ecm
  99594. )
  99595. {
  99596. unsigned residual_bits, best_residual_bits = 0;
  99597. unsigned best_parameters_index = 0;
  99598. unsigned best_partition_order = 0;
  99599. const unsigned blocksize = residual_samples + predictor_order;
  99600. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  99601. min_partition_order = min(min_partition_order, max_partition_order);
  99602. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  99603. if(do_escape_coding)
  99604. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  99605. {
  99606. int partition_order;
  99607. unsigned sum;
  99608. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  99609. if(!
  99610. set_partitioned_rice_(
  99611. #ifdef EXACT_RICE_BITS_CALCULATION
  99612. residual,
  99613. #endif
  99614. abs_residual_partition_sums+sum,
  99615. raw_bits_per_partition+sum,
  99616. residual_samples,
  99617. predictor_order,
  99618. rice_parameter,
  99619. rice_parameter_limit,
  99620. rice_parameter_search_dist,
  99621. (unsigned)partition_order,
  99622. do_escape_coding,
  99623. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  99624. &residual_bits
  99625. )
  99626. )
  99627. {
  99628. FLAC__ASSERT(best_residual_bits != 0);
  99629. break;
  99630. }
  99631. sum += 1u << partition_order;
  99632. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  99633. best_residual_bits = residual_bits;
  99634. best_parameters_index = !best_parameters_index;
  99635. best_partition_order = partition_order;
  99636. }
  99637. }
  99638. }
  99639. best_ecm->data.partitioned_rice.order = best_partition_order;
  99640. {
  99641. /*
  99642. * We are allowed to de-const the pointer based on our special
  99643. * knowledge; it is const to the outside world.
  99644. */
  99645. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  99646. unsigned partition;
  99647. /* save best parameters and raw_bits */
  99648. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  99649. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  99650. if(do_escape_coding)
  99651. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  99652. /*
  99653. * Now need to check if the type should be changed to
  99654. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  99655. * size of the rice parameters.
  99656. */
  99657. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  99658. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  99659. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  99660. break;
  99661. }
  99662. }
  99663. }
  99664. return best_residual_bits;
  99665. }
  99666. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  99667. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  99668. const FLAC__int32 residual[],
  99669. FLAC__uint64 abs_residual_partition_sums[],
  99670. unsigned blocksize,
  99671. unsigned predictor_order,
  99672. unsigned min_partition_order,
  99673. unsigned max_partition_order
  99674. );
  99675. #endif
  99676. void precompute_partition_info_sums_(
  99677. const FLAC__int32 residual[],
  99678. FLAC__uint64 abs_residual_partition_sums[],
  99679. unsigned residual_samples,
  99680. unsigned predictor_order,
  99681. unsigned min_partition_order,
  99682. unsigned max_partition_order,
  99683. unsigned bps
  99684. )
  99685. {
  99686. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  99687. unsigned partitions = 1u << max_partition_order;
  99688. FLAC__ASSERT(default_partition_samples > predictor_order);
  99689. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  99690. /* slightly pessimistic but still catches all common cases */
  99691. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  99692. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  99693. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  99694. return;
  99695. }
  99696. #endif
  99697. /* first do max_partition_order */
  99698. {
  99699. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  99700. /* slightly pessimistic but still catches all common cases */
  99701. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  99702. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  99703. FLAC__uint32 abs_residual_partition_sum;
  99704. for(partition = residual_sample = 0; partition < partitions; partition++) {
  99705. end += default_partition_samples;
  99706. abs_residual_partition_sum = 0;
  99707. for( ; residual_sample < end; residual_sample++)
  99708. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  99709. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  99710. }
  99711. }
  99712. else { /* have to pessimistically use 64 bits for accumulator */
  99713. FLAC__uint64 abs_residual_partition_sum;
  99714. for(partition = residual_sample = 0; partition < partitions; partition++) {
  99715. end += default_partition_samples;
  99716. abs_residual_partition_sum = 0;
  99717. for( ; residual_sample < end; residual_sample++)
  99718. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  99719. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  99720. }
  99721. }
  99722. }
  99723. /* now merge partitions for lower orders */
  99724. {
  99725. unsigned from_partition = 0, to_partition = partitions;
  99726. int partition_order;
  99727. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  99728. unsigned i;
  99729. partitions >>= 1;
  99730. for(i = 0; i < partitions; i++) {
  99731. abs_residual_partition_sums[to_partition++] =
  99732. abs_residual_partition_sums[from_partition ] +
  99733. abs_residual_partition_sums[from_partition+1];
  99734. from_partition += 2;
  99735. }
  99736. }
  99737. }
  99738. }
  99739. void precompute_partition_info_escapes_(
  99740. const FLAC__int32 residual[],
  99741. unsigned raw_bits_per_partition[],
  99742. unsigned residual_samples,
  99743. unsigned predictor_order,
  99744. unsigned min_partition_order,
  99745. unsigned max_partition_order
  99746. )
  99747. {
  99748. int partition_order;
  99749. unsigned from_partition, to_partition = 0;
  99750. const unsigned blocksize = residual_samples + predictor_order;
  99751. /* first do max_partition_order */
  99752. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  99753. FLAC__int32 r;
  99754. FLAC__uint32 rmax;
  99755. unsigned partition, partition_sample, partition_samples, residual_sample;
  99756. const unsigned partitions = 1u << partition_order;
  99757. const unsigned default_partition_samples = blocksize >> partition_order;
  99758. FLAC__ASSERT(default_partition_samples > predictor_order);
  99759. for(partition = residual_sample = 0; partition < partitions; partition++) {
  99760. partition_samples = default_partition_samples;
  99761. if(partition == 0)
  99762. partition_samples -= predictor_order;
  99763. rmax = 0;
  99764. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  99765. r = residual[residual_sample++];
  99766. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  99767. if(r < 0)
  99768. rmax |= ~r;
  99769. else
  99770. rmax |= r;
  99771. }
  99772. /* now we know all residual values are in the range [-rmax-1,rmax] */
  99773. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  99774. }
  99775. to_partition = partitions;
  99776. break; /*@@@ yuck, should remove the 'for' loop instead */
  99777. }
  99778. /* now merge partitions for lower orders */
  99779. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  99780. unsigned m;
  99781. unsigned i;
  99782. const unsigned partitions = 1u << partition_order;
  99783. for(i = 0; i < partitions; i++) {
  99784. m = raw_bits_per_partition[from_partition];
  99785. from_partition++;
  99786. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  99787. from_partition++;
  99788. to_partition++;
  99789. }
  99790. }
  99791. }
  99792. #ifdef EXACT_RICE_BITS_CALCULATION
  99793. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  99794. const unsigned rice_parameter,
  99795. const unsigned partition_samples,
  99796. const FLAC__int32 *residual
  99797. )
  99798. {
  99799. unsigned i, partition_bits =
  99800. 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 */
  99801. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  99802. ;
  99803. for(i = 0; i < partition_samples; i++)
  99804. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  99805. return partition_bits;
  99806. }
  99807. #else
  99808. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  99809. const unsigned rice_parameter,
  99810. const unsigned partition_samples,
  99811. const FLAC__uint64 abs_residual_partition_sum
  99812. )
  99813. {
  99814. return
  99815. 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 */
  99816. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  99817. (
  99818. rice_parameter?
  99819. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  99820. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  99821. )
  99822. - (partition_samples >> 1)
  99823. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  99824. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  99825. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  99826. * So the subtraction term tries to guess how many extra bits were contributed.
  99827. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  99828. */
  99829. ;
  99830. }
  99831. #endif
  99832. FLAC__bool set_partitioned_rice_(
  99833. #ifdef EXACT_RICE_BITS_CALCULATION
  99834. const FLAC__int32 residual[],
  99835. #endif
  99836. const FLAC__uint64 abs_residual_partition_sums[],
  99837. const unsigned raw_bits_per_partition[],
  99838. const unsigned residual_samples,
  99839. const unsigned predictor_order,
  99840. const unsigned suggested_rice_parameter,
  99841. const unsigned rice_parameter_limit,
  99842. const unsigned rice_parameter_search_dist,
  99843. const unsigned partition_order,
  99844. const FLAC__bool search_for_escapes,
  99845. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  99846. unsigned *bits
  99847. )
  99848. {
  99849. unsigned rice_parameter, partition_bits;
  99850. unsigned best_partition_bits, best_rice_parameter = 0;
  99851. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  99852. unsigned *parameters, *raw_bits;
  99853. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99854. unsigned min_rice_parameter, max_rice_parameter;
  99855. #else
  99856. (void)rice_parameter_search_dist;
  99857. #endif
  99858. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  99859. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  99860. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  99861. parameters = partitioned_rice_contents->parameters;
  99862. raw_bits = partitioned_rice_contents->raw_bits;
  99863. if(partition_order == 0) {
  99864. best_partition_bits = (unsigned)(-1);
  99865. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99866. if(rice_parameter_search_dist) {
  99867. if(suggested_rice_parameter < rice_parameter_search_dist)
  99868. min_rice_parameter = 0;
  99869. else
  99870. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  99871. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  99872. if(max_rice_parameter >= rice_parameter_limit) {
  99873. #ifdef DEBUG_VERBOSE
  99874. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  99875. #endif
  99876. max_rice_parameter = rice_parameter_limit - 1;
  99877. }
  99878. }
  99879. else
  99880. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  99881. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  99882. #else
  99883. rice_parameter = suggested_rice_parameter;
  99884. #endif
  99885. #ifdef EXACT_RICE_BITS_CALCULATION
  99886. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  99887. #else
  99888. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  99889. #endif
  99890. if(partition_bits < best_partition_bits) {
  99891. best_rice_parameter = rice_parameter;
  99892. best_partition_bits = partition_bits;
  99893. }
  99894. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99895. }
  99896. #endif
  99897. if(search_for_escapes) {
  99898. 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;
  99899. if(partition_bits <= best_partition_bits) {
  99900. raw_bits[0] = raw_bits_per_partition[0];
  99901. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  99902. best_partition_bits = partition_bits;
  99903. }
  99904. else
  99905. raw_bits[0] = 0;
  99906. }
  99907. parameters[0] = best_rice_parameter;
  99908. bits_ += best_partition_bits;
  99909. }
  99910. else {
  99911. unsigned partition, residual_sample;
  99912. unsigned partition_samples;
  99913. FLAC__uint64 mean, k;
  99914. const unsigned partitions = 1u << partition_order;
  99915. for(partition = residual_sample = 0; partition < partitions; partition++) {
  99916. partition_samples = (residual_samples+predictor_order) >> partition_order;
  99917. if(partition == 0) {
  99918. if(partition_samples <= predictor_order)
  99919. return false;
  99920. else
  99921. partition_samples -= predictor_order;
  99922. }
  99923. mean = abs_residual_partition_sums[partition];
  99924. /* we are basically calculating the size in bits of the
  99925. * average residual magnitude in the partition:
  99926. * rice_parameter = floor(log2(mean/partition_samples))
  99927. * 'mean' is not a good name for the variable, it is
  99928. * actually the sum of magnitudes of all residual values
  99929. * in the partition, so the actual mean is
  99930. * mean/partition_samples
  99931. */
  99932. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  99933. ;
  99934. if(rice_parameter >= rice_parameter_limit) {
  99935. #ifdef DEBUG_VERBOSE
  99936. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  99937. #endif
  99938. rice_parameter = rice_parameter_limit - 1;
  99939. }
  99940. best_partition_bits = (unsigned)(-1);
  99941. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99942. if(rice_parameter_search_dist) {
  99943. if(rice_parameter < rice_parameter_search_dist)
  99944. min_rice_parameter = 0;
  99945. else
  99946. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  99947. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  99948. if(max_rice_parameter >= rice_parameter_limit) {
  99949. #ifdef DEBUG_VERBOSE
  99950. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  99951. #endif
  99952. max_rice_parameter = rice_parameter_limit - 1;
  99953. }
  99954. }
  99955. else
  99956. min_rice_parameter = max_rice_parameter = rice_parameter;
  99957. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  99958. #endif
  99959. #ifdef EXACT_RICE_BITS_CALCULATION
  99960. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  99961. #else
  99962. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  99963. #endif
  99964. if(partition_bits < best_partition_bits) {
  99965. best_rice_parameter = rice_parameter;
  99966. best_partition_bits = partition_bits;
  99967. }
  99968. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99969. }
  99970. #endif
  99971. if(search_for_escapes) {
  99972. 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;
  99973. if(partition_bits <= best_partition_bits) {
  99974. raw_bits[partition] = raw_bits_per_partition[partition];
  99975. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  99976. best_partition_bits = partition_bits;
  99977. }
  99978. else
  99979. raw_bits[partition] = 0;
  99980. }
  99981. parameters[partition] = best_rice_parameter;
  99982. bits_ += best_partition_bits;
  99983. residual_sample += partition_samples;
  99984. }
  99985. }
  99986. *bits = bits_;
  99987. return true;
  99988. }
  99989. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  99990. {
  99991. unsigned i, shift;
  99992. FLAC__int32 x = 0;
  99993. for(i = 0; i < samples && !(x&1); i++)
  99994. x |= signal[i];
  99995. if(x == 0) {
  99996. shift = 0;
  99997. }
  99998. else {
  99999. for(shift = 0; !(x&1); shift++)
  100000. x >>= 1;
  100001. }
  100002. if(shift > 0) {
  100003. for(i = 0; i < samples; i++)
  100004. signal[i] >>= shift;
  100005. }
  100006. return shift;
  100007. }
  100008. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  100009. {
  100010. unsigned channel;
  100011. for(channel = 0; channel < channels; channel++)
  100012. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  100013. fifo->tail += wide_samples;
  100014. FLAC__ASSERT(fifo->tail <= fifo->size);
  100015. }
  100016. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  100017. {
  100018. unsigned channel;
  100019. unsigned sample, wide_sample;
  100020. unsigned tail = fifo->tail;
  100021. sample = input_offset * channels;
  100022. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  100023. for(channel = 0; channel < channels; channel++)
  100024. fifo->data[channel][tail] = input[sample++];
  100025. tail++;
  100026. }
  100027. fifo->tail = tail;
  100028. FLAC__ASSERT(fifo->tail <= fifo->size);
  100029. }
  100030. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  100031. {
  100032. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  100033. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  100034. (void)decoder;
  100035. if(encoder->private_->verify.needs_magic_hack) {
  100036. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  100037. *bytes = FLAC__STREAM_SYNC_LENGTH;
  100038. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  100039. encoder->private_->verify.needs_magic_hack = false;
  100040. }
  100041. else {
  100042. if(encoded_bytes == 0) {
  100043. /*
  100044. * If we get here, a FIFO underflow has occurred,
  100045. * which means there is a bug somewhere.
  100046. */
  100047. FLAC__ASSERT(0);
  100048. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  100049. }
  100050. else if(encoded_bytes < *bytes)
  100051. *bytes = encoded_bytes;
  100052. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  100053. encoder->private_->verify.output.data += *bytes;
  100054. encoder->private_->verify.output.bytes -= *bytes;
  100055. }
  100056. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100057. }
  100058. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  100059. {
  100060. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  100061. unsigned channel;
  100062. const unsigned channels = frame->header.channels;
  100063. const unsigned blocksize = frame->header.blocksize;
  100064. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  100065. (void)decoder;
  100066. for(channel = 0; channel < channels; channel++) {
  100067. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  100068. unsigned i, sample = 0;
  100069. FLAC__int32 expect = 0, got = 0;
  100070. for(i = 0; i < blocksize; i++) {
  100071. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  100072. sample = i;
  100073. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  100074. got = (FLAC__int32)buffer[channel][i];
  100075. break;
  100076. }
  100077. }
  100078. FLAC__ASSERT(i < blocksize);
  100079. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100080. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  100081. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  100082. encoder->private_->verify.error_stats.channel = channel;
  100083. encoder->private_->verify.error_stats.sample = sample;
  100084. encoder->private_->verify.error_stats.expected = expect;
  100085. encoder->private_->verify.error_stats.got = got;
  100086. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  100087. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  100088. }
  100089. }
  100090. /* dequeue the frame from the fifo */
  100091. encoder->private_->verify.input_fifo.tail -= blocksize;
  100092. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  100093. for(channel = 0; channel < channels; channel++)
  100094. 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]));
  100095. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  100096. }
  100097. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  100098. {
  100099. (void)decoder, (void)metadata, (void)client_data;
  100100. }
  100101. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  100102. {
  100103. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  100104. (void)decoder, (void)status;
  100105. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  100106. }
  100107. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  100108. {
  100109. (void)client_data;
  100110. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  100111. if (*bytes == 0) {
  100112. if (feof(encoder->private_->file))
  100113. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  100114. else if (ferror(encoder->private_->file))
  100115. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  100116. }
  100117. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  100118. }
  100119. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  100120. {
  100121. (void)client_data;
  100122. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  100123. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  100124. else
  100125. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  100126. }
  100127. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  100128. {
  100129. off_t offset;
  100130. (void)client_data;
  100131. offset = ftello(encoder->private_->file);
  100132. if(offset < 0) {
  100133. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  100134. }
  100135. else {
  100136. *absolute_byte_offset = (FLAC__uint64)offset;
  100137. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  100138. }
  100139. }
  100140. #ifdef FLAC__VALGRIND_TESTING
  100141. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  100142. {
  100143. size_t ret = fwrite(ptr, size, nmemb, stream);
  100144. if(!ferror(stream))
  100145. fflush(stream);
  100146. return ret;
  100147. }
  100148. #else
  100149. #define local__fwrite fwrite
  100150. #endif
  100151. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  100152. {
  100153. (void)client_data, (void)current_frame;
  100154. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  100155. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  100156. #if FLAC__HAS_OGG
  100157. /* We would like to be able to use 'samples > 0' in the
  100158. * clause here but currently because of the nature of our
  100159. * Ogg writing implementation, 'samples' is always 0 (see
  100160. * ogg_encoder_aspect.c). The downside is extra progress
  100161. * callbacks.
  100162. */
  100163. encoder->private_->is_ogg? true :
  100164. #endif
  100165. samples > 0
  100166. );
  100167. if(call_it) {
  100168. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  100169. * because at this point in the callback chain, the stats
  100170. * have not been updated. Only after we return and control
  100171. * gets back to write_frame_() are the stats updated
  100172. */
  100173. 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);
  100174. }
  100175. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  100176. }
  100177. else
  100178. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  100179. }
  100180. /*
  100181. * This will forcibly set stdout to binary mode (for OSes that require it)
  100182. */
  100183. FILE *get_binary_stdout_(void)
  100184. {
  100185. /* if something breaks here it is probably due to the presence or
  100186. * absence of an underscore before the identifiers 'setmode',
  100187. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100188. */
  100189. #if defined _MSC_VER || defined __MINGW32__
  100190. _setmode(_fileno(stdout), _O_BINARY);
  100191. #elif defined __CYGWIN__
  100192. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100193. setmode(_fileno(stdout), _O_BINARY);
  100194. #elif defined __EMX__
  100195. setmode(fileno(stdout), O_BINARY);
  100196. #endif
  100197. return stdout;
  100198. }
  100199. #endif
  100200. /********* End of inlined file: stream_encoder.c *********/
  100201. /********* Start of inlined file: stream_encoder_framing.c *********/
  100202. /********* Start of inlined file: juce_FlacHeader.h *********/
  100203. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  100204. // tasks..
  100205. #define VERSION "1.2.1"
  100206. #define FLAC__NO_DLL 1
  100207. #ifdef _MSC_VER
  100208. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  100209. #endif
  100210. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  100211. #define FLAC__SYS_DARWIN 1
  100212. #endif
  100213. /********* End of inlined file: juce_FlacHeader.h *********/
  100214. #if JUCE_USE_FLAC
  100215. #if HAVE_CONFIG_H
  100216. # include <config.h>
  100217. #endif
  100218. #include <stdio.h>
  100219. #include <string.h> /* for strlen() */
  100220. #ifdef max
  100221. #undef max
  100222. #endif
  100223. #define max(x,y) ((x)>(y)?(x):(y))
  100224. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  100225. 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);
  100226. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  100227. {
  100228. unsigned i, j;
  100229. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  100230. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100231. return false;
  100232. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  100233. return false;
  100234. /*
  100235. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  100236. */
  100237. i = metadata->length;
  100238. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  100239. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  100240. i -= metadata->data.vorbis_comment.vendor_string.length;
  100241. i += vendor_string_length;
  100242. }
  100243. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  100244. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  100245. return false;
  100246. switch(metadata->type) {
  100247. case FLAC__METADATA_TYPE_STREAMINFO:
  100248. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  100249. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  100250. return false;
  100251. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  100252. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100253. return false;
  100254. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  100255. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100256. return false;
  100257. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  100258. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100259. return false;
  100260. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  100261. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100262. return false;
  100263. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  100264. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  100265. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100266. return false;
  100267. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  100268. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  100269. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100270. return false;
  100271. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  100272. return false;
  100273. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  100274. return false;
  100275. break;
  100276. case FLAC__METADATA_TYPE_PADDING:
  100277. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  100278. return false;
  100279. break;
  100280. case FLAC__METADATA_TYPE_APPLICATION:
  100281. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  100282. return false;
  100283. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  100284. return false;
  100285. break;
  100286. case FLAC__METADATA_TYPE_SEEKTABLE:
  100287. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  100288. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100289. return false;
  100290. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100291. return false;
  100292. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100293. return false;
  100294. }
  100295. break;
  100296. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100297. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  100298. return false;
  100299. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  100300. return false;
  100301. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  100302. return false;
  100303. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  100304. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  100305. return false;
  100306. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  100307. return false;
  100308. }
  100309. break;
  100310. case FLAC__METADATA_TYPE_CUESHEET:
  100311. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100312. 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))
  100313. return false;
  100314. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100315. return false;
  100316. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100317. return false;
  100318. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100319. return false;
  100320. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100321. return false;
  100322. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  100323. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  100324. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100325. return false;
  100326. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100327. return false;
  100328. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100329. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100330. return false;
  100331. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100332. return false;
  100333. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100334. return false;
  100335. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100336. return false;
  100337. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100338. return false;
  100339. for(j = 0; j < track->num_indices; j++) {
  100340. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  100341. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100342. return false;
  100343. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100344. return false;
  100345. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100346. return false;
  100347. }
  100348. }
  100349. break;
  100350. case FLAC__METADATA_TYPE_PICTURE:
  100351. {
  100352. size_t len;
  100353. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100354. return false;
  100355. len = strlen(metadata->data.picture.mime_type);
  100356. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100357. return false;
  100358. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  100359. return false;
  100360. len = strlen((const char *)metadata->data.picture.description);
  100361. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100362. return false;
  100363. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  100364. return false;
  100365. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100366. return false;
  100367. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100368. return false;
  100369. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100370. return false;
  100371. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100372. return false;
  100373. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100374. return false;
  100375. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  100376. return false;
  100377. }
  100378. break;
  100379. default:
  100380. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  100381. return false;
  100382. break;
  100383. }
  100384. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  100385. return true;
  100386. }
  100387. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  100388. {
  100389. unsigned u, blocksize_hint, sample_rate_hint;
  100390. FLAC__byte crc;
  100391. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  100392. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  100393. return false;
  100394. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  100395. return false;
  100396. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  100397. return false;
  100398. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  100399. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  100400. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  100401. blocksize_hint = 0;
  100402. switch(header->blocksize) {
  100403. case 192: u = 1; break;
  100404. case 576: u = 2; break;
  100405. case 1152: u = 3; break;
  100406. case 2304: u = 4; break;
  100407. case 4608: u = 5; break;
  100408. case 256: u = 8; break;
  100409. case 512: u = 9; break;
  100410. case 1024: u = 10; break;
  100411. case 2048: u = 11; break;
  100412. case 4096: u = 12; break;
  100413. case 8192: u = 13; break;
  100414. case 16384: u = 14; break;
  100415. case 32768: u = 15; break;
  100416. default:
  100417. if(header->blocksize <= 0x100)
  100418. blocksize_hint = u = 6;
  100419. else
  100420. blocksize_hint = u = 7;
  100421. break;
  100422. }
  100423. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  100424. return false;
  100425. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  100426. sample_rate_hint = 0;
  100427. switch(header->sample_rate) {
  100428. case 88200: u = 1; break;
  100429. case 176400: u = 2; break;
  100430. case 192000: u = 3; break;
  100431. case 8000: u = 4; break;
  100432. case 16000: u = 5; break;
  100433. case 22050: u = 6; break;
  100434. case 24000: u = 7; break;
  100435. case 32000: u = 8; break;
  100436. case 44100: u = 9; break;
  100437. case 48000: u = 10; break;
  100438. case 96000: u = 11; break;
  100439. default:
  100440. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  100441. sample_rate_hint = u = 12;
  100442. else if(header->sample_rate % 10 == 0)
  100443. sample_rate_hint = u = 14;
  100444. else if(header->sample_rate <= 0xffff)
  100445. sample_rate_hint = u = 13;
  100446. else
  100447. u = 0;
  100448. break;
  100449. }
  100450. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  100451. return false;
  100452. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  100453. switch(header->channel_assignment) {
  100454. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100455. u = header->channels - 1;
  100456. break;
  100457. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100458. FLAC__ASSERT(header->channels == 2);
  100459. u = 8;
  100460. break;
  100461. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100462. FLAC__ASSERT(header->channels == 2);
  100463. u = 9;
  100464. break;
  100465. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100466. FLAC__ASSERT(header->channels == 2);
  100467. u = 10;
  100468. break;
  100469. default:
  100470. FLAC__ASSERT(0);
  100471. }
  100472. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  100473. return false;
  100474. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  100475. switch(header->bits_per_sample) {
  100476. case 8 : u = 1; break;
  100477. case 12: u = 2; break;
  100478. case 16: u = 4; break;
  100479. case 20: u = 5; break;
  100480. case 24: u = 6; break;
  100481. default: u = 0; break;
  100482. }
  100483. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  100484. return false;
  100485. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  100486. return false;
  100487. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  100488. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  100489. return false;
  100490. }
  100491. else {
  100492. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  100493. return false;
  100494. }
  100495. if(blocksize_hint)
  100496. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  100497. return false;
  100498. switch(sample_rate_hint) {
  100499. case 12:
  100500. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  100501. return false;
  100502. break;
  100503. case 13:
  100504. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  100505. return false;
  100506. break;
  100507. case 14:
  100508. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  100509. return false;
  100510. break;
  100511. }
  100512. /* write the CRC */
  100513. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  100514. return false;
  100515. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  100516. return false;
  100517. return true;
  100518. }
  100519. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  100520. {
  100521. FLAC__bool ok;
  100522. ok =
  100523. 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) &&
  100524. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  100525. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  100526. ;
  100527. return ok;
  100528. }
  100529. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  100530. {
  100531. unsigned i;
  100532. 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))
  100533. return false;
  100534. if(wasted_bits)
  100535. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  100536. return false;
  100537. for(i = 0; i < subframe->order; i++)
  100538. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  100539. return false;
  100540. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  100541. return false;
  100542. switch(subframe->entropy_coding_method.type) {
  100543. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100544. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100545. if(!add_residual_partitioned_rice_(
  100546. bw,
  100547. subframe->residual,
  100548. residual_samples,
  100549. subframe->order,
  100550. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  100551. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  100552. subframe->entropy_coding_method.data.partitioned_rice.order,
  100553. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  100554. ))
  100555. return false;
  100556. break;
  100557. default:
  100558. FLAC__ASSERT(0);
  100559. }
  100560. return true;
  100561. }
  100562. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  100563. {
  100564. unsigned i;
  100565. 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))
  100566. return false;
  100567. if(wasted_bits)
  100568. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  100569. return false;
  100570. for(i = 0; i < subframe->order; i++)
  100571. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  100572. return false;
  100573. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  100574. return false;
  100575. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  100576. return false;
  100577. for(i = 0; i < subframe->order; i++)
  100578. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  100579. return false;
  100580. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  100581. return false;
  100582. switch(subframe->entropy_coding_method.type) {
  100583. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100584. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100585. if(!add_residual_partitioned_rice_(
  100586. bw,
  100587. subframe->residual,
  100588. residual_samples,
  100589. subframe->order,
  100590. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  100591. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  100592. subframe->entropy_coding_method.data.partitioned_rice.order,
  100593. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  100594. ))
  100595. return false;
  100596. break;
  100597. default:
  100598. FLAC__ASSERT(0);
  100599. }
  100600. return true;
  100601. }
  100602. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  100603. {
  100604. unsigned i;
  100605. const FLAC__int32 *signal = subframe->data;
  100606. 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))
  100607. return false;
  100608. if(wasted_bits)
  100609. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  100610. return false;
  100611. for(i = 0; i < samples; i++)
  100612. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  100613. return false;
  100614. return true;
  100615. }
  100616. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  100617. {
  100618. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100619. return false;
  100620. switch(method->type) {
  100621. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100622. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100623. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100624. return false;
  100625. break;
  100626. default:
  100627. FLAC__ASSERT(0);
  100628. }
  100629. return true;
  100630. }
  100631. 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)
  100632. {
  100633. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  100634. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  100635. if(partition_order == 0) {
  100636. unsigned i;
  100637. if(raw_bits[0] == 0) {
  100638. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  100639. return false;
  100640. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  100641. return false;
  100642. }
  100643. else {
  100644. FLAC__ASSERT(rice_parameters[0] == 0);
  100645. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  100646. return false;
  100647. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  100648. return false;
  100649. for(i = 0; i < residual_samples; i++) {
  100650. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  100651. return false;
  100652. }
  100653. }
  100654. return true;
  100655. }
  100656. else {
  100657. unsigned i, j, k = 0, k_last = 0;
  100658. unsigned partition_samples;
  100659. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  100660. for(i = 0; i < (1u<<partition_order); i++) {
  100661. partition_samples = default_partition_samples;
  100662. if(i == 0)
  100663. partition_samples -= predictor_order;
  100664. k += partition_samples;
  100665. if(raw_bits[i] == 0) {
  100666. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  100667. return false;
  100668. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  100669. return false;
  100670. }
  100671. else {
  100672. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  100673. return false;
  100674. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  100675. return false;
  100676. for(j = k_last; j < k; j++) {
  100677. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  100678. return false;
  100679. }
  100680. }
  100681. k_last = k;
  100682. }
  100683. return true;
  100684. }
  100685. }
  100686. #endif
  100687. /********* End of inlined file: stream_encoder_framing.c *********/
  100688. /********* Start of inlined file: window_flac.c *********/
  100689. /********* Start of inlined file: juce_FlacHeader.h *********/
  100690. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  100691. // tasks..
  100692. #define VERSION "1.2.1"
  100693. #define FLAC__NO_DLL 1
  100694. #ifdef _MSC_VER
  100695. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  100696. #endif
  100697. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  100698. #define FLAC__SYS_DARWIN 1
  100699. #endif
  100700. /********* End of inlined file: juce_FlacHeader.h *********/
  100701. #if JUCE_USE_FLAC
  100702. #if HAVE_CONFIG_H
  100703. # include <config.h>
  100704. #endif
  100705. #include <math.h>
  100706. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100707. #ifndef M_PI
  100708. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  100709. #define M_PI 3.14159265358979323846
  100710. #endif
  100711. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  100712. {
  100713. const FLAC__int32 N = L - 1;
  100714. FLAC__int32 n;
  100715. if (L & 1) {
  100716. for (n = 0; n <= N/2; n++)
  100717. window[n] = 2.0f * n / (float)N;
  100718. for (; n <= N; n++)
  100719. window[n] = 2.0f - 2.0f * n / (float)N;
  100720. }
  100721. else {
  100722. for (n = 0; n <= L/2-1; n++)
  100723. window[n] = 2.0f * n / (float)N;
  100724. for (; n <= N; n++)
  100725. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  100726. }
  100727. }
  100728. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  100729. {
  100730. const FLAC__int32 N = L - 1;
  100731. FLAC__int32 n;
  100732. for (n = 0; n < L; n++)
  100733. 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)));
  100734. }
  100735. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  100736. {
  100737. const FLAC__int32 N = L - 1;
  100738. FLAC__int32 n;
  100739. for (n = 0; n < L; n++)
  100740. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  100741. }
  100742. /* 4-term -92dB side-lobe */
  100743. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  100744. {
  100745. const FLAC__int32 N = L - 1;
  100746. FLAC__int32 n;
  100747. for (n = 0; n <= N; n++)
  100748. 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));
  100749. }
  100750. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  100751. {
  100752. const FLAC__int32 N = L - 1;
  100753. const double N2 = (double)N / 2.;
  100754. FLAC__int32 n;
  100755. for (n = 0; n <= N; n++) {
  100756. double k = ((double)n - N2) / N2;
  100757. k = 1.0f - k * k;
  100758. window[n] = (FLAC__real)(k * k);
  100759. }
  100760. }
  100761. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  100762. {
  100763. const FLAC__int32 N = L - 1;
  100764. FLAC__int32 n;
  100765. for (n = 0; n < L; n++)
  100766. 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));
  100767. }
  100768. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  100769. {
  100770. const FLAC__int32 N = L - 1;
  100771. const double N2 = (double)N / 2.;
  100772. FLAC__int32 n;
  100773. for (n = 0; n <= N; n++) {
  100774. const double k = ((double)n - N2) / (stddev * N2);
  100775. window[n] = (FLAC__real)exp(-0.5f * k * k);
  100776. }
  100777. }
  100778. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  100779. {
  100780. const FLAC__int32 N = L - 1;
  100781. FLAC__int32 n;
  100782. for (n = 0; n < L; n++)
  100783. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  100784. }
  100785. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  100786. {
  100787. const FLAC__int32 N = L - 1;
  100788. FLAC__int32 n;
  100789. for (n = 0; n < L; n++)
  100790. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  100791. }
  100792. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  100793. {
  100794. const FLAC__int32 N = L - 1;
  100795. FLAC__int32 n;
  100796. for (n = 0; n < L; n++)
  100797. 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));
  100798. }
  100799. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  100800. {
  100801. const FLAC__int32 N = L - 1;
  100802. FLAC__int32 n;
  100803. for (n = 0; n < L; n++)
  100804. 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));
  100805. }
  100806. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  100807. {
  100808. FLAC__int32 n;
  100809. for (n = 0; n < L; n++)
  100810. window[n] = 1.0f;
  100811. }
  100812. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  100813. {
  100814. FLAC__int32 n;
  100815. if (L & 1) {
  100816. for (n = 1; n <= L+1/2; n++)
  100817. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  100818. for (; n <= L; n++)
  100819. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  100820. }
  100821. else {
  100822. for (n = 1; n <= L/2; n++)
  100823. window[n-1] = 2.0f * n / (float)L;
  100824. for (; n <= L; n++)
  100825. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  100826. }
  100827. }
  100828. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  100829. {
  100830. if (p <= 0.0)
  100831. FLAC__window_rectangle(window, L);
  100832. else if (p >= 1.0)
  100833. FLAC__window_hann(window, L);
  100834. else {
  100835. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  100836. FLAC__int32 n;
  100837. /* start with rectangle... */
  100838. FLAC__window_rectangle(window, L);
  100839. /* ...replace ends with hann */
  100840. if (Np > 0) {
  100841. for (n = 0; n <= Np; n++) {
  100842. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  100843. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  100844. }
  100845. }
  100846. }
  100847. }
  100848. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  100849. {
  100850. const FLAC__int32 N = L - 1;
  100851. const double N2 = (double)N / 2.;
  100852. FLAC__int32 n;
  100853. for (n = 0; n <= N; n++) {
  100854. const double k = ((double)n - N2) / N2;
  100855. window[n] = (FLAC__real)(1.0f - k * k);
  100856. }
  100857. }
  100858. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  100859. #endif
  100860. /********* End of inlined file: window_flac.c *********/
  100861. }
  100862. #ifdef _MSC_VER
  100863. #pragma warning (pop)
  100864. #endif
  100865. BEGIN_JUCE_NAMESPACE
  100866. using namespace FlacNamespace;
  100867. #define flacFormatName TRANS("FLAC file")
  100868. static const tchar* const flacExtensions[] = { T(".flac"), 0 };
  100869. class FlacReader : public AudioFormatReader
  100870. {
  100871. FLAC__StreamDecoder* decoder;
  100872. AudioSampleBuffer reservoir;
  100873. int reservoirStart, samplesInReservoir;
  100874. bool ok, scanningForLength;
  100875. public:
  100876. FlacReader (InputStream* const in)
  100877. : AudioFormatReader (in, flacFormatName),
  100878. reservoir (2, 0),
  100879. reservoirStart (0),
  100880. samplesInReservoir (0),
  100881. scanningForLength (false)
  100882. {
  100883. using namespace FlacNamespace;
  100884. lengthInSamples = 0;
  100885. decoder = FLAC__stream_decoder_new();
  100886. ok = FLAC__stream_decoder_init_stream (decoder,
  100887. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  100888. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  100889. (void*) this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  100890. if (ok)
  100891. {
  100892. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  100893. if (lengthInSamples == 0 && sampleRate > 0)
  100894. {
  100895. // the length hasn't been stored in the metadata, so we'll need to
  100896. // work it out the length the hard way, by scanning the whole file..
  100897. scanningForLength = true;
  100898. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  100899. scanningForLength = false;
  100900. const int64 tempLength = lengthInSamples;
  100901. FLAC__stream_decoder_reset (decoder);
  100902. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  100903. lengthInSamples = tempLength;
  100904. }
  100905. }
  100906. }
  100907. ~FlacReader()
  100908. {
  100909. FLAC__stream_decoder_delete (decoder);
  100910. }
  100911. void useMetadata (const FLAC__StreamMetadata_StreamInfo& info)
  100912. {
  100913. sampleRate = info.sample_rate;
  100914. bitsPerSample = info.bits_per_sample;
  100915. lengthInSamples = (unsigned int) info.total_samples;
  100916. numChannels = info.channels;
  100917. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  100918. }
  100919. // returns the number of samples read
  100920. bool read (int** destSamples,
  100921. int64 startSampleInFile,
  100922. int numSamples)
  100923. {
  100924. using namespace FlacNamespace;
  100925. if (! ok)
  100926. return false;
  100927. int offset = 0;
  100928. if (startSampleInFile < 0)
  100929. {
  100930. const int num = (int) jmin ((int64) numSamples, -startSampleInFile);
  100931. int n = 0;
  100932. while (destSamples[n] != 0)
  100933. {
  100934. zeromem (destSamples[n], sizeof (int) * num);
  100935. ++n;
  100936. }
  100937. offset += num;
  100938. startSampleInFile += num;
  100939. numSamples -= num;
  100940. }
  100941. while (numSamples > 0)
  100942. {
  100943. if (startSampleInFile >= reservoirStart
  100944. && startSampleInFile < reservoirStart + samplesInReservoir)
  100945. {
  100946. const int num = (int) jmin ((int64) numSamples,
  100947. reservoirStart + samplesInReservoir - startSampleInFile);
  100948. jassert (num > 0);
  100949. int n = 0;
  100950. while (destSamples[n] != 0)
  100951. {
  100952. memcpy (destSamples[n] + offset,
  100953. reservoir.getSampleData (n, (int) (startSampleInFile - reservoirStart)),
  100954. sizeof (int) * num);
  100955. ++n;
  100956. }
  100957. offset += num;
  100958. startSampleInFile += num;
  100959. numSamples -= num;
  100960. }
  100961. else
  100962. {
  100963. if (startSampleInFile < reservoirStart
  100964. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  100965. {
  100966. if (startSampleInFile >= (int) lengthInSamples)
  100967. {
  100968. samplesInReservoir = 0;
  100969. break;
  100970. }
  100971. // had some problems with flac crashing if the read pos is aligned more
  100972. // accurately than this. Probably fixed in newer versions of the library, though.
  100973. reservoirStart = (int) (startSampleInFile & ~511);
  100974. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  100975. }
  100976. else
  100977. {
  100978. reservoirStart += samplesInReservoir;
  100979. }
  100980. samplesInReservoir = 0;
  100981. FLAC__stream_decoder_process_single (decoder);
  100982. if (samplesInReservoir == 0)
  100983. break;
  100984. }
  100985. }
  100986. if (numSamples > 0)
  100987. {
  100988. int n = 0;
  100989. while (destSamples[n] != 0)
  100990. {
  100991. zeromem (destSamples[n] + offset, sizeof (int) * numSamples);
  100992. ++n;
  100993. }
  100994. }
  100995. return true;
  100996. }
  100997. void useSamples (const FLAC__int32* const buffer[], int numSamples)
  100998. {
  100999. if (scanningForLength)
  101000. {
  101001. lengthInSamples += numSamples;
  101002. }
  101003. else
  101004. {
  101005. if (numSamples > reservoir.getNumSamples())
  101006. reservoir.setSize (numChannels, numSamples, false, false, true);
  101007. const int bitsToShift = 32 - bitsPerSample;
  101008. for (int i = 0; i < (int) numChannels; ++i)
  101009. {
  101010. const FLAC__int32* src = buffer[i];
  101011. int n = i;
  101012. while (src == 0 && n > 0)
  101013. src = buffer [--n];
  101014. if (src != 0)
  101015. {
  101016. int* dest = (int*) reservoir.getSampleData(i);
  101017. for (int j = 0; j < numSamples; ++j)
  101018. dest[j] = src[j] << bitsToShift;
  101019. }
  101020. }
  101021. samplesInReservoir = numSamples;
  101022. }
  101023. }
  101024. static FLAC__StreamDecoderReadStatus readCallback_ (const FLAC__StreamDecoder*, FLAC__byte buffer[], size_t* bytes, void* client_data)
  101025. {
  101026. *bytes = (unsigned int) ((const FlacReader*) client_data)->input->read (buffer, (int) *bytes);
  101027. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101028. }
  101029. static FLAC__StreamDecoderSeekStatus seekCallback_ (const FLAC__StreamDecoder*, FLAC__uint64 absolute_byte_offset, void* client_data)
  101030. {
  101031. ((const FlacReader*) client_data)->input->setPosition ((int) absolute_byte_offset);
  101032. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101033. }
  101034. static FLAC__StreamDecoderTellStatus tellCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* absolute_byte_offset, void* client_data)
  101035. {
  101036. *absolute_byte_offset = ((const FlacReader*) client_data)->input->getPosition();
  101037. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101038. }
  101039. static FLAC__StreamDecoderLengthStatus lengthCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* stream_length, void* client_data)
  101040. {
  101041. *stream_length = ((const FlacReader*) client_data)->input->getTotalLength();
  101042. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101043. }
  101044. static FLAC__bool eofCallback_ (const FLAC__StreamDecoder*, void* client_data)
  101045. {
  101046. return ((const FlacReader*) client_data)->input->isExhausted();
  101047. }
  101048. static FLAC__StreamDecoderWriteStatus writeCallback_ (const FLAC__StreamDecoder*,
  101049. const FLAC__Frame* frame,
  101050. const FLAC__int32* const buffer[],
  101051. void* client_data)
  101052. {
  101053. ((FlacReader*) client_data)->useSamples (buffer, frame->header.blocksize);
  101054. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101055. }
  101056. static void metadataCallback_ (const FLAC__StreamDecoder*,
  101057. const FLAC__StreamMetadata* metadata,
  101058. void* client_data)
  101059. {
  101060. ((FlacReader*) client_data)->useMetadata (metadata->data.stream_info);
  101061. }
  101062. static void errorCallback_ (const FLAC__StreamDecoder*, FLAC__StreamDecoderErrorStatus, void*)
  101063. {
  101064. }
  101065. juce_UseDebuggingNewOperator
  101066. };
  101067. class FlacWriter : public AudioFormatWriter
  101068. {
  101069. FLAC__StreamEncoder* encoder;
  101070. MemoryBlock temp;
  101071. public:
  101072. bool ok;
  101073. FlacWriter (OutputStream* const out,
  101074. const double sampleRate,
  101075. const int numChannels,
  101076. const int bitsPerSample_)
  101077. : AudioFormatWriter (out, flacFormatName,
  101078. sampleRate,
  101079. numChannels,
  101080. bitsPerSample_)
  101081. {
  101082. using namespace FlacNamespace;
  101083. encoder = FLAC__stream_encoder_new();
  101084. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  101085. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  101086. FLAC__stream_encoder_set_channels (encoder, numChannels);
  101087. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin (24, bitsPerSample));
  101088. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  101089. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  101090. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  101091. ok = FLAC__stream_encoder_init_stream (encoder,
  101092. encodeWriteCallback, encodeSeekCallback,
  101093. encodeTellCallback, encodeMetadataCallback,
  101094. (void*) this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  101095. }
  101096. ~FlacWriter()
  101097. {
  101098. if (ok)
  101099. {
  101100. FLAC__stream_encoder_finish (encoder);
  101101. output->flush();
  101102. }
  101103. else
  101104. {
  101105. output = 0; // to stop the base class deleting this, as it needs to be returned
  101106. // to the caller of createWriter()
  101107. }
  101108. FLAC__stream_encoder_delete (encoder);
  101109. }
  101110. bool write (const int** samplesToWrite, int numSamples)
  101111. {
  101112. if (! ok)
  101113. return false;
  101114. int* buf[3];
  101115. const int bitsToShift = 32 - bitsPerSample;
  101116. if (bitsToShift > 0)
  101117. {
  101118. const int numChannels = (samplesToWrite[1] == 0) ? 1 : 2;
  101119. temp.setSize (sizeof (int) * numSamples * numChannels);
  101120. buf[0] = (int*) temp.getData();
  101121. buf[1] = buf[0] + numSamples;
  101122. buf[2] = 0;
  101123. for (int i = numChannels; --i >= 0;)
  101124. {
  101125. if (samplesToWrite[i] != 0)
  101126. {
  101127. for (int j = 0; j < numSamples; ++j)
  101128. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  101129. }
  101130. }
  101131. samplesToWrite = (const int**) buf;
  101132. }
  101133. return FLAC__stream_encoder_process (encoder,
  101134. (const FLAC__int32**) samplesToWrite,
  101135. numSamples) != 0;
  101136. }
  101137. bool writeData (const void* const data, const int size) const
  101138. {
  101139. return output->write (data, size);
  101140. }
  101141. static void packUint32 (FLAC__uint32 val, FLAC__byte* b, const int bytes)
  101142. {
  101143. b += bytes;
  101144. for (int i = 0; i < bytes; ++i)
  101145. {
  101146. *(--b) = (FLAC__byte) (val & 0xff);
  101147. val >>= 8;
  101148. }
  101149. }
  101150. void writeMetaData (const FLAC__StreamMetadata* metadata)
  101151. {
  101152. using namespace FlacNamespace;
  101153. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  101154. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  101155. const unsigned int channelsMinus1 = info.channels - 1;
  101156. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  101157. packUint32 (info.min_blocksize, buffer, 2);
  101158. packUint32 (info.max_blocksize, buffer + 2, 2);
  101159. packUint32 (info.min_framesize, buffer + 4, 3);
  101160. packUint32 (info.max_framesize, buffer + 7, 3);
  101161. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  101162. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  101163. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  101164. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  101165. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  101166. memcpy (buffer + 18, info.md5sum, 16);
  101167. const bool ok = output->setPosition (4);
  101168. (void) ok;
  101169. // if this fails, you've given it an output stream that can't seek! It needs
  101170. // to be able to seek back to write the header
  101171. jassert (ok);
  101172. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  101173. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  101174. }
  101175. static FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FLAC__StreamEncoder*,
  101176. const FLAC__byte buffer[],
  101177. size_t bytes,
  101178. unsigned int /*samples*/,
  101179. unsigned int /*current_frame*/,
  101180. void* client_data)
  101181. {
  101182. using namespace FlacNamespace;
  101183. return ((FlacWriter*) client_data)->writeData (buffer, (int) bytes)
  101184. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  101185. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  101186. }
  101187. static FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FLAC__StreamEncoder*, FLAC__uint64, void*)
  101188. {
  101189. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  101190. }
  101191. static FLAC__StreamEncoderTellStatus encodeTellCallback (const FLAC__StreamEncoder*, FLAC__uint64*, void*)
  101192. {
  101193. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  101194. }
  101195. static void encodeMetadataCallback (const FLAC__StreamEncoder*,
  101196. const FLAC__StreamMetadata* metadata,
  101197. void* client_data)
  101198. {
  101199. ((FlacWriter*) client_data)->writeMetaData (metadata);
  101200. }
  101201. juce_UseDebuggingNewOperator
  101202. };
  101203. FlacAudioFormat::FlacAudioFormat()
  101204. : AudioFormat (flacFormatName, (const tchar**) flacExtensions)
  101205. {
  101206. }
  101207. FlacAudioFormat::~FlacAudioFormat()
  101208. {
  101209. }
  101210. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  101211. {
  101212. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  101213. return Array <int> (rates);
  101214. }
  101215. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  101216. {
  101217. const int depths[] = { 16, 24, 0 };
  101218. return Array <int> (depths);
  101219. }
  101220. bool FlacAudioFormat::canDoStereo()
  101221. {
  101222. return true;
  101223. }
  101224. bool FlacAudioFormat::canDoMono()
  101225. {
  101226. return true;
  101227. }
  101228. bool FlacAudioFormat::isCompressed()
  101229. {
  101230. return true;
  101231. }
  101232. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  101233. const bool deleteStreamIfOpeningFails)
  101234. {
  101235. FlacReader* r = new FlacReader (in);
  101236. if (r->sampleRate == 0)
  101237. {
  101238. if (! deleteStreamIfOpeningFails)
  101239. r->input = 0;
  101240. deleteAndZero (r);
  101241. }
  101242. return r;
  101243. }
  101244. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  101245. double sampleRate,
  101246. unsigned int numberOfChannels,
  101247. int bitsPerSample,
  101248. const StringPairArray& /*metadataValues*/,
  101249. int /*qualityOptionIndex*/)
  101250. {
  101251. if (getPossibleBitDepths().contains (bitsPerSample))
  101252. {
  101253. FlacWriter* w = new FlacWriter (out,
  101254. sampleRate,
  101255. numberOfChannels,
  101256. bitsPerSample);
  101257. if (! w->ok)
  101258. deleteAndZero (w);
  101259. return w;
  101260. }
  101261. return 0;
  101262. }
  101263. END_JUCE_NAMESPACE
  101264. #endif
  101265. /********* End of inlined file: juce_FlacAudioFormat.cpp *********/
  101266. /********* Start of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  101267. #if JUCE_USE_OGGVORBIS
  101268. #if JUCE_MAC
  101269. #define __MACOSX__ 1
  101270. #endif
  101271. namespace OggVorbisNamespace
  101272. {
  101273. /********* Start of inlined file: vorbisenc.h *********/
  101274. #ifndef _OV_ENC_H_
  101275. #define _OV_ENC_H_
  101276. #ifdef __cplusplus
  101277. extern "C"
  101278. {
  101279. #endif /* __cplusplus */
  101280. /********* Start of inlined file: codec.h *********/
  101281. #ifndef _vorbis_codec_h_
  101282. #define _vorbis_codec_h_
  101283. #ifdef __cplusplus
  101284. extern "C"
  101285. {
  101286. #endif /* __cplusplus */
  101287. /********* Start of inlined file: ogg.h *********/
  101288. #ifndef _OGG_H
  101289. #define _OGG_H
  101290. #ifdef __cplusplus
  101291. extern "C" {
  101292. #endif
  101293. /********* Start of inlined file: os_types.h *********/
  101294. #ifndef _OS_TYPES_H
  101295. #define _OS_TYPES_H
  101296. /* make it easy on the folks that want to compile the libs with a
  101297. different malloc than stdlib */
  101298. #define _ogg_malloc malloc
  101299. #define _ogg_calloc calloc
  101300. #define _ogg_realloc realloc
  101301. #define _ogg_free free
  101302. #if defined(_WIN32)
  101303. # if defined(__CYGWIN__)
  101304. # include <_G_config.h>
  101305. typedef _G_int64_t ogg_int64_t;
  101306. typedef _G_int32_t ogg_int32_t;
  101307. typedef _G_uint32_t ogg_uint32_t;
  101308. typedef _G_int16_t ogg_int16_t;
  101309. typedef _G_uint16_t ogg_uint16_t;
  101310. # elif defined(__MINGW32__)
  101311. typedef short ogg_int16_t;
  101312. typedef unsigned short ogg_uint16_t;
  101313. typedef int ogg_int32_t;
  101314. typedef unsigned int ogg_uint32_t;
  101315. typedef long long ogg_int64_t;
  101316. typedef unsigned long long ogg_uint64_t;
  101317. # elif defined(__MWERKS__)
  101318. typedef long long ogg_int64_t;
  101319. typedef int ogg_int32_t;
  101320. typedef unsigned int ogg_uint32_t;
  101321. typedef short ogg_int16_t;
  101322. typedef unsigned short ogg_uint16_t;
  101323. # else
  101324. /* MSVC/Borland */
  101325. typedef __int64 ogg_int64_t;
  101326. typedef __int32 ogg_int32_t;
  101327. typedef unsigned __int32 ogg_uint32_t;
  101328. typedef __int16 ogg_int16_t;
  101329. typedef unsigned __int16 ogg_uint16_t;
  101330. # endif
  101331. #elif defined(__MACOS__)
  101332. # include <sys/types.h>
  101333. typedef SInt16 ogg_int16_t;
  101334. typedef UInt16 ogg_uint16_t;
  101335. typedef SInt32 ogg_int32_t;
  101336. typedef UInt32 ogg_uint32_t;
  101337. typedef SInt64 ogg_int64_t;
  101338. #elif defined(__MACOSX__) /* MacOS X Framework build */
  101339. # include <sys/types.h>
  101340. typedef int16_t ogg_int16_t;
  101341. typedef u_int16_t ogg_uint16_t;
  101342. typedef int32_t ogg_int32_t;
  101343. typedef u_int32_t ogg_uint32_t;
  101344. typedef int64_t ogg_int64_t;
  101345. #elif defined(__BEOS__)
  101346. /* Be */
  101347. # include <inttypes.h>
  101348. typedef int16_t ogg_int16_t;
  101349. typedef u_int16_t ogg_uint16_t;
  101350. typedef int32_t ogg_int32_t;
  101351. typedef u_int32_t ogg_uint32_t;
  101352. typedef int64_t ogg_int64_t;
  101353. #elif defined (__EMX__)
  101354. /* OS/2 GCC */
  101355. typedef short ogg_int16_t;
  101356. typedef unsigned short ogg_uint16_t;
  101357. typedef int ogg_int32_t;
  101358. typedef unsigned int ogg_uint32_t;
  101359. typedef long long ogg_int64_t;
  101360. #elif defined (DJGPP)
  101361. /* DJGPP */
  101362. typedef short ogg_int16_t;
  101363. typedef int ogg_int32_t;
  101364. typedef unsigned int ogg_uint32_t;
  101365. typedef long long ogg_int64_t;
  101366. #elif defined(R5900)
  101367. /* PS2 EE */
  101368. typedef long ogg_int64_t;
  101369. typedef int ogg_int32_t;
  101370. typedef unsigned ogg_uint32_t;
  101371. typedef short ogg_int16_t;
  101372. #elif defined(__SYMBIAN32__)
  101373. /* Symbian GCC */
  101374. typedef signed short ogg_int16_t;
  101375. typedef unsigned short ogg_uint16_t;
  101376. typedef signed int ogg_int32_t;
  101377. typedef unsigned int ogg_uint32_t;
  101378. typedef long long int ogg_int64_t;
  101379. #else
  101380. # include <sys/types.h>
  101381. /********* Start of inlined file: config_types.h *********/
  101382. #ifndef __CONFIG_TYPES_H__
  101383. #define __CONFIG_TYPES_H__
  101384. typedef int16_t ogg_int16_t;
  101385. typedef unsigned short ogg_uint16_t;
  101386. typedef int32_t ogg_int32_t;
  101387. typedef unsigned int ogg_uint32_t;
  101388. typedef int64_t ogg_int64_t;
  101389. #endif
  101390. /********* End of inlined file: config_types.h *********/
  101391. #endif
  101392. #endif /* _OS_TYPES_H */
  101393. /********* End of inlined file: os_types.h *********/
  101394. typedef struct {
  101395. long endbyte;
  101396. int endbit;
  101397. unsigned char *buffer;
  101398. unsigned char *ptr;
  101399. long storage;
  101400. } oggpack_buffer;
  101401. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  101402. typedef struct {
  101403. unsigned char *header;
  101404. long header_len;
  101405. unsigned char *body;
  101406. long body_len;
  101407. } ogg_page;
  101408. ogg_uint32_t bitreverse(ogg_uint32_t x){
  101409. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  101410. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  101411. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  101412. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  101413. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  101414. }
  101415. /* ogg_stream_state contains the current encode/decode state of a logical
  101416. Ogg bitstream **********************************************************/
  101417. typedef struct {
  101418. unsigned char *body_data; /* bytes from packet bodies */
  101419. long body_storage; /* storage elements allocated */
  101420. long body_fill; /* elements stored; fill mark */
  101421. long body_returned; /* elements of fill returned */
  101422. int *lacing_vals; /* The values that will go to the segment table */
  101423. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  101424. this way, but it is simple coupled to the
  101425. lacing fifo */
  101426. long lacing_storage;
  101427. long lacing_fill;
  101428. long lacing_packet;
  101429. long lacing_returned;
  101430. unsigned char header[282]; /* working space for header encode */
  101431. int header_fill;
  101432. int e_o_s; /* set when we have buffered the last packet in the
  101433. logical bitstream */
  101434. int b_o_s; /* set after we've written the initial page
  101435. of a logical bitstream */
  101436. long serialno;
  101437. long pageno;
  101438. ogg_int64_t packetno; /* sequence number for decode; the framing
  101439. knows where there's a hole in the data,
  101440. but we need coupling so that the codec
  101441. (which is in a seperate abstraction
  101442. layer) also knows about the gap */
  101443. ogg_int64_t granulepos;
  101444. } ogg_stream_state;
  101445. /* ogg_packet is used to encapsulate the data and metadata belonging
  101446. to a single raw Ogg/Vorbis packet *************************************/
  101447. typedef struct {
  101448. unsigned char *packet;
  101449. long bytes;
  101450. long b_o_s;
  101451. long e_o_s;
  101452. ogg_int64_t granulepos;
  101453. ogg_int64_t packetno; /* sequence number for decode; the framing
  101454. knows where there's a hole in the data,
  101455. but we need coupling so that the codec
  101456. (which is in a seperate abstraction
  101457. layer) also knows about the gap */
  101458. } ogg_packet;
  101459. typedef struct {
  101460. unsigned char *data;
  101461. int storage;
  101462. int fill;
  101463. int returned;
  101464. int unsynced;
  101465. int headerbytes;
  101466. int bodybytes;
  101467. } ogg_sync_state;
  101468. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  101469. extern void oggpack_writeinit(oggpack_buffer *b);
  101470. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  101471. extern void oggpack_writealign(oggpack_buffer *b);
  101472. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  101473. extern void oggpack_reset(oggpack_buffer *b);
  101474. extern void oggpack_writeclear(oggpack_buffer *b);
  101475. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  101476. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  101477. extern long oggpack_look(oggpack_buffer *b,int bits);
  101478. extern long oggpack_look1(oggpack_buffer *b);
  101479. extern void oggpack_adv(oggpack_buffer *b,int bits);
  101480. extern void oggpack_adv1(oggpack_buffer *b);
  101481. extern long oggpack_read(oggpack_buffer *b,int bits);
  101482. extern long oggpack_read1(oggpack_buffer *b);
  101483. extern long oggpack_bytes(oggpack_buffer *b);
  101484. extern long oggpack_bits(oggpack_buffer *b);
  101485. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  101486. extern void oggpackB_writeinit(oggpack_buffer *b);
  101487. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  101488. extern void oggpackB_writealign(oggpack_buffer *b);
  101489. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  101490. extern void oggpackB_reset(oggpack_buffer *b);
  101491. extern void oggpackB_writeclear(oggpack_buffer *b);
  101492. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  101493. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  101494. extern long oggpackB_look(oggpack_buffer *b,int bits);
  101495. extern long oggpackB_look1(oggpack_buffer *b);
  101496. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  101497. extern void oggpackB_adv1(oggpack_buffer *b);
  101498. extern long oggpackB_read(oggpack_buffer *b,int bits);
  101499. extern long oggpackB_read1(oggpack_buffer *b);
  101500. extern long oggpackB_bytes(oggpack_buffer *b);
  101501. extern long oggpackB_bits(oggpack_buffer *b);
  101502. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  101503. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  101504. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  101505. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  101506. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  101507. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  101508. extern int ogg_sync_init(ogg_sync_state *oy);
  101509. extern int ogg_sync_clear(ogg_sync_state *oy);
  101510. extern int ogg_sync_reset(ogg_sync_state *oy);
  101511. extern int ogg_sync_destroy(ogg_sync_state *oy);
  101512. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  101513. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  101514. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  101515. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  101516. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  101517. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  101518. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  101519. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  101520. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  101521. extern int ogg_stream_clear(ogg_stream_state *os);
  101522. extern int ogg_stream_reset(ogg_stream_state *os);
  101523. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  101524. extern int ogg_stream_destroy(ogg_stream_state *os);
  101525. extern int ogg_stream_eos(ogg_stream_state *os);
  101526. extern void ogg_page_checksum_set(ogg_page *og);
  101527. extern int ogg_page_version(ogg_page *og);
  101528. extern int ogg_page_continued(ogg_page *og);
  101529. extern int ogg_page_bos(ogg_page *og);
  101530. extern int ogg_page_eos(ogg_page *og);
  101531. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  101532. extern int ogg_page_serialno(ogg_page *og);
  101533. extern long ogg_page_pageno(ogg_page *og);
  101534. extern int ogg_page_packets(ogg_page *og);
  101535. extern void ogg_packet_clear(ogg_packet *op);
  101536. #ifdef __cplusplus
  101537. }
  101538. #endif
  101539. #endif /* _OGG_H */
  101540. /********* End of inlined file: ogg.h *********/
  101541. typedef struct vorbis_info{
  101542. int version;
  101543. int channels;
  101544. long rate;
  101545. /* The below bitrate declarations are *hints*.
  101546. Combinations of the three values carry the following implications:
  101547. all three set to the same value:
  101548. implies a fixed rate bitstream
  101549. only nominal set:
  101550. implies a VBR stream that averages the nominal bitrate. No hard
  101551. upper/lower limit
  101552. upper and or lower set:
  101553. implies a VBR bitstream that obeys the bitrate limits. nominal
  101554. may also be set to give a nominal rate.
  101555. none set:
  101556. the coder does not care to speculate.
  101557. */
  101558. long bitrate_upper;
  101559. long bitrate_nominal;
  101560. long bitrate_lower;
  101561. long bitrate_window;
  101562. void *codec_setup;
  101563. } vorbis_info;
  101564. /* vorbis_dsp_state buffers the current vorbis audio
  101565. analysis/synthesis state. The DSP state belongs to a specific
  101566. logical bitstream ****************************************************/
  101567. typedef struct vorbis_dsp_state{
  101568. int analysisp;
  101569. vorbis_info *vi;
  101570. float **pcm;
  101571. float **pcmret;
  101572. int pcm_storage;
  101573. int pcm_current;
  101574. int pcm_returned;
  101575. int preextrapolate;
  101576. int eofflag;
  101577. long lW;
  101578. long W;
  101579. long nW;
  101580. long centerW;
  101581. ogg_int64_t granulepos;
  101582. ogg_int64_t sequence;
  101583. ogg_int64_t glue_bits;
  101584. ogg_int64_t time_bits;
  101585. ogg_int64_t floor_bits;
  101586. ogg_int64_t res_bits;
  101587. void *backend_state;
  101588. } vorbis_dsp_state;
  101589. typedef struct vorbis_block{
  101590. /* necessary stream state for linking to the framing abstraction */
  101591. float **pcm; /* this is a pointer into local storage */
  101592. oggpack_buffer opb;
  101593. long lW;
  101594. long W;
  101595. long nW;
  101596. int pcmend;
  101597. int mode;
  101598. int eofflag;
  101599. ogg_int64_t granulepos;
  101600. ogg_int64_t sequence;
  101601. vorbis_dsp_state *vd; /* For read-only access of configuration */
  101602. /* local storage to avoid remallocing; it's up to the mapping to
  101603. structure it */
  101604. void *localstore;
  101605. long localtop;
  101606. long localalloc;
  101607. long totaluse;
  101608. struct alloc_chain *reap;
  101609. /* bitmetrics for the frame */
  101610. long glue_bits;
  101611. long time_bits;
  101612. long floor_bits;
  101613. long res_bits;
  101614. void *internal;
  101615. } vorbis_block;
  101616. /* vorbis_block is a single block of data to be processed as part of
  101617. the analysis/synthesis stream; it belongs to a specific logical
  101618. bitstream, but is independant from other vorbis_blocks belonging to
  101619. that logical bitstream. *************************************************/
  101620. struct alloc_chain{
  101621. void *ptr;
  101622. struct alloc_chain *next;
  101623. };
  101624. /* vorbis_info contains all the setup information specific to the
  101625. specific compression/decompression mode in progress (eg,
  101626. psychoacoustic settings, channel setup, options, codebook
  101627. etc). vorbis_info and substructures are in backends.h.
  101628. *********************************************************************/
  101629. /* the comments are not part of vorbis_info so that vorbis_info can be
  101630. static storage */
  101631. typedef struct vorbis_comment{
  101632. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  101633. whatever vendor is set to in encode */
  101634. char **user_comments;
  101635. int *comment_lengths;
  101636. int comments;
  101637. char *vendor;
  101638. } vorbis_comment;
  101639. /* libvorbis encodes in two abstraction layers; first we perform DSP
  101640. and produce a packet (see docs/analysis.txt). The packet is then
  101641. coded into a framed OggSquish bitstream by the second layer (see
  101642. docs/framing.txt). Decode is the reverse process; we sync/frame
  101643. the bitstream and extract individual packets, then decode the
  101644. packet back into PCM audio.
  101645. The extra framing/packetizing is used in streaming formats, such as
  101646. files. Over the net (such as with UDP), the framing and
  101647. packetization aren't necessary as they're provided by the transport
  101648. and the streaming layer is not used */
  101649. /* Vorbis PRIMITIVES: general ***************************************/
  101650. extern void vorbis_info_init(vorbis_info *vi);
  101651. extern void vorbis_info_clear(vorbis_info *vi);
  101652. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  101653. extern void vorbis_comment_init(vorbis_comment *vc);
  101654. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  101655. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  101656. char *tag, char *contents);
  101657. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  101658. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  101659. extern void vorbis_comment_clear(vorbis_comment *vc);
  101660. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  101661. extern int vorbis_block_clear(vorbis_block *vb);
  101662. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  101663. extern double vorbis_granule_time(vorbis_dsp_state *v,
  101664. ogg_int64_t granulepos);
  101665. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  101666. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  101667. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  101668. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  101669. vorbis_comment *vc,
  101670. ogg_packet *op,
  101671. ogg_packet *op_comm,
  101672. ogg_packet *op_code);
  101673. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  101674. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  101675. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  101676. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  101677. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  101678. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  101679. ogg_packet *op);
  101680. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  101681. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  101682. ogg_packet *op);
  101683. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  101684. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  101685. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  101686. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  101687. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  101688. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  101689. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  101690. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  101691. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  101692. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  101693. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  101694. /* Vorbis ERRORS and return codes ***********************************/
  101695. #define OV_FALSE -1
  101696. #define OV_EOF -2
  101697. #define OV_HOLE -3
  101698. #define OV_EREAD -128
  101699. #define OV_EFAULT -129
  101700. #define OV_EIMPL -130
  101701. #define OV_EINVAL -131
  101702. #define OV_ENOTVORBIS -132
  101703. #define OV_EBADHEADER -133
  101704. #define OV_EVERSION -134
  101705. #define OV_ENOTAUDIO -135
  101706. #define OV_EBADPACKET -136
  101707. #define OV_EBADLINK -137
  101708. #define OV_ENOSEEK -138
  101709. #ifdef __cplusplus
  101710. }
  101711. #endif /* __cplusplus */
  101712. #endif
  101713. /********* End of inlined file: codec.h *********/
  101714. extern int vorbis_encode_init(vorbis_info *vi,
  101715. long channels,
  101716. long rate,
  101717. long max_bitrate,
  101718. long nominal_bitrate,
  101719. long min_bitrate);
  101720. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  101721. long channels,
  101722. long rate,
  101723. long max_bitrate,
  101724. long nominal_bitrate,
  101725. long min_bitrate);
  101726. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  101727. long channels,
  101728. long rate,
  101729. float quality /* quality level from 0. (lo) to 1. (hi) */
  101730. );
  101731. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  101732. long channels,
  101733. long rate,
  101734. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  101735. );
  101736. extern int vorbis_encode_setup_init(vorbis_info *vi);
  101737. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  101738. /* deprecated rate management supported only for compatability */
  101739. #define OV_ECTL_RATEMANAGE_GET 0x10
  101740. #define OV_ECTL_RATEMANAGE_SET 0x11
  101741. #define OV_ECTL_RATEMANAGE_AVG 0x12
  101742. #define OV_ECTL_RATEMANAGE_HARD 0x13
  101743. struct ovectl_ratemanage_arg {
  101744. int management_active;
  101745. long bitrate_hard_min;
  101746. long bitrate_hard_max;
  101747. double bitrate_hard_window;
  101748. long bitrate_av_lo;
  101749. long bitrate_av_hi;
  101750. double bitrate_av_window;
  101751. double bitrate_av_window_center;
  101752. };
  101753. /* new rate setup */
  101754. #define OV_ECTL_RATEMANAGE2_GET 0x14
  101755. #define OV_ECTL_RATEMANAGE2_SET 0x15
  101756. struct ovectl_ratemanage2_arg {
  101757. int management_active;
  101758. long bitrate_limit_min_kbps;
  101759. long bitrate_limit_max_kbps;
  101760. long bitrate_limit_reservoir_bits;
  101761. double bitrate_limit_reservoir_bias;
  101762. long bitrate_average_kbps;
  101763. double bitrate_average_damping;
  101764. };
  101765. #define OV_ECTL_LOWPASS_GET 0x20
  101766. #define OV_ECTL_LOWPASS_SET 0x21
  101767. #define OV_ECTL_IBLOCK_GET 0x30
  101768. #define OV_ECTL_IBLOCK_SET 0x31
  101769. #ifdef __cplusplus
  101770. }
  101771. #endif /* __cplusplus */
  101772. #endif
  101773. /********* End of inlined file: vorbisenc.h *********/
  101774. /********* Start of inlined file: vorbisfile.h *********/
  101775. #ifndef _OV_FILE_H_
  101776. #define _OV_FILE_H_
  101777. #ifdef __cplusplus
  101778. extern "C"
  101779. {
  101780. #endif /* __cplusplus */
  101781. #include <stdio.h>
  101782. /* The function prototypes for the callbacks are basically the same as for
  101783. * the stdio functions fread, fseek, fclose, ftell.
  101784. * The one difference is that the FILE * arguments have been replaced with
  101785. * a void * - this is to be used as a pointer to whatever internal data these
  101786. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  101787. *
  101788. * If you use other functions, check the docs for these functions and return
  101789. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  101790. * unseekable
  101791. */
  101792. typedef struct {
  101793. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  101794. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  101795. int (*close_func) (void *datasource);
  101796. long (*tell_func) (void *datasource);
  101797. } ov_callbacks;
  101798. #define NOTOPEN 0
  101799. #define PARTOPEN 1
  101800. #define OPENED 2
  101801. #define STREAMSET 3
  101802. #define INITSET 4
  101803. typedef struct OggVorbis_File {
  101804. void *datasource; /* Pointer to a FILE *, etc. */
  101805. int seekable;
  101806. ogg_int64_t offset;
  101807. ogg_int64_t end;
  101808. ogg_sync_state oy;
  101809. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  101810. stream appears */
  101811. int links;
  101812. ogg_int64_t *offsets;
  101813. ogg_int64_t *dataoffsets;
  101814. long *serialnos;
  101815. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  101816. compatability; x2 size, stores both
  101817. beginning and end values */
  101818. vorbis_info *vi;
  101819. vorbis_comment *vc;
  101820. /* Decoding working state local storage */
  101821. ogg_int64_t pcm_offset;
  101822. int ready_state;
  101823. long current_serialno;
  101824. int current_link;
  101825. double bittrack;
  101826. double samptrack;
  101827. ogg_stream_state os; /* take physical pages, weld into a logical
  101828. stream of packets */
  101829. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  101830. vorbis_block vb; /* local working space for packet->PCM decode */
  101831. ov_callbacks callbacks;
  101832. } OggVorbis_File;
  101833. extern int ov_clear(OggVorbis_File *vf);
  101834. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  101835. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  101836. char *initial, long ibytes, ov_callbacks callbacks);
  101837. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  101838. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  101839. char *initial, long ibytes, ov_callbacks callbacks);
  101840. extern int ov_test_open(OggVorbis_File *vf);
  101841. extern long ov_bitrate(OggVorbis_File *vf,int i);
  101842. extern long ov_bitrate_instant(OggVorbis_File *vf);
  101843. extern long ov_streams(OggVorbis_File *vf);
  101844. extern long ov_seekable(OggVorbis_File *vf);
  101845. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  101846. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  101847. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  101848. extern double ov_time_total(OggVorbis_File *vf,int i);
  101849. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  101850. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  101851. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  101852. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  101853. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  101854. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  101855. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  101856. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  101857. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  101858. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  101859. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  101860. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  101861. extern double ov_time_tell(OggVorbis_File *vf);
  101862. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  101863. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  101864. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  101865. int *bitstream);
  101866. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  101867. int bigendianp,int word,int sgned,int *bitstream);
  101868. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  101869. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  101870. extern int ov_halfrate_p(OggVorbis_File *vf);
  101871. #ifdef __cplusplus
  101872. }
  101873. #endif /* __cplusplus */
  101874. #endif
  101875. /********* End of inlined file: vorbisfile.h *********/
  101876. /********* Start of inlined file: bitwise.c *********/
  101877. /* We're 'LSb' endian; if we write a word but read individual bits,
  101878. then we'll read the lsb first */
  101879. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  101880. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  101881. // tasks..
  101882. #ifdef _MSC_VER
  101883. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  101884. #endif
  101885. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  101886. #if JUCE_USE_OGGVORBIS
  101887. #include <string.h>
  101888. #include <stdlib.h>
  101889. #define BUFFER_INCREMENT 256
  101890. static const unsigned long mask[]=
  101891. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  101892. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  101893. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  101894. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  101895. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  101896. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  101897. 0x3fffffff,0x7fffffff,0xffffffff };
  101898. static const unsigned int mask8B[]=
  101899. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  101900. void oggpack_writeinit(oggpack_buffer *b){
  101901. memset(b,0,sizeof(*b));
  101902. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  101903. b->buffer[0]='\0';
  101904. b->storage=BUFFER_INCREMENT;
  101905. }
  101906. void oggpackB_writeinit(oggpack_buffer *b){
  101907. oggpack_writeinit(b);
  101908. }
  101909. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  101910. long bytes=bits>>3;
  101911. bits-=bytes*8;
  101912. b->ptr=b->buffer+bytes;
  101913. b->endbit=bits;
  101914. b->endbyte=bytes;
  101915. *b->ptr&=mask[bits];
  101916. }
  101917. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  101918. long bytes=bits>>3;
  101919. bits-=bytes*8;
  101920. b->ptr=b->buffer+bytes;
  101921. b->endbit=bits;
  101922. b->endbyte=bytes;
  101923. *b->ptr&=mask8B[bits];
  101924. }
  101925. /* Takes only up to 32 bits. */
  101926. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  101927. if(b->endbyte+4>=b->storage){
  101928. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  101929. b->storage+=BUFFER_INCREMENT;
  101930. b->ptr=b->buffer+b->endbyte;
  101931. }
  101932. value&=mask[bits];
  101933. bits+=b->endbit;
  101934. b->ptr[0]|=value<<b->endbit;
  101935. if(bits>=8){
  101936. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  101937. if(bits>=16){
  101938. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  101939. if(bits>=24){
  101940. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  101941. if(bits>=32){
  101942. if(b->endbit)
  101943. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  101944. else
  101945. b->ptr[4]=0;
  101946. }
  101947. }
  101948. }
  101949. }
  101950. b->endbyte+=bits/8;
  101951. b->ptr+=bits/8;
  101952. b->endbit=bits&7;
  101953. }
  101954. /* Takes only up to 32 bits. */
  101955. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  101956. if(b->endbyte+4>=b->storage){
  101957. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  101958. b->storage+=BUFFER_INCREMENT;
  101959. b->ptr=b->buffer+b->endbyte;
  101960. }
  101961. value=(value&mask[bits])<<(32-bits);
  101962. bits+=b->endbit;
  101963. b->ptr[0]|=value>>(24+b->endbit);
  101964. if(bits>=8){
  101965. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  101966. if(bits>=16){
  101967. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  101968. if(bits>=24){
  101969. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  101970. if(bits>=32){
  101971. if(b->endbit)
  101972. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  101973. else
  101974. b->ptr[4]=0;
  101975. }
  101976. }
  101977. }
  101978. }
  101979. b->endbyte+=bits/8;
  101980. b->ptr+=bits/8;
  101981. b->endbit=bits&7;
  101982. }
  101983. void oggpack_writealign(oggpack_buffer *b){
  101984. int bits=8-b->endbit;
  101985. if(bits<8)
  101986. oggpack_write(b,0,bits);
  101987. }
  101988. void oggpackB_writealign(oggpack_buffer *b){
  101989. int bits=8-b->endbit;
  101990. if(bits<8)
  101991. oggpackB_write(b,0,bits);
  101992. }
  101993. static void oggpack_writecopy_helper(oggpack_buffer *b,
  101994. void *source,
  101995. long bits,
  101996. void (*w)(oggpack_buffer *,
  101997. unsigned long,
  101998. int),
  101999. int msb){
  102000. unsigned char *ptr=(unsigned char *)source;
  102001. long bytes=bits/8;
  102002. bits-=bytes*8;
  102003. if(b->endbit){
  102004. int i;
  102005. /* unaligned copy. Do it the hard way. */
  102006. for(i=0;i<bytes;i++)
  102007. w(b,(unsigned long)(ptr[i]),8);
  102008. }else{
  102009. /* aligned block copy */
  102010. if(b->endbyte+bytes+1>=b->storage){
  102011. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  102012. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  102013. b->ptr=b->buffer+b->endbyte;
  102014. }
  102015. memmove(b->ptr,source,bytes);
  102016. b->ptr+=bytes;
  102017. b->endbyte+=bytes;
  102018. *b->ptr=0;
  102019. }
  102020. if(bits){
  102021. if(msb)
  102022. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  102023. else
  102024. w(b,(unsigned long)(ptr[bytes]),bits);
  102025. }
  102026. }
  102027. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  102028. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  102029. }
  102030. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  102031. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  102032. }
  102033. void oggpack_reset(oggpack_buffer *b){
  102034. b->ptr=b->buffer;
  102035. b->buffer[0]=0;
  102036. b->endbit=b->endbyte=0;
  102037. }
  102038. void oggpackB_reset(oggpack_buffer *b){
  102039. oggpack_reset(b);
  102040. }
  102041. void oggpack_writeclear(oggpack_buffer *b){
  102042. _ogg_free(b->buffer);
  102043. memset(b,0,sizeof(*b));
  102044. }
  102045. void oggpackB_writeclear(oggpack_buffer *b){
  102046. oggpack_writeclear(b);
  102047. }
  102048. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  102049. memset(b,0,sizeof(*b));
  102050. b->buffer=b->ptr=buf;
  102051. b->storage=bytes;
  102052. }
  102053. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  102054. oggpack_readinit(b,buf,bytes);
  102055. }
  102056. /* Read in bits without advancing the bitptr; bits <= 32 */
  102057. long oggpack_look(oggpack_buffer *b,int bits){
  102058. unsigned long ret;
  102059. unsigned long m=mask[bits];
  102060. bits+=b->endbit;
  102061. if(b->endbyte+4>=b->storage){
  102062. /* not the main path */
  102063. if(b->endbyte*8+bits>b->storage*8)return(-1);
  102064. }
  102065. ret=b->ptr[0]>>b->endbit;
  102066. if(bits>8){
  102067. ret|=b->ptr[1]<<(8-b->endbit);
  102068. if(bits>16){
  102069. ret|=b->ptr[2]<<(16-b->endbit);
  102070. if(bits>24){
  102071. ret|=b->ptr[3]<<(24-b->endbit);
  102072. if(bits>32 && b->endbit)
  102073. ret|=b->ptr[4]<<(32-b->endbit);
  102074. }
  102075. }
  102076. }
  102077. return(m&ret);
  102078. }
  102079. /* Read in bits without advancing the bitptr; bits <= 32 */
  102080. long oggpackB_look(oggpack_buffer *b,int bits){
  102081. unsigned long ret;
  102082. int m=32-bits;
  102083. bits+=b->endbit;
  102084. if(b->endbyte+4>=b->storage){
  102085. /* not the main path */
  102086. if(b->endbyte*8+bits>b->storage*8)return(-1);
  102087. }
  102088. ret=b->ptr[0]<<(24+b->endbit);
  102089. if(bits>8){
  102090. ret|=b->ptr[1]<<(16+b->endbit);
  102091. if(bits>16){
  102092. ret|=b->ptr[2]<<(8+b->endbit);
  102093. if(bits>24){
  102094. ret|=b->ptr[3]<<(b->endbit);
  102095. if(bits>32 && b->endbit)
  102096. ret|=b->ptr[4]>>(8-b->endbit);
  102097. }
  102098. }
  102099. }
  102100. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  102101. }
  102102. long oggpack_look1(oggpack_buffer *b){
  102103. if(b->endbyte>=b->storage)return(-1);
  102104. return((b->ptr[0]>>b->endbit)&1);
  102105. }
  102106. long oggpackB_look1(oggpack_buffer *b){
  102107. if(b->endbyte>=b->storage)return(-1);
  102108. return((b->ptr[0]>>(7-b->endbit))&1);
  102109. }
  102110. void oggpack_adv(oggpack_buffer *b,int bits){
  102111. bits+=b->endbit;
  102112. b->ptr+=bits/8;
  102113. b->endbyte+=bits/8;
  102114. b->endbit=bits&7;
  102115. }
  102116. void oggpackB_adv(oggpack_buffer *b,int bits){
  102117. oggpack_adv(b,bits);
  102118. }
  102119. void oggpack_adv1(oggpack_buffer *b){
  102120. if(++(b->endbit)>7){
  102121. b->endbit=0;
  102122. b->ptr++;
  102123. b->endbyte++;
  102124. }
  102125. }
  102126. void oggpackB_adv1(oggpack_buffer *b){
  102127. oggpack_adv1(b);
  102128. }
  102129. /* bits <= 32 */
  102130. long oggpack_read(oggpack_buffer *b,int bits){
  102131. long ret;
  102132. unsigned long m=mask[bits];
  102133. bits+=b->endbit;
  102134. if(b->endbyte+4>=b->storage){
  102135. /* not the main path */
  102136. ret=-1L;
  102137. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  102138. }
  102139. ret=b->ptr[0]>>b->endbit;
  102140. if(bits>8){
  102141. ret|=b->ptr[1]<<(8-b->endbit);
  102142. if(bits>16){
  102143. ret|=b->ptr[2]<<(16-b->endbit);
  102144. if(bits>24){
  102145. ret|=b->ptr[3]<<(24-b->endbit);
  102146. if(bits>32 && b->endbit){
  102147. ret|=b->ptr[4]<<(32-b->endbit);
  102148. }
  102149. }
  102150. }
  102151. }
  102152. ret&=m;
  102153. overflow:
  102154. b->ptr+=bits/8;
  102155. b->endbyte+=bits/8;
  102156. b->endbit=bits&7;
  102157. return(ret);
  102158. }
  102159. /* bits <= 32 */
  102160. long oggpackB_read(oggpack_buffer *b,int bits){
  102161. long ret;
  102162. long m=32-bits;
  102163. bits+=b->endbit;
  102164. if(b->endbyte+4>=b->storage){
  102165. /* not the main path */
  102166. ret=-1L;
  102167. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  102168. }
  102169. ret=b->ptr[0]<<(24+b->endbit);
  102170. if(bits>8){
  102171. ret|=b->ptr[1]<<(16+b->endbit);
  102172. if(bits>16){
  102173. ret|=b->ptr[2]<<(8+b->endbit);
  102174. if(bits>24){
  102175. ret|=b->ptr[3]<<(b->endbit);
  102176. if(bits>32 && b->endbit)
  102177. ret|=b->ptr[4]>>(8-b->endbit);
  102178. }
  102179. }
  102180. }
  102181. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  102182. overflow:
  102183. b->ptr+=bits/8;
  102184. b->endbyte+=bits/8;
  102185. b->endbit=bits&7;
  102186. return(ret);
  102187. }
  102188. long oggpack_read1(oggpack_buffer *b){
  102189. long ret;
  102190. if(b->endbyte>=b->storage){
  102191. /* not the main path */
  102192. ret=-1L;
  102193. goto overflow;
  102194. }
  102195. ret=(b->ptr[0]>>b->endbit)&1;
  102196. overflow:
  102197. b->endbit++;
  102198. if(b->endbit>7){
  102199. b->endbit=0;
  102200. b->ptr++;
  102201. b->endbyte++;
  102202. }
  102203. return(ret);
  102204. }
  102205. long oggpackB_read1(oggpack_buffer *b){
  102206. long ret;
  102207. if(b->endbyte>=b->storage){
  102208. /* not the main path */
  102209. ret=-1L;
  102210. goto overflow;
  102211. }
  102212. ret=(b->ptr[0]>>(7-b->endbit))&1;
  102213. overflow:
  102214. b->endbit++;
  102215. if(b->endbit>7){
  102216. b->endbit=0;
  102217. b->ptr++;
  102218. b->endbyte++;
  102219. }
  102220. return(ret);
  102221. }
  102222. long oggpack_bytes(oggpack_buffer *b){
  102223. return(b->endbyte+(b->endbit+7)/8);
  102224. }
  102225. long oggpack_bits(oggpack_buffer *b){
  102226. return(b->endbyte*8+b->endbit);
  102227. }
  102228. long oggpackB_bytes(oggpack_buffer *b){
  102229. return oggpack_bytes(b);
  102230. }
  102231. long oggpackB_bits(oggpack_buffer *b){
  102232. return oggpack_bits(b);
  102233. }
  102234. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  102235. return(b->buffer);
  102236. }
  102237. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  102238. return oggpack_get_buffer(b);
  102239. }
  102240. /* Self test of the bitwise routines; everything else is based on
  102241. them, so they damned well better be solid. */
  102242. #ifdef _V_SELFTEST
  102243. #include <stdio.h>
  102244. static int ilog(unsigned int v){
  102245. int ret=0;
  102246. while(v){
  102247. ret++;
  102248. v>>=1;
  102249. }
  102250. return(ret);
  102251. }
  102252. oggpack_buffer o;
  102253. oggpack_buffer r;
  102254. void report(char *in){
  102255. fprintf(stderr,"%s",in);
  102256. exit(1);
  102257. }
  102258. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  102259. long bytes,i;
  102260. unsigned char *buffer;
  102261. oggpack_reset(&o);
  102262. for(i=0;i<vals;i++)
  102263. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  102264. buffer=oggpack_get_buffer(&o);
  102265. bytes=oggpack_bytes(&o);
  102266. if(bytes!=compsize)report("wrong number of bytes!\n");
  102267. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  102268. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  102269. report("wrote incorrect value!\n");
  102270. }
  102271. oggpack_readinit(&r,buffer,bytes);
  102272. for(i=0;i<vals;i++){
  102273. int tbit=bits?bits:ilog(b[i]);
  102274. if(oggpack_look(&r,tbit)==-1)
  102275. report("out of data!\n");
  102276. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  102277. report("looked at incorrect value!\n");
  102278. if(tbit==1)
  102279. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  102280. report("looked at single bit incorrect value!\n");
  102281. if(tbit==1){
  102282. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  102283. report("read incorrect single bit value!\n");
  102284. }else{
  102285. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  102286. report("read incorrect value!\n");
  102287. }
  102288. }
  102289. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  102290. }
  102291. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  102292. long bytes,i;
  102293. unsigned char *buffer;
  102294. oggpackB_reset(&o);
  102295. for(i=0;i<vals;i++)
  102296. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  102297. buffer=oggpackB_get_buffer(&o);
  102298. bytes=oggpackB_bytes(&o);
  102299. if(bytes!=compsize)report("wrong number of bytes!\n");
  102300. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  102301. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  102302. report("wrote incorrect value!\n");
  102303. }
  102304. oggpackB_readinit(&r,buffer,bytes);
  102305. for(i=0;i<vals;i++){
  102306. int tbit=bits?bits:ilog(b[i]);
  102307. if(oggpackB_look(&r,tbit)==-1)
  102308. report("out of data!\n");
  102309. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  102310. report("looked at incorrect value!\n");
  102311. if(tbit==1)
  102312. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  102313. report("looked at single bit incorrect value!\n");
  102314. if(tbit==1){
  102315. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  102316. report("read incorrect single bit value!\n");
  102317. }else{
  102318. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  102319. report("read incorrect value!\n");
  102320. }
  102321. }
  102322. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  102323. }
  102324. int main(void){
  102325. unsigned char *buffer;
  102326. long bytes,i;
  102327. static unsigned long testbuffer1[]=
  102328. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  102329. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  102330. int test1size=43;
  102331. static unsigned long testbuffer2[]=
  102332. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  102333. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  102334. 85525151,0,12321,1,349528352};
  102335. int test2size=21;
  102336. static unsigned long testbuffer3[]=
  102337. {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,
  102338. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  102339. int test3size=56;
  102340. static unsigned long large[]=
  102341. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  102342. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  102343. 85525151,0,12321,1,2146528352};
  102344. int onesize=33;
  102345. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  102346. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  102347. 223,4};
  102348. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  102349. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  102350. 245,251,128};
  102351. int twosize=6;
  102352. static int two[6]={61,255,255,251,231,29};
  102353. static int twoB[6]={247,63,255,253,249,120};
  102354. int threesize=54;
  102355. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  102356. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  102357. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  102358. 100,52,4,14,18,86,77,1};
  102359. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  102360. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  102361. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  102362. 200,20,254,4,58,106,176,144,0};
  102363. int foursize=38;
  102364. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  102365. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  102366. 28,2,133,0,1};
  102367. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  102368. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  102369. 129,10,4,32};
  102370. int fivesize=45;
  102371. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  102372. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  102373. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  102374. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  102375. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  102376. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  102377. int sixsize=7;
  102378. static int six[7]={17,177,170,242,169,19,148};
  102379. static int sixB[7]={136,141,85,79,149,200,41};
  102380. /* Test read/write together */
  102381. /* Later we test against pregenerated bitstreams */
  102382. oggpack_writeinit(&o);
  102383. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  102384. cliptest(testbuffer1,test1size,0,one,onesize);
  102385. fprintf(stderr,"ok.");
  102386. fprintf(stderr,"\nNull bit call (LSb): ");
  102387. cliptest(testbuffer3,test3size,0,two,twosize);
  102388. fprintf(stderr,"ok.");
  102389. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  102390. cliptest(testbuffer2,test2size,0,three,threesize);
  102391. fprintf(stderr,"ok.");
  102392. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  102393. oggpack_reset(&o);
  102394. for(i=0;i<test2size;i++)
  102395. oggpack_write(&o,large[i],32);
  102396. buffer=oggpack_get_buffer(&o);
  102397. bytes=oggpack_bytes(&o);
  102398. oggpack_readinit(&r,buffer,bytes);
  102399. for(i=0;i<test2size;i++){
  102400. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  102401. if(oggpack_look(&r,32)!=large[i]){
  102402. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  102403. oggpack_look(&r,32),large[i]);
  102404. report("read incorrect value!\n");
  102405. }
  102406. oggpack_adv(&r,32);
  102407. }
  102408. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  102409. fprintf(stderr,"ok.");
  102410. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  102411. cliptest(testbuffer1,test1size,7,four,foursize);
  102412. fprintf(stderr,"ok.");
  102413. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  102414. cliptest(testbuffer2,test2size,17,five,fivesize);
  102415. fprintf(stderr,"ok.");
  102416. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  102417. cliptest(testbuffer3,test3size,1,six,sixsize);
  102418. fprintf(stderr,"ok.");
  102419. fprintf(stderr,"\nTesting read past end (LSb): ");
  102420. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  102421. for(i=0;i<64;i++){
  102422. if(oggpack_read(&r,1)!=0){
  102423. fprintf(stderr,"failed; got -1 prematurely.\n");
  102424. exit(1);
  102425. }
  102426. }
  102427. if(oggpack_look(&r,1)!=-1 ||
  102428. oggpack_read(&r,1)!=-1){
  102429. fprintf(stderr,"failed; read past end without -1.\n");
  102430. exit(1);
  102431. }
  102432. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  102433. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  102434. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  102435. exit(1);
  102436. }
  102437. if(oggpack_look(&r,18)!=0 ||
  102438. oggpack_look(&r,18)!=0){
  102439. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  102440. exit(1);
  102441. }
  102442. if(oggpack_look(&r,19)!=-1 ||
  102443. oggpack_look(&r,19)!=-1){
  102444. fprintf(stderr,"failed; read past end without -1.\n");
  102445. exit(1);
  102446. }
  102447. if(oggpack_look(&r,32)!=-1 ||
  102448. oggpack_look(&r,32)!=-1){
  102449. fprintf(stderr,"failed; read past end without -1.\n");
  102450. exit(1);
  102451. }
  102452. oggpack_writeclear(&o);
  102453. fprintf(stderr,"ok.\n");
  102454. /********** lazy, cut-n-paste retest with MSb packing ***********/
  102455. /* Test read/write together */
  102456. /* Later we test against pregenerated bitstreams */
  102457. oggpackB_writeinit(&o);
  102458. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  102459. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  102460. fprintf(stderr,"ok.");
  102461. fprintf(stderr,"\nNull bit call (MSb): ");
  102462. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  102463. fprintf(stderr,"ok.");
  102464. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  102465. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  102466. fprintf(stderr,"ok.");
  102467. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  102468. oggpackB_reset(&o);
  102469. for(i=0;i<test2size;i++)
  102470. oggpackB_write(&o,large[i],32);
  102471. buffer=oggpackB_get_buffer(&o);
  102472. bytes=oggpackB_bytes(&o);
  102473. oggpackB_readinit(&r,buffer,bytes);
  102474. for(i=0;i<test2size;i++){
  102475. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  102476. if(oggpackB_look(&r,32)!=large[i]){
  102477. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  102478. oggpackB_look(&r,32),large[i]);
  102479. report("read incorrect value!\n");
  102480. }
  102481. oggpackB_adv(&r,32);
  102482. }
  102483. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  102484. fprintf(stderr,"ok.");
  102485. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  102486. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  102487. fprintf(stderr,"ok.");
  102488. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  102489. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  102490. fprintf(stderr,"ok.");
  102491. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  102492. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  102493. fprintf(stderr,"ok.");
  102494. fprintf(stderr,"\nTesting read past end (MSb): ");
  102495. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  102496. for(i=0;i<64;i++){
  102497. if(oggpackB_read(&r,1)!=0){
  102498. fprintf(stderr,"failed; got -1 prematurely.\n");
  102499. exit(1);
  102500. }
  102501. }
  102502. if(oggpackB_look(&r,1)!=-1 ||
  102503. oggpackB_read(&r,1)!=-1){
  102504. fprintf(stderr,"failed; read past end without -1.\n");
  102505. exit(1);
  102506. }
  102507. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  102508. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  102509. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  102510. exit(1);
  102511. }
  102512. if(oggpackB_look(&r,18)!=0 ||
  102513. oggpackB_look(&r,18)!=0){
  102514. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  102515. exit(1);
  102516. }
  102517. if(oggpackB_look(&r,19)!=-1 ||
  102518. oggpackB_look(&r,19)!=-1){
  102519. fprintf(stderr,"failed; read past end without -1.\n");
  102520. exit(1);
  102521. }
  102522. if(oggpackB_look(&r,32)!=-1 ||
  102523. oggpackB_look(&r,32)!=-1){
  102524. fprintf(stderr,"failed; read past end without -1.\n");
  102525. exit(1);
  102526. }
  102527. oggpackB_writeclear(&o);
  102528. fprintf(stderr,"ok.\n\n");
  102529. return(0);
  102530. }
  102531. #endif /* _V_SELFTEST */
  102532. #undef BUFFER_INCREMENT
  102533. #endif
  102534. /********* End of inlined file: bitwise.c *********/
  102535. /********* Start of inlined file: framing.c *********/
  102536. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  102537. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  102538. // tasks..
  102539. #ifdef _MSC_VER
  102540. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  102541. #endif
  102542. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  102543. #if JUCE_USE_OGGVORBIS
  102544. #include <stdlib.h>
  102545. #include <string.h>
  102546. /* A complete description of Ogg framing exists in docs/framing.html */
  102547. int ogg_page_version(ogg_page *og){
  102548. return((int)(og->header[4]));
  102549. }
  102550. int ogg_page_continued(ogg_page *og){
  102551. return((int)(og->header[5]&0x01));
  102552. }
  102553. int ogg_page_bos(ogg_page *og){
  102554. return((int)(og->header[5]&0x02));
  102555. }
  102556. int ogg_page_eos(ogg_page *og){
  102557. return((int)(og->header[5]&0x04));
  102558. }
  102559. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  102560. unsigned char *page=og->header;
  102561. ogg_int64_t granulepos=page[13]&(0xff);
  102562. granulepos= (granulepos<<8)|(page[12]&0xff);
  102563. granulepos= (granulepos<<8)|(page[11]&0xff);
  102564. granulepos= (granulepos<<8)|(page[10]&0xff);
  102565. granulepos= (granulepos<<8)|(page[9]&0xff);
  102566. granulepos= (granulepos<<8)|(page[8]&0xff);
  102567. granulepos= (granulepos<<8)|(page[7]&0xff);
  102568. granulepos= (granulepos<<8)|(page[6]&0xff);
  102569. return(granulepos);
  102570. }
  102571. int ogg_page_serialno(ogg_page *og){
  102572. return(og->header[14] |
  102573. (og->header[15]<<8) |
  102574. (og->header[16]<<16) |
  102575. (og->header[17]<<24));
  102576. }
  102577. long ogg_page_pageno(ogg_page *og){
  102578. return(og->header[18] |
  102579. (og->header[19]<<8) |
  102580. (og->header[20]<<16) |
  102581. (og->header[21]<<24));
  102582. }
  102583. /* returns the number of packets that are completed on this page (if
  102584. the leading packet is begun on a previous page, but ends on this
  102585. page, it's counted */
  102586. /* NOTE:
  102587. If a page consists of a packet begun on a previous page, and a new
  102588. packet begun (but not completed) on this page, the return will be:
  102589. ogg_page_packets(page) ==1,
  102590. ogg_page_continued(page) !=0
  102591. If a page happens to be a single packet that was begun on a
  102592. previous page, and spans to the next page (in the case of a three or
  102593. more page packet), the return will be:
  102594. ogg_page_packets(page) ==0,
  102595. ogg_page_continued(page) !=0
  102596. */
  102597. int ogg_page_packets(ogg_page *og){
  102598. int i,n=og->header[26],count=0;
  102599. for(i=0;i<n;i++)
  102600. if(og->header[27+i]<255)count++;
  102601. return(count);
  102602. }
  102603. #if 0
  102604. /* helper to initialize lookup for direct-table CRC (illustrative; we
  102605. use the static init below) */
  102606. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  102607. int i;
  102608. unsigned long r;
  102609. r = index << 24;
  102610. for (i=0; i<8; i++)
  102611. if (r & 0x80000000UL)
  102612. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  102613. polynomial, although we use an
  102614. unreflected alg and an init/final
  102615. of 0, not 0xffffffff */
  102616. else
  102617. r<<=1;
  102618. return (r & 0xffffffffUL);
  102619. }
  102620. #endif
  102621. static const ogg_uint32_t crc_lookup[256]={
  102622. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  102623. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  102624. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  102625. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  102626. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  102627. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  102628. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  102629. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  102630. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  102631. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  102632. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  102633. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  102634. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  102635. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  102636. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  102637. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  102638. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  102639. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  102640. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  102641. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  102642. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  102643. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  102644. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  102645. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  102646. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  102647. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  102648. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  102649. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  102650. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  102651. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  102652. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  102653. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  102654. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  102655. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  102656. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  102657. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  102658. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  102659. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  102660. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  102661. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  102662. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  102663. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  102664. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  102665. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  102666. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  102667. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  102668. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  102669. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  102670. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  102671. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  102672. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  102673. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  102674. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  102675. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  102676. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  102677. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  102678. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  102679. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  102680. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  102681. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  102682. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  102683. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  102684. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  102685. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  102686. /* init the encode/decode logical stream state */
  102687. int ogg_stream_init(ogg_stream_state *os,int serialno){
  102688. if(os){
  102689. memset(os,0,sizeof(*os));
  102690. os->body_storage=16*1024;
  102691. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  102692. os->lacing_storage=1024;
  102693. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  102694. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  102695. os->serialno=serialno;
  102696. return(0);
  102697. }
  102698. return(-1);
  102699. }
  102700. /* _clear does not free os, only the non-flat storage within */
  102701. int ogg_stream_clear(ogg_stream_state *os){
  102702. if(os){
  102703. if(os->body_data)_ogg_free(os->body_data);
  102704. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  102705. if(os->granule_vals)_ogg_free(os->granule_vals);
  102706. memset(os,0,sizeof(*os));
  102707. }
  102708. return(0);
  102709. }
  102710. int ogg_stream_destroy(ogg_stream_state *os){
  102711. if(os){
  102712. ogg_stream_clear(os);
  102713. _ogg_free(os);
  102714. }
  102715. return(0);
  102716. }
  102717. /* Helpers for ogg_stream_encode; this keeps the structure and
  102718. what's happening fairly clear */
  102719. static void _os_body_expand(ogg_stream_state *os,int needed){
  102720. if(os->body_storage<=os->body_fill+needed){
  102721. os->body_storage+=(needed+1024);
  102722. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  102723. }
  102724. }
  102725. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  102726. if(os->lacing_storage<=os->lacing_fill+needed){
  102727. os->lacing_storage+=(needed+32);
  102728. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  102729. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  102730. }
  102731. }
  102732. /* checksum the page */
  102733. /* Direct table CRC; note that this will be faster in the future if we
  102734. perform the checksum silmultaneously with other copies */
  102735. void ogg_page_checksum_set(ogg_page *og){
  102736. if(og){
  102737. ogg_uint32_t crc_reg=0;
  102738. int i;
  102739. /* safety; needed for API behavior, but not framing code */
  102740. og->header[22]=0;
  102741. og->header[23]=0;
  102742. og->header[24]=0;
  102743. og->header[25]=0;
  102744. for(i=0;i<og->header_len;i++)
  102745. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  102746. for(i=0;i<og->body_len;i++)
  102747. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  102748. og->header[22]=(unsigned char)(crc_reg&0xff);
  102749. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  102750. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  102751. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  102752. }
  102753. }
  102754. /* submit data to the internal buffer of the framing engine */
  102755. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  102756. int lacing_vals=op->bytes/255+1,i;
  102757. if(os->body_returned){
  102758. /* advance packet data according to the body_returned pointer. We
  102759. had to keep it around to return a pointer into the buffer last
  102760. call */
  102761. os->body_fill-=os->body_returned;
  102762. if(os->body_fill)
  102763. memmove(os->body_data,os->body_data+os->body_returned,
  102764. os->body_fill);
  102765. os->body_returned=0;
  102766. }
  102767. /* make sure we have the buffer storage */
  102768. _os_body_expand(os,op->bytes);
  102769. _os_lacing_expand(os,lacing_vals);
  102770. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  102771. the liability of overly clean abstraction for the time being. It
  102772. will actually be fairly easy to eliminate the extra copy in the
  102773. future */
  102774. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  102775. os->body_fill+=op->bytes;
  102776. /* Store lacing vals for this packet */
  102777. for(i=0;i<lacing_vals-1;i++){
  102778. os->lacing_vals[os->lacing_fill+i]=255;
  102779. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  102780. }
  102781. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  102782. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  102783. /* flag the first segment as the beginning of the packet */
  102784. os->lacing_vals[os->lacing_fill]|= 0x100;
  102785. os->lacing_fill+=lacing_vals;
  102786. /* for the sake of completeness */
  102787. os->packetno++;
  102788. if(op->e_o_s)os->e_o_s=1;
  102789. return(0);
  102790. }
  102791. /* This will flush remaining packets into a page (returning nonzero),
  102792. even if there is not enough data to trigger a flush normally
  102793. (undersized page). If there are no packets or partial packets to
  102794. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  102795. try to flush a normal sized page like ogg_stream_pageout; a call to
  102796. ogg_stream_flush does not guarantee that all packets have flushed.
  102797. Only a return value of 0 from ogg_stream_flush indicates all packet
  102798. data is flushed into pages.
  102799. since ogg_stream_flush will flush the last page in a stream even if
  102800. it's undersized, you almost certainly want to use ogg_stream_pageout
  102801. (and *not* ogg_stream_flush) unless you specifically need to flush
  102802. an page regardless of size in the middle of a stream. */
  102803. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  102804. int i;
  102805. int vals=0;
  102806. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  102807. int bytes=0;
  102808. long acc=0;
  102809. ogg_int64_t granule_pos=-1;
  102810. if(maxvals==0)return(0);
  102811. /* construct a page */
  102812. /* decide how many segments to include */
  102813. /* If this is the initial header case, the first page must only include
  102814. the initial header packet */
  102815. if(os->b_o_s==0){ /* 'initial header page' case */
  102816. granule_pos=0;
  102817. for(vals=0;vals<maxvals;vals++){
  102818. if((os->lacing_vals[vals]&0x0ff)<255){
  102819. vals++;
  102820. break;
  102821. }
  102822. }
  102823. }else{
  102824. for(vals=0;vals<maxvals;vals++){
  102825. if(acc>4096)break;
  102826. acc+=os->lacing_vals[vals]&0x0ff;
  102827. if((os->lacing_vals[vals]&0xff)<255)
  102828. granule_pos=os->granule_vals[vals];
  102829. }
  102830. }
  102831. /* construct the header in temp storage */
  102832. memcpy(os->header,"OggS",4);
  102833. /* stream structure version */
  102834. os->header[4]=0x00;
  102835. /* continued packet flag? */
  102836. os->header[5]=0x00;
  102837. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  102838. /* first page flag? */
  102839. if(os->b_o_s==0)os->header[5]|=0x02;
  102840. /* last page flag? */
  102841. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  102842. os->b_o_s=1;
  102843. /* 64 bits of PCM position */
  102844. for(i=6;i<14;i++){
  102845. os->header[i]=(unsigned char)(granule_pos&0xff);
  102846. granule_pos>>=8;
  102847. }
  102848. /* 32 bits of stream serial number */
  102849. {
  102850. long serialno=os->serialno;
  102851. for(i=14;i<18;i++){
  102852. os->header[i]=(unsigned char)(serialno&0xff);
  102853. serialno>>=8;
  102854. }
  102855. }
  102856. /* 32 bits of page counter (we have both counter and page header
  102857. because this val can roll over) */
  102858. if(os->pageno==-1)os->pageno=0; /* because someone called
  102859. stream_reset; this would be a
  102860. strange thing to do in an
  102861. encode stream, but it has
  102862. plausible uses */
  102863. {
  102864. long pageno=os->pageno++;
  102865. for(i=18;i<22;i++){
  102866. os->header[i]=(unsigned char)(pageno&0xff);
  102867. pageno>>=8;
  102868. }
  102869. }
  102870. /* zero for computation; filled in later */
  102871. os->header[22]=0;
  102872. os->header[23]=0;
  102873. os->header[24]=0;
  102874. os->header[25]=0;
  102875. /* segment table */
  102876. os->header[26]=(unsigned char)(vals&0xff);
  102877. for(i=0;i<vals;i++)
  102878. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  102879. /* set pointers in the ogg_page struct */
  102880. og->header=os->header;
  102881. og->header_len=os->header_fill=vals+27;
  102882. og->body=os->body_data+os->body_returned;
  102883. og->body_len=bytes;
  102884. /* advance the lacing data and set the body_returned pointer */
  102885. os->lacing_fill-=vals;
  102886. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  102887. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  102888. os->body_returned+=bytes;
  102889. /* calculate the checksum */
  102890. ogg_page_checksum_set(og);
  102891. /* done */
  102892. return(1);
  102893. }
  102894. /* This constructs pages from buffered packet segments. The pointers
  102895. returned are to static buffers; do not free. The returned buffers are
  102896. good only until the next call (using the same ogg_stream_state) */
  102897. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  102898. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  102899. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  102900. os->lacing_fill>=255 || /* 'segment table full' case */
  102901. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  102902. return(ogg_stream_flush(os,og));
  102903. }
  102904. /* not enough data to construct a page and not end of stream */
  102905. return(0);
  102906. }
  102907. int ogg_stream_eos(ogg_stream_state *os){
  102908. return os->e_o_s;
  102909. }
  102910. /* DECODING PRIMITIVES: packet streaming layer **********************/
  102911. /* This has two layers to place more of the multi-serialno and paging
  102912. control in the application's hands. First, we expose a data buffer
  102913. using ogg_sync_buffer(). The app either copies into the
  102914. buffer, or passes it directly to read(), etc. We then call
  102915. ogg_sync_wrote() to tell how many bytes we just added.
  102916. Pages are returned (pointers into the buffer in ogg_sync_state)
  102917. by ogg_sync_pageout(). The page is then submitted to
  102918. ogg_stream_pagein() along with the appropriate
  102919. ogg_stream_state* (ie, matching serialno). We then get raw
  102920. packets out calling ogg_stream_packetout() with a
  102921. ogg_stream_state. */
  102922. /* initialize the struct to a known state */
  102923. int ogg_sync_init(ogg_sync_state *oy){
  102924. if(oy){
  102925. memset(oy,0,sizeof(*oy));
  102926. }
  102927. return(0);
  102928. }
  102929. /* clear non-flat storage within */
  102930. int ogg_sync_clear(ogg_sync_state *oy){
  102931. if(oy){
  102932. if(oy->data)_ogg_free(oy->data);
  102933. ogg_sync_init(oy);
  102934. }
  102935. return(0);
  102936. }
  102937. int ogg_sync_destroy(ogg_sync_state *oy){
  102938. if(oy){
  102939. ogg_sync_clear(oy);
  102940. _ogg_free(oy);
  102941. }
  102942. return(0);
  102943. }
  102944. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  102945. /* first, clear out any space that has been previously returned */
  102946. if(oy->returned){
  102947. oy->fill-=oy->returned;
  102948. if(oy->fill>0)
  102949. memmove(oy->data,oy->data+oy->returned,oy->fill);
  102950. oy->returned=0;
  102951. }
  102952. if(size>oy->storage-oy->fill){
  102953. /* We need to extend the internal buffer */
  102954. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  102955. if(oy->data)
  102956. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  102957. else
  102958. oy->data=(unsigned char*) _ogg_malloc(newsize);
  102959. oy->storage=newsize;
  102960. }
  102961. /* expose a segment at least as large as requested at the fill mark */
  102962. return((char *)oy->data+oy->fill);
  102963. }
  102964. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  102965. if(oy->fill+bytes>oy->storage)return(-1);
  102966. oy->fill+=bytes;
  102967. return(0);
  102968. }
  102969. /* sync the stream. This is meant to be useful for finding page
  102970. boundaries.
  102971. return values for this:
  102972. -n) skipped n bytes
  102973. 0) page not ready; more data (no bytes skipped)
  102974. n) page synced at current location; page length n bytes
  102975. */
  102976. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  102977. unsigned char *page=oy->data+oy->returned;
  102978. unsigned char *next;
  102979. long bytes=oy->fill-oy->returned;
  102980. if(oy->headerbytes==0){
  102981. int headerbytes,i;
  102982. if(bytes<27)return(0); /* not enough for a header */
  102983. /* verify capture pattern */
  102984. if(memcmp(page,"OggS",4))goto sync_fail;
  102985. headerbytes=page[26]+27;
  102986. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  102987. /* count up body length in the segment table */
  102988. for(i=0;i<page[26];i++)
  102989. oy->bodybytes+=page[27+i];
  102990. oy->headerbytes=headerbytes;
  102991. }
  102992. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  102993. /* The whole test page is buffered. Verify the checksum */
  102994. {
  102995. /* Grab the checksum bytes, set the header field to zero */
  102996. char chksum[4];
  102997. ogg_page log;
  102998. memcpy(chksum,page+22,4);
  102999. memset(page+22,0,4);
  103000. /* set up a temp page struct and recompute the checksum */
  103001. log.header=page;
  103002. log.header_len=oy->headerbytes;
  103003. log.body=page+oy->headerbytes;
  103004. log.body_len=oy->bodybytes;
  103005. ogg_page_checksum_set(&log);
  103006. /* Compare */
  103007. if(memcmp(chksum,page+22,4)){
  103008. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  103009. at all) */
  103010. /* replace the computed checksum with the one actually read in */
  103011. memcpy(page+22,chksum,4);
  103012. /* Bad checksum. Lose sync */
  103013. goto sync_fail;
  103014. }
  103015. }
  103016. /* yes, have a whole page all ready to go */
  103017. {
  103018. unsigned char *page=oy->data+oy->returned;
  103019. long bytes;
  103020. if(og){
  103021. og->header=page;
  103022. og->header_len=oy->headerbytes;
  103023. og->body=page+oy->headerbytes;
  103024. og->body_len=oy->bodybytes;
  103025. }
  103026. oy->unsynced=0;
  103027. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  103028. oy->headerbytes=0;
  103029. oy->bodybytes=0;
  103030. return(bytes);
  103031. }
  103032. sync_fail:
  103033. oy->headerbytes=0;
  103034. oy->bodybytes=0;
  103035. /* search for possible capture */
  103036. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  103037. if(!next)
  103038. next=oy->data+oy->fill;
  103039. oy->returned=next-oy->data;
  103040. return(-(next-page));
  103041. }
  103042. /* sync the stream and get a page. Keep trying until we find a page.
  103043. Supress 'sync errors' after reporting the first.
  103044. return values:
  103045. -1) recapture (hole in data)
  103046. 0) need more data
  103047. 1) page returned
  103048. Returns pointers into buffered data; invalidated by next call to
  103049. _stream, _clear, _init, or _buffer */
  103050. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  103051. /* all we need to do is verify a page at the head of the stream
  103052. buffer. If it doesn't verify, we look for the next potential
  103053. frame */
  103054. for(;;){
  103055. long ret=ogg_sync_pageseek(oy,og);
  103056. if(ret>0){
  103057. /* have a page */
  103058. return(1);
  103059. }
  103060. if(ret==0){
  103061. /* need more data */
  103062. return(0);
  103063. }
  103064. /* head did not start a synced page... skipped some bytes */
  103065. if(!oy->unsynced){
  103066. oy->unsynced=1;
  103067. return(-1);
  103068. }
  103069. /* loop. keep looking */
  103070. }
  103071. }
  103072. /* add the incoming page to the stream state; we decompose the page
  103073. into packet segments here as well. */
  103074. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  103075. unsigned char *header=og->header;
  103076. unsigned char *body=og->body;
  103077. long bodysize=og->body_len;
  103078. int segptr=0;
  103079. int version=ogg_page_version(og);
  103080. int continued=ogg_page_continued(og);
  103081. int bos=ogg_page_bos(og);
  103082. int eos=ogg_page_eos(og);
  103083. ogg_int64_t granulepos=ogg_page_granulepos(og);
  103084. int serialno=ogg_page_serialno(og);
  103085. long pageno=ogg_page_pageno(og);
  103086. int segments=header[26];
  103087. /* clean up 'returned data' */
  103088. {
  103089. long lr=os->lacing_returned;
  103090. long br=os->body_returned;
  103091. /* body data */
  103092. if(br){
  103093. os->body_fill-=br;
  103094. if(os->body_fill)
  103095. memmove(os->body_data,os->body_data+br,os->body_fill);
  103096. os->body_returned=0;
  103097. }
  103098. if(lr){
  103099. /* segment table */
  103100. if(os->lacing_fill-lr){
  103101. memmove(os->lacing_vals,os->lacing_vals+lr,
  103102. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  103103. memmove(os->granule_vals,os->granule_vals+lr,
  103104. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  103105. }
  103106. os->lacing_fill-=lr;
  103107. os->lacing_packet-=lr;
  103108. os->lacing_returned=0;
  103109. }
  103110. }
  103111. /* check the serial number */
  103112. if(serialno!=os->serialno)return(-1);
  103113. if(version>0)return(-1);
  103114. _os_lacing_expand(os,segments+1);
  103115. /* are we in sequence? */
  103116. if(pageno!=os->pageno){
  103117. int i;
  103118. /* unroll previous partial packet (if any) */
  103119. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  103120. os->body_fill-=os->lacing_vals[i]&0xff;
  103121. os->lacing_fill=os->lacing_packet;
  103122. /* make a note of dropped data in segment table */
  103123. if(os->pageno!=-1){
  103124. os->lacing_vals[os->lacing_fill++]=0x400;
  103125. os->lacing_packet++;
  103126. }
  103127. }
  103128. /* are we a 'continued packet' page? If so, we may need to skip
  103129. some segments */
  103130. if(continued){
  103131. if(os->lacing_fill<1 ||
  103132. os->lacing_vals[os->lacing_fill-1]==0x400){
  103133. bos=0;
  103134. for(;segptr<segments;segptr++){
  103135. int val=header[27+segptr];
  103136. body+=val;
  103137. bodysize-=val;
  103138. if(val<255){
  103139. segptr++;
  103140. break;
  103141. }
  103142. }
  103143. }
  103144. }
  103145. if(bodysize){
  103146. _os_body_expand(os,bodysize);
  103147. memcpy(os->body_data+os->body_fill,body,bodysize);
  103148. os->body_fill+=bodysize;
  103149. }
  103150. {
  103151. int saved=-1;
  103152. while(segptr<segments){
  103153. int val=header[27+segptr];
  103154. os->lacing_vals[os->lacing_fill]=val;
  103155. os->granule_vals[os->lacing_fill]=-1;
  103156. if(bos){
  103157. os->lacing_vals[os->lacing_fill]|=0x100;
  103158. bos=0;
  103159. }
  103160. if(val<255)saved=os->lacing_fill;
  103161. os->lacing_fill++;
  103162. segptr++;
  103163. if(val<255)os->lacing_packet=os->lacing_fill;
  103164. }
  103165. /* set the granulepos on the last granuleval of the last full packet */
  103166. if(saved!=-1){
  103167. os->granule_vals[saved]=granulepos;
  103168. }
  103169. }
  103170. if(eos){
  103171. os->e_o_s=1;
  103172. if(os->lacing_fill>0)
  103173. os->lacing_vals[os->lacing_fill-1]|=0x200;
  103174. }
  103175. os->pageno=pageno+1;
  103176. return(0);
  103177. }
  103178. /* clear things to an initial state. Good to call, eg, before seeking */
  103179. int ogg_sync_reset(ogg_sync_state *oy){
  103180. oy->fill=0;
  103181. oy->returned=0;
  103182. oy->unsynced=0;
  103183. oy->headerbytes=0;
  103184. oy->bodybytes=0;
  103185. return(0);
  103186. }
  103187. int ogg_stream_reset(ogg_stream_state *os){
  103188. os->body_fill=0;
  103189. os->body_returned=0;
  103190. os->lacing_fill=0;
  103191. os->lacing_packet=0;
  103192. os->lacing_returned=0;
  103193. os->header_fill=0;
  103194. os->e_o_s=0;
  103195. os->b_o_s=0;
  103196. os->pageno=-1;
  103197. os->packetno=0;
  103198. os->granulepos=0;
  103199. return(0);
  103200. }
  103201. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  103202. ogg_stream_reset(os);
  103203. os->serialno=serialno;
  103204. return(0);
  103205. }
  103206. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  103207. /* The last part of decode. We have the stream broken into packet
  103208. segments. Now we need to group them into packets (or return the
  103209. out of sync markers) */
  103210. int ptr=os->lacing_returned;
  103211. if(os->lacing_packet<=ptr)return(0);
  103212. if(os->lacing_vals[ptr]&0x400){
  103213. /* we need to tell the codec there's a gap; it might need to
  103214. handle previous packet dependencies. */
  103215. os->lacing_returned++;
  103216. os->packetno++;
  103217. return(-1);
  103218. }
  103219. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  103220. to ask if there's a whole packet
  103221. waiting */
  103222. /* Gather the whole packet. We'll have no holes or a partial packet */
  103223. {
  103224. int size=os->lacing_vals[ptr]&0xff;
  103225. int bytes=size;
  103226. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  103227. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  103228. while(size==255){
  103229. int val=os->lacing_vals[++ptr];
  103230. size=val&0xff;
  103231. if(val&0x200)eos=0x200;
  103232. bytes+=size;
  103233. }
  103234. if(op){
  103235. op->e_o_s=eos;
  103236. op->b_o_s=bos;
  103237. op->packet=os->body_data+os->body_returned;
  103238. op->packetno=os->packetno;
  103239. op->granulepos=os->granule_vals[ptr];
  103240. op->bytes=bytes;
  103241. }
  103242. if(adv){
  103243. os->body_returned+=bytes;
  103244. os->lacing_returned=ptr+1;
  103245. os->packetno++;
  103246. }
  103247. }
  103248. return(1);
  103249. }
  103250. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  103251. return _packetout(os,op,1);
  103252. }
  103253. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  103254. return _packetout(os,op,0);
  103255. }
  103256. void ogg_packet_clear(ogg_packet *op) {
  103257. _ogg_free(op->packet);
  103258. memset(op, 0, sizeof(*op));
  103259. }
  103260. #ifdef _V_SELFTEST
  103261. #include <stdio.h>
  103262. ogg_stream_state os_en, os_de;
  103263. ogg_sync_state oy;
  103264. void checkpacket(ogg_packet *op,int len, int no, int pos){
  103265. long j;
  103266. static int sequence=0;
  103267. static int lastno=0;
  103268. if(op->bytes!=len){
  103269. fprintf(stderr,"incorrect packet length!\n");
  103270. exit(1);
  103271. }
  103272. if(op->granulepos!=pos){
  103273. fprintf(stderr,"incorrect packet position!\n");
  103274. exit(1);
  103275. }
  103276. /* packet number just follows sequence/gap; adjust the input number
  103277. for that */
  103278. if(no==0){
  103279. sequence=0;
  103280. }else{
  103281. sequence++;
  103282. if(no>lastno+1)
  103283. sequence++;
  103284. }
  103285. lastno=no;
  103286. if(op->packetno!=sequence){
  103287. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  103288. (long)(op->packetno),sequence);
  103289. exit(1);
  103290. }
  103291. /* Test data */
  103292. for(j=0;j<op->bytes;j++)
  103293. if(op->packet[j]!=((j+no)&0xff)){
  103294. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  103295. j,op->packet[j],(j+no)&0xff);
  103296. exit(1);
  103297. }
  103298. }
  103299. void check_page(unsigned char *data,const int *header,ogg_page *og){
  103300. long j;
  103301. /* Test data */
  103302. for(j=0;j<og->body_len;j++)
  103303. if(og->body[j]!=data[j]){
  103304. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  103305. j,data[j],og->body[j]);
  103306. exit(1);
  103307. }
  103308. /* Test header */
  103309. for(j=0;j<og->header_len;j++){
  103310. if(og->header[j]!=header[j]){
  103311. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  103312. for(j=0;j<header[26]+27;j++)
  103313. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  103314. fprintf(stderr,"\n");
  103315. exit(1);
  103316. }
  103317. }
  103318. if(og->header_len!=header[26]+27){
  103319. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  103320. og->header_len,header[26]+27);
  103321. exit(1);
  103322. }
  103323. }
  103324. void print_header(ogg_page *og){
  103325. int j;
  103326. fprintf(stderr,"\nHEADER:\n");
  103327. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  103328. og->header[0],og->header[1],og->header[2],og->header[3],
  103329. (int)og->header[4],(int)og->header[5]);
  103330. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  103331. (og->header[9]<<24)|(og->header[8]<<16)|
  103332. (og->header[7]<<8)|og->header[6],
  103333. (og->header[17]<<24)|(og->header[16]<<16)|
  103334. (og->header[15]<<8)|og->header[14],
  103335. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  103336. (og->header[19]<<8)|og->header[18]);
  103337. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  103338. (int)og->header[22],(int)og->header[23],
  103339. (int)og->header[24],(int)og->header[25],
  103340. (int)og->header[26]);
  103341. for(j=27;j<og->header_len;j++)
  103342. fprintf(stderr,"%d ",(int)og->header[j]);
  103343. fprintf(stderr,")\n\n");
  103344. }
  103345. void copy_page(ogg_page *og){
  103346. unsigned char *temp=_ogg_malloc(og->header_len);
  103347. memcpy(temp,og->header,og->header_len);
  103348. og->header=temp;
  103349. temp=_ogg_malloc(og->body_len);
  103350. memcpy(temp,og->body,og->body_len);
  103351. og->body=temp;
  103352. }
  103353. void free_page(ogg_page *og){
  103354. _ogg_free (og->header);
  103355. _ogg_free (og->body);
  103356. }
  103357. void error(void){
  103358. fprintf(stderr,"error!\n");
  103359. exit(1);
  103360. }
  103361. /* 17 only */
  103362. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  103363. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103364. 0x01,0x02,0x03,0x04,0,0,0,0,
  103365. 0x15,0xed,0xec,0x91,
  103366. 1,
  103367. 17};
  103368. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  103369. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103370. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103371. 0x01,0x02,0x03,0x04,0,0,0,0,
  103372. 0x59,0x10,0x6c,0x2c,
  103373. 1,
  103374. 17};
  103375. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  103376. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  103377. 0x01,0x02,0x03,0x04,1,0,0,0,
  103378. 0x89,0x33,0x85,0xce,
  103379. 13,
  103380. 254,255,0,255,1,255,245,255,255,0,
  103381. 255,255,90};
  103382. /* nil packets; beginning,middle,end */
  103383. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103384. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103385. 0x01,0x02,0x03,0x04,0,0,0,0,
  103386. 0xff,0x7b,0x23,0x17,
  103387. 1,
  103388. 0};
  103389. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  103390. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  103391. 0x01,0x02,0x03,0x04,1,0,0,0,
  103392. 0x5c,0x3f,0x66,0xcb,
  103393. 17,
  103394. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  103395. 255,255,90,0};
  103396. /* large initial packet */
  103397. const int head1_3[] = {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. 0x01,0x27,0x31,0xaa,
  103401. 18,
  103402. 255,255,255,255,255,255,255,255,
  103403. 255,255,255,255,255,255,255,255,255,10};
  103404. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  103405. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  103406. 0x01,0x02,0x03,0x04,1,0,0,0,
  103407. 0x7f,0x4e,0x8a,0xd2,
  103408. 4,
  103409. 255,4,255,0};
  103410. /* continuing packet test */
  103411. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103412. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103413. 0x01,0x02,0x03,0x04,0,0,0,0,
  103414. 0xff,0x7b,0x23,0x17,
  103415. 1,
  103416. 0};
  103417. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  103418. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  103419. 0x01,0x02,0x03,0x04,1,0,0,0,
  103420. 0x54,0x05,0x51,0xc8,
  103421. 17,
  103422. 255,255,255,255,255,255,255,255,
  103423. 255,255,255,255,255,255,255,255,255};
  103424. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  103425. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  103426. 0x01,0x02,0x03,0x04,2,0,0,0,
  103427. 0xc8,0xc3,0xcb,0xed,
  103428. 5,
  103429. 10,255,4,255,0};
  103430. /* page with the 255 segment limit */
  103431. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103432. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103433. 0x01,0x02,0x03,0x04,0,0,0,0,
  103434. 0xff,0x7b,0x23,0x17,
  103435. 1,
  103436. 0};
  103437. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  103438. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  103439. 0x01,0x02,0x03,0x04,1,0,0,0,
  103440. 0xed,0x2a,0x2e,0xa7,
  103441. 255,
  103442. 10,10,10,10,10,10,10,10,
  103443. 10,10,10,10,10,10,10,10,
  103444. 10,10,10,10,10,10,10,10,
  103445. 10,10,10,10,10,10,10,10,
  103446. 10,10,10,10,10,10,10,10,
  103447. 10,10,10,10,10,10,10,10,
  103448. 10,10,10,10,10,10,10,10,
  103449. 10,10,10,10,10,10,10,10,
  103450. 10,10,10,10,10,10,10,10,
  103451. 10,10,10,10,10,10,10,10,
  103452. 10,10,10,10,10,10,10,10,
  103453. 10,10,10,10,10,10,10,10,
  103454. 10,10,10,10,10,10,10,10,
  103455. 10,10,10,10,10,10,10,10,
  103456. 10,10,10,10,10,10,10,10,
  103457. 10,10,10,10,10,10,10,10,
  103458. 10,10,10,10,10,10,10,10,
  103459. 10,10,10,10,10,10,10,10,
  103460. 10,10,10,10,10,10,10,10,
  103461. 10,10,10,10,10,10,10,10,
  103462. 10,10,10,10,10,10,10,10,
  103463. 10,10,10,10,10,10,10,10,
  103464. 10,10,10,10,10,10,10,10,
  103465. 10,10,10,10,10,10,10,10,
  103466. 10,10,10,10,10,10,10,10,
  103467. 10,10,10,10,10,10,10,10,
  103468. 10,10,10,10,10,10,10,10,
  103469. 10,10,10,10,10,10,10,10,
  103470. 10,10,10,10,10,10,10,10,
  103471. 10,10,10,10,10,10,10,10,
  103472. 10,10,10,10,10,10,10,10,
  103473. 10,10,10,10,10,10,10};
  103474. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  103475. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  103476. 0x01,0x02,0x03,0x04,2,0,0,0,
  103477. 0x6c,0x3b,0x82,0x3d,
  103478. 1,
  103479. 50};
  103480. /* packet that overspans over an entire page */
  103481. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103482. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103483. 0x01,0x02,0x03,0x04,0,0,0,0,
  103484. 0xff,0x7b,0x23,0x17,
  103485. 1,
  103486. 0};
  103487. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  103488. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  103489. 0x01,0x02,0x03,0x04,1,0,0,0,
  103490. 0x3c,0xd9,0x4d,0x3f,
  103491. 17,
  103492. 100,255,255,255,255,255,255,255,255,
  103493. 255,255,255,255,255,255,255,255};
  103494. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  103495. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  103496. 0x01,0x02,0x03,0x04,2,0,0,0,
  103497. 0x01,0xd2,0xe5,0xe5,
  103498. 17,
  103499. 255,255,255,255,255,255,255,255,
  103500. 255,255,255,255,255,255,255,255,255};
  103501. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  103502. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  103503. 0x01,0x02,0x03,0x04,3,0,0,0,
  103504. 0xef,0xdd,0x88,0xde,
  103505. 7,
  103506. 255,255,75,255,4,255,0};
  103507. /* packet that overspans over an entire page */
  103508. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  103509. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  103510. 0x01,0x02,0x03,0x04,0,0,0,0,
  103511. 0xff,0x7b,0x23,0x17,
  103512. 1,
  103513. 0};
  103514. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  103515. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  103516. 0x01,0x02,0x03,0x04,1,0,0,0,
  103517. 0x3c,0xd9,0x4d,0x3f,
  103518. 17,
  103519. 100,255,255,255,255,255,255,255,255,
  103520. 255,255,255,255,255,255,255,255};
  103521. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  103522. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  103523. 0x01,0x02,0x03,0x04,2,0,0,0,
  103524. 0xd4,0xe0,0x60,0xe5,
  103525. 1,0};
  103526. void test_pack(const int *pl, const int **headers, int byteskip,
  103527. int pageskip, int packetskip){
  103528. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  103529. long inptr=0;
  103530. long outptr=0;
  103531. long deptr=0;
  103532. long depacket=0;
  103533. long granule_pos=7,pageno=0;
  103534. int i,j,packets,pageout=pageskip;
  103535. int eosflag=0;
  103536. int bosflag=0;
  103537. int byteskipcount=0;
  103538. ogg_stream_reset(&os_en);
  103539. ogg_stream_reset(&os_de);
  103540. ogg_sync_reset(&oy);
  103541. for(packets=0;packets<packetskip;packets++)
  103542. depacket+=pl[packets];
  103543. for(packets=0;;packets++)if(pl[packets]==-1)break;
  103544. for(i=0;i<packets;i++){
  103545. /* construct a test packet */
  103546. ogg_packet op;
  103547. int len=pl[i];
  103548. op.packet=data+inptr;
  103549. op.bytes=len;
  103550. op.e_o_s=(pl[i+1]<0?1:0);
  103551. op.granulepos=granule_pos;
  103552. granule_pos+=1024;
  103553. for(j=0;j<len;j++)data[inptr++]=i+j;
  103554. /* submit the test packet */
  103555. ogg_stream_packetin(&os_en,&op);
  103556. /* retrieve any finished pages */
  103557. {
  103558. ogg_page og;
  103559. while(ogg_stream_pageout(&os_en,&og)){
  103560. /* We have a page. Check it carefully */
  103561. fprintf(stderr,"%ld, ",pageno);
  103562. if(headers[pageno]==NULL){
  103563. fprintf(stderr,"coded too many pages!\n");
  103564. exit(1);
  103565. }
  103566. check_page(data+outptr,headers[pageno],&og);
  103567. outptr+=og.body_len;
  103568. pageno++;
  103569. if(pageskip){
  103570. bosflag=1;
  103571. pageskip--;
  103572. deptr+=og.body_len;
  103573. }
  103574. /* have a complete page; submit it to sync/decode */
  103575. {
  103576. ogg_page og_de;
  103577. ogg_packet op_de,op_de2;
  103578. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  103579. char *next=buf;
  103580. byteskipcount+=og.header_len;
  103581. if(byteskipcount>byteskip){
  103582. memcpy(next,og.header,byteskipcount-byteskip);
  103583. next+=byteskipcount-byteskip;
  103584. byteskipcount=byteskip;
  103585. }
  103586. byteskipcount+=og.body_len;
  103587. if(byteskipcount>byteskip){
  103588. memcpy(next,og.body,byteskipcount-byteskip);
  103589. next+=byteskipcount-byteskip;
  103590. byteskipcount=byteskip;
  103591. }
  103592. ogg_sync_wrote(&oy,next-buf);
  103593. while(1){
  103594. int ret=ogg_sync_pageout(&oy,&og_de);
  103595. if(ret==0)break;
  103596. if(ret<0)continue;
  103597. /* got a page. Happy happy. Verify that it's good. */
  103598. fprintf(stderr,"(%ld), ",pageout);
  103599. check_page(data+deptr,headers[pageout],&og_de);
  103600. deptr+=og_de.body_len;
  103601. pageout++;
  103602. /* submit it to deconstitution */
  103603. ogg_stream_pagein(&os_de,&og_de);
  103604. /* packets out? */
  103605. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  103606. ogg_stream_packetpeek(&os_de,NULL);
  103607. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  103608. /* verify peek and out match */
  103609. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  103610. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  103611. depacket);
  103612. exit(1);
  103613. }
  103614. /* verify the packet! */
  103615. /* check data */
  103616. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  103617. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  103618. depacket);
  103619. exit(1);
  103620. }
  103621. /* check bos flag */
  103622. if(bosflag==0 && op_de.b_o_s==0){
  103623. fprintf(stderr,"b_o_s flag not set on packet!\n");
  103624. exit(1);
  103625. }
  103626. if(bosflag && op_de.b_o_s){
  103627. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  103628. exit(1);
  103629. }
  103630. bosflag=1;
  103631. depacket+=op_de.bytes;
  103632. /* check eos flag */
  103633. if(eosflag){
  103634. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  103635. exit(1);
  103636. }
  103637. if(op_de.e_o_s)eosflag=1;
  103638. /* check granulepos flag */
  103639. if(op_de.granulepos!=-1){
  103640. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  103641. }
  103642. }
  103643. }
  103644. }
  103645. }
  103646. }
  103647. }
  103648. _ogg_free(data);
  103649. if(headers[pageno]!=NULL){
  103650. fprintf(stderr,"did not write last page!\n");
  103651. exit(1);
  103652. }
  103653. if(headers[pageout]!=NULL){
  103654. fprintf(stderr,"did not decode last page!\n");
  103655. exit(1);
  103656. }
  103657. if(inptr!=outptr){
  103658. fprintf(stderr,"encoded page data incomplete!\n");
  103659. exit(1);
  103660. }
  103661. if(inptr!=deptr){
  103662. fprintf(stderr,"decoded page data incomplete!\n");
  103663. exit(1);
  103664. }
  103665. if(inptr!=depacket){
  103666. fprintf(stderr,"decoded packet data incomplete!\n");
  103667. exit(1);
  103668. }
  103669. if(!eosflag){
  103670. fprintf(stderr,"Never got a packet with EOS set!\n");
  103671. exit(1);
  103672. }
  103673. fprintf(stderr,"ok.\n");
  103674. }
  103675. int main(void){
  103676. ogg_stream_init(&os_en,0x04030201);
  103677. ogg_stream_init(&os_de,0x04030201);
  103678. ogg_sync_init(&oy);
  103679. /* Exercise each code path in the framing code. Also verify that
  103680. the checksums are working. */
  103681. {
  103682. /* 17 only */
  103683. const int packets[]={17, -1};
  103684. const int *headret[]={head1_0,NULL};
  103685. fprintf(stderr,"testing single page encoding... ");
  103686. test_pack(packets,headret,0,0,0);
  103687. }
  103688. {
  103689. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  103690. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  103691. const int *headret[]={head1_1,head2_1,NULL};
  103692. fprintf(stderr,"testing basic page encoding... ");
  103693. test_pack(packets,headret,0,0,0);
  103694. }
  103695. {
  103696. /* nil packets; beginning,middle,end */
  103697. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  103698. const int *headret[]={head1_2,head2_2,NULL};
  103699. fprintf(stderr,"testing basic nil packets... ");
  103700. test_pack(packets,headret,0,0,0);
  103701. }
  103702. {
  103703. /* large initial packet */
  103704. const int packets[]={4345,259,255,-1};
  103705. const int *headret[]={head1_3,head2_3,NULL};
  103706. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  103707. test_pack(packets,headret,0,0,0);
  103708. }
  103709. {
  103710. /* continuing packet test */
  103711. const int packets[]={0,4345,259,255,-1};
  103712. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  103713. fprintf(stderr,"testing single packet page span... ");
  103714. test_pack(packets,headret,0,0,0);
  103715. }
  103716. /* page with the 255 segment limit */
  103717. {
  103718. const int packets[]={0,10,10,10,10,10,10,10,10,
  103719. 10,10,10,10,10,10,10,10,
  103720. 10,10,10,10,10,10,10,10,
  103721. 10,10,10,10,10,10,10,10,
  103722. 10,10,10,10,10,10,10,10,
  103723. 10,10,10,10,10,10,10,10,
  103724. 10,10,10,10,10,10,10,10,
  103725. 10,10,10,10,10,10,10,10,
  103726. 10,10,10,10,10,10,10,10,
  103727. 10,10,10,10,10,10,10,10,
  103728. 10,10,10,10,10,10,10,10,
  103729. 10,10,10,10,10,10,10,10,
  103730. 10,10,10,10,10,10,10,10,
  103731. 10,10,10,10,10,10,10,10,
  103732. 10,10,10,10,10,10,10,10,
  103733. 10,10,10,10,10,10,10,10,
  103734. 10,10,10,10,10,10,10,10,
  103735. 10,10,10,10,10,10,10,10,
  103736. 10,10,10,10,10,10,10,10,
  103737. 10,10,10,10,10,10,10,10,
  103738. 10,10,10,10,10,10,10,10,
  103739. 10,10,10,10,10,10,10,10,
  103740. 10,10,10,10,10,10,10,10,
  103741. 10,10,10,10,10,10,10,10,
  103742. 10,10,10,10,10,10,10,10,
  103743. 10,10,10,10,10,10,10,10,
  103744. 10,10,10,10,10,10,10,10,
  103745. 10,10,10,10,10,10,10,10,
  103746. 10,10,10,10,10,10,10,10,
  103747. 10,10,10,10,10,10,10,10,
  103748. 10,10,10,10,10,10,10,10,
  103749. 10,10,10,10,10,10,10,50,-1};
  103750. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  103751. fprintf(stderr,"testing max packet segments... ");
  103752. test_pack(packets,headret,0,0,0);
  103753. }
  103754. {
  103755. /* packet that overspans over an entire page */
  103756. const int packets[]={0,100,9000,259,255,-1};
  103757. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  103758. fprintf(stderr,"testing very large packets... ");
  103759. test_pack(packets,headret,0,0,0);
  103760. }
  103761. {
  103762. /* test for the libogg 1.1.1 resync in large continuation bug
  103763. found by Josh Coalson) */
  103764. const int packets[]={0,100,9000,259,255,-1};
  103765. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  103766. fprintf(stderr,"testing continuation resync in very large packets... ");
  103767. test_pack(packets,headret,100,2,3);
  103768. }
  103769. {
  103770. /* term only page. why not? */
  103771. const int packets[]={0,100,4080,-1};
  103772. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  103773. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  103774. test_pack(packets,headret,0,0,0);
  103775. }
  103776. {
  103777. /* build a bunch of pages for testing */
  103778. unsigned char *data=_ogg_malloc(1024*1024);
  103779. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  103780. int inptr=0,i,j;
  103781. ogg_page og[5];
  103782. ogg_stream_reset(&os_en);
  103783. for(i=0;pl[i]!=-1;i++){
  103784. ogg_packet op;
  103785. int len=pl[i];
  103786. op.packet=data+inptr;
  103787. op.bytes=len;
  103788. op.e_o_s=(pl[i+1]<0?1:0);
  103789. op.granulepos=(i+1)*1000;
  103790. for(j=0;j<len;j++)data[inptr++]=i+j;
  103791. ogg_stream_packetin(&os_en,&op);
  103792. }
  103793. _ogg_free(data);
  103794. /* retrieve finished pages */
  103795. for(i=0;i<5;i++){
  103796. if(ogg_stream_pageout(&os_en,&og[i])==0){
  103797. fprintf(stderr,"Too few pages output building sync tests!\n");
  103798. exit(1);
  103799. }
  103800. copy_page(&og[i]);
  103801. }
  103802. /* Test lost pages on pagein/packetout: no rollback */
  103803. {
  103804. ogg_page temp;
  103805. ogg_packet test;
  103806. fprintf(stderr,"Testing loss of pages... ");
  103807. ogg_sync_reset(&oy);
  103808. ogg_stream_reset(&os_de);
  103809. for(i=0;i<5;i++){
  103810. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  103811. og[i].header_len);
  103812. ogg_sync_wrote(&oy,og[i].header_len);
  103813. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  103814. ogg_sync_wrote(&oy,og[i].body_len);
  103815. }
  103816. ogg_sync_pageout(&oy,&temp);
  103817. ogg_stream_pagein(&os_de,&temp);
  103818. ogg_sync_pageout(&oy,&temp);
  103819. ogg_stream_pagein(&os_de,&temp);
  103820. ogg_sync_pageout(&oy,&temp);
  103821. /* skip */
  103822. ogg_sync_pageout(&oy,&temp);
  103823. ogg_stream_pagein(&os_de,&temp);
  103824. /* do we get the expected results/packets? */
  103825. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103826. checkpacket(&test,0,0,0);
  103827. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103828. checkpacket(&test,100,1,-1);
  103829. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103830. checkpacket(&test,4079,2,3000);
  103831. if(ogg_stream_packetout(&os_de,&test)!=-1){
  103832. fprintf(stderr,"Error: loss of page did not return error\n");
  103833. exit(1);
  103834. }
  103835. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103836. checkpacket(&test,76,5,-1);
  103837. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103838. checkpacket(&test,34,6,-1);
  103839. fprintf(stderr,"ok.\n");
  103840. }
  103841. /* Test lost pages on pagein/packetout: rollback with continuation */
  103842. {
  103843. ogg_page temp;
  103844. ogg_packet test;
  103845. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  103846. ogg_sync_reset(&oy);
  103847. ogg_stream_reset(&os_de);
  103848. for(i=0;i<5;i++){
  103849. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  103850. og[i].header_len);
  103851. ogg_sync_wrote(&oy,og[i].header_len);
  103852. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  103853. ogg_sync_wrote(&oy,og[i].body_len);
  103854. }
  103855. ogg_sync_pageout(&oy,&temp);
  103856. ogg_stream_pagein(&os_de,&temp);
  103857. ogg_sync_pageout(&oy,&temp);
  103858. ogg_stream_pagein(&os_de,&temp);
  103859. ogg_sync_pageout(&oy,&temp);
  103860. ogg_stream_pagein(&os_de,&temp);
  103861. ogg_sync_pageout(&oy,&temp);
  103862. /* skip */
  103863. ogg_sync_pageout(&oy,&temp);
  103864. ogg_stream_pagein(&os_de,&temp);
  103865. /* do we get the expected results/packets? */
  103866. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103867. checkpacket(&test,0,0,0);
  103868. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103869. checkpacket(&test,100,1,-1);
  103870. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103871. checkpacket(&test,4079,2,3000);
  103872. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103873. checkpacket(&test,2956,3,4000);
  103874. if(ogg_stream_packetout(&os_de,&test)!=-1){
  103875. fprintf(stderr,"Error: loss of page did not return error\n");
  103876. exit(1);
  103877. }
  103878. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103879. checkpacket(&test,300,13,14000);
  103880. fprintf(stderr,"ok.\n");
  103881. }
  103882. /* the rest only test sync */
  103883. {
  103884. ogg_page og_de;
  103885. /* Test fractional page inputs: incomplete capture */
  103886. fprintf(stderr,"Testing sync on partial inputs... ");
  103887. ogg_sync_reset(&oy);
  103888. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103889. 3);
  103890. ogg_sync_wrote(&oy,3);
  103891. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103892. /* Test fractional page inputs: incomplete fixed header */
  103893. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  103894. 20);
  103895. ogg_sync_wrote(&oy,20);
  103896. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103897. /* Test fractional page inputs: incomplete header */
  103898. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  103899. 5);
  103900. ogg_sync_wrote(&oy,5);
  103901. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103902. /* Test fractional page inputs: incomplete body */
  103903. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  103904. og[1].header_len-28);
  103905. ogg_sync_wrote(&oy,og[1].header_len-28);
  103906. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103907. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  103908. ogg_sync_wrote(&oy,1000);
  103909. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103910. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  103911. og[1].body_len-1000);
  103912. ogg_sync_wrote(&oy,og[1].body_len-1000);
  103913. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103914. fprintf(stderr,"ok.\n");
  103915. }
  103916. /* Test fractional page inputs: page + incomplete capture */
  103917. {
  103918. ogg_page og_de;
  103919. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  103920. ogg_sync_reset(&oy);
  103921. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103922. og[1].header_len);
  103923. ogg_sync_wrote(&oy,og[1].header_len);
  103924. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103925. og[1].body_len);
  103926. ogg_sync_wrote(&oy,og[1].body_len);
  103927. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103928. 20);
  103929. ogg_sync_wrote(&oy,20);
  103930. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103931. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103932. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  103933. og[1].header_len-20);
  103934. ogg_sync_wrote(&oy,og[1].header_len-20);
  103935. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103936. og[1].body_len);
  103937. ogg_sync_wrote(&oy,og[1].body_len);
  103938. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103939. fprintf(stderr,"ok.\n");
  103940. }
  103941. /* Test recapture: garbage + page */
  103942. {
  103943. ogg_page og_de;
  103944. fprintf(stderr,"Testing search for capture... ");
  103945. ogg_sync_reset(&oy);
  103946. /* 'garbage' */
  103947. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103948. og[1].body_len);
  103949. ogg_sync_wrote(&oy,og[1].body_len);
  103950. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103951. og[1].header_len);
  103952. ogg_sync_wrote(&oy,og[1].header_len);
  103953. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103954. og[1].body_len);
  103955. ogg_sync_wrote(&oy,og[1].body_len);
  103956. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  103957. 20);
  103958. ogg_sync_wrote(&oy,20);
  103959. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103960. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103961. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103962. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  103963. og[2].header_len-20);
  103964. ogg_sync_wrote(&oy,og[2].header_len-20);
  103965. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  103966. og[2].body_len);
  103967. ogg_sync_wrote(&oy,og[2].body_len);
  103968. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103969. fprintf(stderr,"ok.\n");
  103970. }
  103971. /* Test recapture: page + garbage + page */
  103972. {
  103973. ogg_page og_de;
  103974. fprintf(stderr,"Testing recapture... ");
  103975. ogg_sync_reset(&oy);
  103976. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103977. og[1].header_len);
  103978. ogg_sync_wrote(&oy,og[1].header_len);
  103979. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103980. og[1].body_len);
  103981. ogg_sync_wrote(&oy,og[1].body_len);
  103982. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  103983. og[2].header_len);
  103984. ogg_sync_wrote(&oy,og[2].header_len);
  103985. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  103986. og[2].header_len);
  103987. ogg_sync_wrote(&oy,og[2].header_len);
  103988. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103989. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  103990. og[2].body_len-5);
  103991. ogg_sync_wrote(&oy,og[2].body_len-5);
  103992. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  103993. og[3].header_len);
  103994. ogg_sync_wrote(&oy,og[3].header_len);
  103995. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  103996. og[3].body_len);
  103997. ogg_sync_wrote(&oy,og[3].body_len);
  103998. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103999. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  104000. fprintf(stderr,"ok.\n");
  104001. }
  104002. /* Free page data that was previously copied */
  104003. {
  104004. for(i=0;i<5;i++){
  104005. free_page(&og[i]);
  104006. }
  104007. }
  104008. }
  104009. return(0);
  104010. }
  104011. #endif
  104012. #endif
  104013. /********* End of inlined file: framing.c *********/
  104014. /********* Start of inlined file: analysis.c *********/
  104015. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  104016. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104017. // tasks..
  104018. #ifdef _MSC_VER
  104019. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104020. #endif
  104021. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  104022. #if JUCE_USE_OGGVORBIS
  104023. #include <stdio.h>
  104024. #include <string.h>
  104025. #include <math.h>
  104026. /********* Start of inlined file: codec_internal.h *********/
  104027. #ifndef _V_CODECI_H_
  104028. #define _V_CODECI_H_
  104029. /********* Start of inlined file: envelope.h *********/
  104030. #ifndef _V_ENVELOPE_
  104031. #define _V_ENVELOPE_
  104032. /********* Start of inlined file: mdct.h *********/
  104033. #ifndef _OGG_mdct_H_
  104034. #define _OGG_mdct_H_
  104035. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  104036. #ifdef MDCT_INTEGERIZED
  104037. #define DATA_TYPE int
  104038. #define REG_TYPE register int
  104039. #define TRIGBITS 14
  104040. #define cPI3_8 6270
  104041. #define cPI2_8 11585
  104042. #define cPI1_8 15137
  104043. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  104044. #define MULT_NORM(x) ((x)>>TRIGBITS)
  104045. #define HALVE(x) ((x)>>1)
  104046. #else
  104047. #define DATA_TYPE float
  104048. #define REG_TYPE float
  104049. #define cPI3_8 .38268343236508977175F
  104050. #define cPI2_8 .70710678118654752441F
  104051. #define cPI1_8 .92387953251128675613F
  104052. #define FLOAT_CONV(x) (x)
  104053. #define MULT_NORM(x) (x)
  104054. #define HALVE(x) ((x)*.5f)
  104055. #endif
  104056. typedef struct {
  104057. int n;
  104058. int log2n;
  104059. DATA_TYPE *trig;
  104060. int *bitrev;
  104061. DATA_TYPE scale;
  104062. } mdct_lookup;
  104063. extern void mdct_init(mdct_lookup *lookup,int n);
  104064. extern void mdct_clear(mdct_lookup *l);
  104065. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  104066. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  104067. #endif
  104068. /********* End of inlined file: mdct.h *********/
  104069. #define VE_PRE 16
  104070. #define VE_WIN 4
  104071. #define VE_POST 2
  104072. #define VE_AMP (VE_PRE+VE_POST-1)
  104073. #define VE_BANDS 7
  104074. #define VE_NEARDC 15
  104075. #define VE_MINSTRETCH 2 /* a bit less than short block */
  104076. #define VE_MAXSTRETCH 12 /* one-third full block */
  104077. typedef struct {
  104078. float ampbuf[VE_AMP];
  104079. int ampptr;
  104080. float nearDC[VE_NEARDC];
  104081. float nearDC_acc;
  104082. float nearDC_partialacc;
  104083. int nearptr;
  104084. } envelope_filter_state;
  104085. typedef struct {
  104086. int begin;
  104087. int end;
  104088. float *window;
  104089. float total;
  104090. } envelope_band;
  104091. typedef struct {
  104092. int ch;
  104093. int winlength;
  104094. int searchstep;
  104095. float minenergy;
  104096. mdct_lookup mdct;
  104097. float *mdct_win;
  104098. envelope_band band[VE_BANDS];
  104099. envelope_filter_state *filter;
  104100. int stretch;
  104101. int *mark;
  104102. long storage;
  104103. long current;
  104104. long curmark;
  104105. long cursor;
  104106. } envelope_lookup;
  104107. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  104108. extern void _ve_envelope_clear(envelope_lookup *e);
  104109. extern long _ve_envelope_search(vorbis_dsp_state *v);
  104110. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  104111. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  104112. #endif
  104113. /********* End of inlined file: envelope.h *********/
  104114. /********* Start of inlined file: codebook.h *********/
  104115. #ifndef _V_CODEBOOK_H_
  104116. #define _V_CODEBOOK_H_
  104117. /* This structure encapsulates huffman and VQ style encoding books; it
  104118. doesn't do anything specific to either.
  104119. valuelist/quantlist are nonNULL (and q_* significant) only if
  104120. there's entry->value mapping to be done.
  104121. If encode-side mapping must be done (and thus the entry needs to be
  104122. hunted), the auxiliary encode pointer will point to a decision
  104123. tree. This is true of both VQ and huffman, but is mostly useful
  104124. with VQ.
  104125. */
  104126. typedef struct static_codebook{
  104127. long dim; /* codebook dimensions (elements per vector) */
  104128. long entries; /* codebook entries */
  104129. long *lengthlist; /* codeword lengths in bits */
  104130. /* mapping ***************************************************************/
  104131. int maptype; /* 0=none
  104132. 1=implicitly populated values from map column
  104133. 2=listed arbitrary values */
  104134. /* The below does a linear, single monotonic sequence mapping. */
  104135. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  104136. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  104137. int q_quant; /* bits: 0 < quant <= 16 */
  104138. int q_sequencep; /* bitflag */
  104139. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  104140. map == 2: list of dim*entries quantized entry vals
  104141. */
  104142. /* encode helpers ********************************************************/
  104143. struct encode_aux_nearestmatch *nearest_tree;
  104144. struct encode_aux_threshmatch *thresh_tree;
  104145. struct encode_aux_pigeonhole *pigeon_tree;
  104146. int allocedp;
  104147. } static_codebook;
  104148. /* this structures an arbitrary trained book to quickly find the
  104149. nearest cell match */
  104150. typedef struct encode_aux_nearestmatch{
  104151. /* pre-calculated partitioning tree */
  104152. long *ptr0;
  104153. long *ptr1;
  104154. long *p; /* decision points (each is an entry) */
  104155. long *q; /* decision points (each is an entry) */
  104156. long aux; /* number of tree entries */
  104157. long alloc;
  104158. } encode_aux_nearestmatch;
  104159. /* assumes a maptype of 1; encode side only, so that's OK */
  104160. typedef struct encode_aux_threshmatch{
  104161. float *quantthresh;
  104162. long *quantmap;
  104163. int quantvals;
  104164. int threshvals;
  104165. } encode_aux_threshmatch;
  104166. typedef struct encode_aux_pigeonhole{
  104167. float min;
  104168. float del;
  104169. int mapentries;
  104170. int quantvals;
  104171. long *pigeonmap;
  104172. long fittotal;
  104173. long *fitlist;
  104174. long *fitmap;
  104175. long *fitlength;
  104176. } encode_aux_pigeonhole;
  104177. typedef struct codebook{
  104178. long dim; /* codebook dimensions (elements per vector) */
  104179. long entries; /* codebook entries */
  104180. long used_entries; /* populated codebook entries */
  104181. const static_codebook *c;
  104182. /* for encode, the below are entry-ordered, fully populated */
  104183. /* for decode, the below are ordered by bitreversed codeword and only
  104184. used entries are populated */
  104185. float *valuelist; /* list of dim*entries actual entry values */
  104186. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  104187. int *dec_index; /* only used if sparseness collapsed */
  104188. char *dec_codelengths;
  104189. ogg_uint32_t *dec_firsttable;
  104190. int dec_firsttablen;
  104191. int dec_maxlength;
  104192. } codebook;
  104193. extern void vorbis_staticbook_clear(static_codebook *b);
  104194. extern void vorbis_staticbook_destroy(static_codebook *b);
  104195. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  104196. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  104197. extern void vorbis_book_clear(codebook *b);
  104198. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  104199. extern float *_book_logdist(const static_codebook *b,float *vals);
  104200. extern float _float32_unpack(long val);
  104201. extern long _float32_pack(float val);
  104202. extern int _best(codebook *book, float *a, int step);
  104203. extern int _ilog(unsigned int v);
  104204. extern long _book_maptype1_quantvals(const static_codebook *b);
  104205. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  104206. extern long vorbis_book_codeword(codebook *book,int entry);
  104207. extern long vorbis_book_codelen(codebook *book,int entry);
  104208. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  104209. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  104210. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  104211. extern int vorbis_book_errorv(codebook *book, float *a);
  104212. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  104213. oggpack_buffer *b);
  104214. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  104215. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  104216. oggpack_buffer *b,int n);
  104217. extern long vorbis_book_decodev_set(codebook *book, float *a,
  104218. oggpack_buffer *b,int n);
  104219. extern long vorbis_book_decodev_add(codebook *book, float *a,
  104220. oggpack_buffer *b,int n);
  104221. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  104222. long off,int ch,
  104223. oggpack_buffer *b,int n);
  104224. #endif
  104225. /********* End of inlined file: codebook.h *********/
  104226. #define BLOCKTYPE_IMPULSE 0
  104227. #define BLOCKTYPE_PADDING 1
  104228. #define BLOCKTYPE_TRANSITION 0
  104229. #define BLOCKTYPE_LONG 1
  104230. #define PACKETBLOBS 15
  104231. typedef struct vorbis_block_internal{
  104232. float **pcmdelay; /* this is a pointer into local storage */
  104233. float ampmax;
  104234. int blocktype;
  104235. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  104236. blob [PACKETBLOBS/2] points to
  104237. the oggpack_buffer in the
  104238. main vorbis_block */
  104239. } vorbis_block_internal;
  104240. typedef void vorbis_look_floor;
  104241. typedef void vorbis_look_residue;
  104242. typedef void vorbis_look_transform;
  104243. /* mode ************************************************************/
  104244. typedef struct {
  104245. int blockflag;
  104246. int windowtype;
  104247. int transformtype;
  104248. int mapping;
  104249. } vorbis_info_mode;
  104250. typedef void vorbis_info_floor;
  104251. typedef void vorbis_info_residue;
  104252. typedef void vorbis_info_mapping;
  104253. /********* Start of inlined file: psy.h *********/
  104254. #ifndef _V_PSY_H_
  104255. #define _V_PSY_H_
  104256. /********* Start of inlined file: smallft.h *********/
  104257. #ifndef _V_SMFT_H_
  104258. #define _V_SMFT_H_
  104259. typedef struct {
  104260. int n;
  104261. float *trigcache;
  104262. int *splitcache;
  104263. } drft_lookup;
  104264. extern void drft_forward(drft_lookup *l,float *data);
  104265. extern void drft_backward(drft_lookup *l,float *data);
  104266. extern void drft_init(drft_lookup *l,int n);
  104267. extern void drft_clear(drft_lookup *l);
  104268. #endif
  104269. /********* End of inlined file: smallft.h *********/
  104270. /********* Start of inlined file: backends.h *********/
  104271. /* this is exposed up here because we need it for static modes.
  104272. Lookups for each backend aren't exposed because there's no reason
  104273. to do so */
  104274. #ifndef _vorbis_backend_h_
  104275. #define _vorbis_backend_h_
  104276. /* this would all be simpler/shorter with templates, but.... */
  104277. /* Floor backend generic *****************************************/
  104278. typedef struct{
  104279. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  104280. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  104281. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  104282. void (*free_info) (vorbis_info_floor *);
  104283. void (*free_look) (vorbis_look_floor *);
  104284. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  104285. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  104286. void *buffer,float *);
  104287. } vorbis_func_floor;
  104288. typedef struct{
  104289. int order;
  104290. long rate;
  104291. long barkmap;
  104292. int ampbits;
  104293. int ampdB;
  104294. int numbooks; /* <= 16 */
  104295. int books[16];
  104296. float lessthan; /* encode-only config setting hacks for libvorbis */
  104297. float greaterthan; /* encode-only config setting hacks for libvorbis */
  104298. } vorbis_info_floor0;
  104299. #define VIF_POSIT 63
  104300. #define VIF_CLASS 16
  104301. #define VIF_PARTS 31
  104302. typedef struct{
  104303. int partitions; /* 0 to 31 */
  104304. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  104305. int class_dim[VIF_CLASS]; /* 1 to 8 */
  104306. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  104307. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  104308. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  104309. int mult; /* 1 2 3 or 4 */
  104310. int postlist[VIF_POSIT+2]; /* first two implicit */
  104311. /* encode side analysis parameters */
  104312. float maxover;
  104313. float maxunder;
  104314. float maxerr;
  104315. float twofitweight;
  104316. float twofitatten;
  104317. int n;
  104318. } vorbis_info_floor1;
  104319. /* Residue backend generic *****************************************/
  104320. typedef struct{
  104321. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  104322. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  104323. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  104324. vorbis_info_residue *);
  104325. void (*free_info) (vorbis_info_residue *);
  104326. void (*free_look) (vorbis_look_residue *);
  104327. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  104328. float **,int *,int);
  104329. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  104330. vorbis_look_residue *,
  104331. float **,float **,int *,int,long **);
  104332. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  104333. float **,int *,int);
  104334. } vorbis_func_residue;
  104335. typedef struct vorbis_info_residue0{
  104336. /* block-partitioned VQ coded straight residue */
  104337. long begin;
  104338. long end;
  104339. /* first stage (lossless partitioning) */
  104340. int grouping; /* group n vectors per partition */
  104341. int partitions; /* possible codebooks for a partition */
  104342. int groupbook; /* huffbook for partitioning */
  104343. int secondstages[64]; /* expanded out to pointers in lookup */
  104344. int booklist[256]; /* list of second stage books */
  104345. float classmetric1[64];
  104346. float classmetric2[64];
  104347. } vorbis_info_residue0;
  104348. /* Mapping backend generic *****************************************/
  104349. typedef struct{
  104350. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  104351. oggpack_buffer *);
  104352. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  104353. void (*free_info) (vorbis_info_mapping *);
  104354. int (*forward) (struct vorbis_block *vb);
  104355. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  104356. } vorbis_func_mapping;
  104357. typedef struct vorbis_info_mapping0{
  104358. int submaps; /* <= 16 */
  104359. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  104360. int floorsubmap[16]; /* [mux] submap to floors */
  104361. int residuesubmap[16]; /* [mux] submap to residue */
  104362. int coupling_steps;
  104363. int coupling_mag[256];
  104364. int coupling_ang[256];
  104365. } vorbis_info_mapping0;
  104366. #endif
  104367. /********* End of inlined file: backends.h *********/
  104368. #ifndef EHMER_MAX
  104369. #define EHMER_MAX 56
  104370. #endif
  104371. /* psychoacoustic setup ********************************************/
  104372. #define P_BANDS 17 /* 62Hz to 16kHz */
  104373. #define P_LEVELS 8 /* 30dB to 100dB */
  104374. #define P_LEVEL_0 30. /* 30 dB */
  104375. #define P_NOISECURVES 3
  104376. #define NOISE_COMPAND_LEVELS 40
  104377. typedef struct vorbis_info_psy{
  104378. int blockflag;
  104379. float ath_adjatt;
  104380. float ath_maxatt;
  104381. float tone_masteratt[P_NOISECURVES];
  104382. float tone_centerboost;
  104383. float tone_decay;
  104384. float tone_abs_limit;
  104385. float toneatt[P_BANDS];
  104386. int noisemaskp;
  104387. float noisemaxsupp;
  104388. float noisewindowlo;
  104389. float noisewindowhi;
  104390. int noisewindowlomin;
  104391. int noisewindowhimin;
  104392. int noisewindowfixed;
  104393. float noiseoff[P_NOISECURVES][P_BANDS];
  104394. float noisecompand[NOISE_COMPAND_LEVELS];
  104395. float max_curve_dB;
  104396. int normal_channel_p;
  104397. int normal_point_p;
  104398. int normal_start;
  104399. int normal_partition;
  104400. double normal_thresh;
  104401. } vorbis_info_psy;
  104402. typedef struct{
  104403. int eighth_octave_lines;
  104404. /* for block long/short tuning; encode only */
  104405. float preecho_thresh[VE_BANDS];
  104406. float postecho_thresh[VE_BANDS];
  104407. float stretch_penalty;
  104408. float preecho_minenergy;
  104409. float ampmax_att_per_sec;
  104410. /* channel coupling config */
  104411. int coupling_pkHz[PACKETBLOBS];
  104412. int coupling_pointlimit[2][PACKETBLOBS];
  104413. int coupling_prepointamp[PACKETBLOBS];
  104414. int coupling_postpointamp[PACKETBLOBS];
  104415. int sliding_lowpass[2][PACKETBLOBS];
  104416. } vorbis_info_psy_global;
  104417. typedef struct {
  104418. float ampmax;
  104419. int channels;
  104420. vorbis_info_psy_global *gi;
  104421. int coupling_pointlimit[2][P_NOISECURVES];
  104422. } vorbis_look_psy_global;
  104423. typedef struct {
  104424. int n;
  104425. struct vorbis_info_psy *vi;
  104426. float ***tonecurves;
  104427. float **noiseoffset;
  104428. float *ath;
  104429. long *octave; /* in n.ocshift format */
  104430. long *bark;
  104431. long firstoc;
  104432. long shiftoc;
  104433. int eighth_octave_lines; /* power of two, please */
  104434. int total_octave_lines;
  104435. long rate; /* cache it */
  104436. float m_val; /* Masking compensation value */
  104437. } vorbis_look_psy;
  104438. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  104439. vorbis_info_psy_global *gi,int n,long rate);
  104440. extern void _vp_psy_clear(vorbis_look_psy *p);
  104441. extern void *_vi_psy_dup(void *source);
  104442. extern void _vi_psy_free(vorbis_info_psy *i);
  104443. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  104444. extern void _vp_remove_floor(vorbis_look_psy *p,
  104445. float *mdct,
  104446. int *icodedflr,
  104447. float *residue,
  104448. int sliding_lowpass);
  104449. extern void _vp_noisemask(vorbis_look_psy *p,
  104450. float *logmdct,
  104451. float *logmask);
  104452. extern void _vp_tonemask(vorbis_look_psy *p,
  104453. float *logfft,
  104454. float *logmask,
  104455. float global_specmax,
  104456. float local_specmax);
  104457. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  104458. float *noise,
  104459. float *tone,
  104460. int offset_select,
  104461. float *logmask,
  104462. float *mdct,
  104463. float *logmdct);
  104464. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  104465. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  104466. vorbis_info_psy_global *g,
  104467. vorbis_look_psy *p,
  104468. vorbis_info_mapping0 *vi,
  104469. float **mdct);
  104470. extern void _vp_couple(int blobno,
  104471. vorbis_info_psy_global *g,
  104472. vorbis_look_psy *p,
  104473. vorbis_info_mapping0 *vi,
  104474. float **res,
  104475. float **mag_memo,
  104476. int **mag_sort,
  104477. int **ifloor,
  104478. int *nonzero,
  104479. int sliding_lowpass);
  104480. extern void _vp_noise_normalize(vorbis_look_psy *p,
  104481. float *in,float *out,int *sortedindex);
  104482. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  104483. float *magnitudes,int *sortedindex);
  104484. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  104485. vorbis_look_psy *p,
  104486. vorbis_info_mapping0 *vi,
  104487. float **mags);
  104488. extern void hf_reduction(vorbis_info_psy_global *g,
  104489. vorbis_look_psy *p,
  104490. vorbis_info_mapping0 *vi,
  104491. float **mdct);
  104492. #endif
  104493. /********* End of inlined file: psy.h *********/
  104494. /********* Start of inlined file: bitrate.h *********/
  104495. #ifndef _V_BITRATE_H_
  104496. #define _V_BITRATE_H_
  104497. /********* Start of inlined file: os.h *********/
  104498. #ifndef _OS_H
  104499. #define _OS_H
  104500. /********************************************************************
  104501. * *
  104502. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  104503. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  104504. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  104505. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  104506. * *
  104507. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  104508. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  104509. * *
  104510. ********************************************************************
  104511. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  104512. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  104513. ********************************************************************/
  104514. #ifdef HAVE_CONFIG_H
  104515. #include "config.h"
  104516. #endif
  104517. #include <math.h>
  104518. /********* Start of inlined file: misc.h *********/
  104519. #ifndef _V_RANDOM_H_
  104520. #define _V_RANDOM_H_
  104521. extern int analysis_noisy;
  104522. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  104523. extern void _vorbis_block_ripcord(vorbis_block *vb);
  104524. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  104525. ogg_int64_t off);
  104526. #ifdef DEBUG_MALLOC
  104527. #define _VDBG_GRAPHFILE "malloc.m"
  104528. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  104529. extern void _VDBG_free(void *ptr,char *file,long line);
  104530. #ifndef MISC_C
  104531. #undef _ogg_malloc
  104532. #undef _ogg_calloc
  104533. #undef _ogg_realloc
  104534. #undef _ogg_free
  104535. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  104536. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  104537. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  104538. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  104539. #endif
  104540. #endif
  104541. #endif
  104542. /********* End of inlined file: misc.h *********/
  104543. #ifndef _V_IFDEFJAIL_H_
  104544. # define _V_IFDEFJAIL_H_
  104545. # ifdef __GNUC__
  104546. # define STIN static __inline__
  104547. # elif _WIN32
  104548. # define STIN static __inline
  104549. # else
  104550. # define STIN static
  104551. # endif
  104552. #ifdef DJGPP
  104553. # define rint(x) (floor((x)+0.5f))
  104554. #endif
  104555. #ifndef M_PI
  104556. # define M_PI (3.1415926536f)
  104557. #endif
  104558. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  104559. # include <malloc.h>
  104560. # define rint(x) (floor((x)+0.5f))
  104561. # define NO_FLOAT_MATH_LIB
  104562. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  104563. #endif
  104564. #if defined(__SYMBIAN32__) && defined(__WINS__)
  104565. void *_alloca(size_t size);
  104566. # define alloca _alloca
  104567. #endif
  104568. #ifndef FAST_HYPOT
  104569. # define FAST_HYPOT hypot
  104570. #endif
  104571. #endif
  104572. #ifdef HAVE_ALLOCA_H
  104573. # include <alloca.h>
  104574. #endif
  104575. #ifdef USE_MEMORY_H
  104576. # include <memory.h>
  104577. #endif
  104578. #ifndef min
  104579. # define min(x,y) ((x)>(y)?(y):(x))
  104580. #endif
  104581. #ifndef max
  104582. # define max(x,y) ((x)<(y)?(y):(x))
  104583. #endif
  104584. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  104585. # define VORBIS_FPU_CONTROL
  104586. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  104587. Because of encapsulation constraints (GCC can't see inside the asm
  104588. block and so we end up doing stupid things like a store/load that
  104589. is collectively a noop), we do it this way */
  104590. /* we must set up the fpu before this works!! */
  104591. typedef ogg_int16_t vorbis_fpu_control;
  104592. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  104593. ogg_int16_t ret;
  104594. ogg_int16_t temp;
  104595. __asm__ __volatile__("fnstcw %0\n\t"
  104596. "movw %0,%%dx\n\t"
  104597. "orw $62463,%%dx\n\t"
  104598. "movw %%dx,%1\n\t"
  104599. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  104600. *fpu=ret;
  104601. }
  104602. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  104603. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  104604. }
  104605. /* assumes the FPU is in round mode! */
  104606. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  104607. we get extra fst/fld to
  104608. truncate precision */
  104609. int i;
  104610. __asm__("fistl %0": "=m"(i) : "t"(f));
  104611. return(i);
  104612. }
  104613. #endif
  104614. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  104615. # define VORBIS_FPU_CONTROL
  104616. typedef ogg_int16_t vorbis_fpu_control;
  104617. static __inline int vorbis_ftoi(double f){
  104618. int i;
  104619. __asm{
  104620. fld f
  104621. fistp i
  104622. }
  104623. return i;
  104624. }
  104625. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  104626. }
  104627. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  104628. }
  104629. #endif
  104630. #ifndef VORBIS_FPU_CONTROL
  104631. typedef int vorbis_fpu_control;
  104632. static int vorbis_ftoi(double f){
  104633. return (int)(f+.5);
  104634. }
  104635. /* We don't have special code for this compiler/arch, so do it the slow way */
  104636. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  104637. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  104638. #endif
  104639. #endif /* _OS_H */
  104640. /********* End of inlined file: os.h *********/
  104641. /* encode side bitrate tracking */
  104642. typedef struct bitrate_manager_state {
  104643. int managed;
  104644. long avg_reservoir;
  104645. long minmax_reservoir;
  104646. long avg_bitsper;
  104647. long min_bitsper;
  104648. long max_bitsper;
  104649. long short_per_long;
  104650. double avgfloat;
  104651. vorbis_block *vb;
  104652. int choice;
  104653. } bitrate_manager_state;
  104654. typedef struct bitrate_manager_info{
  104655. long avg_rate;
  104656. long min_rate;
  104657. long max_rate;
  104658. long reservoir_bits;
  104659. double reservoir_bias;
  104660. double slew_damp;
  104661. } bitrate_manager_info;
  104662. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  104663. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  104664. extern int vorbis_bitrate_managed(vorbis_block *vb);
  104665. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  104666. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  104667. #endif
  104668. /********* End of inlined file: bitrate.h *********/
  104669. static int ilog(unsigned int v){
  104670. int ret=0;
  104671. while(v){
  104672. ret++;
  104673. v>>=1;
  104674. }
  104675. return(ret);
  104676. }
  104677. static int ilog2(unsigned int v){
  104678. int ret=0;
  104679. if(v)--v;
  104680. while(v){
  104681. ret++;
  104682. v>>=1;
  104683. }
  104684. return(ret);
  104685. }
  104686. typedef struct private_state {
  104687. /* local lookup storage */
  104688. envelope_lookup *ve; /* envelope lookup */
  104689. int window[2];
  104690. vorbis_look_transform **transform[2]; /* block, type */
  104691. drft_lookup fft_look[2];
  104692. int modebits;
  104693. vorbis_look_floor **flr;
  104694. vorbis_look_residue **residue;
  104695. vorbis_look_psy *psy;
  104696. vorbis_look_psy_global *psy_g_look;
  104697. /* local storage, only used on the encoding side. This way the
  104698. application does not need to worry about freeing some packets'
  104699. memory and not others'; packet storage is always tracked.
  104700. Cleared next call to a _dsp_ function */
  104701. unsigned char *header;
  104702. unsigned char *header1;
  104703. unsigned char *header2;
  104704. bitrate_manager_state bms;
  104705. ogg_int64_t sample_count;
  104706. } private_state;
  104707. /* codec_setup_info contains all the setup information specific to the
  104708. specific compression/decompression mode in progress (eg,
  104709. psychoacoustic settings, channel setup, options, codebook
  104710. etc).
  104711. *********************************************************************/
  104712. /********* Start of inlined file: highlevel.h *********/
  104713. typedef struct highlevel_byblocktype {
  104714. double tone_mask_setting;
  104715. double tone_peaklimit_setting;
  104716. double noise_bias_setting;
  104717. double noise_compand_setting;
  104718. } highlevel_byblocktype;
  104719. typedef struct highlevel_encode_setup {
  104720. void *setup;
  104721. int set_in_stone;
  104722. double base_setting;
  104723. double long_setting;
  104724. double short_setting;
  104725. double impulse_noisetune;
  104726. int managed;
  104727. long bitrate_min;
  104728. long bitrate_av;
  104729. double bitrate_av_damp;
  104730. long bitrate_max;
  104731. long bitrate_reservoir;
  104732. double bitrate_reservoir_bias;
  104733. int impulse_block_p;
  104734. int noise_normalize_p;
  104735. double stereo_point_setting;
  104736. double lowpass_kHz;
  104737. double ath_floating_dB;
  104738. double ath_absolute_dB;
  104739. double amplitude_track_dBpersec;
  104740. double trigger_setting;
  104741. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  104742. } highlevel_encode_setup;
  104743. /********* End of inlined file: highlevel.h *********/
  104744. typedef struct codec_setup_info {
  104745. /* Vorbis supports only short and long blocks, but allows the
  104746. encoder to choose the sizes */
  104747. long blocksizes[2];
  104748. /* modes are the primary means of supporting on-the-fly different
  104749. blocksizes, different channel mappings (LR or M/A),
  104750. different residue backends, etc. Each mode consists of a
  104751. blocksize flag and a mapping (along with the mapping setup */
  104752. int modes;
  104753. int maps;
  104754. int floors;
  104755. int residues;
  104756. int books;
  104757. int psys; /* encode only */
  104758. vorbis_info_mode *mode_param[64];
  104759. int map_type[64];
  104760. vorbis_info_mapping *map_param[64];
  104761. int floor_type[64];
  104762. vorbis_info_floor *floor_param[64];
  104763. int residue_type[64];
  104764. vorbis_info_residue *residue_param[64];
  104765. static_codebook *book_param[256];
  104766. codebook *fullbooks;
  104767. vorbis_info_psy *psy_param[4]; /* encode only */
  104768. vorbis_info_psy_global psy_g_param;
  104769. bitrate_manager_info bi;
  104770. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  104771. highly redundant structure, but
  104772. improves clarity of program flow. */
  104773. int halfrate_flag; /* painless downsample for decode */
  104774. } codec_setup_info;
  104775. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  104776. extern void _vp_global_free(vorbis_look_psy_global *look);
  104777. #endif
  104778. /********* End of inlined file: codec_internal.h *********/
  104779. /********* Start of inlined file: registry.h *********/
  104780. #ifndef _V_REG_H_
  104781. #define _V_REG_H_
  104782. #define VI_TRANSFORMB 1
  104783. #define VI_WINDOWB 1
  104784. #define VI_TIMEB 1
  104785. #define VI_FLOORB 2
  104786. #define VI_RESB 3
  104787. #define VI_MAPB 1
  104788. extern vorbis_func_floor *_floor_P[];
  104789. extern vorbis_func_residue *_residue_P[];
  104790. extern vorbis_func_mapping *_mapping_P[];
  104791. #endif
  104792. /********* End of inlined file: registry.h *********/
  104793. /********* Start of inlined file: scales.h *********/
  104794. #ifndef _V_SCALES_H_
  104795. #define _V_SCALES_H_
  104796. #include <math.h>
  104797. /* 20log10(x) */
  104798. #define VORBIS_IEEE_FLOAT32 1
  104799. #ifdef VORBIS_IEEE_FLOAT32
  104800. static float unitnorm(float x){
  104801. union {
  104802. ogg_uint32_t i;
  104803. float f;
  104804. } ix;
  104805. ix.f = x;
  104806. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  104807. return ix.f;
  104808. }
  104809. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  104810. static float todB(const float *x){
  104811. union {
  104812. ogg_uint32_t i;
  104813. float f;
  104814. } ix;
  104815. ix.f = *x;
  104816. ix.i = ix.i&0x7fffffff;
  104817. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  104818. }
  104819. #define todB_nn(x) todB(x)
  104820. #else
  104821. static float unitnorm(float x){
  104822. if(x<0)return(-1.f);
  104823. return(1.f);
  104824. }
  104825. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  104826. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  104827. #endif
  104828. #define fromdB(x) (exp((x)*.11512925f))
  104829. /* The bark scale equations are approximations, since the original
  104830. table was somewhat hand rolled. The below are chosen to have the
  104831. best possible fit to the rolled tables, thus their somewhat odd
  104832. appearance (these are more accurate and over a longer range than
  104833. the oft-quoted bark equations found in the texts I have). The
  104834. approximations are valid from 0 - 30kHz (nyquist) or so.
  104835. all f in Hz, z in Bark */
  104836. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  104837. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  104838. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  104839. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  104840. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  104841. 0.0 */
  104842. #define toOC(n) (log(n)*1.442695f-5.965784f)
  104843. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  104844. #endif
  104845. /********* End of inlined file: scales.h *********/
  104846. int analysis_noisy=1;
  104847. /* decides between modes, dispatches to the appropriate mapping. */
  104848. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  104849. int ret,i;
  104850. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  104851. vb->glue_bits=0;
  104852. vb->time_bits=0;
  104853. vb->floor_bits=0;
  104854. vb->res_bits=0;
  104855. /* first things first. Make sure encode is ready */
  104856. for(i=0;i<PACKETBLOBS;i++)
  104857. oggpack_reset(vbi->packetblob[i]);
  104858. /* we only have one mapping type (0), and we let the mapping code
  104859. itself figure out what soft mode to use. This allows easier
  104860. bitrate management */
  104861. if((ret=_mapping_P[0]->forward(vb)))
  104862. return(ret);
  104863. if(op){
  104864. if(vorbis_bitrate_managed(vb))
  104865. /* The app is using a bitmanaged mode... but not using the
  104866. bitrate management interface. */
  104867. return(OV_EINVAL);
  104868. op->packet=oggpack_get_buffer(&vb->opb);
  104869. op->bytes=oggpack_bytes(&vb->opb);
  104870. op->b_o_s=0;
  104871. op->e_o_s=vb->eofflag;
  104872. op->granulepos=vb->granulepos;
  104873. op->packetno=vb->sequence; /* for sake of completeness */
  104874. }
  104875. return(0);
  104876. }
  104877. /* there was no great place to put this.... */
  104878. void _analysis_output_always(char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  104879. int j;
  104880. FILE *of;
  104881. char buffer[80];
  104882. /* if(i==5870){*/
  104883. sprintf(buffer,"%s_%d.m",base,i);
  104884. of=fopen(buffer,"w");
  104885. if(!of)perror("failed to open data dump file");
  104886. for(j=0;j<n;j++){
  104887. if(bark){
  104888. float b=toBARK((4000.f*j/n)+.25);
  104889. fprintf(of,"%f ",b);
  104890. }else
  104891. if(off!=0)
  104892. fprintf(of,"%f ",(double)(j+off)/8000.);
  104893. else
  104894. fprintf(of,"%f ",(double)j);
  104895. if(dB){
  104896. float val;
  104897. if(v[j]==0.)
  104898. val=-140.;
  104899. else
  104900. val=todB(v+j);
  104901. fprintf(of,"%f\n",val);
  104902. }else{
  104903. fprintf(of,"%f\n",v[j]);
  104904. }
  104905. }
  104906. fclose(of);
  104907. /* } */
  104908. }
  104909. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  104910. ogg_int64_t off){
  104911. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  104912. }
  104913. #endif
  104914. /********* End of inlined file: analysis.c *********/
  104915. /********* Start of inlined file: bitrate.c *********/
  104916. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  104917. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104918. // tasks..
  104919. #ifdef _MSC_VER
  104920. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104921. #endif
  104922. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  104923. #if JUCE_USE_OGGVORBIS
  104924. #include <stdlib.h>
  104925. #include <string.h>
  104926. #include <math.h>
  104927. /* compute bitrate tracking setup */
  104928. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  104929. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  104930. bitrate_manager_info *bi=&ci->bi;
  104931. memset(bm,0,sizeof(*bm));
  104932. if(bi && (bi->reservoir_bits>0)){
  104933. long ratesamples=vi->rate;
  104934. int halfsamples=ci->blocksizes[0]>>1;
  104935. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  104936. bm->managed=1;
  104937. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  104938. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  104939. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  104940. bm->avgfloat=PACKETBLOBS/2;
  104941. /* not a necessary fix, but one that leads to a more balanced
  104942. typical initialization */
  104943. {
  104944. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  104945. bm->minmax_reservoir=desired_fill;
  104946. bm->avg_reservoir=desired_fill;
  104947. }
  104948. }
  104949. }
  104950. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  104951. memset(bm,0,sizeof(*bm));
  104952. return;
  104953. }
  104954. int vorbis_bitrate_managed(vorbis_block *vb){
  104955. vorbis_dsp_state *vd=vb->vd;
  104956. private_state *b=(private_state*)vd->backend_state;
  104957. bitrate_manager_state *bm=&b->bms;
  104958. if(bm && bm->managed)return(1);
  104959. return(0);
  104960. }
  104961. /* finish taking in the block we just processed */
  104962. int vorbis_bitrate_addblock(vorbis_block *vb){
  104963. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  104964. vorbis_dsp_state *vd=vb->vd;
  104965. private_state *b=(private_state*)vd->backend_state;
  104966. bitrate_manager_state *bm=&b->bms;
  104967. vorbis_info *vi=vd->vi;
  104968. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  104969. bitrate_manager_info *bi=&ci->bi;
  104970. int choice=rint(bm->avgfloat);
  104971. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104972. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  104973. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  104974. int samples=ci->blocksizes[vb->W]>>1;
  104975. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  104976. if(!bm->managed){
  104977. /* not a bitrate managed stream, but for API simplicity, we'll
  104978. buffer the packet to keep the code path clean */
  104979. if(bm->vb)return(-1); /* one has been submitted without
  104980. being claimed */
  104981. bm->vb=vb;
  104982. return(0);
  104983. }
  104984. bm->vb=vb;
  104985. /* look ahead for avg floater */
  104986. if(bm->avg_bitsper>0){
  104987. double slew=0.;
  104988. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  104989. double slewlimit= 15./bi->slew_damp;
  104990. /* choosing a new floater:
  104991. if we're over target, we slew down
  104992. if we're under target, we slew up
  104993. choose slew as follows: look through packetblobs of this frame
  104994. and set slew as the first in the appropriate direction that
  104995. gives us the slew we want. This may mean no slew if delta is
  104996. already favorable.
  104997. Then limit slew to slew max */
  104998. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  104999. while(choice>0 && this_bits>avg_target_bits &&
  105000. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  105001. choice--;
  105002. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105003. }
  105004. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  105005. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  105006. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  105007. choice++;
  105008. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105009. }
  105010. }
  105011. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  105012. if(slew<-slewlimit)slew=-slewlimit;
  105013. if(slew>slewlimit)slew=slewlimit;
  105014. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  105015. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105016. }
  105017. /* enforce min(if used) on the current floater (if used) */
  105018. if(bm->min_bitsper>0){
  105019. /* do we need to force the bitrate up? */
  105020. if(this_bits<min_target_bits){
  105021. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  105022. choice++;
  105023. if(choice>=PACKETBLOBS)break;
  105024. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105025. }
  105026. }
  105027. }
  105028. /* enforce max (if used) on the current floater (if used) */
  105029. if(bm->max_bitsper>0){
  105030. /* do we need to force the bitrate down? */
  105031. if(this_bits>max_target_bits){
  105032. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  105033. choice--;
  105034. if(choice<0)break;
  105035. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105036. }
  105037. }
  105038. }
  105039. /* Choice of packetblobs now made based on floater, and min/max
  105040. requirements. Now boundary check extreme choices */
  105041. if(choice<0){
  105042. /* choosing a smaller packetblob is insufficient to trim bitrate.
  105043. frame will need to be truncated */
  105044. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  105045. bm->choice=choice=0;
  105046. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  105047. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  105048. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105049. }
  105050. }else{
  105051. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  105052. if(choice>=PACKETBLOBS)
  105053. choice=PACKETBLOBS-1;
  105054. bm->choice=choice;
  105055. /* prop up bitrate according to demand. pad this frame out with zeroes */
  105056. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  105057. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  105058. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  105059. }
  105060. /* now we have the final packet and the final packet size. Update statistics */
  105061. /* min and max reservoir */
  105062. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  105063. if(max_target_bits>0 && this_bits>max_target_bits){
  105064. bm->minmax_reservoir+=(this_bits-max_target_bits);
  105065. }else if(min_target_bits>0 && this_bits<min_target_bits){
  105066. bm->minmax_reservoir+=(this_bits-min_target_bits);
  105067. }else{
  105068. /* inbetween; we want to take reservoir toward but not past desired_fill */
  105069. if(bm->minmax_reservoir>desired_fill){
  105070. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  105071. bm->minmax_reservoir+=(this_bits-max_target_bits);
  105072. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  105073. }else{
  105074. bm->minmax_reservoir=desired_fill;
  105075. }
  105076. }else{
  105077. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  105078. bm->minmax_reservoir+=(this_bits-min_target_bits);
  105079. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  105080. }else{
  105081. bm->minmax_reservoir=desired_fill;
  105082. }
  105083. }
  105084. }
  105085. }
  105086. /* avg reservoir */
  105087. if(bm->avg_bitsper>0){
  105088. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  105089. bm->avg_reservoir+=this_bits-avg_target_bits;
  105090. }
  105091. return(0);
  105092. }
  105093. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  105094. private_state *b=(private_state*)vd->backend_state;
  105095. bitrate_manager_state *bm=&b->bms;
  105096. vorbis_block *vb=bm->vb;
  105097. int choice=PACKETBLOBS/2;
  105098. if(!vb)return 0;
  105099. if(op){
  105100. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  105101. if(vorbis_bitrate_managed(vb))
  105102. choice=bm->choice;
  105103. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  105104. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  105105. op->b_o_s=0;
  105106. op->e_o_s=vb->eofflag;
  105107. op->granulepos=vb->granulepos;
  105108. op->packetno=vb->sequence; /* for sake of completeness */
  105109. }
  105110. bm->vb=0;
  105111. return(1);
  105112. }
  105113. #endif
  105114. /********* End of inlined file: bitrate.c *********/
  105115. /********* Start of inlined file: block.c *********/
  105116. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105117. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105118. // tasks..
  105119. #ifdef _MSC_VER
  105120. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105121. #endif
  105122. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105123. #if JUCE_USE_OGGVORBIS
  105124. #include <stdio.h>
  105125. #include <stdlib.h>
  105126. #include <string.h>
  105127. /********* Start of inlined file: window.h *********/
  105128. #ifndef _V_WINDOW_
  105129. #define _V_WINDOW_
  105130. extern float *_vorbis_window_get(int n);
  105131. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  105132. int lW,int W,int nW);
  105133. #endif
  105134. /********* End of inlined file: window.h *********/
  105135. /********* Start of inlined file: lpc.h *********/
  105136. #ifndef _V_LPC_H_
  105137. #define _V_LPC_H_
  105138. /* simple linear scale LPC code */
  105139. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  105140. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  105141. float *data,long n);
  105142. #endif
  105143. /********* End of inlined file: lpc.h *********/
  105144. /* pcm accumulator examples (not exhaustive):
  105145. <-------------- lW ---------------->
  105146. <--------------- W ---------------->
  105147. : .....|..... _______________ |
  105148. : .''' | '''_--- | |\ |
  105149. :.....''' |_____--- '''......| | \_______|
  105150. :.................|__________________|_______|__|______|
  105151. |<------ Sl ------>| > Sr < |endW
  105152. |beginSl |endSl | |endSr
  105153. |beginW |endlW |beginSr
  105154. |< lW >|
  105155. <--------------- W ---------------->
  105156. | | .. ______________ |
  105157. | | ' `/ | ---_ |
  105158. |___.'___/`. | ---_____|
  105159. |_______|__|_______|_________________|
  105160. | >|Sl|< |<------ Sr ----->|endW
  105161. | | |endSl |beginSr |endSr
  105162. |beginW | |endlW
  105163. mult[0] |beginSl mult[n]
  105164. <-------------- lW ----------------->
  105165. |<--W-->|
  105166. : .............. ___ | |
  105167. : .''' |`/ \ | |
  105168. :.....''' |/`....\|...|
  105169. :.........................|___|___|___|
  105170. |Sl |Sr |endW
  105171. | | |endSr
  105172. | |beginSr
  105173. | |endSl
  105174. |beginSl
  105175. |beginW
  105176. */
  105177. /* block abstraction setup *********************************************/
  105178. #ifndef WORD_ALIGN
  105179. #define WORD_ALIGN 8
  105180. #endif
  105181. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  105182. int i;
  105183. memset(vb,0,sizeof(*vb));
  105184. vb->vd=v;
  105185. vb->localalloc=0;
  105186. vb->localstore=NULL;
  105187. if(v->analysisp){
  105188. vorbis_block_internal *vbi=(vorbis_block_internal*)
  105189. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  105190. vbi->ampmax=-9999;
  105191. for(i=0;i<PACKETBLOBS;i++){
  105192. if(i==PACKETBLOBS/2){
  105193. vbi->packetblob[i]=&vb->opb;
  105194. }else{
  105195. vbi->packetblob[i]=
  105196. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  105197. }
  105198. oggpack_writeinit(vbi->packetblob[i]);
  105199. }
  105200. }
  105201. return(0);
  105202. }
  105203. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  105204. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  105205. if(bytes+vb->localtop>vb->localalloc){
  105206. /* can't just _ogg_realloc... there are outstanding pointers */
  105207. if(vb->localstore){
  105208. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  105209. vb->totaluse+=vb->localtop;
  105210. link->next=vb->reap;
  105211. link->ptr=vb->localstore;
  105212. vb->reap=link;
  105213. }
  105214. /* highly conservative */
  105215. vb->localalloc=bytes;
  105216. vb->localstore=_ogg_malloc(vb->localalloc);
  105217. vb->localtop=0;
  105218. }
  105219. {
  105220. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  105221. vb->localtop+=bytes;
  105222. return ret;
  105223. }
  105224. }
  105225. /* reap the chain, pull the ripcord */
  105226. void _vorbis_block_ripcord(vorbis_block *vb){
  105227. /* reap the chain */
  105228. struct alloc_chain *reap=vb->reap;
  105229. while(reap){
  105230. struct alloc_chain *next=reap->next;
  105231. _ogg_free(reap->ptr);
  105232. memset(reap,0,sizeof(*reap));
  105233. _ogg_free(reap);
  105234. reap=next;
  105235. }
  105236. /* consolidate storage */
  105237. if(vb->totaluse){
  105238. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  105239. vb->localalloc+=vb->totaluse;
  105240. vb->totaluse=0;
  105241. }
  105242. /* pull the ripcord */
  105243. vb->localtop=0;
  105244. vb->reap=NULL;
  105245. }
  105246. int vorbis_block_clear(vorbis_block *vb){
  105247. int i;
  105248. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  105249. _vorbis_block_ripcord(vb);
  105250. if(vb->localstore)_ogg_free(vb->localstore);
  105251. if(vbi){
  105252. for(i=0;i<PACKETBLOBS;i++){
  105253. oggpack_writeclear(vbi->packetblob[i]);
  105254. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  105255. }
  105256. _ogg_free(vbi);
  105257. }
  105258. memset(vb,0,sizeof(*vb));
  105259. return(0);
  105260. }
  105261. /* Analysis side code, but directly related to blocking. Thus it's
  105262. here and not in analysis.c (which is for analysis transforms only).
  105263. The init is here because some of it is shared */
  105264. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  105265. int i;
  105266. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105267. private_state *b=NULL;
  105268. int hs;
  105269. if(ci==NULL) return 1;
  105270. hs=ci->halfrate_flag;
  105271. memset(v,0,sizeof(*v));
  105272. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  105273. v->vi=vi;
  105274. b->modebits=ilog2(ci->modes);
  105275. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  105276. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  105277. /* MDCT is tranform 0 */
  105278. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  105279. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  105280. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  105281. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  105282. /* Vorbis I uses only window type 0 */
  105283. b->window[0]=ilog2(ci->blocksizes[0])-6;
  105284. b->window[1]=ilog2(ci->blocksizes[1])-6;
  105285. if(encp){ /* encode/decode differ here */
  105286. /* analysis always needs an fft */
  105287. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  105288. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  105289. /* finish the codebooks */
  105290. if(!ci->fullbooks){
  105291. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  105292. for(i=0;i<ci->books;i++)
  105293. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  105294. }
  105295. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  105296. for(i=0;i<ci->psys;i++){
  105297. _vp_psy_init(b->psy+i,
  105298. ci->psy_param[i],
  105299. &ci->psy_g_param,
  105300. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  105301. vi->rate);
  105302. }
  105303. v->analysisp=1;
  105304. }else{
  105305. /* finish the codebooks */
  105306. if(!ci->fullbooks){
  105307. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  105308. for(i=0;i<ci->books;i++){
  105309. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  105310. /* decode codebooks are now standalone after init */
  105311. vorbis_staticbook_destroy(ci->book_param[i]);
  105312. ci->book_param[i]=NULL;
  105313. }
  105314. }
  105315. }
  105316. /* initialize the storage vectors. blocksize[1] is small for encode,
  105317. but the correct size for decode */
  105318. v->pcm_storage=ci->blocksizes[1];
  105319. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  105320. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  105321. {
  105322. int i;
  105323. for(i=0;i<vi->channels;i++)
  105324. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  105325. }
  105326. /* all 1 (large block) or 0 (small block) */
  105327. /* explicitly set for the sake of clarity */
  105328. v->lW=0; /* previous window size */
  105329. v->W=0; /* current window size */
  105330. /* all vector indexes */
  105331. v->centerW=ci->blocksizes[1]/2;
  105332. v->pcm_current=v->centerW;
  105333. /* initialize all the backend lookups */
  105334. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  105335. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  105336. for(i=0;i<ci->floors;i++)
  105337. b->flr[i]=_floor_P[ci->floor_type[i]]->
  105338. look(v,ci->floor_param[i]);
  105339. for(i=0;i<ci->residues;i++)
  105340. b->residue[i]=_residue_P[ci->residue_type[i]]->
  105341. look(v,ci->residue_param[i]);
  105342. return 0;
  105343. }
  105344. /* arbitrary settings and spec-mandated numbers get filled in here */
  105345. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  105346. private_state *b=NULL;
  105347. if(_vds_shared_init(v,vi,1))return 1;
  105348. b=(private_state*)v->backend_state;
  105349. b->psy_g_look=_vp_global_look(vi);
  105350. /* Initialize the envelope state storage */
  105351. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  105352. _ve_envelope_init(b->ve,vi);
  105353. vorbis_bitrate_init(vi,&b->bms);
  105354. /* compressed audio packets start after the headers
  105355. with sequence number 3 */
  105356. v->sequence=3;
  105357. return(0);
  105358. }
  105359. void vorbis_dsp_clear(vorbis_dsp_state *v){
  105360. int i;
  105361. if(v){
  105362. vorbis_info *vi=v->vi;
  105363. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  105364. private_state *b=(private_state*)v->backend_state;
  105365. if(b){
  105366. if(b->ve){
  105367. _ve_envelope_clear(b->ve);
  105368. _ogg_free(b->ve);
  105369. }
  105370. if(b->transform[0]){
  105371. mdct_clear((mdct_lookup*) b->transform[0][0]);
  105372. _ogg_free(b->transform[0][0]);
  105373. _ogg_free(b->transform[0]);
  105374. }
  105375. if(b->transform[1]){
  105376. mdct_clear((mdct_lookup*) b->transform[1][0]);
  105377. _ogg_free(b->transform[1][0]);
  105378. _ogg_free(b->transform[1]);
  105379. }
  105380. if(b->flr){
  105381. for(i=0;i<ci->floors;i++)
  105382. _floor_P[ci->floor_type[i]]->
  105383. free_look(b->flr[i]);
  105384. _ogg_free(b->flr);
  105385. }
  105386. if(b->residue){
  105387. for(i=0;i<ci->residues;i++)
  105388. _residue_P[ci->residue_type[i]]->
  105389. free_look(b->residue[i]);
  105390. _ogg_free(b->residue);
  105391. }
  105392. if(b->psy){
  105393. for(i=0;i<ci->psys;i++)
  105394. _vp_psy_clear(b->psy+i);
  105395. _ogg_free(b->psy);
  105396. }
  105397. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  105398. vorbis_bitrate_clear(&b->bms);
  105399. drft_clear(&b->fft_look[0]);
  105400. drft_clear(&b->fft_look[1]);
  105401. }
  105402. if(v->pcm){
  105403. for(i=0;i<vi->channels;i++)
  105404. if(v->pcm[i])_ogg_free(v->pcm[i]);
  105405. _ogg_free(v->pcm);
  105406. if(v->pcmret)_ogg_free(v->pcmret);
  105407. }
  105408. if(b){
  105409. /* free header, header1, header2 */
  105410. if(b->header)_ogg_free(b->header);
  105411. if(b->header1)_ogg_free(b->header1);
  105412. if(b->header2)_ogg_free(b->header2);
  105413. _ogg_free(b);
  105414. }
  105415. memset(v,0,sizeof(*v));
  105416. }
  105417. }
  105418. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  105419. int i;
  105420. vorbis_info *vi=v->vi;
  105421. private_state *b=(private_state*)v->backend_state;
  105422. /* free header, header1, header2 */
  105423. if(b->header)_ogg_free(b->header);b->header=NULL;
  105424. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  105425. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  105426. /* Do we have enough storage space for the requested buffer? If not,
  105427. expand the PCM (and envelope) storage */
  105428. if(v->pcm_current+vals>=v->pcm_storage){
  105429. v->pcm_storage=v->pcm_current+vals*2;
  105430. for(i=0;i<vi->channels;i++){
  105431. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  105432. }
  105433. }
  105434. for(i=0;i<vi->channels;i++)
  105435. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  105436. return(v->pcmret);
  105437. }
  105438. static void _preextrapolate_helper(vorbis_dsp_state *v){
  105439. int i;
  105440. int order=32;
  105441. float *lpc=(float*)alloca(order*sizeof(*lpc));
  105442. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  105443. long j;
  105444. v->preextrapolate=1;
  105445. if(v->pcm_current-v->centerW>order*2){ /* safety */
  105446. for(i=0;i<v->vi->channels;i++){
  105447. /* need to run the extrapolation in reverse! */
  105448. for(j=0;j<v->pcm_current;j++)
  105449. work[j]=v->pcm[i][v->pcm_current-j-1];
  105450. /* prime as above */
  105451. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  105452. /* run the predictor filter */
  105453. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  105454. order,
  105455. work+v->pcm_current-v->centerW,
  105456. v->centerW);
  105457. for(j=0;j<v->pcm_current;j++)
  105458. v->pcm[i][v->pcm_current-j-1]=work[j];
  105459. }
  105460. }
  105461. }
  105462. /* call with val<=0 to set eof */
  105463. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  105464. vorbis_info *vi=v->vi;
  105465. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105466. if(vals<=0){
  105467. int order=32;
  105468. int i;
  105469. float *lpc=(float*) alloca(order*sizeof(*lpc));
  105470. /* if it wasn't done earlier (very short sample) */
  105471. if(!v->preextrapolate)
  105472. _preextrapolate_helper(v);
  105473. /* We're encoding the end of the stream. Just make sure we have
  105474. [at least] a few full blocks of zeroes at the end. */
  105475. /* actually, we don't want zeroes; that could drop a large
  105476. amplitude off a cliff, creating spread spectrum noise that will
  105477. suck to encode. Extrapolate for the sake of cleanliness. */
  105478. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  105479. v->eofflag=v->pcm_current;
  105480. v->pcm_current+=ci->blocksizes[1]*3;
  105481. for(i=0;i<vi->channels;i++){
  105482. if(v->eofflag>order*2){
  105483. /* extrapolate with LPC to fill in */
  105484. long n;
  105485. /* make a predictor filter */
  105486. n=v->eofflag;
  105487. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  105488. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  105489. /* run the predictor filter */
  105490. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  105491. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  105492. }else{
  105493. /* not enough data to extrapolate (unlikely to happen due to
  105494. guarding the overlap, but bulletproof in case that
  105495. assumtion goes away). zeroes will do. */
  105496. memset(v->pcm[i]+v->eofflag,0,
  105497. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  105498. }
  105499. }
  105500. }else{
  105501. if(v->pcm_current+vals>v->pcm_storage)
  105502. return(OV_EINVAL);
  105503. v->pcm_current+=vals;
  105504. /* we may want to reverse extrapolate the beginning of a stream
  105505. too... in case we're beginning on a cliff! */
  105506. /* clumsy, but simple. It only runs once, so simple is good. */
  105507. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  105508. _preextrapolate_helper(v);
  105509. }
  105510. return(0);
  105511. }
  105512. /* do the deltas, envelope shaping, pre-echo and determine the size of
  105513. the next block on which to continue analysis */
  105514. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  105515. int i;
  105516. vorbis_info *vi=v->vi;
  105517. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105518. private_state *b=(private_state*)v->backend_state;
  105519. vorbis_look_psy_global *g=b->psy_g_look;
  105520. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  105521. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  105522. /* check to see if we're started... */
  105523. if(!v->preextrapolate)return(0);
  105524. /* check to see if we're done... */
  105525. if(v->eofflag==-1)return(0);
  105526. /* By our invariant, we have lW, W and centerW set. Search for
  105527. the next boundary so we can determine nW (the next window size)
  105528. which lets us compute the shape of the current block's window */
  105529. /* we do an envelope search even on a single blocksize; we may still
  105530. be throwing more bits at impulses, and envelope search handles
  105531. marking impulses too. */
  105532. {
  105533. long bp=_ve_envelope_search(v);
  105534. if(bp==-1){
  105535. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  105536. full long block */
  105537. v->nW=0;
  105538. }else{
  105539. if(ci->blocksizes[0]==ci->blocksizes[1])
  105540. v->nW=0;
  105541. else
  105542. v->nW=bp;
  105543. }
  105544. }
  105545. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  105546. {
  105547. /* center of next block + next block maximum right side. */
  105548. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  105549. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  105550. although this check is
  105551. less strict that the
  105552. _ve_envelope_search,
  105553. the search is not run
  105554. if we only use one
  105555. block size */
  105556. }
  105557. /* fill in the block. Note that for a short window, lW and nW are *short*
  105558. regardless of actual settings in the stream */
  105559. _vorbis_block_ripcord(vb);
  105560. vb->lW=v->lW;
  105561. vb->W=v->W;
  105562. vb->nW=v->nW;
  105563. if(v->W){
  105564. if(!v->lW || !v->nW){
  105565. vbi->blocktype=BLOCKTYPE_TRANSITION;
  105566. /*fprintf(stderr,"-");*/
  105567. }else{
  105568. vbi->blocktype=BLOCKTYPE_LONG;
  105569. /*fprintf(stderr,"_");*/
  105570. }
  105571. }else{
  105572. if(_ve_envelope_mark(v)){
  105573. vbi->blocktype=BLOCKTYPE_IMPULSE;
  105574. /*fprintf(stderr,"|");*/
  105575. }else{
  105576. vbi->blocktype=BLOCKTYPE_PADDING;
  105577. /*fprintf(stderr,".");*/
  105578. }
  105579. }
  105580. vb->vd=v;
  105581. vb->sequence=v->sequence++;
  105582. vb->granulepos=v->granulepos;
  105583. vb->pcmend=ci->blocksizes[v->W];
  105584. /* copy the vectors; this uses the local storage in vb */
  105585. /* this tracks 'strongest peak' for later psychoacoustics */
  105586. /* moved to the global psy state; clean this mess up */
  105587. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  105588. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  105589. vbi->ampmax=g->ampmax;
  105590. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  105591. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  105592. for(i=0;i<vi->channels;i++){
  105593. vbi->pcmdelay[i]=
  105594. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  105595. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  105596. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  105597. /* before we added the delay
  105598. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  105599. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  105600. */
  105601. }
  105602. /* handle eof detection: eof==0 means that we've not yet received EOF
  105603. eof>0 marks the last 'real' sample in pcm[]
  105604. eof<0 'no more to do'; doesn't get here */
  105605. if(v->eofflag){
  105606. if(v->centerW>=v->eofflag){
  105607. v->eofflag=-1;
  105608. vb->eofflag=1;
  105609. return(1);
  105610. }
  105611. }
  105612. /* advance storage vectors and clean up */
  105613. {
  105614. int new_centerNext=ci->blocksizes[1]/2;
  105615. int movementW=centerNext-new_centerNext;
  105616. if(movementW>0){
  105617. _ve_envelope_shift(b->ve,movementW);
  105618. v->pcm_current-=movementW;
  105619. for(i=0;i<vi->channels;i++)
  105620. memmove(v->pcm[i],v->pcm[i]+movementW,
  105621. v->pcm_current*sizeof(*v->pcm[i]));
  105622. v->lW=v->W;
  105623. v->W=v->nW;
  105624. v->centerW=new_centerNext;
  105625. if(v->eofflag){
  105626. v->eofflag-=movementW;
  105627. if(v->eofflag<=0)v->eofflag=-1;
  105628. /* do not add padding to end of stream! */
  105629. if(v->centerW>=v->eofflag){
  105630. v->granulepos+=movementW-(v->centerW-v->eofflag);
  105631. }else{
  105632. v->granulepos+=movementW;
  105633. }
  105634. }else{
  105635. v->granulepos+=movementW;
  105636. }
  105637. }
  105638. }
  105639. /* done */
  105640. return(1);
  105641. }
  105642. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  105643. vorbis_info *vi=v->vi;
  105644. codec_setup_info *ci;
  105645. int hs;
  105646. if(!v->backend_state)return -1;
  105647. if(!vi)return -1;
  105648. ci=(codec_setup_info*) vi->codec_setup;
  105649. if(!ci)return -1;
  105650. hs=ci->halfrate_flag;
  105651. v->centerW=ci->blocksizes[1]>>(hs+1);
  105652. v->pcm_current=v->centerW>>hs;
  105653. v->pcm_returned=-1;
  105654. v->granulepos=-1;
  105655. v->sequence=-1;
  105656. v->eofflag=0;
  105657. ((private_state *)(v->backend_state))->sample_count=-1;
  105658. return(0);
  105659. }
  105660. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  105661. if(_vds_shared_init(v,vi,0)) return 1;
  105662. vorbis_synthesis_restart(v);
  105663. return 0;
  105664. }
  105665. /* Unlike in analysis, the window is only partially applied for each
  105666. block. The time domain envelope is not yet handled at the point of
  105667. calling (as it relies on the previous block). */
  105668. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  105669. vorbis_info *vi=v->vi;
  105670. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105671. private_state *b=(private_state*)v->backend_state;
  105672. int hs=ci->halfrate_flag;
  105673. int i,j;
  105674. if(!vb)return(OV_EINVAL);
  105675. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  105676. v->lW=v->W;
  105677. v->W=vb->W;
  105678. v->nW=-1;
  105679. if((v->sequence==-1)||
  105680. (v->sequence+1 != vb->sequence)){
  105681. v->granulepos=-1; /* out of sequence; lose count */
  105682. b->sample_count=-1;
  105683. }
  105684. v->sequence=vb->sequence;
  105685. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  105686. was called on block */
  105687. int n=ci->blocksizes[v->W]>>(hs+1);
  105688. int n0=ci->blocksizes[0]>>(hs+1);
  105689. int n1=ci->blocksizes[1]>>(hs+1);
  105690. int thisCenter;
  105691. int prevCenter;
  105692. v->glue_bits+=vb->glue_bits;
  105693. v->time_bits+=vb->time_bits;
  105694. v->floor_bits+=vb->floor_bits;
  105695. v->res_bits+=vb->res_bits;
  105696. if(v->centerW){
  105697. thisCenter=n1;
  105698. prevCenter=0;
  105699. }else{
  105700. thisCenter=0;
  105701. prevCenter=n1;
  105702. }
  105703. /* v->pcm is now used like a two-stage double buffer. We don't want
  105704. to have to constantly shift *or* adjust memory usage. Don't
  105705. accept a new block until the old is shifted out */
  105706. for(j=0;j<vi->channels;j++){
  105707. /* the overlap/add section */
  105708. if(v->lW){
  105709. if(v->W){
  105710. /* large/large */
  105711. float *w=_vorbis_window_get(b->window[1]-hs);
  105712. float *pcm=v->pcm[j]+prevCenter;
  105713. float *p=vb->pcm[j];
  105714. for(i=0;i<n1;i++)
  105715. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  105716. }else{
  105717. /* large/small */
  105718. float *w=_vorbis_window_get(b->window[0]-hs);
  105719. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  105720. float *p=vb->pcm[j];
  105721. for(i=0;i<n0;i++)
  105722. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  105723. }
  105724. }else{
  105725. if(v->W){
  105726. /* small/large */
  105727. float *w=_vorbis_window_get(b->window[0]-hs);
  105728. float *pcm=v->pcm[j]+prevCenter;
  105729. float *p=vb->pcm[j]+n1/2-n0/2;
  105730. for(i=0;i<n0;i++)
  105731. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  105732. for(;i<n1/2+n0/2;i++)
  105733. pcm[i]=p[i];
  105734. }else{
  105735. /* small/small */
  105736. float *w=_vorbis_window_get(b->window[0]-hs);
  105737. float *pcm=v->pcm[j]+prevCenter;
  105738. float *p=vb->pcm[j];
  105739. for(i=0;i<n0;i++)
  105740. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  105741. }
  105742. }
  105743. /* the copy section */
  105744. {
  105745. float *pcm=v->pcm[j]+thisCenter;
  105746. float *p=vb->pcm[j]+n;
  105747. for(i=0;i<n;i++)
  105748. pcm[i]=p[i];
  105749. }
  105750. }
  105751. if(v->centerW)
  105752. v->centerW=0;
  105753. else
  105754. v->centerW=n1;
  105755. /* deal with initial packet state; we do this using the explicit
  105756. pcm_returned==-1 flag otherwise we're sensitive to first block
  105757. being short or long */
  105758. if(v->pcm_returned==-1){
  105759. v->pcm_returned=thisCenter;
  105760. v->pcm_current=thisCenter;
  105761. }else{
  105762. v->pcm_returned=prevCenter;
  105763. v->pcm_current=prevCenter+
  105764. ((ci->blocksizes[v->lW]/4+
  105765. ci->blocksizes[v->W]/4)>>hs);
  105766. }
  105767. }
  105768. /* track the frame number... This is for convenience, but also
  105769. making sure our last packet doesn't end with added padding. If
  105770. the last packet is partial, the number of samples we'll have to
  105771. return will be past the vb->granulepos.
  105772. This is not foolproof! It will be confused if we begin
  105773. decoding at the last page after a seek or hole. In that case,
  105774. we don't have a starting point to judge where the last frame
  105775. is. For this reason, vorbisfile will always try to make sure
  105776. it reads the last two marked pages in proper sequence */
  105777. if(b->sample_count==-1){
  105778. b->sample_count=0;
  105779. }else{
  105780. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  105781. }
  105782. if(v->granulepos==-1){
  105783. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  105784. v->granulepos=vb->granulepos;
  105785. /* is this a short page? */
  105786. if(b->sample_count>v->granulepos){
  105787. /* corner case; if this is both the first and last audio page,
  105788. then spec says the end is cut, not beginning */
  105789. if(vb->eofflag){
  105790. /* trim the end */
  105791. /* no preceeding granulepos; assume we started at zero (we'd
  105792. have to in a short single-page stream) */
  105793. /* granulepos could be -1 due to a seek, but that would result
  105794. in a long count, not short count */
  105795. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  105796. }else{
  105797. /* trim the beginning */
  105798. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  105799. if(v->pcm_returned>v->pcm_current)
  105800. v->pcm_returned=v->pcm_current;
  105801. }
  105802. }
  105803. }
  105804. }else{
  105805. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  105806. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  105807. if(v->granulepos>vb->granulepos){
  105808. long extra=v->granulepos-vb->granulepos;
  105809. if(extra)
  105810. if(vb->eofflag){
  105811. /* partial last frame. Strip the extra samples off */
  105812. v->pcm_current-=extra>>hs;
  105813. } /* else {Shouldn't happen *unless* the bitstream is out of
  105814. spec. Either way, believe the bitstream } */
  105815. } /* else {Shouldn't happen *unless* the bitstream is out of
  105816. spec. Either way, believe the bitstream } */
  105817. v->granulepos=vb->granulepos;
  105818. }
  105819. }
  105820. /* Update, cleanup */
  105821. if(vb->eofflag)v->eofflag=1;
  105822. return(0);
  105823. }
  105824. /* pcm==NULL indicates we just want the pending samples, no more */
  105825. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  105826. vorbis_info *vi=v->vi;
  105827. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  105828. if(pcm){
  105829. int i;
  105830. for(i=0;i<vi->channels;i++)
  105831. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  105832. *pcm=v->pcmret;
  105833. }
  105834. return(v->pcm_current-v->pcm_returned);
  105835. }
  105836. return(0);
  105837. }
  105838. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  105839. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  105840. v->pcm_returned+=n;
  105841. return(0);
  105842. }
  105843. /* intended for use with a specific vorbisfile feature; we want access
  105844. to the [usually synthetic/postextrapolated] buffer and lapping at
  105845. the end of a decode cycle, specifically, a half-short-block worth.
  105846. This funtion works like pcmout above, except it will also expose
  105847. this implicit buffer data not normally decoded. */
  105848. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  105849. vorbis_info *vi=v->vi;
  105850. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  105851. int hs=ci->halfrate_flag;
  105852. int n=ci->blocksizes[v->W]>>(hs+1);
  105853. int n0=ci->blocksizes[0]>>(hs+1);
  105854. int n1=ci->blocksizes[1]>>(hs+1);
  105855. int i,j;
  105856. if(v->pcm_returned<0)return 0;
  105857. /* our returned data ends at pcm_returned; because the synthesis pcm
  105858. buffer is a two-fragment ring, that means our data block may be
  105859. fragmented by buffering, wrapping or a short block not filling
  105860. out a buffer. To simplify things, we unfragment if it's at all
  105861. possibly needed. Otherwise, we'd need to call lapout more than
  105862. once as well as hold additional dsp state. Opt for
  105863. simplicity. */
  105864. /* centerW was advanced by blockin; it would be the center of the
  105865. *next* block */
  105866. if(v->centerW==n1){
  105867. /* the data buffer wraps; swap the halves */
  105868. /* slow, sure, small */
  105869. for(j=0;j<vi->channels;j++){
  105870. float *p=v->pcm[j];
  105871. for(i=0;i<n1;i++){
  105872. float temp=p[i];
  105873. p[i]=p[i+n1];
  105874. p[i+n1]=temp;
  105875. }
  105876. }
  105877. v->pcm_current-=n1;
  105878. v->pcm_returned-=n1;
  105879. v->centerW=0;
  105880. }
  105881. /* solidify buffer into contiguous space */
  105882. if((v->lW^v->W)==1){
  105883. /* long/short or short/long */
  105884. for(j=0;j<vi->channels;j++){
  105885. float *s=v->pcm[j];
  105886. float *d=v->pcm[j]+(n1-n0)/2;
  105887. for(i=(n1+n0)/2-1;i>=0;--i)
  105888. d[i]=s[i];
  105889. }
  105890. v->pcm_returned+=(n1-n0)/2;
  105891. v->pcm_current+=(n1-n0)/2;
  105892. }else{
  105893. if(v->lW==0){
  105894. /* short/short */
  105895. for(j=0;j<vi->channels;j++){
  105896. float *s=v->pcm[j];
  105897. float *d=v->pcm[j]+n1-n0;
  105898. for(i=n0-1;i>=0;--i)
  105899. d[i]=s[i];
  105900. }
  105901. v->pcm_returned+=n1-n0;
  105902. v->pcm_current+=n1-n0;
  105903. }
  105904. }
  105905. if(pcm){
  105906. int i;
  105907. for(i=0;i<vi->channels;i++)
  105908. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  105909. *pcm=v->pcmret;
  105910. }
  105911. return(n1+n-v->pcm_returned);
  105912. }
  105913. float *vorbis_window(vorbis_dsp_state *v,int W){
  105914. vorbis_info *vi=v->vi;
  105915. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  105916. int hs=ci->halfrate_flag;
  105917. private_state *b=(private_state*)v->backend_state;
  105918. if(b->window[W]-1<0)return NULL;
  105919. return _vorbis_window_get(b->window[W]-hs);
  105920. }
  105921. #endif
  105922. /********* End of inlined file: block.c *********/
  105923. /********* Start of inlined file: codebook.c *********/
  105924. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105925. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105926. // tasks..
  105927. #ifdef _MSC_VER
  105928. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105929. #endif
  105930. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105931. #if JUCE_USE_OGGVORBIS
  105932. #include <stdlib.h>
  105933. #include <string.h>
  105934. #include <math.h>
  105935. /* packs the given codebook into the bitstream **************************/
  105936. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  105937. long i,j;
  105938. int ordered=0;
  105939. /* first the basic parameters */
  105940. oggpack_write(opb,0x564342,24);
  105941. oggpack_write(opb,c->dim,16);
  105942. oggpack_write(opb,c->entries,24);
  105943. /* pack the codewords. There are two packings; length ordered and
  105944. length random. Decide between the two now. */
  105945. for(i=1;i<c->entries;i++)
  105946. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  105947. if(i==c->entries)ordered=1;
  105948. if(ordered){
  105949. /* length ordered. We only need to say how many codewords of
  105950. each length. The actual codewords are generated
  105951. deterministically */
  105952. long count=0;
  105953. oggpack_write(opb,1,1); /* ordered */
  105954. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  105955. for(i=1;i<c->entries;i++){
  105956. long thisx=c->lengthlist[i];
  105957. long last=c->lengthlist[i-1];
  105958. if(thisx>last){
  105959. for(j=last;j<thisx;j++){
  105960. oggpack_write(opb,i-count,_ilog(c->entries-count));
  105961. count=i;
  105962. }
  105963. }
  105964. }
  105965. oggpack_write(opb,i-count,_ilog(c->entries-count));
  105966. }else{
  105967. /* length random. Again, we don't code the codeword itself, just
  105968. the length. This time, though, we have to encode each length */
  105969. oggpack_write(opb,0,1); /* unordered */
  105970. /* algortihmic mapping has use for 'unused entries', which we tag
  105971. here. The algorithmic mapping happens as usual, but the unused
  105972. entry has no codeword. */
  105973. for(i=0;i<c->entries;i++)
  105974. if(c->lengthlist[i]==0)break;
  105975. if(i==c->entries){
  105976. oggpack_write(opb,0,1); /* no unused entries */
  105977. for(i=0;i<c->entries;i++)
  105978. oggpack_write(opb,c->lengthlist[i]-1,5);
  105979. }else{
  105980. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  105981. for(i=0;i<c->entries;i++){
  105982. if(c->lengthlist[i]==0){
  105983. oggpack_write(opb,0,1);
  105984. }else{
  105985. oggpack_write(opb,1,1);
  105986. oggpack_write(opb,c->lengthlist[i]-1,5);
  105987. }
  105988. }
  105989. }
  105990. }
  105991. /* is the entry number the desired return value, or do we have a
  105992. mapping? If we have a mapping, what type? */
  105993. oggpack_write(opb,c->maptype,4);
  105994. switch(c->maptype){
  105995. case 0:
  105996. /* no mapping */
  105997. break;
  105998. case 1:case 2:
  105999. /* implicitly populated value mapping */
  106000. /* explicitly populated value mapping */
  106001. if(!c->quantlist){
  106002. /* no quantlist? error */
  106003. return(-1);
  106004. }
  106005. /* values that define the dequantization */
  106006. oggpack_write(opb,c->q_min,32);
  106007. oggpack_write(opb,c->q_delta,32);
  106008. oggpack_write(opb,c->q_quant-1,4);
  106009. oggpack_write(opb,c->q_sequencep,1);
  106010. {
  106011. int quantvals;
  106012. switch(c->maptype){
  106013. case 1:
  106014. /* a single column of (c->entries/c->dim) quantized values for
  106015. building a full value list algorithmically (square lattice) */
  106016. quantvals=_book_maptype1_quantvals(c);
  106017. break;
  106018. case 2:
  106019. /* every value (c->entries*c->dim total) specified explicitly */
  106020. quantvals=c->entries*c->dim;
  106021. break;
  106022. default: /* NOT_REACHABLE */
  106023. quantvals=-1;
  106024. }
  106025. /* quantized values */
  106026. for(i=0;i<quantvals;i++)
  106027. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  106028. }
  106029. break;
  106030. default:
  106031. /* error case; we don't have any other map types now */
  106032. return(-1);
  106033. }
  106034. return(0);
  106035. }
  106036. /* unpacks a codebook from the packet buffer into the codebook struct,
  106037. readies the codebook auxiliary structures for decode *************/
  106038. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  106039. long i,j;
  106040. memset(s,0,sizeof(*s));
  106041. s->allocedp=1;
  106042. /* make sure alignment is correct */
  106043. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  106044. /* first the basic parameters */
  106045. s->dim=oggpack_read(opb,16);
  106046. s->entries=oggpack_read(opb,24);
  106047. if(s->entries==-1)goto _eofout;
  106048. /* codeword ordering.... length ordered or unordered? */
  106049. switch((int)oggpack_read(opb,1)){
  106050. case 0:
  106051. /* unordered */
  106052. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  106053. /* allocated but unused entries? */
  106054. if(oggpack_read(opb,1)){
  106055. /* yes, unused entries */
  106056. for(i=0;i<s->entries;i++){
  106057. if(oggpack_read(opb,1)){
  106058. long num=oggpack_read(opb,5);
  106059. if(num==-1)goto _eofout;
  106060. s->lengthlist[i]=num+1;
  106061. }else
  106062. s->lengthlist[i]=0;
  106063. }
  106064. }else{
  106065. /* all entries used; no tagging */
  106066. for(i=0;i<s->entries;i++){
  106067. long num=oggpack_read(opb,5);
  106068. if(num==-1)goto _eofout;
  106069. s->lengthlist[i]=num+1;
  106070. }
  106071. }
  106072. break;
  106073. case 1:
  106074. /* ordered */
  106075. {
  106076. long length=oggpack_read(opb,5)+1;
  106077. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  106078. for(i=0;i<s->entries;){
  106079. long num=oggpack_read(opb,_ilog(s->entries-i));
  106080. if(num==-1)goto _eofout;
  106081. for(j=0;j<num && i<s->entries;j++,i++)
  106082. s->lengthlist[i]=length;
  106083. length++;
  106084. }
  106085. }
  106086. break;
  106087. default:
  106088. /* EOF */
  106089. return(-1);
  106090. }
  106091. /* Do we have a mapping to unpack? */
  106092. switch((s->maptype=oggpack_read(opb,4))){
  106093. case 0:
  106094. /* no mapping */
  106095. break;
  106096. case 1: case 2:
  106097. /* implicitly populated value mapping */
  106098. /* explicitly populated value mapping */
  106099. s->q_min=oggpack_read(opb,32);
  106100. s->q_delta=oggpack_read(opb,32);
  106101. s->q_quant=oggpack_read(opb,4)+1;
  106102. s->q_sequencep=oggpack_read(opb,1);
  106103. {
  106104. int quantvals=0;
  106105. switch(s->maptype){
  106106. case 1:
  106107. quantvals=_book_maptype1_quantvals(s);
  106108. break;
  106109. case 2:
  106110. quantvals=s->entries*s->dim;
  106111. break;
  106112. }
  106113. /* quantized values */
  106114. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  106115. for(i=0;i<quantvals;i++)
  106116. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  106117. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  106118. }
  106119. break;
  106120. default:
  106121. goto _errout;
  106122. }
  106123. /* all set */
  106124. return(0);
  106125. _errout:
  106126. _eofout:
  106127. vorbis_staticbook_clear(s);
  106128. return(-1);
  106129. }
  106130. /* returns the number of bits ************************************************/
  106131. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  106132. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  106133. return(book->c->lengthlist[a]);
  106134. }
  106135. /* One the encode side, our vector writers are each designed for a
  106136. specific purpose, and the encoder is not flexible without modification:
  106137. The LSP vector coder uses a single stage nearest-match with no
  106138. interleave, so no step and no error return. This is specced by floor0
  106139. and doesn't change.
  106140. Residue0 encoding interleaves, uses multiple stages, and each stage
  106141. peels of a specific amount of resolution from a lattice (thus we want
  106142. to match by threshold, not nearest match). Residue doesn't *have* to
  106143. be encoded that way, but to change it, one will need to add more
  106144. infrastructure on the encode side (decode side is specced and simpler) */
  106145. /* floor0 LSP (single stage, non interleaved, nearest match) */
  106146. /* returns entry number and *modifies a* to the quantization value *****/
  106147. int vorbis_book_errorv(codebook *book,float *a){
  106148. int dim=book->dim,k;
  106149. int best=_best(book,a,1);
  106150. for(k=0;k<dim;k++)
  106151. a[k]=(book->valuelist+best*dim)[k];
  106152. return(best);
  106153. }
  106154. /* returns the number of bits and *modifies a* to the quantization value *****/
  106155. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  106156. int k,dim=book->dim;
  106157. for(k=0;k<dim;k++)
  106158. a[k]=(book->valuelist+best*dim)[k];
  106159. return(vorbis_book_encode(book,best,b));
  106160. }
  106161. /* the 'eliminate the decode tree' optimization actually requires the
  106162. codewords to be MSb first, not LSb. This is an annoying inelegancy
  106163. (and one of the first places where carefully thought out design
  106164. turned out to be wrong; Vorbis II and future Ogg codecs should go
  106165. to an MSb bitpacker), but not actually the huge hit it appears to
  106166. be. The first-stage decode table catches most words so that
  106167. bitreverse is not in the main execution path. */
  106168. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  106169. int read=book->dec_maxlength;
  106170. long lo,hi;
  106171. long lok = oggpack_look(b,book->dec_firsttablen);
  106172. if (lok >= 0) {
  106173. long entry = book->dec_firsttable[lok];
  106174. if(entry&0x80000000UL){
  106175. lo=(entry>>15)&0x7fff;
  106176. hi=book->used_entries-(entry&0x7fff);
  106177. }else{
  106178. oggpack_adv(b, book->dec_codelengths[entry-1]);
  106179. return(entry-1);
  106180. }
  106181. }else{
  106182. lo=0;
  106183. hi=book->used_entries;
  106184. }
  106185. lok = oggpack_look(b, read);
  106186. while(lok<0 && read>1)
  106187. lok = oggpack_look(b, --read);
  106188. if(lok<0)return -1;
  106189. /* bisect search for the codeword in the ordered list */
  106190. {
  106191. ogg_uint32_t testword=bitreverse((ogg_uint32_t)lok);
  106192. while(hi-lo>1){
  106193. long p=(hi-lo)>>1;
  106194. long test=book->codelist[lo+p]>testword;
  106195. lo+=p&(test-1);
  106196. hi-=p&(-test);
  106197. }
  106198. if(book->dec_codelengths[lo]<=read){
  106199. oggpack_adv(b, book->dec_codelengths[lo]);
  106200. return(lo);
  106201. }
  106202. }
  106203. oggpack_adv(b, read);
  106204. return(-1);
  106205. }
  106206. /* Decode side is specced and easier, because we don't need to find
  106207. matches using different criteria; we simply read and map. There are
  106208. two things we need to do 'depending':
  106209. We may need to support interleave. We don't really, but it's
  106210. convenient to do it here rather than rebuild the vector later.
  106211. Cascades may be additive or multiplicitive; this is not inherent in
  106212. the codebook, but set in the code using the codebook. Like
  106213. interleaving, it's easiest to do it here.
  106214. addmul==0 -> declarative (set the value)
  106215. addmul==1 -> additive
  106216. addmul==2 -> multiplicitive */
  106217. /* returns the [original, not compacted] entry number or -1 on eof *********/
  106218. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  106219. long packed_entry=decode_packed_entry_number(book,b);
  106220. if(packed_entry>=0)
  106221. return(book->dec_index[packed_entry]);
  106222. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  106223. return(packed_entry);
  106224. }
  106225. /* returns 0 on OK or -1 on eof *************************************/
  106226. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  106227. int step=n/book->dim;
  106228. long *entry = (long*)alloca(sizeof(*entry)*step);
  106229. float **t = (float**)alloca(sizeof(*t)*step);
  106230. int i,j,o;
  106231. for (i = 0; i < step; i++) {
  106232. entry[i]=decode_packed_entry_number(book,b);
  106233. if(entry[i]==-1)return(-1);
  106234. t[i] = book->valuelist+entry[i]*book->dim;
  106235. }
  106236. for(i=0,o=0;i<book->dim;i++,o+=step)
  106237. for (j=0;j<step;j++)
  106238. a[o+j]+=t[j][i];
  106239. return(0);
  106240. }
  106241. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  106242. int i,j,entry;
  106243. float *t;
  106244. if(book->dim>8){
  106245. for(i=0;i<n;){
  106246. entry = decode_packed_entry_number(book,b);
  106247. if(entry==-1)return(-1);
  106248. t = book->valuelist+entry*book->dim;
  106249. for (j=0;j<book->dim;)
  106250. a[i++]+=t[j++];
  106251. }
  106252. }else{
  106253. for(i=0;i<n;){
  106254. entry = decode_packed_entry_number(book,b);
  106255. if(entry==-1)return(-1);
  106256. t = book->valuelist+entry*book->dim;
  106257. j=0;
  106258. switch((int)book->dim){
  106259. case 8:
  106260. a[i++]+=t[j++];
  106261. case 7:
  106262. a[i++]+=t[j++];
  106263. case 6:
  106264. a[i++]+=t[j++];
  106265. case 5:
  106266. a[i++]+=t[j++];
  106267. case 4:
  106268. a[i++]+=t[j++];
  106269. case 3:
  106270. a[i++]+=t[j++];
  106271. case 2:
  106272. a[i++]+=t[j++];
  106273. case 1:
  106274. a[i++]+=t[j++];
  106275. case 0:
  106276. break;
  106277. }
  106278. }
  106279. }
  106280. return(0);
  106281. }
  106282. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  106283. int i,j,entry;
  106284. float *t;
  106285. for(i=0;i<n;){
  106286. entry = decode_packed_entry_number(book,b);
  106287. if(entry==-1)return(-1);
  106288. t = book->valuelist+entry*book->dim;
  106289. for (j=0;j<book->dim;)
  106290. a[i++]=t[j++];
  106291. }
  106292. return(0);
  106293. }
  106294. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  106295. oggpack_buffer *b,int n){
  106296. long i,j,entry;
  106297. int chptr=0;
  106298. for(i=offset/ch;i<(offset+n)/ch;){
  106299. entry = decode_packed_entry_number(book,b);
  106300. if(entry==-1)return(-1);
  106301. {
  106302. const float *t = book->valuelist+entry*book->dim;
  106303. for (j=0;j<book->dim;j++){
  106304. a[chptr++][i]+=t[j];
  106305. if(chptr==ch){
  106306. chptr=0;
  106307. i++;
  106308. }
  106309. }
  106310. }
  106311. }
  106312. return(0);
  106313. }
  106314. #ifdef _V_SELFTEST
  106315. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  106316. number of vectors through (keeping track of the quantized values),
  106317. and decode using the unpacked book. quantized version of in should
  106318. exactly equal out */
  106319. #include <stdio.h>
  106320. #include "vorbis/book/lsp20_0.vqh"
  106321. #include "vorbis/book/res0a_13.vqh"
  106322. #define TESTSIZE 40
  106323. float test1[TESTSIZE]={
  106324. 0.105939f,
  106325. 0.215373f,
  106326. 0.429117f,
  106327. 0.587974f,
  106328. 0.181173f,
  106329. 0.296583f,
  106330. 0.515707f,
  106331. 0.715261f,
  106332. 0.162327f,
  106333. 0.263834f,
  106334. 0.342876f,
  106335. 0.406025f,
  106336. 0.103571f,
  106337. 0.223561f,
  106338. 0.368513f,
  106339. 0.540313f,
  106340. 0.136672f,
  106341. 0.395882f,
  106342. 0.587183f,
  106343. 0.652476f,
  106344. 0.114338f,
  106345. 0.417300f,
  106346. 0.525486f,
  106347. 0.698679f,
  106348. 0.147492f,
  106349. 0.324481f,
  106350. 0.643089f,
  106351. 0.757582f,
  106352. 0.139556f,
  106353. 0.215795f,
  106354. 0.324559f,
  106355. 0.399387f,
  106356. 0.120236f,
  106357. 0.267420f,
  106358. 0.446940f,
  106359. 0.608760f,
  106360. 0.115587f,
  106361. 0.287234f,
  106362. 0.571081f,
  106363. 0.708603f,
  106364. };
  106365. float test3[TESTSIZE]={
  106366. 0,1,-2,3,4,-5,6,7,8,9,
  106367. 8,-2,7,-1,4,6,8,3,1,-9,
  106368. 10,11,12,13,14,15,26,17,18,19,
  106369. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  106370. static_codebook *testlist[]={&_vq_book_lsp20_0,
  106371. &_vq_book_res0a_13,NULL};
  106372. float *testvec[]={test1,test3};
  106373. int main(){
  106374. oggpack_buffer write;
  106375. oggpack_buffer read;
  106376. long ptr=0,i;
  106377. oggpack_writeinit(&write);
  106378. fprintf(stderr,"Testing codebook abstraction...:\n");
  106379. while(testlist[ptr]){
  106380. codebook c;
  106381. static_codebook s;
  106382. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  106383. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  106384. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  106385. memset(iv,0,sizeof(*iv)*TESTSIZE);
  106386. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  106387. /* pack the codebook, write the testvector */
  106388. oggpack_reset(&write);
  106389. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  106390. we can write */
  106391. vorbis_staticbook_pack(testlist[ptr],&write);
  106392. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  106393. for(i=0;i<TESTSIZE;i+=c.dim){
  106394. int best=_best(&c,qv+i,1);
  106395. vorbis_book_encodev(&c,best,qv+i,&write);
  106396. }
  106397. vorbis_book_clear(&c);
  106398. fprintf(stderr,"OK.\n");
  106399. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  106400. /* transfer the write data to a read buffer and unpack/read */
  106401. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  106402. if(vorbis_staticbook_unpack(&read,&s)){
  106403. fprintf(stderr,"Error unpacking codebook.\n");
  106404. exit(1);
  106405. }
  106406. if(vorbis_book_init_decode(&c,&s)){
  106407. fprintf(stderr,"Error initializing codebook.\n");
  106408. exit(1);
  106409. }
  106410. for(i=0;i<TESTSIZE;i+=c.dim)
  106411. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  106412. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  106413. exit(1);
  106414. }
  106415. for(i=0;i<TESTSIZE;i++)
  106416. if(fabs(qv[i]-iv[i])>.000001){
  106417. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  106418. iv[i],qv[i],i);
  106419. exit(1);
  106420. }
  106421. fprintf(stderr,"OK\n");
  106422. ptr++;
  106423. }
  106424. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  106425. exit(0);
  106426. }
  106427. #endif
  106428. #endif
  106429. /********* End of inlined file: codebook.c *********/
  106430. /********* Start of inlined file: envelope.c *********/
  106431. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106432. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106433. // tasks..
  106434. #ifdef _MSC_VER
  106435. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106436. #endif
  106437. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106438. #if JUCE_USE_OGGVORBIS
  106439. #include <stdlib.h>
  106440. #include <string.h>
  106441. #include <stdio.h>
  106442. #include <math.h>
  106443. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  106444. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106445. vorbis_info_psy_global *gi=&ci->psy_g_param;
  106446. int ch=vi->channels;
  106447. int i,j;
  106448. int n=e->winlength=128;
  106449. e->searchstep=64; /* not random */
  106450. e->minenergy=gi->preecho_minenergy;
  106451. e->ch=ch;
  106452. e->storage=128;
  106453. e->cursor=ci->blocksizes[1]/2;
  106454. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  106455. mdct_init(&e->mdct,n);
  106456. for(i=0;i<n;i++){
  106457. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  106458. e->mdct_win[i]*=e->mdct_win[i];
  106459. }
  106460. /* magic follows */
  106461. e->band[0].begin=2; e->band[0].end=4;
  106462. e->band[1].begin=4; e->band[1].end=5;
  106463. e->band[2].begin=6; e->band[2].end=6;
  106464. e->band[3].begin=9; e->band[3].end=8;
  106465. e->band[4].begin=13; e->band[4].end=8;
  106466. e->band[5].begin=17; e->band[5].end=8;
  106467. e->band[6].begin=22; e->band[6].end=8;
  106468. for(j=0;j<VE_BANDS;j++){
  106469. n=e->band[j].end;
  106470. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  106471. for(i=0;i<n;i++){
  106472. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  106473. e->band[j].total+=e->band[j].window[i];
  106474. }
  106475. e->band[j].total=1./e->band[j].total;
  106476. }
  106477. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  106478. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  106479. }
  106480. void _ve_envelope_clear(envelope_lookup *e){
  106481. int i;
  106482. mdct_clear(&e->mdct);
  106483. for(i=0;i<VE_BANDS;i++)
  106484. _ogg_free(e->band[i].window);
  106485. _ogg_free(e->mdct_win);
  106486. _ogg_free(e->filter);
  106487. _ogg_free(e->mark);
  106488. memset(e,0,sizeof(*e));
  106489. }
  106490. /* fairly straight threshhold-by-band based until we find something
  106491. that works better and isn't patented. */
  106492. static int _ve_amp(envelope_lookup *ve,
  106493. vorbis_info_psy_global *gi,
  106494. float *data,
  106495. envelope_band *bands,
  106496. envelope_filter_state *filters,
  106497. long pos){
  106498. long n=ve->winlength;
  106499. int ret=0;
  106500. long i,j;
  106501. float decay;
  106502. /* we want to have a 'minimum bar' for energy, else we're just
  106503. basing blocks on quantization noise that outweighs the signal
  106504. itself (for low power signals) */
  106505. float minV=ve->minenergy;
  106506. float *vec=(float*) alloca(n*sizeof(*vec));
  106507. /* stretch is used to gradually lengthen the number of windows
  106508. considered prevoius-to-potential-trigger */
  106509. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  106510. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  106511. if(penalty<0.f)penalty=0.f;
  106512. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  106513. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  106514. totalshift+pos*ve->searchstep);*/
  106515. /* window and transform */
  106516. for(i=0;i<n;i++)
  106517. vec[i]=data[i]*ve->mdct_win[i];
  106518. mdct_forward(&ve->mdct,vec,vec);
  106519. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  106520. /* near-DC spreading function; this has nothing to do with
  106521. psychoacoustics, just sidelobe leakage and window size */
  106522. {
  106523. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  106524. int ptr=filters->nearptr;
  106525. /* the accumulation is regularly refreshed from scratch to avoid
  106526. floating point creep */
  106527. if(ptr==0){
  106528. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  106529. filters->nearDC_partialacc=temp;
  106530. }else{
  106531. decay=filters->nearDC_acc+=temp;
  106532. filters->nearDC_partialacc+=temp;
  106533. }
  106534. filters->nearDC_acc-=filters->nearDC[ptr];
  106535. filters->nearDC[ptr]=temp;
  106536. decay*=(1./(VE_NEARDC+1));
  106537. filters->nearptr++;
  106538. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  106539. decay=todB(&decay)*.5-15.f;
  106540. }
  106541. /* perform spreading and limiting, also smooth the spectrum. yes,
  106542. the MDCT results in all real coefficients, but it still *behaves*
  106543. like real/imaginary pairs */
  106544. for(i=0;i<n/2;i+=2){
  106545. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  106546. val=todB(&val)*.5f;
  106547. if(val<decay)val=decay;
  106548. if(val<minV)val=minV;
  106549. vec[i>>1]=val;
  106550. decay-=8.;
  106551. }
  106552. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  106553. /* perform preecho/postecho triggering by band */
  106554. for(j=0;j<VE_BANDS;j++){
  106555. float acc=0.;
  106556. float valmax,valmin;
  106557. /* accumulate amplitude */
  106558. for(i=0;i<bands[j].end;i++)
  106559. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  106560. acc*=bands[j].total;
  106561. /* convert amplitude to delta */
  106562. {
  106563. int p,thisx=filters[j].ampptr;
  106564. float postmax,postmin,premax=-99999.f,premin=99999.f;
  106565. p=thisx;
  106566. p--;
  106567. if(p<0)p+=VE_AMP;
  106568. postmax=max(acc,filters[j].ampbuf[p]);
  106569. postmin=min(acc,filters[j].ampbuf[p]);
  106570. for(i=0;i<stretch;i++){
  106571. p--;
  106572. if(p<0)p+=VE_AMP;
  106573. premax=max(premax,filters[j].ampbuf[p]);
  106574. premin=min(premin,filters[j].ampbuf[p]);
  106575. }
  106576. valmin=postmin-premin;
  106577. valmax=postmax-premax;
  106578. /*filters[j].markers[pos]=valmax;*/
  106579. filters[j].ampbuf[thisx]=acc;
  106580. filters[j].ampptr++;
  106581. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  106582. }
  106583. /* look at min/max, decide trigger */
  106584. if(valmax>gi->preecho_thresh[j]+penalty){
  106585. ret|=1;
  106586. ret|=4;
  106587. }
  106588. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  106589. }
  106590. return(ret);
  106591. }
  106592. #if 0
  106593. static int seq=0;
  106594. static ogg_int64_t totalshift=-1024;
  106595. #endif
  106596. long _ve_envelope_search(vorbis_dsp_state *v){
  106597. vorbis_info *vi=v->vi;
  106598. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  106599. vorbis_info_psy_global *gi=&ci->psy_g_param;
  106600. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  106601. long i,j;
  106602. int first=ve->current/ve->searchstep;
  106603. int last=v->pcm_current/ve->searchstep-VE_WIN;
  106604. if(first<0)first=0;
  106605. /* make sure we have enough storage to match the PCM */
  106606. if(last+VE_WIN+VE_POST>ve->storage){
  106607. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  106608. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  106609. }
  106610. for(j=first;j<last;j++){
  106611. int ret=0;
  106612. ve->stretch++;
  106613. if(ve->stretch>VE_MAXSTRETCH*2)
  106614. ve->stretch=VE_MAXSTRETCH*2;
  106615. for(i=0;i<ve->ch;i++){
  106616. float *pcm=v->pcm[i]+ve->searchstep*(j);
  106617. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  106618. }
  106619. ve->mark[j+VE_POST]=0;
  106620. if(ret&1){
  106621. ve->mark[j]=1;
  106622. ve->mark[j+1]=1;
  106623. }
  106624. if(ret&2){
  106625. ve->mark[j]=1;
  106626. if(j>0)ve->mark[j-1]=1;
  106627. }
  106628. if(ret&4)ve->stretch=-1;
  106629. }
  106630. ve->current=last*ve->searchstep;
  106631. {
  106632. long centerW=v->centerW;
  106633. long testW=
  106634. centerW+
  106635. ci->blocksizes[v->W]/4+
  106636. ci->blocksizes[1]/2+
  106637. ci->blocksizes[0]/4;
  106638. j=ve->cursor;
  106639. while(j<ve->current-(ve->searchstep)){/* account for postecho
  106640. working back one window */
  106641. if(j>=testW)return(1);
  106642. ve->cursor=j;
  106643. if(ve->mark[j/ve->searchstep]){
  106644. if(j>centerW){
  106645. #if 0
  106646. if(j>ve->curmark){
  106647. float *marker=alloca(v->pcm_current*sizeof(*marker));
  106648. int l,m;
  106649. memset(marker,0,sizeof(*marker)*v->pcm_current);
  106650. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  106651. seq,
  106652. (totalshift+ve->cursor)/44100.,
  106653. (totalshift+j)/44100.);
  106654. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  106655. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  106656. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  106657. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  106658. for(m=0;m<VE_BANDS;m++){
  106659. char buf[80];
  106660. sprintf(buf,"delL%d",m);
  106661. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  106662. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  106663. }
  106664. for(m=0;m<VE_BANDS;m++){
  106665. char buf[80];
  106666. sprintf(buf,"delR%d",m);
  106667. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  106668. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  106669. }
  106670. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  106671. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  106672. seq++;
  106673. }
  106674. #endif
  106675. ve->curmark=j;
  106676. if(j>=testW)return(1);
  106677. return(0);
  106678. }
  106679. }
  106680. j+=ve->searchstep;
  106681. }
  106682. }
  106683. return(-1);
  106684. }
  106685. int _ve_envelope_mark(vorbis_dsp_state *v){
  106686. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  106687. vorbis_info *vi=v->vi;
  106688. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106689. long centerW=v->centerW;
  106690. long beginW=centerW-ci->blocksizes[v->W]/4;
  106691. long endW=centerW+ci->blocksizes[v->W]/4;
  106692. if(v->W){
  106693. beginW-=ci->blocksizes[v->lW]/4;
  106694. endW+=ci->blocksizes[v->nW]/4;
  106695. }else{
  106696. beginW-=ci->blocksizes[0]/4;
  106697. endW+=ci->blocksizes[0]/4;
  106698. }
  106699. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  106700. {
  106701. long first=beginW/ve->searchstep;
  106702. long last=endW/ve->searchstep;
  106703. long i;
  106704. for(i=first;i<last;i++)
  106705. if(ve->mark[i])return(1);
  106706. }
  106707. return(0);
  106708. }
  106709. void _ve_envelope_shift(envelope_lookup *e,long shift){
  106710. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  106711. ahead of ve->current */
  106712. int smallshift=shift/e->searchstep;
  106713. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  106714. #if 0
  106715. for(i=0;i<VE_BANDS*e->ch;i++)
  106716. memmove(e->filter[i].markers,
  106717. e->filter[i].markers+smallshift,
  106718. (1024-smallshift)*sizeof(*(*e->filter).markers));
  106719. totalshift+=shift;
  106720. #endif
  106721. e->current-=shift;
  106722. if(e->curmark>=0)
  106723. e->curmark-=shift;
  106724. e->cursor-=shift;
  106725. }
  106726. #endif
  106727. /********* End of inlined file: envelope.c *********/
  106728. /********* Start of inlined file: floor0.c *********/
  106729. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106730. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106731. // tasks..
  106732. #ifdef _MSC_VER
  106733. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106734. #endif
  106735. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106736. #if JUCE_USE_OGGVORBIS
  106737. #include <stdlib.h>
  106738. #include <string.h>
  106739. #include <math.h>
  106740. /********* Start of inlined file: lsp.h *********/
  106741. #ifndef _V_LSP_H_
  106742. #define _V_LSP_H_
  106743. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  106744. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  106745. float *lsp,int m,
  106746. float amp,float ampoffset);
  106747. #endif
  106748. /********* End of inlined file: lsp.h *********/
  106749. #include <stdio.h>
  106750. typedef struct {
  106751. int ln;
  106752. int m;
  106753. int **linearmap;
  106754. int n[2];
  106755. vorbis_info_floor0 *vi;
  106756. long bits;
  106757. long frames;
  106758. } vorbis_look_floor0;
  106759. /***********************************************/
  106760. static void floor0_free_info(vorbis_info_floor *i){
  106761. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  106762. if(info){
  106763. memset(info,0,sizeof(*info));
  106764. _ogg_free(info);
  106765. }
  106766. }
  106767. static void floor0_free_look(vorbis_look_floor *i){
  106768. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  106769. if(look){
  106770. if(look->linearmap){
  106771. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  106772. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  106773. _ogg_free(look->linearmap);
  106774. }
  106775. memset(look,0,sizeof(*look));
  106776. _ogg_free(look);
  106777. }
  106778. }
  106779. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  106780. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106781. int j;
  106782. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  106783. info->order=oggpack_read(opb,8);
  106784. info->rate=oggpack_read(opb,16);
  106785. info->barkmap=oggpack_read(opb,16);
  106786. info->ampbits=oggpack_read(opb,6);
  106787. info->ampdB=oggpack_read(opb,8);
  106788. info->numbooks=oggpack_read(opb,4)+1;
  106789. if(info->order<1)goto err_out;
  106790. if(info->rate<1)goto err_out;
  106791. if(info->barkmap<1)goto err_out;
  106792. if(info->numbooks<1)goto err_out;
  106793. for(j=0;j<info->numbooks;j++){
  106794. info->books[j]=oggpack_read(opb,8);
  106795. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  106796. }
  106797. return(info);
  106798. err_out:
  106799. floor0_free_info(info);
  106800. return(NULL);
  106801. }
  106802. /* initialize Bark scale and normalization lookups. We could do this
  106803. with static tables, but Vorbis allows a number of possible
  106804. combinations, so it's best to do it computationally.
  106805. The below is authoritative in terms of defining scale mapping.
  106806. Note that the scale depends on the sampling rate as well as the
  106807. linear block and mapping sizes */
  106808. static void floor0_map_lazy_init(vorbis_block *vb,
  106809. vorbis_info_floor *infoX,
  106810. vorbis_look_floor0 *look){
  106811. if(!look->linearmap[vb->W]){
  106812. vorbis_dsp_state *vd=vb->vd;
  106813. vorbis_info *vi=vd->vi;
  106814. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106815. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  106816. int W=vb->W;
  106817. int n=ci->blocksizes[W]/2,j;
  106818. /* we choose a scaling constant so that:
  106819. floor(bark(rate/2-1)*C)=mapped-1
  106820. floor(bark(rate/2)*C)=mapped */
  106821. float scale=look->ln/toBARK(info->rate/2.f);
  106822. /* the mapping from a linear scale to a smaller bark scale is
  106823. straightforward. We do *not* make sure that the linear mapping
  106824. does not skip bark-scale bins; the decoder simply skips them and
  106825. the encoder may do what it wishes in filling them. They're
  106826. necessary in some mapping combinations to keep the scale spacing
  106827. accurate */
  106828. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  106829. for(j=0;j<n;j++){
  106830. int val=floor( toBARK((info->rate/2.f)/n*j)
  106831. *scale); /* bark numbers represent band edges */
  106832. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  106833. look->linearmap[W][j]=val;
  106834. }
  106835. look->linearmap[W][j]=-1;
  106836. look->n[W]=n;
  106837. }
  106838. }
  106839. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  106840. vorbis_info_floor *i){
  106841. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  106842. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  106843. look->m=info->order;
  106844. look->ln=info->barkmap;
  106845. look->vi=info;
  106846. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  106847. return look;
  106848. }
  106849. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  106850. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  106851. vorbis_info_floor0 *info=look->vi;
  106852. int j,k;
  106853. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  106854. if(ampraw>0){ /* also handles the -1 out of data case */
  106855. long maxval=(1<<info->ampbits)-1;
  106856. float amp=(float)ampraw/maxval*info->ampdB;
  106857. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  106858. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  106859. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  106860. codebook *b=ci->fullbooks+info->books[booknum];
  106861. float last=0.f;
  106862. /* the additional b->dim is a guard against any possible stack
  106863. smash; b->dim is provably more than we can overflow the
  106864. vector */
  106865. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  106866. for(j=0;j<look->m;j+=b->dim)
  106867. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  106868. for(j=0;j<look->m;){
  106869. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  106870. last=lsp[j-1];
  106871. }
  106872. lsp[look->m]=amp;
  106873. return(lsp);
  106874. }
  106875. }
  106876. eop:
  106877. return(NULL);
  106878. }
  106879. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  106880. void *memo,float *out){
  106881. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  106882. vorbis_info_floor0 *info=look->vi;
  106883. floor0_map_lazy_init(vb,info,look);
  106884. if(memo){
  106885. float *lsp=(float *)memo;
  106886. float amp=lsp[look->m];
  106887. /* take the coefficients back to a spectral envelope curve */
  106888. vorbis_lsp_to_curve(out,
  106889. look->linearmap[vb->W],
  106890. look->n[vb->W],
  106891. look->ln,
  106892. lsp,look->m,amp,(float)info->ampdB);
  106893. return(1);
  106894. }
  106895. memset(out,0,sizeof(*out)*look->n[vb->W]);
  106896. return(0);
  106897. }
  106898. /* export hooks */
  106899. vorbis_func_floor floor0_exportbundle={
  106900. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  106901. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  106902. };
  106903. #endif
  106904. /********* End of inlined file: floor0.c *********/
  106905. /********* Start of inlined file: floor1.c *********/
  106906. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106907. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106908. // tasks..
  106909. #ifdef _MSC_VER
  106910. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106911. #endif
  106912. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106913. #if JUCE_USE_OGGVORBIS
  106914. #include <stdlib.h>
  106915. #include <string.h>
  106916. #include <math.h>
  106917. #include <stdio.h>
  106918. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  106919. typedef struct {
  106920. int sorted_index[VIF_POSIT+2];
  106921. int forward_index[VIF_POSIT+2];
  106922. int reverse_index[VIF_POSIT+2];
  106923. int hineighbor[VIF_POSIT];
  106924. int loneighbor[VIF_POSIT];
  106925. int posts;
  106926. int n;
  106927. int quant_q;
  106928. vorbis_info_floor1 *vi;
  106929. long phrasebits;
  106930. long postbits;
  106931. long frames;
  106932. } vorbis_look_floor1;
  106933. typedef struct lsfit_acc{
  106934. long x0;
  106935. long x1;
  106936. long xa;
  106937. long ya;
  106938. long x2a;
  106939. long y2a;
  106940. long xya;
  106941. long an;
  106942. } lsfit_acc;
  106943. /***********************************************/
  106944. static void floor1_free_info(vorbis_info_floor *i){
  106945. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  106946. if(info){
  106947. memset(info,0,sizeof(*info));
  106948. _ogg_free(info);
  106949. }
  106950. }
  106951. static void floor1_free_look(vorbis_look_floor *i){
  106952. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  106953. if(look){
  106954. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  106955. (float)look->phrasebits/look->frames,
  106956. (float)look->postbits/look->frames,
  106957. (float)(look->postbits+look->phrasebits)/look->frames);*/
  106958. memset(look,0,sizeof(*look));
  106959. _ogg_free(look);
  106960. }
  106961. }
  106962. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  106963. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  106964. int j,k;
  106965. int count=0;
  106966. int rangebits;
  106967. int maxposit=info->postlist[1];
  106968. int maxclass=-1;
  106969. /* save out partitions */
  106970. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  106971. for(j=0;j<info->partitions;j++){
  106972. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  106973. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  106974. }
  106975. /* save out partition classes */
  106976. for(j=0;j<maxclass+1;j++){
  106977. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  106978. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  106979. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  106980. for(k=0;k<(1<<info->class_subs[j]);k++)
  106981. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  106982. }
  106983. /* save out the post list */
  106984. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  106985. oggpack_write(opb,ilog2(maxposit),4);
  106986. rangebits=ilog2(maxposit);
  106987. for(j=0,k=0;j<info->partitions;j++){
  106988. count+=info->class_dim[info->partitionclass[j]];
  106989. for(;k<count;k++)
  106990. oggpack_write(opb,info->postlist[k+2],rangebits);
  106991. }
  106992. }
  106993. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  106994. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106995. int j,k,count=0,maxclass=-1,rangebits;
  106996. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  106997. /* read partitions */
  106998. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  106999. for(j=0;j<info->partitions;j++){
  107000. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  107001. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  107002. }
  107003. /* read partition classes */
  107004. for(j=0;j<maxclass+1;j++){
  107005. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  107006. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  107007. if(info->class_subs[j]<0)
  107008. goto err_out;
  107009. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  107010. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  107011. goto err_out;
  107012. for(k=0;k<(1<<info->class_subs[j]);k++){
  107013. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  107014. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  107015. goto err_out;
  107016. }
  107017. }
  107018. /* read the post list */
  107019. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  107020. rangebits=oggpack_read(opb,4);
  107021. for(j=0,k=0;j<info->partitions;j++){
  107022. count+=info->class_dim[info->partitionclass[j]];
  107023. for(;k<count;k++){
  107024. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  107025. if(t<0 || t>=(1<<rangebits))
  107026. goto err_out;
  107027. }
  107028. }
  107029. info->postlist[0]=0;
  107030. info->postlist[1]=1<<rangebits;
  107031. return(info);
  107032. err_out:
  107033. floor1_free_info(info);
  107034. return(NULL);
  107035. }
  107036. static int icomp(const void *a,const void *b){
  107037. return(**(int **)a-**(int **)b);
  107038. }
  107039. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  107040. vorbis_info_floor *in){
  107041. int *sortpointer[VIF_POSIT+2];
  107042. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  107043. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  107044. int i,j,n=0;
  107045. look->vi=info;
  107046. look->n=info->postlist[1];
  107047. /* we drop each position value in-between already decoded values,
  107048. and use linear interpolation to predict each new value past the
  107049. edges. The positions are read in the order of the position
  107050. list... we precompute the bounding positions in the lookup. Of
  107051. course, the neighbors can change (if a position is declined), but
  107052. this is an initial mapping */
  107053. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  107054. n+=2;
  107055. look->posts=n;
  107056. /* also store a sorted position index */
  107057. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  107058. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  107059. /* points from sort order back to range number */
  107060. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  107061. /* points from range order to sorted position */
  107062. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  107063. /* we actually need the post values too */
  107064. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  107065. /* quantize values to multiplier spec */
  107066. switch(info->mult){
  107067. case 1: /* 1024 -> 256 */
  107068. look->quant_q=256;
  107069. break;
  107070. case 2: /* 1024 -> 128 */
  107071. look->quant_q=128;
  107072. break;
  107073. case 3: /* 1024 -> 86 */
  107074. look->quant_q=86;
  107075. break;
  107076. case 4: /* 1024 -> 64 */
  107077. look->quant_q=64;
  107078. break;
  107079. }
  107080. /* discover our neighbors for decode where we don't use fit flags
  107081. (that would push the neighbors outward) */
  107082. for(i=0;i<n-2;i++){
  107083. int lo=0;
  107084. int hi=1;
  107085. int lx=0;
  107086. int hx=look->n;
  107087. int currentx=info->postlist[i+2];
  107088. for(j=0;j<i+2;j++){
  107089. int x=info->postlist[j];
  107090. if(x>lx && x<currentx){
  107091. lo=j;
  107092. lx=x;
  107093. }
  107094. if(x<hx && x>currentx){
  107095. hi=j;
  107096. hx=x;
  107097. }
  107098. }
  107099. look->loneighbor[i]=lo;
  107100. look->hineighbor[i]=hi;
  107101. }
  107102. return(look);
  107103. }
  107104. static int render_point(int x0,int x1,int y0,int y1,int x){
  107105. y0&=0x7fff; /* mask off flag */
  107106. y1&=0x7fff;
  107107. {
  107108. int dy=y1-y0;
  107109. int adx=x1-x0;
  107110. int ady=abs(dy);
  107111. int err=ady*(x-x0);
  107112. int off=err/adx;
  107113. if(dy<0)return(y0-off);
  107114. return(y0+off);
  107115. }
  107116. }
  107117. static int vorbis_dBquant(const float *x){
  107118. int i= *x*7.3142857f+1023.5f;
  107119. if(i>1023)return(1023);
  107120. if(i<0)return(0);
  107121. return i;
  107122. }
  107123. static float FLOOR1_fromdB_LOOKUP[256]={
  107124. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  107125. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  107126. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  107127. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  107128. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  107129. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  107130. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  107131. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  107132. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  107133. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  107134. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  107135. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  107136. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  107137. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  107138. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  107139. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  107140. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  107141. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  107142. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  107143. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  107144. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  107145. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  107146. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  107147. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  107148. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  107149. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  107150. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  107151. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  107152. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  107153. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  107154. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  107155. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  107156. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  107157. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  107158. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  107159. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  107160. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  107161. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  107162. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  107163. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  107164. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  107165. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  107166. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  107167. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  107168. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  107169. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  107170. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  107171. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  107172. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  107173. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  107174. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  107175. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  107176. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  107177. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  107178. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  107179. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  107180. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  107181. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  107182. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  107183. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  107184. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  107185. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  107186. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  107187. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  107188. };
  107189. static void render_line(int x0,int x1,int y0,int y1,float *d){
  107190. int dy=y1-y0;
  107191. int adx=x1-x0;
  107192. int ady=abs(dy);
  107193. int base=dy/adx;
  107194. int sy=(dy<0?base-1:base+1);
  107195. int x=x0;
  107196. int y=y0;
  107197. int err=0;
  107198. ady-=abs(base*adx);
  107199. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  107200. while(++x<x1){
  107201. err=err+ady;
  107202. if(err>=adx){
  107203. err-=adx;
  107204. y+=sy;
  107205. }else{
  107206. y+=base;
  107207. }
  107208. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  107209. }
  107210. }
  107211. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  107212. int dy=y1-y0;
  107213. int adx=x1-x0;
  107214. int ady=abs(dy);
  107215. int base=dy/adx;
  107216. int sy=(dy<0?base-1:base+1);
  107217. int x=x0;
  107218. int y=y0;
  107219. int err=0;
  107220. ady-=abs(base*adx);
  107221. d[x]=y;
  107222. while(++x<x1){
  107223. err=err+ady;
  107224. if(err>=adx){
  107225. err-=adx;
  107226. y+=sy;
  107227. }else{
  107228. y+=base;
  107229. }
  107230. d[x]=y;
  107231. }
  107232. }
  107233. /* the floor has already been filtered to only include relevant sections */
  107234. static int accumulate_fit(const float *flr,const float *mdct,
  107235. int x0, int x1,lsfit_acc *a,
  107236. int n,vorbis_info_floor1 *info){
  107237. long i;
  107238. 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;
  107239. memset(a,0,sizeof(*a));
  107240. a->x0=x0;
  107241. a->x1=x1;
  107242. if(x1>=n)x1=n-1;
  107243. for(i=x0;i<=x1;i++){
  107244. int quantized=vorbis_dBquant(flr+i);
  107245. if(quantized){
  107246. if(mdct[i]+info->twofitatten>=flr[i]){
  107247. xa += i;
  107248. ya += quantized;
  107249. x2a += i*i;
  107250. y2a += quantized*quantized;
  107251. xya += i*quantized;
  107252. na++;
  107253. }else{
  107254. xb += i;
  107255. yb += quantized;
  107256. x2b += i*i;
  107257. y2b += quantized*quantized;
  107258. xyb += i*quantized;
  107259. nb++;
  107260. }
  107261. }
  107262. }
  107263. xb+=xa;
  107264. yb+=ya;
  107265. x2b+=x2a;
  107266. y2b+=y2a;
  107267. xyb+=xya;
  107268. nb+=na;
  107269. /* weight toward the actually used frequencies if we meet the threshhold */
  107270. {
  107271. int weight=nb*info->twofitweight/(na+1);
  107272. a->xa=xa*weight+xb;
  107273. a->ya=ya*weight+yb;
  107274. a->x2a=x2a*weight+x2b;
  107275. a->y2a=y2a*weight+y2b;
  107276. a->xya=xya*weight+xyb;
  107277. a->an=na*weight+nb;
  107278. }
  107279. return(na);
  107280. }
  107281. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  107282. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  107283. long x0=a[0].x0;
  107284. long x1=a[fits-1].x1;
  107285. for(i=0;i<fits;i++){
  107286. x+=a[i].xa;
  107287. y+=a[i].ya;
  107288. x2+=a[i].x2a;
  107289. y2+=a[i].y2a;
  107290. xy+=a[i].xya;
  107291. an+=a[i].an;
  107292. }
  107293. if(*y0>=0){
  107294. x+= x0;
  107295. y+= *y0;
  107296. x2+= x0 * x0;
  107297. y2+= *y0 * *y0;
  107298. xy+= *y0 * x0;
  107299. an++;
  107300. }
  107301. if(*y1>=0){
  107302. x+= x1;
  107303. y+= *y1;
  107304. x2+= x1 * x1;
  107305. y2+= *y1 * *y1;
  107306. xy+= *y1 * x1;
  107307. an++;
  107308. }
  107309. if(an){
  107310. /* need 64 bit multiplies, which C doesn't give portably as int */
  107311. double fx=x;
  107312. double fy=y;
  107313. double fx2=x2;
  107314. double fxy=xy;
  107315. double denom=1./(an*fx2-fx*fx);
  107316. double a=(fy*fx2-fxy*fx)*denom;
  107317. double b=(an*fxy-fx*fy)*denom;
  107318. *y0=rint(a+b*x0);
  107319. *y1=rint(a+b*x1);
  107320. /* limit to our range! */
  107321. if(*y0>1023)*y0=1023;
  107322. if(*y1>1023)*y1=1023;
  107323. if(*y0<0)*y0=0;
  107324. if(*y1<0)*y1=0;
  107325. }else{
  107326. *y0=0;
  107327. *y1=0;
  107328. }
  107329. }
  107330. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  107331. long y=0;
  107332. int i;
  107333. for(i=0;i<fits && y==0;i++)
  107334. y+=a[i].ya;
  107335. *y0=*y1=y;
  107336. }*/
  107337. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  107338. const float *mdct,
  107339. vorbis_info_floor1 *info){
  107340. int dy=y1-y0;
  107341. int adx=x1-x0;
  107342. int ady=abs(dy);
  107343. int base=dy/adx;
  107344. int sy=(dy<0?base-1:base+1);
  107345. int x=x0;
  107346. int y=y0;
  107347. int err=0;
  107348. int val=vorbis_dBquant(mask+x);
  107349. int mse=0;
  107350. int n=0;
  107351. ady-=abs(base*adx);
  107352. mse=(y-val);
  107353. mse*=mse;
  107354. n++;
  107355. if(mdct[x]+info->twofitatten>=mask[x]){
  107356. if(y+info->maxover<val)return(1);
  107357. if(y-info->maxunder>val)return(1);
  107358. }
  107359. while(++x<x1){
  107360. err=err+ady;
  107361. if(err>=adx){
  107362. err-=adx;
  107363. y+=sy;
  107364. }else{
  107365. y+=base;
  107366. }
  107367. val=vorbis_dBquant(mask+x);
  107368. mse+=((y-val)*(y-val));
  107369. n++;
  107370. if(mdct[x]+info->twofitatten>=mask[x]){
  107371. if(val){
  107372. if(y+info->maxover<val)return(1);
  107373. if(y-info->maxunder>val)return(1);
  107374. }
  107375. }
  107376. }
  107377. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  107378. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  107379. if(mse/n>info->maxerr)return(1);
  107380. return(0);
  107381. }
  107382. static int post_Y(int *A,int *B,int pos){
  107383. if(A[pos]<0)
  107384. return B[pos];
  107385. if(B[pos]<0)
  107386. return A[pos];
  107387. return (A[pos]+B[pos])>>1;
  107388. }
  107389. int *floor1_fit(vorbis_block *vb,void *look_,
  107390. const float *logmdct, /* in */
  107391. const float *logmask){
  107392. long i,j;
  107393. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  107394. vorbis_info_floor1 *info=look->vi;
  107395. long n=look->n;
  107396. long posts=look->posts;
  107397. long nonzero=0;
  107398. lsfit_acc fits[VIF_POSIT+1];
  107399. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  107400. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  107401. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  107402. int hineighbor[VIF_POSIT+2];
  107403. int *output=NULL;
  107404. int memo[VIF_POSIT+2];
  107405. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  107406. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  107407. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  107408. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  107409. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  107410. /* quantize the relevant floor points and collect them into line fit
  107411. structures (one per minimal division) at the same time */
  107412. if(posts==0){
  107413. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  107414. }else{
  107415. for(i=0;i<posts-1;i++)
  107416. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  107417. look->sorted_index[i+1],fits+i,
  107418. n,info);
  107419. }
  107420. if(nonzero){
  107421. /* start by fitting the implicit base case.... */
  107422. int y0=-200;
  107423. int y1=-200;
  107424. fit_line(fits,posts-1,&y0,&y1);
  107425. fit_valueA[0]=y0;
  107426. fit_valueB[0]=y0;
  107427. fit_valueB[1]=y1;
  107428. fit_valueA[1]=y1;
  107429. /* Non degenerate case */
  107430. /* start progressive splitting. This is a greedy, non-optimal
  107431. algorithm, but simple and close enough to the best
  107432. answer. */
  107433. for(i=2;i<posts;i++){
  107434. int sortpos=look->reverse_index[i];
  107435. int ln=loneighbor[sortpos];
  107436. int hn=hineighbor[sortpos];
  107437. /* eliminate repeat searches of a particular range with a memo */
  107438. if(memo[ln]!=hn){
  107439. /* haven't performed this error search yet */
  107440. int lsortpos=look->reverse_index[ln];
  107441. int hsortpos=look->reverse_index[hn];
  107442. memo[ln]=hn;
  107443. {
  107444. /* A note: we want to bound/minimize *local*, not global, error */
  107445. int lx=info->postlist[ln];
  107446. int hx=info->postlist[hn];
  107447. int ly=post_Y(fit_valueA,fit_valueB,ln);
  107448. int hy=post_Y(fit_valueA,fit_valueB,hn);
  107449. if(ly==-1 || hy==-1){
  107450. exit(1);
  107451. }
  107452. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  107453. /* outside error bounds/begin search area. Split it. */
  107454. int ly0=-200;
  107455. int ly1=-200;
  107456. int hy0=-200;
  107457. int hy1=-200;
  107458. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  107459. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  107460. /* store new edge values */
  107461. fit_valueB[ln]=ly0;
  107462. if(ln==0)fit_valueA[ln]=ly0;
  107463. fit_valueA[i]=ly1;
  107464. fit_valueB[i]=hy0;
  107465. fit_valueA[hn]=hy1;
  107466. if(hn==1)fit_valueB[hn]=hy1;
  107467. if(ly1>=0 || hy0>=0){
  107468. /* store new neighbor values */
  107469. for(j=sortpos-1;j>=0;j--)
  107470. if(hineighbor[j]==hn)
  107471. hineighbor[j]=i;
  107472. else
  107473. break;
  107474. for(j=sortpos+1;j<posts;j++)
  107475. if(loneighbor[j]==ln)
  107476. loneighbor[j]=i;
  107477. else
  107478. break;
  107479. }
  107480. }else{
  107481. fit_valueA[i]=-200;
  107482. fit_valueB[i]=-200;
  107483. }
  107484. }
  107485. }
  107486. }
  107487. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  107488. output[0]=post_Y(fit_valueA,fit_valueB,0);
  107489. output[1]=post_Y(fit_valueA,fit_valueB,1);
  107490. /* fill in posts marked as not using a fit; we will zero
  107491. back out to 'unused' when encoding them so long as curve
  107492. interpolation doesn't force them into use */
  107493. for(i=2;i<posts;i++){
  107494. int ln=look->loneighbor[i-2];
  107495. int hn=look->hineighbor[i-2];
  107496. int x0=info->postlist[ln];
  107497. int x1=info->postlist[hn];
  107498. int y0=output[ln];
  107499. int y1=output[hn];
  107500. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  107501. int vx=post_Y(fit_valueA,fit_valueB,i);
  107502. if(vx>=0 && predicted!=vx){
  107503. output[i]=vx;
  107504. }else{
  107505. output[i]= predicted|0x8000;
  107506. }
  107507. }
  107508. }
  107509. return(output);
  107510. }
  107511. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  107512. int *A,int *B,
  107513. int del){
  107514. long i;
  107515. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  107516. long posts=look->posts;
  107517. int *output=NULL;
  107518. if(A && B){
  107519. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  107520. for(i=0;i<posts;i++){
  107521. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  107522. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  107523. }
  107524. }
  107525. return(output);
  107526. }
  107527. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  107528. void*look_,
  107529. int *post,int *ilogmask){
  107530. long i,j;
  107531. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  107532. vorbis_info_floor1 *info=look->vi;
  107533. long posts=look->posts;
  107534. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  107535. int out[VIF_POSIT+2];
  107536. static_codebook **sbooks=ci->book_param;
  107537. codebook *books=ci->fullbooks;
  107538. static long seq=0;
  107539. /* quantize values to multiplier spec */
  107540. if(post){
  107541. for(i=0;i<posts;i++){
  107542. int val=post[i]&0x7fff;
  107543. switch(info->mult){
  107544. case 1: /* 1024 -> 256 */
  107545. val>>=2;
  107546. break;
  107547. case 2: /* 1024 -> 128 */
  107548. val>>=3;
  107549. break;
  107550. case 3: /* 1024 -> 86 */
  107551. val/=12;
  107552. break;
  107553. case 4: /* 1024 -> 64 */
  107554. val>>=4;
  107555. break;
  107556. }
  107557. post[i]=val | (post[i]&0x8000);
  107558. }
  107559. out[0]=post[0];
  107560. out[1]=post[1];
  107561. /* find prediction values for each post and subtract them */
  107562. for(i=2;i<posts;i++){
  107563. int ln=look->loneighbor[i-2];
  107564. int hn=look->hineighbor[i-2];
  107565. int x0=info->postlist[ln];
  107566. int x1=info->postlist[hn];
  107567. int y0=post[ln];
  107568. int y1=post[hn];
  107569. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  107570. if((post[i]&0x8000) || (predicted==post[i])){
  107571. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  107572. in interpolation */
  107573. out[i]=0;
  107574. }else{
  107575. int headroom=(look->quant_q-predicted<predicted?
  107576. look->quant_q-predicted:predicted);
  107577. int val=post[i]-predicted;
  107578. /* at this point the 'deviation' value is in the range +/- max
  107579. range, but the real, unique range can always be mapped to
  107580. only [0-maxrange). So we want to wrap the deviation into
  107581. this limited range, but do it in the way that least screws
  107582. an essentially gaussian probability distribution. */
  107583. if(val<0)
  107584. if(val<-headroom)
  107585. val=headroom-val-1;
  107586. else
  107587. val=-1-(val<<1);
  107588. else
  107589. if(val>=headroom)
  107590. val= val+headroom;
  107591. else
  107592. val<<=1;
  107593. out[i]=val;
  107594. post[ln]&=0x7fff;
  107595. post[hn]&=0x7fff;
  107596. }
  107597. }
  107598. /* we have everything we need. pack it out */
  107599. /* mark nontrivial floor */
  107600. oggpack_write(opb,1,1);
  107601. /* beginning/end post */
  107602. look->frames++;
  107603. look->postbits+=ilog(look->quant_q-1)*2;
  107604. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  107605. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  107606. /* partition by partition */
  107607. for(i=0,j=2;i<info->partitions;i++){
  107608. int classx=info->partitionclass[i];
  107609. int cdim=info->class_dim[classx];
  107610. int csubbits=info->class_subs[classx];
  107611. int csub=1<<csubbits;
  107612. int bookas[8]={0,0,0,0,0,0,0,0};
  107613. int cval=0;
  107614. int cshift=0;
  107615. int k,l;
  107616. /* generate the partition's first stage cascade value */
  107617. if(csubbits){
  107618. int maxval[8];
  107619. for(k=0;k<csub;k++){
  107620. int booknum=info->class_subbook[classx][k];
  107621. if(booknum<0){
  107622. maxval[k]=1;
  107623. }else{
  107624. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  107625. }
  107626. }
  107627. for(k=0;k<cdim;k++){
  107628. for(l=0;l<csub;l++){
  107629. int val=out[j+k];
  107630. if(val<maxval[l]){
  107631. bookas[k]=l;
  107632. break;
  107633. }
  107634. }
  107635. cval|= bookas[k]<<cshift;
  107636. cshift+=csubbits;
  107637. }
  107638. /* write it */
  107639. look->phrasebits+=
  107640. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  107641. #ifdef TRAIN_FLOOR1
  107642. {
  107643. FILE *of;
  107644. char buffer[80];
  107645. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  107646. vb->pcmend/2,posts-2,class);
  107647. of=fopen(buffer,"a");
  107648. fprintf(of,"%d\n",cval);
  107649. fclose(of);
  107650. }
  107651. #endif
  107652. }
  107653. /* write post values */
  107654. for(k=0;k<cdim;k++){
  107655. int book=info->class_subbook[classx][bookas[k]];
  107656. if(book>=0){
  107657. /* hack to allow training with 'bad' books */
  107658. if(out[j+k]<(books+book)->entries)
  107659. look->postbits+=vorbis_book_encode(books+book,
  107660. out[j+k],opb);
  107661. /*else
  107662. fprintf(stderr,"+!");*/
  107663. #ifdef TRAIN_FLOOR1
  107664. {
  107665. FILE *of;
  107666. char buffer[80];
  107667. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  107668. vb->pcmend/2,posts-2,class,bookas[k]);
  107669. of=fopen(buffer,"a");
  107670. fprintf(of,"%d\n",out[j+k]);
  107671. fclose(of);
  107672. }
  107673. #endif
  107674. }
  107675. }
  107676. j+=cdim;
  107677. }
  107678. {
  107679. /* generate quantized floor equivalent to what we'd unpack in decode */
  107680. /* render the lines */
  107681. int hx=0;
  107682. int lx=0;
  107683. int ly=post[0]*info->mult;
  107684. for(j=1;j<look->posts;j++){
  107685. int current=look->forward_index[j];
  107686. int hy=post[current]&0x7fff;
  107687. if(hy==post[current]){
  107688. hy*=info->mult;
  107689. hx=info->postlist[current];
  107690. render_line0(lx,hx,ly,hy,ilogmask);
  107691. lx=hx;
  107692. ly=hy;
  107693. }
  107694. }
  107695. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  107696. seq++;
  107697. return(1);
  107698. }
  107699. }else{
  107700. oggpack_write(opb,0,1);
  107701. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  107702. seq++;
  107703. return(0);
  107704. }
  107705. }
  107706. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  107707. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  107708. vorbis_info_floor1 *info=look->vi;
  107709. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  107710. int i,j,k;
  107711. codebook *books=ci->fullbooks;
  107712. /* unpack wrapped/predicted values from stream */
  107713. if(oggpack_read(&vb->opb,1)==1){
  107714. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  107715. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  107716. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  107717. /* partition by partition */
  107718. for(i=0,j=2;i<info->partitions;i++){
  107719. int classx=info->partitionclass[i];
  107720. int cdim=info->class_dim[classx];
  107721. int csubbits=info->class_subs[classx];
  107722. int csub=1<<csubbits;
  107723. int cval=0;
  107724. /* decode the partition's first stage cascade value */
  107725. if(csubbits){
  107726. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  107727. if(cval==-1)goto eop;
  107728. }
  107729. for(k=0;k<cdim;k++){
  107730. int book=info->class_subbook[classx][cval&(csub-1)];
  107731. cval>>=csubbits;
  107732. if(book>=0){
  107733. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  107734. goto eop;
  107735. }else{
  107736. fit_value[j+k]=0;
  107737. }
  107738. }
  107739. j+=cdim;
  107740. }
  107741. /* unwrap positive values and reconsitute via linear interpolation */
  107742. for(i=2;i<look->posts;i++){
  107743. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  107744. info->postlist[look->hineighbor[i-2]],
  107745. fit_value[look->loneighbor[i-2]],
  107746. fit_value[look->hineighbor[i-2]],
  107747. info->postlist[i]);
  107748. int hiroom=look->quant_q-predicted;
  107749. int loroom=predicted;
  107750. int room=(hiroom<loroom?hiroom:loroom)<<1;
  107751. int val=fit_value[i];
  107752. if(val){
  107753. if(val>=room){
  107754. if(hiroom>loroom){
  107755. val = val-loroom;
  107756. }else{
  107757. val = -1-(val-hiroom);
  107758. }
  107759. }else{
  107760. if(val&1){
  107761. val= -((val+1)>>1);
  107762. }else{
  107763. val>>=1;
  107764. }
  107765. }
  107766. fit_value[i]=val+predicted;
  107767. fit_value[look->loneighbor[i-2]]&=0x7fff;
  107768. fit_value[look->hineighbor[i-2]]&=0x7fff;
  107769. }else{
  107770. fit_value[i]=predicted|0x8000;
  107771. }
  107772. }
  107773. return(fit_value);
  107774. }
  107775. eop:
  107776. return(NULL);
  107777. }
  107778. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  107779. float *out){
  107780. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  107781. vorbis_info_floor1 *info=look->vi;
  107782. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  107783. int n=ci->blocksizes[vb->W]/2;
  107784. int j;
  107785. if(memo){
  107786. /* render the lines */
  107787. int *fit_value=(int *)memo;
  107788. int hx=0;
  107789. int lx=0;
  107790. int ly=fit_value[0]*info->mult;
  107791. for(j=1;j<look->posts;j++){
  107792. int current=look->forward_index[j];
  107793. int hy=fit_value[current]&0x7fff;
  107794. if(hy==fit_value[current]){
  107795. hy*=info->mult;
  107796. hx=info->postlist[current];
  107797. render_line(lx,hx,ly,hy,out);
  107798. lx=hx;
  107799. ly=hy;
  107800. }
  107801. }
  107802. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  107803. return(1);
  107804. }
  107805. memset(out,0,sizeof(*out)*n);
  107806. return(0);
  107807. }
  107808. /* export hooks */
  107809. vorbis_func_floor floor1_exportbundle={
  107810. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  107811. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  107812. };
  107813. #endif
  107814. /********* End of inlined file: floor1.c *********/
  107815. /********* Start of inlined file: info.c *********/
  107816. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107817. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107818. // tasks..
  107819. #ifdef _MSC_VER
  107820. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107821. #endif
  107822. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107823. #if JUCE_USE_OGGVORBIS
  107824. /* general handling of the header and the vorbis_info structure (and
  107825. substructures) */
  107826. #include <stdlib.h>
  107827. #include <string.h>
  107828. #include <ctype.h>
  107829. static void _v_writestring(oggpack_buffer *o,char *s, int bytes){
  107830. while(bytes--){
  107831. oggpack_write(o,*s++,8);
  107832. }
  107833. }
  107834. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  107835. while(bytes--){
  107836. *buf++=oggpack_read(o,8);
  107837. }
  107838. }
  107839. void vorbis_comment_init(vorbis_comment *vc){
  107840. memset(vc,0,sizeof(*vc));
  107841. }
  107842. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  107843. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  107844. (vc->comments+2)*sizeof(*vc->user_comments));
  107845. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  107846. (vc->comments+2)*sizeof(*vc->comment_lengths));
  107847. vc->comment_lengths[vc->comments]=strlen(comment);
  107848. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  107849. strcpy(vc->user_comments[vc->comments], comment);
  107850. vc->comments++;
  107851. vc->user_comments[vc->comments]=NULL;
  107852. }
  107853. void vorbis_comment_add_tag(vorbis_comment *vc, char *tag, char *contents){
  107854. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  107855. strcpy(comment, tag);
  107856. strcat(comment, "=");
  107857. strcat(comment, contents);
  107858. vorbis_comment_add(vc, comment);
  107859. }
  107860. /* This is more or less the same as strncasecmp - but that doesn't exist
  107861. * everywhere, and this is a fairly trivial function, so we include it */
  107862. static int tagcompare(const char *s1, const char *s2, int n){
  107863. int c=0;
  107864. while(c < n){
  107865. if(toupper(s1[c]) != toupper(s2[c]))
  107866. return !0;
  107867. c++;
  107868. }
  107869. return 0;
  107870. }
  107871. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  107872. long i;
  107873. int found = 0;
  107874. int taglen = strlen(tag)+1; /* +1 for the = we append */
  107875. char *fulltag = (char*)alloca(taglen+ 1);
  107876. strcpy(fulltag, tag);
  107877. strcat(fulltag, "=");
  107878. for(i=0;i<vc->comments;i++){
  107879. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  107880. if(count == found)
  107881. /* We return a pointer to the data, not a copy */
  107882. return vc->user_comments[i] + taglen;
  107883. else
  107884. found++;
  107885. }
  107886. }
  107887. return NULL; /* didn't find anything */
  107888. }
  107889. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  107890. int i,count=0;
  107891. int taglen = strlen(tag)+1; /* +1 for the = we append */
  107892. char *fulltag = (char*)alloca(taglen+1);
  107893. strcpy(fulltag,tag);
  107894. strcat(fulltag, "=");
  107895. for(i=0;i<vc->comments;i++){
  107896. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  107897. count++;
  107898. }
  107899. return count;
  107900. }
  107901. void vorbis_comment_clear(vorbis_comment *vc){
  107902. if(vc){
  107903. long i;
  107904. for(i=0;i<vc->comments;i++)
  107905. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  107906. if(vc->user_comments)_ogg_free(vc->user_comments);
  107907. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  107908. if(vc->vendor)_ogg_free(vc->vendor);
  107909. }
  107910. memset(vc,0,sizeof(*vc));
  107911. }
  107912. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  107913. They may be equal, but short will never ge greater than long */
  107914. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  107915. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  107916. return ci ? ci->blocksizes[zo] : -1;
  107917. }
  107918. /* used by synthesis, which has a full, alloced vi */
  107919. void vorbis_info_init(vorbis_info *vi){
  107920. memset(vi,0,sizeof(*vi));
  107921. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  107922. }
  107923. void vorbis_info_clear(vorbis_info *vi){
  107924. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107925. int i;
  107926. if(ci){
  107927. for(i=0;i<ci->modes;i++)
  107928. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  107929. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  107930. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  107931. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  107932. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  107933. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  107934. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  107935. for(i=0;i<ci->books;i++){
  107936. if(ci->book_param[i]){
  107937. /* knows if the book was not alloced */
  107938. vorbis_staticbook_destroy(ci->book_param[i]);
  107939. }
  107940. if(ci->fullbooks)
  107941. vorbis_book_clear(ci->fullbooks+i);
  107942. }
  107943. if(ci->fullbooks)
  107944. _ogg_free(ci->fullbooks);
  107945. for(i=0;i<ci->psys;i++)
  107946. _vi_psy_free(ci->psy_param[i]);
  107947. _ogg_free(ci);
  107948. }
  107949. memset(vi,0,sizeof(*vi));
  107950. }
  107951. /* Header packing/unpacking ********************************************/
  107952. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  107953. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107954. if(!ci)return(OV_EFAULT);
  107955. vi->version=oggpack_read(opb,32);
  107956. if(vi->version!=0)return(OV_EVERSION);
  107957. vi->channels=oggpack_read(opb,8);
  107958. vi->rate=oggpack_read(opb,32);
  107959. vi->bitrate_upper=oggpack_read(opb,32);
  107960. vi->bitrate_nominal=oggpack_read(opb,32);
  107961. vi->bitrate_lower=oggpack_read(opb,32);
  107962. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  107963. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  107964. if(vi->rate<1)goto err_out;
  107965. if(vi->channels<1)goto err_out;
  107966. if(ci->blocksizes[0]<8)goto err_out;
  107967. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  107968. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  107969. return(0);
  107970. err_out:
  107971. vorbis_info_clear(vi);
  107972. return(OV_EBADHEADER);
  107973. }
  107974. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  107975. int i;
  107976. int vendorlen=oggpack_read(opb,32);
  107977. if(vendorlen<0)goto err_out;
  107978. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  107979. _v_readstring(opb,vc->vendor,vendorlen);
  107980. vc->comments=oggpack_read(opb,32);
  107981. if(vc->comments<0)goto err_out;
  107982. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  107983. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  107984. for(i=0;i<vc->comments;i++){
  107985. int len=oggpack_read(opb,32);
  107986. if(len<0)goto err_out;
  107987. vc->comment_lengths[i]=len;
  107988. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  107989. _v_readstring(opb,vc->user_comments[i],len);
  107990. }
  107991. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  107992. return(0);
  107993. err_out:
  107994. vorbis_comment_clear(vc);
  107995. return(OV_EBADHEADER);
  107996. }
  107997. /* all of the real encoding details are here. The modes, books,
  107998. everything */
  107999. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  108000. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108001. int i;
  108002. if(!ci)return(OV_EFAULT);
  108003. /* codebooks */
  108004. ci->books=oggpack_read(opb,8)+1;
  108005. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  108006. for(i=0;i<ci->books;i++){
  108007. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  108008. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  108009. }
  108010. /* time backend settings; hooks are unused */
  108011. {
  108012. int times=oggpack_read(opb,6)+1;
  108013. for(i=0;i<times;i++){
  108014. int test=oggpack_read(opb,16);
  108015. if(test<0 || test>=VI_TIMEB)goto err_out;
  108016. }
  108017. }
  108018. /* floor backend settings */
  108019. ci->floors=oggpack_read(opb,6)+1;
  108020. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  108021. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  108022. for(i=0;i<ci->floors;i++){
  108023. ci->floor_type[i]=oggpack_read(opb,16);
  108024. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  108025. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  108026. if(!ci->floor_param[i])goto err_out;
  108027. }
  108028. /* residue backend settings */
  108029. ci->residues=oggpack_read(opb,6)+1;
  108030. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  108031. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  108032. for(i=0;i<ci->residues;i++){
  108033. ci->residue_type[i]=oggpack_read(opb,16);
  108034. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  108035. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  108036. if(!ci->residue_param[i])goto err_out;
  108037. }
  108038. /* map backend settings */
  108039. ci->maps=oggpack_read(opb,6)+1;
  108040. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  108041. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  108042. for(i=0;i<ci->maps;i++){
  108043. ci->map_type[i]=oggpack_read(opb,16);
  108044. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  108045. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  108046. if(!ci->map_param[i])goto err_out;
  108047. }
  108048. /* mode settings */
  108049. ci->modes=oggpack_read(opb,6)+1;
  108050. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  108051. for(i=0;i<ci->modes;i++){
  108052. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  108053. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  108054. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  108055. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  108056. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  108057. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  108058. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  108059. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  108060. }
  108061. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  108062. return(0);
  108063. err_out:
  108064. vorbis_info_clear(vi);
  108065. return(OV_EBADHEADER);
  108066. }
  108067. /* The Vorbis header is in three packets; the initial small packet in
  108068. the first page that identifies basic parameters, a second packet
  108069. with bitstream comments and a third packet that holds the
  108070. codebook. */
  108071. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  108072. oggpack_buffer opb;
  108073. if(op){
  108074. oggpack_readinit(&opb,op->packet,op->bytes);
  108075. /* Which of the three types of header is this? */
  108076. /* Also verify header-ness, vorbis */
  108077. {
  108078. char buffer[6];
  108079. int packtype=oggpack_read(&opb,8);
  108080. memset(buffer,0,6);
  108081. _v_readstring(&opb,buffer,6);
  108082. if(memcmp(buffer,"vorbis",6)){
  108083. /* not a vorbis header */
  108084. return(OV_ENOTVORBIS);
  108085. }
  108086. switch(packtype){
  108087. case 0x01: /* least significant *bit* is read first */
  108088. if(!op->b_o_s){
  108089. /* Not the initial packet */
  108090. return(OV_EBADHEADER);
  108091. }
  108092. if(vi->rate!=0){
  108093. /* previously initialized info header */
  108094. return(OV_EBADHEADER);
  108095. }
  108096. return(_vorbis_unpack_info(vi,&opb));
  108097. case 0x03: /* least significant *bit* is read first */
  108098. if(vi->rate==0){
  108099. /* um... we didn't get the initial header */
  108100. return(OV_EBADHEADER);
  108101. }
  108102. return(_vorbis_unpack_comment(vc,&opb));
  108103. case 0x05: /* least significant *bit* is read first */
  108104. if(vi->rate==0 || vc->vendor==NULL){
  108105. /* um... we didn;t get the initial header or comments yet */
  108106. return(OV_EBADHEADER);
  108107. }
  108108. return(_vorbis_unpack_books(vi,&opb));
  108109. default:
  108110. /* Not a valid vorbis header type */
  108111. return(OV_EBADHEADER);
  108112. break;
  108113. }
  108114. }
  108115. }
  108116. return(OV_EBADHEADER);
  108117. }
  108118. /* pack side **********************************************************/
  108119. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  108120. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108121. if(!ci)return(OV_EFAULT);
  108122. /* preamble */
  108123. oggpack_write(opb,0x01,8);
  108124. _v_writestring(opb,"vorbis", 6);
  108125. /* basic information about the stream */
  108126. oggpack_write(opb,0x00,32);
  108127. oggpack_write(opb,vi->channels,8);
  108128. oggpack_write(opb,vi->rate,32);
  108129. oggpack_write(opb,vi->bitrate_upper,32);
  108130. oggpack_write(opb,vi->bitrate_nominal,32);
  108131. oggpack_write(opb,vi->bitrate_lower,32);
  108132. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  108133. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  108134. oggpack_write(opb,1,1);
  108135. return(0);
  108136. }
  108137. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  108138. char temp[]="Xiph.Org libVorbis I 20050304";
  108139. int bytes = strlen(temp);
  108140. /* preamble */
  108141. oggpack_write(opb,0x03,8);
  108142. _v_writestring(opb,"vorbis", 6);
  108143. /* vendor */
  108144. oggpack_write(opb,bytes,32);
  108145. _v_writestring(opb,temp, bytes);
  108146. /* comments */
  108147. oggpack_write(opb,vc->comments,32);
  108148. if(vc->comments){
  108149. int i;
  108150. for(i=0;i<vc->comments;i++){
  108151. if(vc->user_comments[i]){
  108152. oggpack_write(opb,vc->comment_lengths[i],32);
  108153. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  108154. }else{
  108155. oggpack_write(opb,0,32);
  108156. }
  108157. }
  108158. }
  108159. oggpack_write(opb,1,1);
  108160. return(0);
  108161. }
  108162. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  108163. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108164. int i;
  108165. if(!ci)return(OV_EFAULT);
  108166. oggpack_write(opb,0x05,8);
  108167. _v_writestring(opb,"vorbis", 6);
  108168. /* books */
  108169. oggpack_write(opb,ci->books-1,8);
  108170. for(i=0;i<ci->books;i++)
  108171. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  108172. /* times; hook placeholders */
  108173. oggpack_write(opb,0,6);
  108174. oggpack_write(opb,0,16);
  108175. /* floors */
  108176. oggpack_write(opb,ci->floors-1,6);
  108177. for(i=0;i<ci->floors;i++){
  108178. oggpack_write(opb,ci->floor_type[i],16);
  108179. if(_floor_P[ci->floor_type[i]]->pack)
  108180. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  108181. else
  108182. goto err_out;
  108183. }
  108184. /* residues */
  108185. oggpack_write(opb,ci->residues-1,6);
  108186. for(i=0;i<ci->residues;i++){
  108187. oggpack_write(opb,ci->residue_type[i],16);
  108188. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  108189. }
  108190. /* maps */
  108191. oggpack_write(opb,ci->maps-1,6);
  108192. for(i=0;i<ci->maps;i++){
  108193. oggpack_write(opb,ci->map_type[i],16);
  108194. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  108195. }
  108196. /* modes */
  108197. oggpack_write(opb,ci->modes-1,6);
  108198. for(i=0;i<ci->modes;i++){
  108199. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  108200. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  108201. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  108202. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  108203. }
  108204. oggpack_write(opb,1,1);
  108205. return(0);
  108206. err_out:
  108207. return(-1);
  108208. }
  108209. int vorbis_commentheader_out(vorbis_comment *vc,
  108210. ogg_packet *op){
  108211. oggpack_buffer opb;
  108212. oggpack_writeinit(&opb);
  108213. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  108214. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  108215. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  108216. op->bytes=oggpack_bytes(&opb);
  108217. op->b_o_s=0;
  108218. op->e_o_s=0;
  108219. op->granulepos=0;
  108220. op->packetno=1;
  108221. return 0;
  108222. }
  108223. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  108224. vorbis_comment *vc,
  108225. ogg_packet *op,
  108226. ogg_packet *op_comm,
  108227. ogg_packet *op_code){
  108228. int ret=OV_EIMPL;
  108229. vorbis_info *vi=v->vi;
  108230. oggpack_buffer opb;
  108231. private_state *b=(private_state*)v->backend_state;
  108232. if(!b){
  108233. ret=OV_EFAULT;
  108234. goto err_out;
  108235. }
  108236. /* first header packet **********************************************/
  108237. oggpack_writeinit(&opb);
  108238. if(_vorbis_pack_info(&opb,vi))goto err_out;
  108239. /* build the packet */
  108240. if(b->header)_ogg_free(b->header);
  108241. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  108242. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  108243. op->packet=b->header;
  108244. op->bytes=oggpack_bytes(&opb);
  108245. op->b_o_s=1;
  108246. op->e_o_s=0;
  108247. op->granulepos=0;
  108248. op->packetno=0;
  108249. /* second header packet (comments) **********************************/
  108250. oggpack_reset(&opb);
  108251. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  108252. if(b->header1)_ogg_free(b->header1);
  108253. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  108254. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  108255. op_comm->packet=b->header1;
  108256. op_comm->bytes=oggpack_bytes(&opb);
  108257. op_comm->b_o_s=0;
  108258. op_comm->e_o_s=0;
  108259. op_comm->granulepos=0;
  108260. op_comm->packetno=1;
  108261. /* third header packet (modes/codebooks) ****************************/
  108262. oggpack_reset(&opb);
  108263. if(_vorbis_pack_books(&opb,vi))goto err_out;
  108264. if(b->header2)_ogg_free(b->header2);
  108265. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  108266. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  108267. op_code->packet=b->header2;
  108268. op_code->bytes=oggpack_bytes(&opb);
  108269. op_code->b_o_s=0;
  108270. op_code->e_o_s=0;
  108271. op_code->granulepos=0;
  108272. op_code->packetno=2;
  108273. oggpack_writeclear(&opb);
  108274. return(0);
  108275. err_out:
  108276. oggpack_writeclear(&opb);
  108277. memset(op,0,sizeof(*op));
  108278. memset(op_comm,0,sizeof(*op_comm));
  108279. memset(op_code,0,sizeof(*op_code));
  108280. if(b->header)_ogg_free(b->header);
  108281. if(b->header1)_ogg_free(b->header1);
  108282. if(b->header2)_ogg_free(b->header2);
  108283. b->header=NULL;
  108284. b->header1=NULL;
  108285. b->header2=NULL;
  108286. return(ret);
  108287. }
  108288. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  108289. if(granulepos>=0)
  108290. return((double)granulepos/v->vi->rate);
  108291. return(-1);
  108292. }
  108293. #endif
  108294. /********* End of inlined file: info.c *********/
  108295. /********* Start of inlined file: lpc.c *********/
  108296. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  108297. are derived from code written by Jutta Degener and Carsten Bormann;
  108298. thus we include their copyright below. The entirety of this file
  108299. is freely redistributable on the condition that both of these
  108300. copyright notices are preserved without modification. */
  108301. /* Preserved Copyright: *********************************************/
  108302. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  108303. Technische Universita"t Berlin
  108304. Any use of this software is permitted provided that this notice is not
  108305. removed and that neither the authors nor the Technische Universita"t
  108306. Berlin are deemed to have made any representations as to the
  108307. suitability of this software for any purpose nor are held responsible
  108308. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  108309. THIS SOFTWARE.
  108310. As a matter of courtesy, the authors request to be informed about uses
  108311. this software has found, about bugs in this software, and about any
  108312. improvements that may be of general interest.
  108313. Berlin, 28.11.1994
  108314. Jutta Degener
  108315. Carsten Bormann
  108316. *********************************************************************/
  108317. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108318. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108319. // tasks..
  108320. #ifdef _MSC_VER
  108321. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108322. #endif
  108323. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108324. #if JUCE_USE_OGGVORBIS
  108325. #include <stdlib.h>
  108326. #include <string.h>
  108327. #include <math.h>
  108328. /* Autocorrelation LPC coeff generation algorithm invented by
  108329. N. Levinson in 1947, modified by J. Durbin in 1959. */
  108330. /* Input : n elements of time doamin data
  108331. Output: m lpc coefficients, excitation energy */
  108332. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  108333. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  108334. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  108335. double error;
  108336. int i,j;
  108337. /* autocorrelation, p+1 lag coefficients */
  108338. j=m+1;
  108339. while(j--){
  108340. double d=0; /* double needed for accumulator depth */
  108341. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  108342. aut[j]=d;
  108343. }
  108344. /* Generate lpc coefficients from autocorr values */
  108345. error=aut[0];
  108346. for(i=0;i<m;i++){
  108347. double r= -aut[i+1];
  108348. if(error==0){
  108349. memset(lpci,0,m*sizeof(*lpci));
  108350. return 0;
  108351. }
  108352. /* Sum up this iteration's reflection coefficient; note that in
  108353. Vorbis we don't save it. If anyone wants to recycle this code
  108354. and needs reflection coefficients, save the results of 'r' from
  108355. each iteration. */
  108356. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  108357. r/=error;
  108358. /* Update LPC coefficients and total error */
  108359. lpc[i]=r;
  108360. for(j=0;j<i/2;j++){
  108361. double tmp=lpc[j];
  108362. lpc[j]+=r*lpc[i-1-j];
  108363. lpc[i-1-j]+=r*tmp;
  108364. }
  108365. if(i%2)lpc[j]+=lpc[j]*r;
  108366. error*=1.f-r*r;
  108367. }
  108368. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  108369. /* we need the error value to know how big an impulse to hit the
  108370. filter with later */
  108371. return error;
  108372. }
  108373. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  108374. float *data,long n){
  108375. /* in: coeff[0...m-1] LPC coefficients
  108376. prime[0...m-1] initial values (allocated size of n+m-1)
  108377. out: data[0...n-1] data samples */
  108378. long i,j,o,p;
  108379. float y;
  108380. float *work=(float*)alloca(sizeof(*work)*(m+n));
  108381. if(!prime)
  108382. for(i=0;i<m;i++)
  108383. work[i]=0.f;
  108384. else
  108385. for(i=0;i<m;i++)
  108386. work[i]=prime[i];
  108387. for(i=0;i<n;i++){
  108388. y=0;
  108389. o=i;
  108390. p=m;
  108391. for(j=0;j<m;j++)
  108392. y-=work[o++]*coeff[--p];
  108393. data[i]=work[o]=y;
  108394. }
  108395. }
  108396. #endif
  108397. /********* End of inlined file: lpc.c *********/
  108398. /********* Start of inlined file: lsp.c *********/
  108399. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  108400. an iterative root polisher (CACM algorithm 283). It *is* possible
  108401. to confuse this algorithm into not converging; that should only
  108402. happen with absurdly closely spaced roots (very sharp peaks in the
  108403. LPC f response) which in turn should be impossible in our use of
  108404. the code. If this *does* happen anyway, it's a bug in the floor
  108405. finder; find the cause of the confusion (probably a single bin
  108406. spike or accidental near-float-limit resolution problems) and
  108407. correct it. */
  108408. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108409. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108410. // tasks..
  108411. #ifdef _MSC_VER
  108412. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108413. #endif
  108414. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108415. #if JUCE_USE_OGGVORBIS
  108416. #include <math.h>
  108417. #include <string.h>
  108418. #include <stdlib.h>
  108419. /********* Start of inlined file: lookup.h *********/
  108420. #ifndef _V_LOOKUP_H_
  108421. #ifdef FLOAT_LOOKUP
  108422. extern float vorbis_coslook(float a);
  108423. extern float vorbis_invsqlook(float a);
  108424. extern float vorbis_invsq2explook(int a);
  108425. extern float vorbis_fromdBlook(float a);
  108426. #endif
  108427. #ifdef INT_LOOKUP
  108428. extern long vorbis_invsqlook_i(long a,long e);
  108429. extern long vorbis_coslook_i(long a);
  108430. extern float vorbis_fromdBlook_i(long a);
  108431. #endif
  108432. #endif
  108433. /********* End of inlined file: lookup.h *********/
  108434. /* three possible LSP to f curve functions; the exact computation
  108435. (float), a lookup based float implementation, and an integer
  108436. implementation. The float lookup is likely the optimal choice on
  108437. any machine with an FPU. The integer implementation is *not* fixed
  108438. point (due to the need for a large dynamic range and thus a
  108439. seperately tracked exponent) and thus much more complex than the
  108440. relatively simple float implementations. It's mostly for future
  108441. work on a fully fixed point implementation for processors like the
  108442. ARM family. */
  108443. /* undefine both for the 'old' but more precise implementation */
  108444. #define FLOAT_LOOKUP
  108445. #undef INT_LOOKUP
  108446. #ifdef FLOAT_LOOKUP
  108447. /********* Start of inlined file: lookup.c *********/
  108448. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108449. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108450. // tasks..
  108451. #ifdef _MSC_VER
  108452. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108453. #endif
  108454. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108455. #if JUCE_USE_OGGVORBIS
  108456. #include <math.h>
  108457. /********* Start of inlined file: lookup.h *********/
  108458. #ifndef _V_LOOKUP_H_
  108459. #ifdef FLOAT_LOOKUP
  108460. extern float vorbis_coslook(float a);
  108461. extern float vorbis_invsqlook(float a);
  108462. extern float vorbis_invsq2explook(int a);
  108463. extern float vorbis_fromdBlook(float a);
  108464. #endif
  108465. #ifdef INT_LOOKUP
  108466. extern long vorbis_invsqlook_i(long a,long e);
  108467. extern long vorbis_coslook_i(long a);
  108468. extern float vorbis_fromdBlook_i(long a);
  108469. #endif
  108470. #endif
  108471. /********* End of inlined file: lookup.h *********/
  108472. /********* Start of inlined file: lookup_data.h *********/
  108473. #ifndef _V_LOOKUP_DATA_H_
  108474. #ifdef FLOAT_LOOKUP
  108475. #define COS_LOOKUP_SZ 128
  108476. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  108477. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  108478. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  108479. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  108480. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  108481. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  108482. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  108483. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  108484. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  108485. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  108486. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  108487. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  108488. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  108489. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  108490. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  108491. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  108492. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  108493. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  108494. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  108495. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  108496. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  108497. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  108498. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  108499. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  108500. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  108501. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  108502. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  108503. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  108504. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  108505. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  108506. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  108507. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  108508. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  108509. -1.0000000000000f,
  108510. };
  108511. #define INVSQ_LOOKUP_SZ 32
  108512. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  108513. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  108514. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  108515. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  108516. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  108517. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  108518. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  108519. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  108520. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  108521. 1.000000000000f,
  108522. };
  108523. #define INVSQ2EXP_LOOKUP_MIN (-32)
  108524. #define INVSQ2EXP_LOOKUP_MAX 32
  108525. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  108526. INVSQ2EXP_LOOKUP_MIN+1]={
  108527. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  108528. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  108529. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  108530. 1024.f, 724.0773439f, 512.f, 362.038672f,
  108531. 256.f, 181.019336f, 128.f, 90.50966799f,
  108532. 64.f, 45.254834f, 32.f, 22.627417f,
  108533. 16.f, 11.3137085f, 8.f, 5.656854249f,
  108534. 4.f, 2.828427125f, 2.f, 1.414213562f,
  108535. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  108536. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  108537. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  108538. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  108539. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  108540. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  108541. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  108542. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  108543. 1.525878906e-05f,
  108544. };
  108545. #endif
  108546. #define FROMdB_LOOKUP_SZ 35
  108547. #define FROMdB2_LOOKUP_SZ 32
  108548. #define FROMdB_SHIFT 5
  108549. #define FROMdB2_SHIFT 3
  108550. #define FROMdB2_MASK 31
  108551. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  108552. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  108553. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  108554. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  108555. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  108556. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  108557. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  108558. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  108559. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  108560. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  108561. };
  108562. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  108563. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  108564. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  108565. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  108566. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  108567. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  108568. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  108569. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  108570. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  108571. };
  108572. #ifdef INT_LOOKUP
  108573. #define INVSQ_LOOKUP_I_SHIFT 10
  108574. #define INVSQ_LOOKUP_I_MASK 1023
  108575. static long INVSQ_LOOKUP_I[64+1]={
  108576. 92682l, 91966l, 91267l, 90583l,
  108577. 89915l, 89261l, 88621l, 87995l,
  108578. 87381l, 86781l, 86192l, 85616l,
  108579. 85051l, 84497l, 83953l, 83420l,
  108580. 82897l, 82384l, 81880l, 81385l,
  108581. 80899l, 80422l, 79953l, 79492l,
  108582. 79039l, 78594l, 78156l, 77726l,
  108583. 77302l, 76885l, 76475l, 76072l,
  108584. 75674l, 75283l, 74898l, 74519l,
  108585. 74146l, 73778l, 73415l, 73058l,
  108586. 72706l, 72359l, 72016l, 71679l,
  108587. 71347l, 71019l, 70695l, 70376l,
  108588. 70061l, 69750l, 69444l, 69141l,
  108589. 68842l, 68548l, 68256l, 67969l,
  108590. 67685l, 67405l, 67128l, 66855l,
  108591. 66585l, 66318l, 66054l, 65794l,
  108592. 65536l,
  108593. };
  108594. #define COS_LOOKUP_I_SHIFT 9
  108595. #define COS_LOOKUP_I_MASK 511
  108596. #define COS_LOOKUP_I_SZ 128
  108597. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  108598. 16384l, 16379l, 16364l, 16340l,
  108599. 16305l, 16261l, 16207l, 16143l,
  108600. 16069l, 15986l, 15893l, 15791l,
  108601. 15679l, 15557l, 15426l, 15286l,
  108602. 15137l, 14978l, 14811l, 14635l,
  108603. 14449l, 14256l, 14053l, 13842l,
  108604. 13623l, 13395l, 13160l, 12916l,
  108605. 12665l, 12406l, 12140l, 11866l,
  108606. 11585l, 11297l, 11003l, 10702l,
  108607. 10394l, 10080l, 9760l, 9434l,
  108608. 9102l, 8765l, 8423l, 8076l,
  108609. 7723l, 7366l, 7005l, 6639l,
  108610. 6270l, 5897l, 5520l, 5139l,
  108611. 4756l, 4370l, 3981l, 3590l,
  108612. 3196l, 2801l, 2404l, 2006l,
  108613. 1606l, 1205l, 804l, 402l,
  108614. 0l, -401l, -803l, -1204l,
  108615. -1605l, -2005l, -2403l, -2800l,
  108616. -3195l, -3589l, -3980l, -4369l,
  108617. -4755l, -5138l, -5519l, -5896l,
  108618. -6269l, -6638l, -7004l, -7365l,
  108619. -7722l, -8075l, -8422l, -8764l,
  108620. -9101l, -9433l, -9759l, -10079l,
  108621. -10393l, -10701l, -11002l, -11296l,
  108622. -11584l, -11865l, -12139l, -12405l,
  108623. -12664l, -12915l, -13159l, -13394l,
  108624. -13622l, -13841l, -14052l, -14255l,
  108625. -14448l, -14634l, -14810l, -14977l,
  108626. -15136l, -15285l, -15425l, -15556l,
  108627. -15678l, -15790l, -15892l, -15985l,
  108628. -16068l, -16142l, -16206l, -16260l,
  108629. -16304l, -16339l, -16363l, -16378l,
  108630. -16383l,
  108631. };
  108632. #endif
  108633. #endif
  108634. /********* End of inlined file: lookup_data.h *********/
  108635. #ifdef FLOAT_LOOKUP
  108636. /* interpolated lookup based cos function, domain 0 to PI only */
  108637. float vorbis_coslook(float a){
  108638. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  108639. int i=vorbis_ftoi(d-.5);
  108640. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  108641. }
  108642. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  108643. float vorbis_invsqlook(float a){
  108644. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  108645. int i=vorbis_ftoi(d-.5f);
  108646. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  108647. }
  108648. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  108649. float vorbis_invsq2explook(int a){
  108650. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  108651. }
  108652. #include <stdio.h>
  108653. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  108654. float vorbis_fromdBlook(float a){
  108655. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  108656. return (i<0)?1.f:
  108657. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  108658. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  108659. }
  108660. #endif
  108661. #ifdef INT_LOOKUP
  108662. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  108663. 16.16 format
  108664. returns in m.8 format */
  108665. long vorbis_invsqlook_i(long a,long e){
  108666. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  108667. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  108668. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  108669. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  108670. d)>>16); /* result 1.16 */
  108671. e+=32;
  108672. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  108673. e=(e>>1)-8;
  108674. return(val>>e);
  108675. }
  108676. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  108677. /* a is in n.12 format */
  108678. float vorbis_fromdBlook_i(long a){
  108679. int i=(-a)>>(12-FROMdB2_SHIFT);
  108680. return (i<0)?1.f:
  108681. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  108682. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  108683. }
  108684. /* interpolated lookup based cos function, domain 0 to PI only */
  108685. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  108686. long vorbis_coslook_i(long a){
  108687. int i=a>>COS_LOOKUP_I_SHIFT;
  108688. int d=a&COS_LOOKUP_I_MASK;
  108689. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  108690. COS_LOOKUP_I_SHIFT);
  108691. }
  108692. #endif
  108693. #endif
  108694. /********* End of inlined file: lookup.c *********/
  108695. /* catch this in the build system; we #include for
  108696. compilers (like gcc) that can't inline across
  108697. modules */
  108698. /* side effect: changes *lsp to cosines of lsp */
  108699. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  108700. float amp,float ampoffset){
  108701. int i;
  108702. float wdel=M_PI/ln;
  108703. vorbis_fpu_control fpu;
  108704. (void) fpu; // to avoid an unused variable warning
  108705. vorbis_fpu_setround(&fpu);
  108706. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  108707. i=0;
  108708. while(i<n){
  108709. int k=map[i];
  108710. int qexp;
  108711. float p=.7071067812f;
  108712. float q=.7071067812f;
  108713. float w=vorbis_coslook(wdel*k);
  108714. float *ftmp=lsp;
  108715. int c=m>>1;
  108716. do{
  108717. q*=ftmp[0]-w;
  108718. p*=ftmp[1]-w;
  108719. ftmp+=2;
  108720. }while(--c);
  108721. if(m&1){
  108722. /* odd order filter; slightly assymetric */
  108723. /* the last coefficient */
  108724. q*=ftmp[0]-w;
  108725. q*=q;
  108726. p*=p*(1.f-w*w);
  108727. }else{
  108728. /* even order filter; still symmetric */
  108729. q*=q*(1.f+w);
  108730. p*=p*(1.f-w);
  108731. }
  108732. q=frexp(p+q,&qexp);
  108733. q=vorbis_fromdBlook(amp*
  108734. vorbis_invsqlook(q)*
  108735. vorbis_invsq2explook(qexp+m)-
  108736. ampoffset);
  108737. do{
  108738. curve[i++]*=q;
  108739. }while(map[i]==k);
  108740. }
  108741. vorbis_fpu_restore(fpu);
  108742. }
  108743. #else
  108744. #ifdef INT_LOOKUP
  108745. /********* Start of inlined file: lookup.c *********/
  108746. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108747. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108748. // tasks..
  108749. #ifdef _MSC_VER
  108750. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108751. #endif
  108752. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108753. #if JUCE_USE_OGGVORBIS
  108754. #include <math.h>
  108755. /********* Start of inlined file: lookup.h *********/
  108756. #ifndef _V_LOOKUP_H_
  108757. #ifdef FLOAT_LOOKUP
  108758. extern float vorbis_coslook(float a);
  108759. extern float vorbis_invsqlook(float a);
  108760. extern float vorbis_invsq2explook(int a);
  108761. extern float vorbis_fromdBlook(float a);
  108762. #endif
  108763. #ifdef INT_LOOKUP
  108764. extern long vorbis_invsqlook_i(long a,long e);
  108765. extern long vorbis_coslook_i(long a);
  108766. extern float vorbis_fromdBlook_i(long a);
  108767. #endif
  108768. #endif
  108769. /********* End of inlined file: lookup.h *********/
  108770. /********* Start of inlined file: lookup_data.h *********/
  108771. #ifndef _V_LOOKUP_DATA_H_
  108772. #ifdef FLOAT_LOOKUP
  108773. #define COS_LOOKUP_SZ 128
  108774. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  108775. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  108776. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  108777. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  108778. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  108779. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  108780. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  108781. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  108782. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  108783. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  108784. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  108785. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  108786. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  108787. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  108788. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  108789. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  108790. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  108791. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  108792. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  108793. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  108794. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  108795. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  108796. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  108797. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  108798. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  108799. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  108800. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  108801. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  108802. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  108803. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  108804. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  108805. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  108806. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  108807. -1.0000000000000f,
  108808. };
  108809. #define INVSQ_LOOKUP_SZ 32
  108810. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  108811. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  108812. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  108813. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  108814. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  108815. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  108816. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  108817. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  108818. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  108819. 1.000000000000f,
  108820. };
  108821. #define INVSQ2EXP_LOOKUP_MIN (-32)
  108822. #define INVSQ2EXP_LOOKUP_MAX 32
  108823. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  108824. INVSQ2EXP_LOOKUP_MIN+1]={
  108825. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  108826. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  108827. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  108828. 1024.f, 724.0773439f, 512.f, 362.038672f,
  108829. 256.f, 181.019336f, 128.f, 90.50966799f,
  108830. 64.f, 45.254834f, 32.f, 22.627417f,
  108831. 16.f, 11.3137085f, 8.f, 5.656854249f,
  108832. 4.f, 2.828427125f, 2.f, 1.414213562f,
  108833. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  108834. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  108835. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  108836. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  108837. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  108838. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  108839. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  108840. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  108841. 1.525878906e-05f,
  108842. };
  108843. #endif
  108844. #define FROMdB_LOOKUP_SZ 35
  108845. #define FROMdB2_LOOKUP_SZ 32
  108846. #define FROMdB_SHIFT 5
  108847. #define FROMdB2_SHIFT 3
  108848. #define FROMdB2_MASK 31
  108849. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  108850. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  108851. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  108852. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  108853. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  108854. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  108855. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  108856. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  108857. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  108858. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  108859. };
  108860. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  108861. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  108862. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  108863. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  108864. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  108865. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  108866. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  108867. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  108868. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  108869. };
  108870. #ifdef INT_LOOKUP
  108871. #define INVSQ_LOOKUP_I_SHIFT 10
  108872. #define INVSQ_LOOKUP_I_MASK 1023
  108873. static long INVSQ_LOOKUP_I[64+1]={
  108874. 92682l, 91966l, 91267l, 90583l,
  108875. 89915l, 89261l, 88621l, 87995l,
  108876. 87381l, 86781l, 86192l, 85616l,
  108877. 85051l, 84497l, 83953l, 83420l,
  108878. 82897l, 82384l, 81880l, 81385l,
  108879. 80899l, 80422l, 79953l, 79492l,
  108880. 79039l, 78594l, 78156l, 77726l,
  108881. 77302l, 76885l, 76475l, 76072l,
  108882. 75674l, 75283l, 74898l, 74519l,
  108883. 74146l, 73778l, 73415l, 73058l,
  108884. 72706l, 72359l, 72016l, 71679l,
  108885. 71347l, 71019l, 70695l, 70376l,
  108886. 70061l, 69750l, 69444l, 69141l,
  108887. 68842l, 68548l, 68256l, 67969l,
  108888. 67685l, 67405l, 67128l, 66855l,
  108889. 66585l, 66318l, 66054l, 65794l,
  108890. 65536l,
  108891. };
  108892. #define COS_LOOKUP_I_SHIFT 9
  108893. #define COS_LOOKUP_I_MASK 511
  108894. #define COS_LOOKUP_I_SZ 128
  108895. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  108896. 16384l, 16379l, 16364l, 16340l,
  108897. 16305l, 16261l, 16207l, 16143l,
  108898. 16069l, 15986l, 15893l, 15791l,
  108899. 15679l, 15557l, 15426l, 15286l,
  108900. 15137l, 14978l, 14811l, 14635l,
  108901. 14449l, 14256l, 14053l, 13842l,
  108902. 13623l, 13395l, 13160l, 12916l,
  108903. 12665l, 12406l, 12140l, 11866l,
  108904. 11585l, 11297l, 11003l, 10702l,
  108905. 10394l, 10080l, 9760l, 9434l,
  108906. 9102l, 8765l, 8423l, 8076l,
  108907. 7723l, 7366l, 7005l, 6639l,
  108908. 6270l, 5897l, 5520l, 5139l,
  108909. 4756l, 4370l, 3981l, 3590l,
  108910. 3196l, 2801l, 2404l, 2006l,
  108911. 1606l, 1205l, 804l, 402l,
  108912. 0l, -401l, -803l, -1204l,
  108913. -1605l, -2005l, -2403l, -2800l,
  108914. -3195l, -3589l, -3980l, -4369l,
  108915. -4755l, -5138l, -5519l, -5896l,
  108916. -6269l, -6638l, -7004l, -7365l,
  108917. -7722l, -8075l, -8422l, -8764l,
  108918. -9101l, -9433l, -9759l, -10079l,
  108919. -10393l, -10701l, -11002l, -11296l,
  108920. -11584l, -11865l, -12139l, -12405l,
  108921. -12664l, -12915l, -13159l, -13394l,
  108922. -13622l, -13841l, -14052l, -14255l,
  108923. -14448l, -14634l, -14810l, -14977l,
  108924. -15136l, -15285l, -15425l, -15556l,
  108925. -15678l, -15790l, -15892l, -15985l,
  108926. -16068l, -16142l, -16206l, -16260l,
  108927. -16304l, -16339l, -16363l, -16378l,
  108928. -16383l,
  108929. };
  108930. #endif
  108931. #endif
  108932. /********* End of inlined file: lookup_data.h *********/
  108933. #ifdef FLOAT_LOOKUP
  108934. /* interpolated lookup based cos function, domain 0 to PI only */
  108935. float vorbis_coslook(float a){
  108936. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  108937. int i=vorbis_ftoi(d-.5);
  108938. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  108939. }
  108940. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  108941. float vorbis_invsqlook(float a){
  108942. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  108943. int i=vorbis_ftoi(d-.5f);
  108944. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  108945. }
  108946. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  108947. float vorbis_invsq2explook(int a){
  108948. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  108949. }
  108950. #include <stdio.h>
  108951. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  108952. float vorbis_fromdBlook(float a){
  108953. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  108954. return (i<0)?1.f:
  108955. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  108956. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  108957. }
  108958. #endif
  108959. #ifdef INT_LOOKUP
  108960. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  108961. 16.16 format
  108962. returns in m.8 format */
  108963. long vorbis_invsqlook_i(long a,long e){
  108964. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  108965. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  108966. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  108967. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  108968. d)>>16); /* result 1.16 */
  108969. e+=32;
  108970. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  108971. e=(e>>1)-8;
  108972. return(val>>e);
  108973. }
  108974. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  108975. /* a is in n.12 format */
  108976. float vorbis_fromdBlook_i(long a){
  108977. int i=(-a)>>(12-FROMdB2_SHIFT);
  108978. return (i<0)?1.f:
  108979. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  108980. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  108981. }
  108982. /* interpolated lookup based cos function, domain 0 to PI only */
  108983. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  108984. long vorbis_coslook_i(long a){
  108985. int i=a>>COS_LOOKUP_I_SHIFT;
  108986. int d=a&COS_LOOKUP_I_MASK;
  108987. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  108988. COS_LOOKUP_I_SHIFT);
  108989. }
  108990. #endif
  108991. #endif
  108992. /********* End of inlined file: lookup.c *********/
  108993. /* catch this in the build system; we #include for
  108994. compilers (like gcc) that can't inline across
  108995. modules */
  108996. static int MLOOP_1[64]={
  108997. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  108998. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  108999. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  109000. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  109001. };
  109002. static int MLOOP_2[64]={
  109003. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  109004. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  109005. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  109006. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  109007. };
  109008. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  109009. /* side effect: changes *lsp to cosines of lsp */
  109010. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  109011. float amp,float ampoffset){
  109012. /* 0 <= m < 256 */
  109013. /* set up for using all int later */
  109014. int i;
  109015. int ampoffseti=rint(ampoffset*4096.f);
  109016. int ampi=rint(amp*16.f);
  109017. long *ilsp=alloca(m*sizeof(*ilsp));
  109018. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  109019. i=0;
  109020. while(i<n){
  109021. int j,k=map[i];
  109022. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  109023. unsigned long qi=46341;
  109024. int qexp=0,shift;
  109025. long wi=vorbis_coslook_i(k*65536/ln);
  109026. qi*=labs(ilsp[0]-wi);
  109027. pi*=labs(ilsp[1]-wi);
  109028. for(j=3;j<m;j+=2){
  109029. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  109030. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  109031. shift=MLOOP_3[(pi|qi)>>16];
  109032. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  109033. pi=(pi>>shift)*labs(ilsp[j]-wi);
  109034. qexp+=shift;
  109035. }
  109036. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  109037. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  109038. shift=MLOOP_3[(pi|qi)>>16];
  109039. /* pi,qi normalized collectively, both tracked using qexp */
  109040. if(m&1){
  109041. /* odd order filter; slightly assymetric */
  109042. /* the last coefficient */
  109043. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  109044. pi=(pi>>shift)<<14;
  109045. qexp+=shift;
  109046. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  109047. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  109048. shift=MLOOP_3[(pi|qi)>>16];
  109049. pi>>=shift;
  109050. qi>>=shift;
  109051. qexp+=shift-14*((m+1)>>1);
  109052. pi=((pi*pi)>>16);
  109053. qi=((qi*qi)>>16);
  109054. qexp=qexp*2+m;
  109055. pi*=(1<<14)-((wi*wi)>>14);
  109056. qi+=pi>>14;
  109057. }else{
  109058. /* even order filter; still symmetric */
  109059. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  109060. worth tracking step by step */
  109061. pi>>=shift;
  109062. qi>>=shift;
  109063. qexp+=shift-7*m;
  109064. pi=((pi*pi)>>16);
  109065. qi=((qi*qi)>>16);
  109066. qexp=qexp*2+m;
  109067. pi*=(1<<14)-wi;
  109068. qi*=(1<<14)+wi;
  109069. qi=(qi+pi)>>14;
  109070. }
  109071. /* we've let the normalization drift because it wasn't important;
  109072. however, for the lookup, things must be normalized again. We
  109073. need at most one right shift or a number of left shifts */
  109074. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  109075. qi>>=1; qexp++;
  109076. }else
  109077. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  109078. qi<<=1; qexp--;
  109079. }
  109080. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  109081. vorbis_invsqlook_i(qi,qexp)-
  109082. /* m.8, m+n<=8 */
  109083. ampoffseti); /* 8.12[0] */
  109084. curve[i]*=amp;
  109085. while(map[++i]==k)curve[i]*=amp;
  109086. }
  109087. }
  109088. #else
  109089. /* old, nonoptimized but simple version for any poor sap who needs to
  109090. figure out what the hell this code does, or wants the other
  109091. fraction of a dB precision */
  109092. /* side effect: changes *lsp to cosines of lsp */
  109093. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  109094. float amp,float ampoffset){
  109095. int i;
  109096. float wdel=M_PI/ln;
  109097. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  109098. i=0;
  109099. while(i<n){
  109100. int j,k=map[i];
  109101. float p=.5f;
  109102. float q=.5f;
  109103. float w=2.f*cos(wdel*k);
  109104. for(j=1;j<m;j+=2){
  109105. q *= w-lsp[j-1];
  109106. p *= w-lsp[j];
  109107. }
  109108. if(j==m){
  109109. /* odd order filter; slightly assymetric */
  109110. /* the last coefficient */
  109111. q*=w-lsp[j-1];
  109112. p*=p*(4.f-w*w);
  109113. q*=q;
  109114. }else{
  109115. /* even order filter; still symmetric */
  109116. p*=p*(2.f-w);
  109117. q*=q*(2.f+w);
  109118. }
  109119. q=fromdB(amp/sqrt(p+q)-ampoffset);
  109120. curve[i]*=q;
  109121. while(map[++i]==k)curve[i]*=q;
  109122. }
  109123. }
  109124. #endif
  109125. #endif
  109126. static void cheby(float *g, int ord) {
  109127. int i, j;
  109128. g[0] *= .5f;
  109129. for(i=2; i<= ord; i++) {
  109130. for(j=ord; j >= i; j--) {
  109131. g[j-2] -= g[j];
  109132. g[j] += g[j];
  109133. }
  109134. }
  109135. }
  109136. static int comp(const void *a,const void *b){
  109137. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  109138. }
  109139. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  109140. but there are root sets for which it gets into limit cycles
  109141. (exacerbated by zero suppression) and fails. We can't afford to
  109142. fail, even if the failure is 1 in 100,000,000, so we now use
  109143. Laguerre and later polish with Newton-Raphson (which can then
  109144. afford to fail) */
  109145. #define EPSILON 10e-7
  109146. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  109147. int i,m;
  109148. double lastdelta=0.f;
  109149. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  109150. for(i=0;i<=ord;i++)defl[i]=a[i];
  109151. for(m=ord;m>0;m--){
  109152. double newx=0.f,delta;
  109153. /* iterate a root */
  109154. while(1){
  109155. double p=defl[m],pp=0.f,ppp=0.f,denom;
  109156. /* eval the polynomial and its first two derivatives */
  109157. for(i=m;i>0;i--){
  109158. ppp = newx*ppp + pp;
  109159. pp = newx*pp + p;
  109160. p = newx*p + defl[i-1];
  109161. }
  109162. /* Laguerre's method */
  109163. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  109164. if(denom<0)
  109165. return(-1); /* complex root! The LPC generator handed us a bad filter */
  109166. if(pp>0){
  109167. denom = pp + sqrt(denom);
  109168. if(denom<EPSILON)denom=EPSILON;
  109169. }else{
  109170. denom = pp - sqrt(denom);
  109171. if(denom>-(EPSILON))denom=-(EPSILON);
  109172. }
  109173. delta = m*p/denom;
  109174. newx -= delta;
  109175. if(delta<0.f)delta*=-1;
  109176. if(fabs(delta/newx)<10e-12)break;
  109177. lastdelta=delta;
  109178. }
  109179. r[m-1]=newx;
  109180. /* forward deflation */
  109181. for(i=m;i>0;i--)
  109182. defl[i-1]+=newx*defl[i];
  109183. defl++;
  109184. }
  109185. return(0);
  109186. }
  109187. /* for spit-and-polish only */
  109188. static int Newton_Raphson(float *a,int ord,float *r){
  109189. int i, k, count=0;
  109190. double error=1.f;
  109191. double *root=(double*)alloca(ord*sizeof(*root));
  109192. for(i=0; i<ord;i++) root[i] = r[i];
  109193. while(error>1e-20){
  109194. error=0;
  109195. for(i=0; i<ord; i++) { /* Update each point. */
  109196. double pp=0.,delta;
  109197. double rooti=root[i];
  109198. double p=a[ord];
  109199. for(k=ord-1; k>= 0; k--) {
  109200. pp= pp* rooti + p;
  109201. p = p * rooti + a[k];
  109202. }
  109203. delta = p/pp;
  109204. root[i] -= delta;
  109205. error+= delta*delta;
  109206. }
  109207. if(count>40)return(-1);
  109208. count++;
  109209. }
  109210. /* Replaced the original bubble sort with a real sort. With your
  109211. help, we can eliminate the bubble sort in our lifetime. --Monty */
  109212. for(i=0; i<ord;i++) r[i] = root[i];
  109213. return(0);
  109214. }
  109215. /* Convert lpc coefficients to lsp coefficients */
  109216. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  109217. int order2=(m+1)>>1;
  109218. int g1_order,g2_order;
  109219. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  109220. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  109221. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  109222. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  109223. int i;
  109224. /* even and odd are slightly different base cases */
  109225. g1_order=(m+1)>>1;
  109226. g2_order=(m) >>1;
  109227. /* Compute the lengths of the x polynomials. */
  109228. /* Compute the first half of K & R F1 & F2 polynomials. */
  109229. /* Compute half of the symmetric and antisymmetric polynomials. */
  109230. /* Remove the roots at +1 and -1. */
  109231. g1[g1_order] = 1.f;
  109232. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  109233. g2[g2_order] = 1.f;
  109234. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  109235. if(g1_order>g2_order){
  109236. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  109237. }else{
  109238. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  109239. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  109240. }
  109241. /* Convert into polynomials in cos(alpha) */
  109242. cheby(g1,g1_order);
  109243. cheby(g2,g2_order);
  109244. /* Find the roots of the 2 even polynomials.*/
  109245. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  109246. Laguerre_With_Deflation(g2,g2_order,g2r))
  109247. return(-1);
  109248. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  109249. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  109250. qsort(g1r,g1_order,sizeof(*g1r),comp);
  109251. qsort(g2r,g2_order,sizeof(*g2r),comp);
  109252. for(i=0;i<g1_order;i++)
  109253. lsp[i*2] = acos(g1r[i]);
  109254. for(i=0;i<g2_order;i++)
  109255. lsp[i*2+1] = acos(g2r[i]);
  109256. return(0);
  109257. }
  109258. #endif
  109259. /********* End of inlined file: lsp.c *********/
  109260. /********* Start of inlined file: mapping0.c *********/
  109261. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109262. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109263. // tasks..
  109264. #ifdef _MSC_VER
  109265. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109266. #endif
  109267. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109268. #if JUCE_USE_OGGVORBIS
  109269. #include <stdlib.h>
  109270. #include <stdio.h>
  109271. #include <string.h>
  109272. #include <math.h>
  109273. /* simplistic, wasteful way of doing this (unique lookup for each
  109274. mode/submapping); there should be a central repository for
  109275. identical lookups. That will require minor work, so I'm putting it
  109276. off as low priority.
  109277. Why a lookup for each backend in a given mode? Because the
  109278. blocksize is set by the mode, and low backend lookups may require
  109279. parameters from other areas of the mode/mapping */
  109280. static void mapping0_free_info(vorbis_info_mapping *i){
  109281. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  109282. if(info){
  109283. memset(info,0,sizeof(*info));
  109284. _ogg_free(info);
  109285. }
  109286. }
  109287. static int ilog3(unsigned int v){
  109288. int ret=0;
  109289. if(v)--v;
  109290. while(v){
  109291. ret++;
  109292. v>>=1;
  109293. }
  109294. return(ret);
  109295. }
  109296. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  109297. oggpack_buffer *opb){
  109298. int i;
  109299. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  109300. /* another 'we meant to do it this way' hack... up to beta 4, we
  109301. packed 4 binary zeros here to signify one submapping in use. We
  109302. now redefine that to mean four bitflags that indicate use of
  109303. deeper features; bit0:submappings, bit1:coupling,
  109304. bit2,3:reserved. This is backward compatable with all actual uses
  109305. of the beta code. */
  109306. if(info->submaps>1){
  109307. oggpack_write(opb,1,1);
  109308. oggpack_write(opb,info->submaps-1,4);
  109309. }else
  109310. oggpack_write(opb,0,1);
  109311. if(info->coupling_steps>0){
  109312. oggpack_write(opb,1,1);
  109313. oggpack_write(opb,info->coupling_steps-1,8);
  109314. for(i=0;i<info->coupling_steps;i++){
  109315. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  109316. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  109317. }
  109318. }else
  109319. oggpack_write(opb,0,1);
  109320. oggpack_write(opb,0,2); /* 2,3:reserved */
  109321. /* we don't write the channel submappings if we only have one... */
  109322. if(info->submaps>1){
  109323. for(i=0;i<vi->channels;i++)
  109324. oggpack_write(opb,info->chmuxlist[i],4);
  109325. }
  109326. for(i=0;i<info->submaps;i++){
  109327. oggpack_write(opb,0,8); /* time submap unused */
  109328. oggpack_write(opb,info->floorsubmap[i],8);
  109329. oggpack_write(opb,info->residuesubmap[i],8);
  109330. }
  109331. }
  109332. /* also responsible for range checking */
  109333. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  109334. int i;
  109335. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  109336. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109337. memset(info,0,sizeof(*info));
  109338. if(oggpack_read(opb,1))
  109339. info->submaps=oggpack_read(opb,4)+1;
  109340. else
  109341. info->submaps=1;
  109342. if(oggpack_read(opb,1)){
  109343. info->coupling_steps=oggpack_read(opb,8)+1;
  109344. for(i=0;i<info->coupling_steps;i++){
  109345. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  109346. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  109347. if(testM<0 ||
  109348. testA<0 ||
  109349. testM==testA ||
  109350. testM>=vi->channels ||
  109351. testA>=vi->channels) goto err_out;
  109352. }
  109353. }
  109354. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  109355. if(info->submaps>1){
  109356. for(i=0;i<vi->channels;i++){
  109357. info->chmuxlist[i]=oggpack_read(opb,4);
  109358. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  109359. }
  109360. }
  109361. for(i=0;i<info->submaps;i++){
  109362. oggpack_read(opb,8); /* time submap unused */
  109363. info->floorsubmap[i]=oggpack_read(opb,8);
  109364. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  109365. info->residuesubmap[i]=oggpack_read(opb,8);
  109366. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  109367. }
  109368. return info;
  109369. err_out:
  109370. mapping0_free_info(info);
  109371. return(NULL);
  109372. }
  109373. #if 0
  109374. static long seq=0;
  109375. static ogg_int64_t total=0;
  109376. static float FLOOR1_fromdB_LOOKUP[256]={
  109377. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  109378. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  109379. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  109380. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  109381. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  109382. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  109383. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  109384. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  109385. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  109386. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  109387. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  109388. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  109389. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  109390. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  109391. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  109392. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  109393. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  109394. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  109395. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  109396. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  109397. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  109398. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  109399. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  109400. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  109401. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  109402. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  109403. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  109404. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  109405. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  109406. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  109407. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  109408. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  109409. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  109410. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  109411. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  109412. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  109413. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  109414. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  109415. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  109416. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  109417. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  109418. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  109419. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  109420. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  109421. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  109422. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  109423. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  109424. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  109425. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  109426. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  109427. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  109428. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  109429. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  109430. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  109431. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  109432. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  109433. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  109434. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  109435. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  109436. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  109437. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  109438. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  109439. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  109440. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  109441. };
  109442. #endif
  109443. extern int *floor1_fit(vorbis_block *vb,void *look,
  109444. const float *logmdct, /* in */
  109445. const float *logmask);
  109446. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  109447. int *A,int *B,
  109448. int del);
  109449. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  109450. void*look,
  109451. int *post,int *ilogmask);
  109452. static int mapping0_forward(vorbis_block *vb){
  109453. vorbis_dsp_state *vd=vb->vd;
  109454. vorbis_info *vi=vd->vi;
  109455. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109456. private_state *b=(private_state*)vb->vd->backend_state;
  109457. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  109458. int n=vb->pcmend;
  109459. int i,j,k;
  109460. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  109461. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  109462. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  109463. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  109464. float global_ampmax=vbi->ampmax;
  109465. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  109466. int blocktype=vbi->blocktype;
  109467. int modenumber=vb->W;
  109468. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  109469. vorbis_look_psy *psy_look=
  109470. b->psy+blocktype+(vb->W?2:0);
  109471. vb->mode=modenumber;
  109472. for(i=0;i<vi->channels;i++){
  109473. float scale=4.f/n;
  109474. float scale_dB;
  109475. float *pcm =vb->pcm[i];
  109476. float *logfft =pcm;
  109477. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  109478. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  109479. todB estimation used on IEEE 754
  109480. compliant machines had a bug that
  109481. returned dB values about a third
  109482. of a decibel too high. The bug
  109483. was harmless because tunings
  109484. implicitly took that into
  109485. account. However, fixing the bug
  109486. in the estimator requires
  109487. changing all the tunings as well.
  109488. For now, it's easier to sync
  109489. things back up here, and
  109490. recalibrate the tunings in the
  109491. next major model upgrade. */
  109492. #if 0
  109493. if(vi->channels==2)
  109494. if(i==0)
  109495. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  109496. else
  109497. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  109498. #endif
  109499. /* window the PCM data */
  109500. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  109501. #if 0
  109502. if(vi->channels==2)
  109503. if(i==0)
  109504. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  109505. else
  109506. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  109507. #endif
  109508. /* transform the PCM data */
  109509. /* only MDCT right now.... */
  109510. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  109511. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  109512. drft_forward(&b->fft_look[vb->W],pcm);
  109513. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  109514. original todB estimation used on
  109515. IEEE 754 compliant machines had a
  109516. bug that returned dB values about
  109517. a third of a decibel too high.
  109518. The bug was harmless because
  109519. tunings implicitly took that into
  109520. account. However, fixing the bug
  109521. in the estimator requires
  109522. changing all the tunings as well.
  109523. For now, it's easier to sync
  109524. things back up here, and
  109525. recalibrate the tunings in the
  109526. next major model upgrade. */
  109527. local_ampmax[i]=logfft[0];
  109528. for(j=1;j<n-1;j+=2){
  109529. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  109530. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  109531. .345 is a hack; the original todB
  109532. estimation used on IEEE 754
  109533. compliant machines had a bug that
  109534. returned dB values about a third
  109535. of a decibel too high. The bug
  109536. was harmless because tunings
  109537. implicitly took that into
  109538. account. However, fixing the bug
  109539. in the estimator requires
  109540. changing all the tunings as well.
  109541. For now, it's easier to sync
  109542. things back up here, and
  109543. recalibrate the tunings in the
  109544. next major model upgrade. */
  109545. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  109546. }
  109547. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  109548. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  109549. #if 0
  109550. if(vi->channels==2){
  109551. if(i==0){
  109552. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  109553. }else{
  109554. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  109555. }
  109556. }
  109557. #endif
  109558. }
  109559. {
  109560. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  109561. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  109562. for(i=0;i<vi->channels;i++){
  109563. /* the encoder setup assumes that all the modes used by any
  109564. specific bitrate tweaking use the same floor */
  109565. int submap=info->chmuxlist[i];
  109566. /* the following makes things clearer to *me* anyway */
  109567. float *mdct =gmdct[i];
  109568. float *logfft =vb->pcm[i];
  109569. float *logmdct =logfft+n/2;
  109570. float *logmask =logfft;
  109571. vb->mode=modenumber;
  109572. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  109573. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  109574. for(j=0;j<n/2;j++)
  109575. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  109576. todB estimation used on IEEE 754
  109577. compliant machines had a bug that
  109578. returned dB values about a third
  109579. of a decibel too high. The bug
  109580. was harmless because tunings
  109581. implicitly took that into
  109582. account. However, fixing the bug
  109583. in the estimator requires
  109584. changing all the tunings as well.
  109585. For now, it's easier to sync
  109586. things back up here, and
  109587. recalibrate the tunings in the
  109588. next major model upgrade. */
  109589. #if 0
  109590. if(vi->channels==2){
  109591. if(i==0)
  109592. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  109593. else
  109594. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  109595. }else{
  109596. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  109597. }
  109598. #endif
  109599. /* first step; noise masking. Not only does 'noise masking'
  109600. give us curves from which we can decide how much resolution
  109601. to give noise parts of the spectrum, it also implicitly hands
  109602. us a tonality estimate (the larger the value in the
  109603. 'noise_depth' vector, the more tonal that area is) */
  109604. _vp_noisemask(psy_look,
  109605. logmdct,
  109606. noise); /* noise does not have by-frequency offset
  109607. bias applied yet */
  109608. #if 0
  109609. if(vi->channels==2){
  109610. if(i==0)
  109611. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  109612. else
  109613. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  109614. }
  109615. #endif
  109616. /* second step: 'all the other crap'; all the stuff that isn't
  109617. computed/fit for bitrate management goes in the second psy
  109618. vector. This includes tone masking, peak limiting and ATH */
  109619. _vp_tonemask(psy_look,
  109620. logfft,
  109621. tone,
  109622. global_ampmax,
  109623. local_ampmax[i]);
  109624. #if 0
  109625. if(vi->channels==2){
  109626. if(i==0)
  109627. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  109628. else
  109629. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  109630. }
  109631. #endif
  109632. /* third step; we offset the noise vectors, overlay tone
  109633. masking. We then do a floor1-specific line fit. If we're
  109634. performing bitrate management, the line fit is performed
  109635. multiple times for up/down tweakage on demand. */
  109636. #if 0
  109637. {
  109638. float aotuv[psy_look->n];
  109639. #endif
  109640. _vp_offset_and_mix(psy_look,
  109641. noise,
  109642. tone,
  109643. 1,
  109644. logmask,
  109645. mdct,
  109646. logmdct);
  109647. #if 0
  109648. if(vi->channels==2){
  109649. if(i==0)
  109650. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  109651. else
  109652. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  109653. }
  109654. }
  109655. #endif
  109656. #if 0
  109657. if(vi->channels==2){
  109658. if(i==0)
  109659. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  109660. else
  109661. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  109662. }
  109663. #endif
  109664. /* this algorithm is hardwired to floor 1 for now; abort out if
  109665. we're *not* floor1. This won't happen unless someone has
  109666. broken the encode setup lib. Guard it anyway. */
  109667. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  109668. floor_posts[i][PACKETBLOBS/2]=
  109669. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  109670. logmdct,
  109671. logmask);
  109672. /* are we managing bitrate? If so, perform two more fits for
  109673. later rate tweaking (fits represent hi/lo) */
  109674. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  109675. /* higher rate by way of lower noise curve */
  109676. _vp_offset_and_mix(psy_look,
  109677. noise,
  109678. tone,
  109679. 2,
  109680. logmask,
  109681. mdct,
  109682. logmdct);
  109683. #if 0
  109684. if(vi->channels==2){
  109685. if(i==0)
  109686. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  109687. else
  109688. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  109689. }
  109690. #endif
  109691. floor_posts[i][PACKETBLOBS-1]=
  109692. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  109693. logmdct,
  109694. logmask);
  109695. /* lower rate by way of higher noise curve */
  109696. _vp_offset_and_mix(psy_look,
  109697. noise,
  109698. tone,
  109699. 0,
  109700. logmask,
  109701. mdct,
  109702. logmdct);
  109703. #if 0
  109704. if(vi->channels==2)
  109705. if(i==0)
  109706. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  109707. else
  109708. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  109709. #endif
  109710. floor_posts[i][0]=
  109711. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  109712. logmdct,
  109713. logmask);
  109714. /* we also interpolate a range of intermediate curves for
  109715. intermediate rates */
  109716. for(k=1;k<PACKETBLOBS/2;k++)
  109717. floor_posts[i][k]=
  109718. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  109719. floor_posts[i][0],
  109720. floor_posts[i][PACKETBLOBS/2],
  109721. k*65536/(PACKETBLOBS/2));
  109722. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  109723. floor_posts[i][k]=
  109724. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  109725. floor_posts[i][PACKETBLOBS/2],
  109726. floor_posts[i][PACKETBLOBS-1],
  109727. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  109728. }
  109729. }
  109730. }
  109731. vbi->ampmax=global_ampmax;
  109732. /*
  109733. the next phases are performed once for vbr-only and PACKETBLOB
  109734. times for bitrate managed modes.
  109735. 1) encode actual mode being used
  109736. 2) encode the floor for each channel, compute coded mask curve/res
  109737. 3) normalize and couple.
  109738. 4) encode residue
  109739. 5) save packet bytes to the packetblob vector
  109740. */
  109741. /* iterate over the many masking curve fits we've created */
  109742. {
  109743. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  109744. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  109745. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  109746. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  109747. float **mag_memo;
  109748. int **mag_sort;
  109749. if(info->coupling_steps){
  109750. mag_memo=_vp_quantize_couple_memo(vb,
  109751. &ci->psy_g_param,
  109752. psy_look,
  109753. info,
  109754. gmdct);
  109755. mag_sort=_vp_quantize_couple_sort(vb,
  109756. psy_look,
  109757. info,
  109758. mag_memo);
  109759. hf_reduction(&ci->psy_g_param,
  109760. psy_look,
  109761. info,
  109762. mag_memo);
  109763. }
  109764. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  109765. if(psy_look->vi->normal_channel_p){
  109766. for(i=0;i<vi->channels;i++){
  109767. float *mdct =gmdct[i];
  109768. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  109769. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  109770. }
  109771. }
  109772. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  109773. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  109774. k++){
  109775. oggpack_buffer *opb=vbi->packetblob[k];
  109776. /* start out our new packet blob with packet type and mode */
  109777. /* Encode the packet type */
  109778. oggpack_write(opb,0,1);
  109779. /* Encode the modenumber */
  109780. /* Encode frame mode, pre,post windowsize, then dispatch */
  109781. oggpack_write(opb,modenumber,b->modebits);
  109782. if(vb->W){
  109783. oggpack_write(opb,vb->lW,1);
  109784. oggpack_write(opb,vb->nW,1);
  109785. }
  109786. /* encode floor, compute masking curve, sep out residue */
  109787. for(i=0;i<vi->channels;i++){
  109788. int submap=info->chmuxlist[i];
  109789. float *mdct =gmdct[i];
  109790. float *res =vb->pcm[i];
  109791. int *ilogmask=ilogmaskch[i]=
  109792. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  109793. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  109794. floor_posts[i][k],
  109795. ilogmask);
  109796. #if 0
  109797. {
  109798. char buf[80];
  109799. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  109800. float work[n/2];
  109801. for(j=0;j<n/2;j++)
  109802. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  109803. _analysis_output(buf,seq,work,n/2,1,1,0);
  109804. }
  109805. #endif
  109806. _vp_remove_floor(psy_look,
  109807. mdct,
  109808. ilogmask,
  109809. res,
  109810. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  109811. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  109812. #if 0
  109813. {
  109814. char buf[80];
  109815. float work[n/2];
  109816. for(j=0;j<n/2;j++)
  109817. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  109818. sprintf(buf,"resI%c%d",i?'R':'L',k);
  109819. _analysis_output(buf,seq,work,n/2,1,1,0);
  109820. }
  109821. #endif
  109822. }
  109823. /* our iteration is now based on masking curve, not prequant and
  109824. coupling. Only one prequant/coupling step */
  109825. /* quantize/couple */
  109826. /* incomplete implementation that assumes the tree is all depth
  109827. one, or no tree at all */
  109828. if(info->coupling_steps){
  109829. _vp_couple(k,
  109830. &ci->psy_g_param,
  109831. psy_look,
  109832. info,
  109833. vb->pcm,
  109834. mag_memo,
  109835. mag_sort,
  109836. ilogmaskch,
  109837. nonzero,
  109838. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  109839. }
  109840. /* classify and encode by submap */
  109841. for(i=0;i<info->submaps;i++){
  109842. int ch_in_bundle=0;
  109843. long **classifications;
  109844. int resnum=info->residuesubmap[i];
  109845. for(j=0;j<vi->channels;j++){
  109846. if(info->chmuxlist[j]==i){
  109847. zerobundle[ch_in_bundle]=0;
  109848. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  109849. res_bundle[ch_in_bundle]=vb->pcm[j];
  109850. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  109851. }
  109852. }
  109853. classifications=_residue_P[ci->residue_type[resnum]]->
  109854. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  109855. _residue_P[ci->residue_type[resnum]]->
  109856. forward(opb,vb,b->residue[resnum],
  109857. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  109858. }
  109859. /* ok, done encoding. Next protopacket. */
  109860. }
  109861. }
  109862. #if 0
  109863. seq++;
  109864. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  109865. #endif
  109866. return(0);
  109867. }
  109868. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  109869. vorbis_dsp_state *vd=vb->vd;
  109870. vorbis_info *vi=vd->vi;
  109871. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  109872. private_state *b=(private_state*)vd->backend_state;
  109873. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  109874. int i,j;
  109875. long n=vb->pcmend=ci->blocksizes[vb->W];
  109876. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  109877. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  109878. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  109879. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  109880. /* recover the spectral envelope; store it in the PCM vector for now */
  109881. for(i=0;i<vi->channels;i++){
  109882. int submap=info->chmuxlist[i];
  109883. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  109884. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  109885. if(floormemo[i])
  109886. nonzero[i]=1;
  109887. else
  109888. nonzero[i]=0;
  109889. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  109890. }
  109891. /* channel coupling can 'dirty' the nonzero listing */
  109892. for(i=0;i<info->coupling_steps;i++){
  109893. if(nonzero[info->coupling_mag[i]] ||
  109894. nonzero[info->coupling_ang[i]]){
  109895. nonzero[info->coupling_mag[i]]=1;
  109896. nonzero[info->coupling_ang[i]]=1;
  109897. }
  109898. }
  109899. /* recover the residue into our working vectors */
  109900. for(i=0;i<info->submaps;i++){
  109901. int ch_in_bundle=0;
  109902. for(j=0;j<vi->channels;j++){
  109903. if(info->chmuxlist[j]==i){
  109904. if(nonzero[j])
  109905. zerobundle[ch_in_bundle]=1;
  109906. else
  109907. zerobundle[ch_in_bundle]=0;
  109908. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  109909. }
  109910. }
  109911. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  109912. inverse(vb,b->residue[info->residuesubmap[i]],
  109913. pcmbundle,zerobundle,ch_in_bundle);
  109914. }
  109915. /* channel coupling */
  109916. for(i=info->coupling_steps-1;i>=0;i--){
  109917. float *pcmM=vb->pcm[info->coupling_mag[i]];
  109918. float *pcmA=vb->pcm[info->coupling_ang[i]];
  109919. for(j=0;j<n/2;j++){
  109920. float mag=pcmM[j];
  109921. float ang=pcmA[j];
  109922. if(mag>0)
  109923. if(ang>0){
  109924. pcmM[j]=mag;
  109925. pcmA[j]=mag-ang;
  109926. }else{
  109927. pcmA[j]=mag;
  109928. pcmM[j]=mag+ang;
  109929. }
  109930. else
  109931. if(ang>0){
  109932. pcmM[j]=mag;
  109933. pcmA[j]=mag+ang;
  109934. }else{
  109935. pcmA[j]=mag;
  109936. pcmM[j]=mag-ang;
  109937. }
  109938. }
  109939. }
  109940. /* compute and apply spectral envelope */
  109941. for(i=0;i<vi->channels;i++){
  109942. float *pcm=vb->pcm[i];
  109943. int submap=info->chmuxlist[i];
  109944. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  109945. inverse2(vb,b->flr[info->floorsubmap[submap]],
  109946. floormemo[i],pcm);
  109947. }
  109948. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  109949. /* only MDCT right now.... */
  109950. for(i=0;i<vi->channels;i++){
  109951. float *pcm=vb->pcm[i];
  109952. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  109953. }
  109954. /* all done! */
  109955. return(0);
  109956. }
  109957. /* export hooks */
  109958. vorbis_func_mapping mapping0_exportbundle={
  109959. &mapping0_pack,
  109960. &mapping0_unpack,
  109961. &mapping0_free_info,
  109962. &mapping0_forward,
  109963. &mapping0_inverse
  109964. };
  109965. #endif
  109966. /********* End of inlined file: mapping0.c *********/
  109967. /********* Start of inlined file: mdct.c *********/
  109968. /* this can also be run as an integer transform by uncommenting a
  109969. define in mdct.h; the integerization is a first pass and although
  109970. it's likely stable for Vorbis, the dynamic range is constrained and
  109971. roundoff isn't done (so it's noisy). Consider it functional, but
  109972. only a starting point. There's no point on a machine with an FPU */
  109973. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109974. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109975. // tasks..
  109976. #ifdef _MSC_VER
  109977. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109978. #endif
  109979. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109980. #if JUCE_USE_OGGVORBIS
  109981. #include <stdio.h>
  109982. #include <stdlib.h>
  109983. #include <string.h>
  109984. #include <math.h>
  109985. /* build lookups for trig functions; also pre-figure scaling and
  109986. some window function algebra. */
  109987. void mdct_init(mdct_lookup *lookup,int n){
  109988. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  109989. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  109990. int i;
  109991. int n2=n>>1;
  109992. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  109993. lookup->n=n;
  109994. lookup->trig=T;
  109995. lookup->bitrev=bitrev;
  109996. /* trig lookups... */
  109997. for(i=0;i<n/4;i++){
  109998. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  109999. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  110000. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  110001. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  110002. }
  110003. for(i=0;i<n/8;i++){
  110004. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  110005. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  110006. }
  110007. /* bitreverse lookup... */
  110008. {
  110009. int mask=(1<<(log2n-1))-1,i,j;
  110010. int msb=1<<(log2n-2);
  110011. for(i=0;i<n/8;i++){
  110012. int acc=0;
  110013. for(j=0;msb>>j;j++)
  110014. if((msb>>j)&i)acc|=1<<j;
  110015. bitrev[i*2]=((~acc)&mask)-1;
  110016. bitrev[i*2+1]=acc;
  110017. }
  110018. }
  110019. lookup->scale=FLOAT_CONV(4.f/n);
  110020. }
  110021. /* 8 point butterfly (in place, 4 register) */
  110022. STIN void mdct_butterfly_8(DATA_TYPE *x){
  110023. REG_TYPE r0 = x[6] + x[2];
  110024. REG_TYPE r1 = x[6] - x[2];
  110025. REG_TYPE r2 = x[4] + x[0];
  110026. REG_TYPE r3 = x[4] - x[0];
  110027. x[6] = r0 + r2;
  110028. x[4] = r0 - r2;
  110029. r0 = x[5] - x[1];
  110030. r2 = x[7] - x[3];
  110031. x[0] = r1 + r0;
  110032. x[2] = r1 - r0;
  110033. r0 = x[5] + x[1];
  110034. r1 = x[7] + x[3];
  110035. x[3] = r2 + r3;
  110036. x[1] = r2 - r3;
  110037. x[7] = r1 + r0;
  110038. x[5] = r1 - r0;
  110039. }
  110040. /* 16 point butterfly (in place, 4 register) */
  110041. STIN void mdct_butterfly_16(DATA_TYPE *x){
  110042. REG_TYPE r0 = x[1] - x[9];
  110043. REG_TYPE r1 = x[0] - x[8];
  110044. x[8] += x[0];
  110045. x[9] += x[1];
  110046. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  110047. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  110048. r0 = x[3] - x[11];
  110049. r1 = x[10] - x[2];
  110050. x[10] += x[2];
  110051. x[11] += x[3];
  110052. x[2] = r0;
  110053. x[3] = r1;
  110054. r0 = x[12] - x[4];
  110055. r1 = x[13] - x[5];
  110056. x[12] += x[4];
  110057. x[13] += x[5];
  110058. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  110059. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  110060. r0 = x[14] - x[6];
  110061. r1 = x[15] - x[7];
  110062. x[14] += x[6];
  110063. x[15] += x[7];
  110064. x[6] = r0;
  110065. x[7] = r1;
  110066. mdct_butterfly_8(x);
  110067. mdct_butterfly_8(x+8);
  110068. }
  110069. /* 32 point butterfly (in place, 4 register) */
  110070. STIN void mdct_butterfly_32(DATA_TYPE *x){
  110071. REG_TYPE r0 = x[30] - x[14];
  110072. REG_TYPE r1 = x[31] - x[15];
  110073. x[30] += x[14];
  110074. x[31] += x[15];
  110075. x[14] = r0;
  110076. x[15] = r1;
  110077. r0 = x[28] - x[12];
  110078. r1 = x[29] - x[13];
  110079. x[28] += x[12];
  110080. x[29] += x[13];
  110081. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  110082. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  110083. r0 = x[26] - x[10];
  110084. r1 = x[27] - x[11];
  110085. x[26] += x[10];
  110086. x[27] += x[11];
  110087. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  110088. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  110089. r0 = x[24] - x[8];
  110090. r1 = x[25] - x[9];
  110091. x[24] += x[8];
  110092. x[25] += x[9];
  110093. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  110094. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  110095. r0 = x[22] - x[6];
  110096. r1 = x[7] - x[23];
  110097. x[22] += x[6];
  110098. x[23] += x[7];
  110099. x[6] = r1;
  110100. x[7] = r0;
  110101. r0 = x[4] - x[20];
  110102. r1 = x[5] - x[21];
  110103. x[20] += x[4];
  110104. x[21] += x[5];
  110105. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  110106. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  110107. r0 = x[2] - x[18];
  110108. r1 = x[3] - x[19];
  110109. x[18] += x[2];
  110110. x[19] += x[3];
  110111. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  110112. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  110113. r0 = x[0] - x[16];
  110114. r1 = x[1] - x[17];
  110115. x[16] += x[0];
  110116. x[17] += x[1];
  110117. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  110118. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  110119. mdct_butterfly_16(x);
  110120. mdct_butterfly_16(x+16);
  110121. }
  110122. /* N point first stage butterfly (in place, 2 register) */
  110123. STIN void mdct_butterfly_first(DATA_TYPE *T,
  110124. DATA_TYPE *x,
  110125. int points){
  110126. DATA_TYPE *x1 = x + points - 8;
  110127. DATA_TYPE *x2 = x + (points>>1) - 8;
  110128. REG_TYPE r0;
  110129. REG_TYPE r1;
  110130. do{
  110131. r0 = x1[6] - x2[6];
  110132. r1 = x1[7] - x2[7];
  110133. x1[6] += x2[6];
  110134. x1[7] += x2[7];
  110135. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110136. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110137. r0 = x1[4] - x2[4];
  110138. r1 = x1[5] - x2[5];
  110139. x1[4] += x2[4];
  110140. x1[5] += x2[5];
  110141. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  110142. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  110143. r0 = x1[2] - x2[2];
  110144. r1 = x1[3] - x2[3];
  110145. x1[2] += x2[2];
  110146. x1[3] += x2[3];
  110147. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  110148. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  110149. r0 = x1[0] - x2[0];
  110150. r1 = x1[1] - x2[1];
  110151. x1[0] += x2[0];
  110152. x1[1] += x2[1];
  110153. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  110154. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  110155. x1-=8;
  110156. x2-=8;
  110157. T+=16;
  110158. }while(x2>=x);
  110159. }
  110160. /* N/stage point generic N stage butterfly (in place, 2 register) */
  110161. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  110162. DATA_TYPE *x,
  110163. int points,
  110164. int trigint){
  110165. DATA_TYPE *x1 = x + points - 8;
  110166. DATA_TYPE *x2 = x + (points>>1) - 8;
  110167. REG_TYPE r0;
  110168. REG_TYPE r1;
  110169. do{
  110170. r0 = x1[6] - x2[6];
  110171. r1 = x1[7] - x2[7];
  110172. x1[6] += x2[6];
  110173. x1[7] += x2[7];
  110174. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110175. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110176. T+=trigint;
  110177. r0 = x1[4] - x2[4];
  110178. r1 = x1[5] - x2[5];
  110179. x1[4] += x2[4];
  110180. x1[5] += x2[5];
  110181. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110182. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110183. T+=trigint;
  110184. r0 = x1[2] - x2[2];
  110185. r1 = x1[3] - x2[3];
  110186. x1[2] += x2[2];
  110187. x1[3] += x2[3];
  110188. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110189. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110190. T+=trigint;
  110191. r0 = x1[0] - x2[0];
  110192. r1 = x1[1] - x2[1];
  110193. x1[0] += x2[0];
  110194. x1[1] += x2[1];
  110195. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  110196. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  110197. T+=trigint;
  110198. x1-=8;
  110199. x2-=8;
  110200. }while(x2>=x);
  110201. }
  110202. STIN void mdct_butterflies(mdct_lookup *init,
  110203. DATA_TYPE *x,
  110204. int points){
  110205. DATA_TYPE *T=init->trig;
  110206. int stages=init->log2n-5;
  110207. int i,j;
  110208. if(--stages>0){
  110209. mdct_butterfly_first(T,x,points);
  110210. }
  110211. for(i=1;--stages>0;i++){
  110212. for(j=0;j<(1<<i);j++)
  110213. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  110214. }
  110215. for(j=0;j<points;j+=32)
  110216. mdct_butterfly_32(x+j);
  110217. }
  110218. void mdct_clear(mdct_lookup *l){
  110219. if(l){
  110220. if(l->trig)_ogg_free(l->trig);
  110221. if(l->bitrev)_ogg_free(l->bitrev);
  110222. memset(l,0,sizeof(*l));
  110223. }
  110224. }
  110225. STIN void mdct_bitreverse(mdct_lookup *init,
  110226. DATA_TYPE *x){
  110227. int n = init->n;
  110228. int *bit = init->bitrev;
  110229. DATA_TYPE *w0 = x;
  110230. DATA_TYPE *w1 = x = w0+(n>>1);
  110231. DATA_TYPE *T = init->trig+n;
  110232. do{
  110233. DATA_TYPE *x0 = x+bit[0];
  110234. DATA_TYPE *x1 = x+bit[1];
  110235. REG_TYPE r0 = x0[1] - x1[1];
  110236. REG_TYPE r1 = x0[0] + x1[0];
  110237. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  110238. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  110239. w1 -= 4;
  110240. r0 = HALVE(x0[1] + x1[1]);
  110241. r1 = HALVE(x0[0] - x1[0]);
  110242. w0[0] = r0 + r2;
  110243. w1[2] = r0 - r2;
  110244. w0[1] = r1 + r3;
  110245. w1[3] = r3 - r1;
  110246. x0 = x+bit[2];
  110247. x1 = x+bit[3];
  110248. r0 = x0[1] - x1[1];
  110249. r1 = x0[0] + x1[0];
  110250. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  110251. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  110252. r0 = HALVE(x0[1] + x1[1]);
  110253. r1 = HALVE(x0[0] - x1[0]);
  110254. w0[2] = r0 + r2;
  110255. w1[0] = r0 - r2;
  110256. w0[3] = r1 + r3;
  110257. w1[1] = r3 - r1;
  110258. T += 4;
  110259. bit += 4;
  110260. w0 += 4;
  110261. }while(w0<w1);
  110262. }
  110263. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  110264. int n=init->n;
  110265. int n2=n>>1;
  110266. int n4=n>>2;
  110267. /* rotate */
  110268. DATA_TYPE *iX = in+n2-7;
  110269. DATA_TYPE *oX = out+n2+n4;
  110270. DATA_TYPE *T = init->trig+n4;
  110271. do{
  110272. oX -= 4;
  110273. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  110274. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  110275. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  110276. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  110277. iX -= 8;
  110278. T += 4;
  110279. }while(iX>=in);
  110280. iX = in+n2-8;
  110281. oX = out+n2+n4;
  110282. T = init->trig+n4;
  110283. do{
  110284. T -= 4;
  110285. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  110286. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  110287. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  110288. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  110289. iX -= 8;
  110290. oX += 4;
  110291. }while(iX>=in);
  110292. mdct_butterflies(init,out+n2,n2);
  110293. mdct_bitreverse(init,out);
  110294. /* roatate + window */
  110295. {
  110296. DATA_TYPE *oX1=out+n2+n4;
  110297. DATA_TYPE *oX2=out+n2+n4;
  110298. DATA_TYPE *iX =out;
  110299. T =init->trig+n2;
  110300. do{
  110301. oX1-=4;
  110302. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  110303. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  110304. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  110305. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  110306. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  110307. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  110308. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  110309. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  110310. oX2+=4;
  110311. iX += 8;
  110312. T += 8;
  110313. }while(iX<oX1);
  110314. iX=out+n2+n4;
  110315. oX1=out+n4;
  110316. oX2=oX1;
  110317. do{
  110318. oX1-=4;
  110319. iX-=4;
  110320. oX2[0] = -(oX1[3] = iX[3]);
  110321. oX2[1] = -(oX1[2] = iX[2]);
  110322. oX2[2] = -(oX1[1] = iX[1]);
  110323. oX2[3] = -(oX1[0] = iX[0]);
  110324. oX2+=4;
  110325. }while(oX2<iX);
  110326. iX=out+n2+n4;
  110327. oX1=out+n2+n4;
  110328. oX2=out+n2;
  110329. do{
  110330. oX1-=4;
  110331. oX1[0]= iX[3];
  110332. oX1[1]= iX[2];
  110333. oX1[2]= iX[1];
  110334. oX1[3]= iX[0];
  110335. iX+=4;
  110336. }while(oX1>oX2);
  110337. }
  110338. }
  110339. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  110340. int n=init->n;
  110341. int n2=n>>1;
  110342. int n4=n>>2;
  110343. int n8=n>>3;
  110344. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  110345. DATA_TYPE *w2=w+n2;
  110346. /* rotate */
  110347. /* window + rotate + step 1 */
  110348. REG_TYPE r0;
  110349. REG_TYPE r1;
  110350. DATA_TYPE *x0=in+n2+n4;
  110351. DATA_TYPE *x1=x0+1;
  110352. DATA_TYPE *T=init->trig+n2;
  110353. int i=0;
  110354. for(i=0;i<n8;i+=2){
  110355. x0 -=4;
  110356. T-=2;
  110357. r0= x0[2] + x1[0];
  110358. r1= x0[0] + x1[2];
  110359. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  110360. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  110361. x1 +=4;
  110362. }
  110363. x1=in+1;
  110364. for(;i<n2-n8;i+=2){
  110365. T-=2;
  110366. x0 -=4;
  110367. r0= x0[2] - x1[0];
  110368. r1= x0[0] - x1[2];
  110369. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  110370. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  110371. x1 +=4;
  110372. }
  110373. x0=in+n;
  110374. for(;i<n2;i+=2){
  110375. T-=2;
  110376. x0 -=4;
  110377. r0= -x0[2] - x1[0];
  110378. r1= -x0[0] - x1[2];
  110379. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  110380. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  110381. x1 +=4;
  110382. }
  110383. mdct_butterflies(init,w+n2,n2);
  110384. mdct_bitreverse(init,w);
  110385. /* roatate + window */
  110386. T=init->trig+n2;
  110387. x0=out+n2;
  110388. for(i=0;i<n4;i++){
  110389. x0--;
  110390. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  110391. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  110392. w+=2;
  110393. T+=2;
  110394. }
  110395. }
  110396. #endif
  110397. /********* End of inlined file: mdct.c *********/
  110398. /********* Start of inlined file: psy.c *********/
  110399. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110400. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110401. // tasks..
  110402. #ifdef _MSC_VER
  110403. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110404. #endif
  110405. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110406. #if JUCE_USE_OGGVORBIS
  110407. #include <stdlib.h>
  110408. #include <math.h>
  110409. #include <string.h>
  110410. /********* Start of inlined file: masking.h *********/
  110411. #ifndef _V_MASKING_H_
  110412. #define _V_MASKING_H_
  110413. /* more detailed ATH; the bass if flat to save stressing the floor
  110414. overly for only a bin or two of savings. */
  110415. #define MAX_ATH 88
  110416. static float ATH[]={
  110417. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  110418. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  110419. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  110420. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  110421. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  110422. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  110423. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  110424. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  110425. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  110426. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  110427. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  110428. };
  110429. /* The tone masking curves from Ehmer's and Fielder's papers have been
  110430. replaced by an empirically collected data set. The previously
  110431. published values were, far too often, simply on crack. */
  110432. #define EHMER_OFFSET 16
  110433. #define EHMER_MAX 56
  110434. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  110435. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  110436. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  110437. for collection of these curves) */
  110438. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  110439. /* 62.5 Hz */
  110440. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  110441. -60, -60, -60, -60, -62, -62, -65, -73,
  110442. -69, -68, -68, -67, -70, -70, -72, -74,
  110443. -75, -79, -79, -80, -83, -88, -93, -100,
  110444. -110, -999, -999, -999, -999, -999, -999, -999,
  110445. -999, -999, -999, -999, -999, -999, -999, -999,
  110446. -999, -999, -999, -999, -999, -999, -999, -999},
  110447. { -48, -48, -48, -48, -48, -48, -48, -48,
  110448. -48, -48, -48, -48, -48, -53, -61, -66,
  110449. -66, -68, -67, -70, -76, -76, -72, -73,
  110450. -75, -76, -78, -79, -83, -88, -93, -100,
  110451. -110, -999, -999, -999, -999, -999, -999, -999,
  110452. -999, -999, -999, -999, -999, -999, -999, -999,
  110453. -999, -999, -999, -999, -999, -999, -999, -999},
  110454. { -37, -37, -37, -37, -37, -37, -37, -37,
  110455. -38, -40, -42, -46, -48, -53, -55, -62,
  110456. -65, -58, -56, -56, -61, -60, -65, -67,
  110457. -69, -71, -77, -77, -78, -80, -82, -84,
  110458. -88, -93, -98, -106, -112, -999, -999, -999,
  110459. -999, -999, -999, -999, -999, -999, -999, -999,
  110460. -999, -999, -999, -999, -999, -999, -999, -999},
  110461. { -25, -25, -25, -25, -25, -25, -25, -25,
  110462. -25, -26, -27, -29, -32, -38, -48, -52,
  110463. -52, -50, -48, -48, -51, -52, -54, -60,
  110464. -67, -67, -66, -68, -69, -73, -73, -76,
  110465. -80, -81, -81, -85, -85, -86, -88, -93,
  110466. -100, -110, -999, -999, -999, -999, -999, -999,
  110467. -999, -999, -999, -999, -999, -999, -999, -999},
  110468. { -16, -16, -16, -16, -16, -16, -16, -16,
  110469. -17, -19, -20, -22, -26, -28, -31, -40,
  110470. -47, -39, -39, -40, -42, -43, -47, -51,
  110471. -57, -52, -55, -55, -60, -58, -62, -63,
  110472. -70, -67, -69, -72, -73, -77, -80, -82,
  110473. -83, -87, -90, -94, -98, -104, -115, -999,
  110474. -999, -999, -999, -999, -999, -999, -999, -999},
  110475. { -8, -8, -8, -8, -8, -8, -8, -8,
  110476. -8, -8, -10, -11, -15, -19, -25, -30,
  110477. -34, -31, -30, -31, -29, -32, -35, -42,
  110478. -48, -42, -44, -46, -50, -50, -51, -52,
  110479. -59, -54, -55, -55, -58, -62, -63, -66,
  110480. -72, -73, -76, -75, -78, -80, -80, -81,
  110481. -84, -88, -90, -94, -98, -101, -106, -110}},
  110482. /* 88Hz */
  110483. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  110484. -66, -66, -66, -66, -66, -67, -67, -67,
  110485. -76, -72, -71, -74, -76, -76, -75, -78,
  110486. -79, -79, -81, -83, -86, -89, -93, -97,
  110487. -100, -105, -110, -999, -999, -999, -999, -999,
  110488. -999, -999, -999, -999, -999, -999, -999, -999,
  110489. -999, -999, -999, -999, -999, -999, -999, -999},
  110490. { -47, -47, -47, -47, -47, -47, -47, -47,
  110491. -47, -47, -47, -48, -51, -55, -59, -66,
  110492. -66, -66, -67, -66, -68, -69, -70, -74,
  110493. -79, -77, -77, -78, -80, -81, -82, -84,
  110494. -86, -88, -91, -95, -100, -108, -116, -999,
  110495. -999, -999, -999, -999, -999, -999, -999, -999,
  110496. -999, -999, -999, -999, -999, -999, -999, -999},
  110497. { -36, -36, -36, -36, -36, -36, -36, -36,
  110498. -36, -37, -37, -41, -44, -48, -51, -58,
  110499. -62, -60, -57, -59, -59, -60, -63, -65,
  110500. -72, -71, -70, -72, -74, -77, -76, -78,
  110501. -81, -81, -80, -83, -86, -91, -96, -100,
  110502. -105, -110, -999, -999, -999, -999, -999, -999,
  110503. -999, -999, -999, -999, -999, -999, -999, -999},
  110504. { -28, -28, -28, -28, -28, -28, -28, -28,
  110505. -28, -30, -32, -32, -33, -35, -41, -49,
  110506. -50, -49, -47, -48, -48, -52, -51, -57,
  110507. -65, -61, -59, -61, -64, -69, -70, -74,
  110508. -77, -77, -78, -81, -84, -85, -87, -90,
  110509. -92, -96, -100, -107, -112, -999, -999, -999,
  110510. -999, -999, -999, -999, -999, -999, -999, -999},
  110511. { -19, -19, -19, -19, -19, -19, -19, -19,
  110512. -20, -21, -23, -27, -30, -35, -36, -41,
  110513. -46, -44, -42, -40, -41, -41, -43, -48,
  110514. -55, -53, -52, -53, -56, -59, -58, -60,
  110515. -67, -66, -69, -71, -72, -75, -79, -81,
  110516. -84, -87, -90, -93, -97, -101, -107, -114,
  110517. -999, -999, -999, -999, -999, -999, -999, -999},
  110518. { -9, -9, -9, -9, -9, -9, -9, -9,
  110519. -11, -12, -12, -15, -16, -20, -23, -30,
  110520. -37, -34, -33, -34, -31, -32, -32, -38,
  110521. -47, -44, -41, -40, -47, -49, -46, -46,
  110522. -58, -50, -50, -54, -58, -62, -64, -67,
  110523. -67, -70, -72, -76, -79, -83, -87, -91,
  110524. -96, -100, -104, -110, -999, -999, -999, -999}},
  110525. /* 125 Hz */
  110526. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  110527. -62, -62, -63, -64, -66, -67, -66, -68,
  110528. -75, -72, -76, -75, -76, -78, -79, -82,
  110529. -84, -85, -90, -94, -101, -110, -999, -999,
  110530. -999, -999, -999, -999, -999, -999, -999, -999,
  110531. -999, -999, -999, -999, -999, -999, -999, -999,
  110532. -999, -999, -999, -999, -999, -999, -999, -999},
  110533. { -59, -59, -59, -59, -59, -59, -59, -59,
  110534. -59, -59, -59, -60, -60, -61, -63, -66,
  110535. -71, -68, -70, -70, -71, -72, -72, -75,
  110536. -81, -78, -79, -82, -83, -86, -90, -97,
  110537. -103, -113, -999, -999, -999, -999, -999, -999,
  110538. -999, -999, -999, -999, -999, -999, -999, -999,
  110539. -999, -999, -999, -999, -999, -999, -999, -999},
  110540. { -53, -53, -53, -53, -53, -53, -53, -53,
  110541. -53, -54, -55, -57, -56, -57, -55, -61,
  110542. -65, -60, -60, -62, -63, -63, -66, -68,
  110543. -74, -73, -75, -75, -78, -80, -80, -82,
  110544. -85, -90, -96, -101, -108, -999, -999, -999,
  110545. -999, -999, -999, -999, -999, -999, -999, -999,
  110546. -999, -999, -999, -999, -999, -999, -999, -999},
  110547. { -46, -46, -46, -46, -46, -46, -46, -46,
  110548. -46, -46, -47, -47, -47, -47, -48, -51,
  110549. -57, -51, -49, -50, -51, -53, -54, -59,
  110550. -66, -60, -62, -67, -67, -70, -72, -75,
  110551. -76, -78, -81, -85, -88, -94, -97, -104,
  110552. -112, -999, -999, -999, -999, -999, -999, -999,
  110553. -999, -999, -999, -999, -999, -999, -999, -999},
  110554. { -36, -36, -36, -36, -36, -36, -36, -36,
  110555. -39, -41, -42, -42, -39, -38, -41, -43,
  110556. -52, -44, -40, -39, -37, -37, -40, -47,
  110557. -54, -50, -48, -50, -55, -61, -59, -62,
  110558. -66, -66, -66, -69, -69, -73, -74, -74,
  110559. -75, -77, -79, -82, -87, -91, -95, -100,
  110560. -108, -115, -999, -999, -999, -999, -999, -999},
  110561. { -28, -26, -24, -22, -20, -20, -23, -29,
  110562. -30, -31, -28, -27, -28, -28, -28, -35,
  110563. -40, -33, -32, -29, -30, -30, -30, -37,
  110564. -45, -41, -37, -38, -45, -47, -47, -48,
  110565. -53, -49, -48, -50, -49, -49, -51, -52,
  110566. -58, -56, -57, -56, -60, -61, -62, -70,
  110567. -72, -74, -78, -83, -88, -93, -100, -106}},
  110568. /* 177 Hz */
  110569. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110570. -999, -110, -105, -100, -95, -91, -87, -83,
  110571. -80, -78, -76, -78, -78, -81, -83, -85,
  110572. -86, -85, -86, -87, -90, -97, -107, -999,
  110573. -999, -999, -999, -999, -999, -999, -999, -999,
  110574. -999, -999, -999, -999, -999, -999, -999, -999,
  110575. -999, -999, -999, -999, -999, -999, -999, -999},
  110576. {-999, -999, -999, -110, -105, -100, -95, -90,
  110577. -85, -81, -77, -73, -70, -67, -67, -68,
  110578. -75, -73, -70, -69, -70, -72, -75, -79,
  110579. -84, -83, -84, -86, -88, -89, -89, -93,
  110580. -98, -105, -112, -999, -999, -999, -999, -999,
  110581. -999, -999, -999, -999, -999, -999, -999, -999,
  110582. -999, -999, -999, -999, -999, -999, -999, -999},
  110583. {-105, -100, -95, -90, -85, -80, -76, -71,
  110584. -68, -68, -65, -63, -63, -62, -62, -64,
  110585. -65, -64, -61, -62, -63, -64, -66, -68,
  110586. -73, -73, -74, -75, -76, -81, -83, -85,
  110587. -88, -89, -92, -95, -100, -108, -999, -999,
  110588. -999, -999, -999, -999, -999, -999, -999, -999,
  110589. -999, -999, -999, -999, -999, -999, -999, -999},
  110590. { -80, -75, -71, -68, -65, -63, -62, -61,
  110591. -61, -61, -61, -59, -56, -57, -53, -50,
  110592. -58, -52, -50, -50, -52, -53, -54, -58,
  110593. -67, -63, -67, -68, -72, -75, -78, -80,
  110594. -81, -81, -82, -85, -89, -90, -93, -97,
  110595. -101, -107, -114, -999, -999, -999, -999, -999,
  110596. -999, -999, -999, -999, -999, -999, -999, -999},
  110597. { -65, -61, -59, -57, -56, -55, -55, -56,
  110598. -56, -57, -55, -53, -52, -47, -44, -44,
  110599. -50, -44, -41, -39, -39, -42, -40, -46,
  110600. -51, -49, -50, -53, -54, -63, -60, -61,
  110601. -62, -66, -66, -66, -70, -73, -74, -75,
  110602. -76, -75, -79, -85, -89, -91, -96, -102,
  110603. -110, -999, -999, -999, -999, -999, -999, -999},
  110604. { -52, -50, -49, -49, -48, -48, -48, -49,
  110605. -50, -50, -49, -46, -43, -39, -35, -33,
  110606. -38, -36, -32, -29, -32, -32, -32, -35,
  110607. -44, -39, -38, -38, -46, -50, -45, -46,
  110608. -53, -50, -50, -50, -54, -54, -53, -53,
  110609. -56, -57, -59, -66, -70, -72, -74, -79,
  110610. -83, -85, -90, -97, -114, -999, -999, -999}},
  110611. /* 250 Hz */
  110612. {{-999, -999, -999, -999, -999, -999, -110, -105,
  110613. -100, -95, -90, -86, -80, -75, -75, -79,
  110614. -80, -79, -80, -81, -82, -88, -95, -103,
  110615. -110, -999, -999, -999, -999, -999, -999, -999,
  110616. -999, -999, -999, -999, -999, -999, -999, -999,
  110617. -999, -999, -999, -999, -999, -999, -999, -999,
  110618. -999, -999, -999, -999, -999, -999, -999, -999},
  110619. {-999, -999, -999, -999, -108, -103, -98, -93,
  110620. -88, -83, -79, -78, -75, -71, -67, -68,
  110621. -73, -73, -72, -73, -75, -77, -80, -82,
  110622. -88, -93, -100, -107, -114, -999, -999, -999,
  110623. -999, -999, -999, -999, -999, -999, -999, -999,
  110624. -999, -999, -999, -999, -999, -999, -999, -999,
  110625. -999, -999, -999, -999, -999, -999, -999, -999},
  110626. {-999, -999, -999, -110, -105, -101, -96, -90,
  110627. -86, -81, -77, -73, -69, -66, -61, -62,
  110628. -66, -64, -62, -65, -66, -70, -72, -76,
  110629. -81, -80, -84, -90, -95, -102, -110, -999,
  110630. -999, -999, -999, -999, -999, -999, -999, -999,
  110631. -999, -999, -999, -999, -999, -999, -999, -999,
  110632. -999, -999, -999, -999, -999, -999, -999, -999},
  110633. {-999, -999, -999, -107, -103, -97, -92, -88,
  110634. -83, -79, -74, -70, -66, -59, -53, -58,
  110635. -62, -55, -54, -54, -54, -58, -61, -62,
  110636. -72, -70, -72, -75, -78, -80, -81, -80,
  110637. -83, -83, -88, -93, -100, -107, -115, -999,
  110638. -999, -999, -999, -999, -999, -999, -999, -999,
  110639. -999, -999, -999, -999, -999, -999, -999, -999},
  110640. {-999, -999, -999, -105, -100, -95, -90, -85,
  110641. -80, -75, -70, -66, -62, -56, -48, -44,
  110642. -48, -46, -46, -43, -46, -48, -48, -51,
  110643. -58, -58, -59, -60, -62, -62, -61, -61,
  110644. -65, -64, -65, -68, -70, -74, -75, -78,
  110645. -81, -86, -95, -110, -999, -999, -999, -999,
  110646. -999, -999, -999, -999, -999, -999, -999, -999},
  110647. {-999, -999, -105, -100, -95, -90, -85, -80,
  110648. -75, -70, -65, -61, -55, -49, -39, -33,
  110649. -40, -35, -32, -38, -40, -33, -35, -37,
  110650. -46, -41, -45, -44, -46, -42, -45, -46,
  110651. -52, -50, -50, -50, -54, -54, -55, -57,
  110652. -62, -64, -66, -68, -70, -76, -81, -90,
  110653. -100, -110, -999, -999, -999, -999, -999, -999}},
  110654. /* 354 hz */
  110655. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110656. -105, -98, -90, -85, -82, -83, -80, -78,
  110657. -84, -79, -80, -83, -87, -89, -91, -93,
  110658. -99, -106, -117, -999, -999, -999, -999, -999,
  110659. -999, -999, -999, -999, -999, -999, -999, -999,
  110660. -999, -999, -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. -105, -98, -90, -85, -80, -75, -70, -68,
  110664. -74, -72, -74, -77, -80, -82, -85, -87,
  110665. -92, -89, -91, -95, -100, -106, -112, -999,
  110666. -999, -999, -999, -999, -999, -999, -999, -999,
  110667. -999, -999, -999, -999, -999, -999, -999, -999,
  110668. -999, -999, -999, -999, -999, -999, -999, -999},
  110669. {-999, -999, -999, -999, -999, -999, -999, -999,
  110670. -105, -98, -90, -83, -75, -71, -63, -64,
  110671. -67, -62, -64, -67, -70, -73, -77, -81,
  110672. -84, -83, -85, -89, -90, -93, -98, -104,
  110673. -109, -114, -999, -999, -999, -999, -999, -999,
  110674. -999, -999, -999, -999, -999, -999, -999, -999,
  110675. -999, -999, -999, -999, -999, -999, -999, -999},
  110676. {-999, -999, -999, -999, -999, -999, -999, -999,
  110677. -103, -96, -88, -81, -75, -68, -58, -54,
  110678. -56, -54, -56, -56, -58, -60, -63, -66,
  110679. -74, -69, -72, -72, -75, -74, -77, -81,
  110680. -81, -82, -84, -87, -93, -96, -99, -104,
  110681. -110, -999, -999, -999, -999, -999, -999, -999,
  110682. -999, -999, -999, -999, -999, -999, -999, -999},
  110683. {-999, -999, -999, -999, -999, -108, -102, -96,
  110684. -91, -85, -80, -74, -68, -60, -51, -46,
  110685. -48, -46, -43, -45, -47, -47, -49, -48,
  110686. -56, -53, -55, -58, -57, -63, -58, -60,
  110687. -66, -64, -67, -70, -70, -74, -77, -84,
  110688. -86, -89, -91, -93, -94, -101, -109, -118,
  110689. -999, -999, -999, -999, -999, -999, -999, -999},
  110690. {-999, -999, -999, -108, -103, -98, -93, -88,
  110691. -83, -78, -73, -68, -60, -53, -44, -35,
  110692. -38, -38, -34, -34, -36, -40, -41, -44,
  110693. -51, -45, -46, -47, -46, -54, -50, -49,
  110694. -50, -50, -50, -51, -54, -57, -58, -60,
  110695. -66, -66, -66, -64, -65, -68, -77, -82,
  110696. -87, -95, -110, -999, -999, -999, -999, -999}},
  110697. /* 500 Hz */
  110698. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110699. -107, -102, -97, -92, -87, -83, -78, -75,
  110700. -82, -79, -83, -85, -89, -92, -95, -98,
  110701. -101, -105, -109, -113, -999, -999, -999, -999,
  110702. -999, -999, -999, -999, -999, -999, -999, -999,
  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, -106,
  110706. -100, -95, -90, -86, -81, -78, -74, -69,
  110707. -74, -74, -76, -79, -83, -84, -86, -89,
  110708. -92, -97, -93, -100, -103, -107, -110, -999,
  110709. -999, -999, -999, -999, -999, -999, -999, -999,
  110710. -999, -999, -999, -999, -999, -999, -999, -999,
  110711. -999, -999, -999, -999, -999, -999, -999, -999},
  110712. {-999, -999, -999, -999, -999, -999, -106, -100,
  110713. -95, -90, -87, -83, -80, -75, -69, -60,
  110714. -66, -66, -68, -70, -74, -78, -79, -81,
  110715. -81, -83, -84, -87, -93, -96, -99, -103,
  110716. -107, -110, -999, -999, -999, -999, -999, -999,
  110717. -999, -999, -999, -999, -999, -999, -999, -999,
  110718. -999, -999, -999, -999, -999, -999, -999, -999},
  110719. {-999, -999, -999, -999, -999, -108, -103, -98,
  110720. -93, -89, -85, -82, -78, -71, -62, -55,
  110721. -58, -58, -54, -54, -55, -59, -61, -62,
  110722. -70, -66, -66, -67, -70, -72, -75, -78,
  110723. -84, -84, -84, -88, -91, -90, -95, -98,
  110724. -102, -103, -106, -110, -999, -999, -999, -999,
  110725. -999, -999, -999, -999, -999, -999, -999, -999},
  110726. {-999, -999, -999, -999, -108, -103, -98, -94,
  110727. -90, -87, -82, -79, -73, -67, -58, -47,
  110728. -50, -45, -41, -45, -48, -44, -44, -49,
  110729. -54, -51, -48, -47, -49, -50, -51, -57,
  110730. -58, -60, -63, -69, -70, -69, -71, -74,
  110731. -78, -82, -90, -95, -101, -105, -110, -999,
  110732. -999, -999, -999, -999, -999, -999, -999, -999},
  110733. {-999, -999, -999, -105, -101, -97, -93, -90,
  110734. -85, -80, -77, -72, -65, -56, -48, -37,
  110735. -40, -36, -34, -40, -50, -47, -38, -41,
  110736. -47, -38, -35, -39, -38, -43, -40, -45,
  110737. -50, -45, -44, -47, -50, -55, -48, -48,
  110738. -52, -66, -70, -76, -82, -90, -97, -105,
  110739. -110, -999, -999, -999, -999, -999, -999, -999}},
  110740. /* 707 Hz */
  110741. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110742. -999, -108, -103, -98, -93, -86, -79, -76,
  110743. -83, -81, -85, -87, -89, -93, -98, -102,
  110744. -107, -112, -999, -999, -999, -999, -999, -999,
  110745. -999, -999, -999, -999, -999, -999, -999, -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, -108, -103, -98, -93, -86, -79, -71,
  110750. -77, -74, -77, -79, -81, -84, -85, -90,
  110751. -92, -93, -92, -98, -101, -108, -112, -999,
  110752. -999, -999, -999, -999, -999, -999, -999, -999,
  110753. -999, -999, -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. -108, -103, -98, -93, -87, -78, -68, -65,
  110757. -66, -62, -65, -67, -70, -73, -75, -78,
  110758. -82, -82, -83, -84, -91, -93, -98, -102,
  110759. -106, -110, -999, -999, -999, -999, -999, -999,
  110760. -999, -999, -999, -999, -999, -999, -999, -999,
  110761. -999, -999, -999, -999, -999, -999, -999, -999},
  110762. {-999, -999, -999, -999, -999, -999, -999, -999,
  110763. -105, -100, -95, -90, -82, -74, -62, -57,
  110764. -58, -56, -51, -52, -52, -54, -54, -58,
  110765. -66, -59, -60, -63, -66, -69, -73, -79,
  110766. -83, -84, -80, -81, -81, -82, -88, -92,
  110767. -98, -105, -113, -999, -999, -999, -999, -999,
  110768. -999, -999, -999, -999, -999, -999, -999, -999},
  110769. {-999, -999, -999, -999, -999, -999, -999, -107,
  110770. -102, -97, -92, -84, -79, -69, -57, -47,
  110771. -52, -47, -44, -45, -50, -52, -42, -42,
  110772. -53, -43, -43, -48, -51, -56, -55, -52,
  110773. -57, -59, -61, -62, -67, -71, -78, -83,
  110774. -86, -94, -98, -103, -110, -999, -999, -999,
  110775. -999, -999, -999, -999, -999, -999, -999, -999},
  110776. {-999, -999, -999, -999, -999, -999, -105, -100,
  110777. -95, -90, -84, -78, -70, -61, -51, -41,
  110778. -40, -38, -40, -46, -52, -51, -41, -40,
  110779. -46, -40, -38, -38, -41, -46, -41, -46,
  110780. -47, -43, -43, -45, -41, -45, -56, -67,
  110781. -68, -83, -87, -90, -95, -102, -107, -113,
  110782. -999, -999, -999, -999, -999, -999, -999, -999}},
  110783. /* 1000 Hz */
  110784. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110785. -999, -109, -105, -101, -96, -91, -84, -77,
  110786. -82, -82, -85, -89, -94, -100, -106, -110,
  110787. -999, -999, -999, -999, -999, -999, -999, -999,
  110788. -999, -999, -999, -999, -999, -999, -999, -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, -106, -103, -98, -92, -85, -80, -71,
  110793. -75, -72, -76, -80, -84, -86, -89, -93,
  110794. -100, -107, -113, -999, -999, -999, -999, -999,
  110795. -999, -999, -999, -999, -999, -999, -999, -999,
  110796. -999, -999, -999, -999, -999, -999, -999, -999,
  110797. -999, -999, -999, -999, -999, -999, -999, -999},
  110798. {-999, -999, -999, -999, -999, -999, -999, -107,
  110799. -104, -101, -97, -92, -88, -84, -80, -64,
  110800. -66, -63, -64, -66, -69, -73, -77, -83,
  110801. -83, -86, -91, -98, -104, -111, -999, -999,
  110802. -999, -999, -999, -999, -999, -999, -999, -999,
  110803. -999, -999, -999, -999, -999, -999, -999, -999,
  110804. -999, -999, -999, -999, -999, -999, -999, -999},
  110805. {-999, -999, -999, -999, -999, -999, -999, -107,
  110806. -104, -101, -97, -92, -90, -84, -74, -57,
  110807. -58, -52, -55, -54, -50, -52, -50, -52,
  110808. -63, -62, -69, -76, -77, -78, -78, -79,
  110809. -82, -88, -94, -100, -106, -111, -999, -999,
  110810. -999, -999, -999, -999, -999, -999, -999, -999,
  110811. -999, -999, -999, -999, -999, -999, -999, -999},
  110812. {-999, -999, -999, -999, -999, -999, -106, -102,
  110813. -98, -95, -90, -85, -83, -78, -70, -50,
  110814. -50, -41, -44, -49, -47, -50, -50, -44,
  110815. -55, -46, -47, -48, -48, -54, -49, -49,
  110816. -58, -62, -71, -81, -87, -92, -97, -102,
  110817. -108, -114, -999, -999, -999, -999, -999, -999,
  110818. -999, -999, -999, -999, -999, -999, -999, -999},
  110819. {-999, -999, -999, -999, -999, -999, -106, -102,
  110820. -98, -95, -90, -85, -83, -78, -70, -45,
  110821. -43, -41, -47, -50, -51, -50, -49, -45,
  110822. -47, -41, -44, -41, -39, -43, -38, -37,
  110823. -40, -41, -44, -50, -58, -65, -73, -79,
  110824. -85, -92, -97, -101, -105, -109, -113, -999,
  110825. -999, -999, -999, -999, -999, -999, -999, -999}},
  110826. /* 1414 Hz */
  110827. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110828. -999, -999, -999, -107, -100, -95, -87, -81,
  110829. -85, -83, -88, -93, -100, -107, -114, -999,
  110830. -999, -999, -999, -999, -999, -999, -999, -999,
  110831. -999, -999, -999, -999, -999, -999, -999, -999,
  110832. -999, -999, -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, -107, -101, -95, -88, -83, -76,
  110836. -73, -72, -79, -84, -90, -95, -100, -105,
  110837. -110, -115, -999, -999, -999, -999, -999, -999,
  110838. -999, -999, -999, -999, -999, -999, -999, -999,
  110839. -999, -999, -999, -999, -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, -104, -98, -92, -87, -81, -70,
  110843. -65, -62, -67, -71, -74, -80, -85, -91,
  110844. -95, -99, -103, -108, -111, -114, -999, -999,
  110845. -999, -999, -999, -999, -999, -999, -999, -999,
  110846. -999, -999, -999, -999, -999, -999, -999, -999,
  110847. -999, -999, -999, -999, -999, -999, -999, -999},
  110848. {-999, -999, -999, -999, -999, -999, -999, -999,
  110849. -999, -999, -103, -97, -90, -85, -76, -60,
  110850. -56, -54, -60, -62, -61, -56, -63, -65,
  110851. -73, -74, -77, -75, -78, -81, -86, -87,
  110852. -88, -91, -94, -98, -103, -110, -999, -999,
  110853. -999, -999, -999, -999, -999, -999, -999, -999,
  110854. -999, -999, -999, -999, -999, -999, -999, -999},
  110855. {-999, -999, -999, -999, -999, -999, -999, -105,
  110856. -100, -97, -92, -86, -81, -79, -70, -57,
  110857. -51, -47, -51, -58, -60, -56, -53, -50,
  110858. -58, -52, -50, -50, -53, -55, -64, -69,
  110859. -71, -85, -82, -78, -81, -85, -95, -102,
  110860. -112, -999, -999, -999, -999, -999, -999, -999,
  110861. -999, -999, -999, -999, -999, -999, -999, -999},
  110862. {-999, -999, -999, -999, -999, -999, -999, -105,
  110863. -100, -97, -92, -85, -83, -79, -72, -49,
  110864. -40, -43, -43, -54, -56, -51, -50, -40,
  110865. -43, -38, -36, -35, -37, -38, -37, -44,
  110866. -54, -60, -57, -60, -70, -75, -84, -92,
  110867. -103, -112, -999, -999, -999, -999, -999, -999,
  110868. -999, -999, -999, -999, -999, -999, -999, -999}},
  110869. /* 2000 Hz */
  110870. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110871. -999, -999, -999, -110, -102, -95, -89, -82,
  110872. -83, -84, -90, -92, -99, -107, -113, -999,
  110873. -999, -999, -999, -999, -999, -999, -999, -999,
  110874. -999, -999, -999, -999, -999, -999, -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, -107, -101, -95, -89, -83, -72,
  110879. -74, -78, -85, -88, -88, -90, -92, -98,
  110880. -105, -111, -999, -999, -999, -999, -999, -999,
  110881. -999, -999, -999, -999, -999, -999, -999, -999,
  110882. -999, -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, -109, -103, -97, -93, -87, -81, -70,
  110886. -70, -67, -75, -73, -76, -79, -81, -83,
  110887. -88, -89, -97, -103, -110, -999, -999, -999,
  110888. -999, -999, -999, -999, -999, -999, -999, -999,
  110889. -999, -999, -999, -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, -107, -100, -94, -88, -83, -75, -63,
  110893. -59, -59, -63, -66, -60, -62, -67, -67,
  110894. -77, -76, -81, -88, -86, -92, -96, -102,
  110895. -109, -116, -999, -999, -999, -999, -999, -999,
  110896. -999, -999, -999, -999, -999, -999, -999, -999,
  110897. -999, -999, -999, -999, -999, -999, -999, -999},
  110898. {-999, -999, -999, -999, -999, -999, -999, -999,
  110899. -999, -105, -98, -92, -86, -81, -73, -56,
  110900. -52, -47, -55, -60, -58, -52, -51, -45,
  110901. -49, -50, -53, -54, -61, -71, -70, -69,
  110902. -78, -79, -87, -90, -96, -104, -112, -999,
  110903. -999, -999, -999, -999, -999, -999, -999, -999,
  110904. -999, -999, -999, -999, -999, -999, -999, -999},
  110905. {-999, -999, -999, -999, -999, -999, -999, -999,
  110906. -999, -103, -96, -90, -86, -78, -70, -51,
  110907. -42, -47, -48, -55, -54, -54, -53, -42,
  110908. -35, -28, -33, -38, -37, -44, -47, -49,
  110909. -54, -63, -68, -78, -82, -89, -94, -99,
  110910. -104, -109, -114, -999, -999, -999, -999, -999,
  110911. -999, -999, -999, -999, -999, -999, -999, -999}},
  110912. /* 2828 Hz */
  110913. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110914. -999, -999, -999, -999, -110, -100, -90, -79,
  110915. -85, -81, -82, -82, -89, -94, -99, -103,
  110916. -109, -115, -999, -999, -999, -999, -999, -999,
  110917. -999, -999, -999, -999, -999, -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, -105, -97, -85, -72,
  110922. -74, -70, -70, -70, -76, -85, -91, -93,
  110923. -97, -103, -109, -115, -999, -999, -999, -999,
  110924. -999, -999, -999, -999, -999, -999, -999, -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, -112, -93, -81, -68,
  110929. -62, -60, -60, -57, -63, -70, -77, -82,
  110930. -90, -93, -98, -104, -109, -113, -999, -999,
  110931. -999, -999, -999, -999, -999, -999, -999, -999,
  110932. -999, -999, -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, -113, -100, -93, -84, -63,
  110936. -58, -48, -53, -54, -52, -52, -57, -64,
  110937. -66, -76, -83, -81, -85, -85, -90, -95,
  110938. -98, -101, -103, -106, -108, -111, -999, -999,
  110939. -999, -999, -999, -999, -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, -105, -95, -86, -74, -53,
  110943. -50, -38, -43, -49, -43, -42, -39, -39,
  110944. -46, -52, -57, -56, -72, -69, -74, -81,
  110945. -87, -92, -94, -97, -99, -102, -105, -108,
  110946. -999, -999, -999, -999, -999, -999, -999, -999,
  110947. -999, -999, -999, -999, -999, -999, -999, -999},
  110948. {-999, -999, -999, -999, -999, -999, -999, -999,
  110949. -999, -999, -108, -99, -90, -76, -66, -45,
  110950. -43, -41, -44, -47, -43, -47, -40, -30,
  110951. -31, -31, -39, -33, -40, -41, -43, -53,
  110952. -59, -70, -73, -77, -79, -82, -84, -87,
  110953. -999, -999, -999, -999, -999, -999, -999, -999,
  110954. -999, -999, -999, -999, -999, -999, -999, -999}},
  110955. /* 4000 Hz */
  110956. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110957. -999, -999, -999, -999, -999, -110, -91, -76,
  110958. -75, -85, -93, -98, -104, -110, -999, -999,
  110959. -999, -999, -999, -999, -999, -999, -999, -999,
  110960. -999, -999, -999, -999, -999, -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, -110, -91, -70,
  110965. -70, -75, -86, -89, -94, -98, -101, -106,
  110966. -110, -999, -999, -999, -999, -999, -999, -999,
  110967. -999, -999, -999, -999, -999, -999, -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, -110, -95, -80, -60,
  110972. -65, -64, -74, -83, -88, -91, -95, -99,
  110973. -103, -107, -110, -999, -999, -999, -999, -999,
  110974. -999, -999, -999, -999, -999, -999, -999, -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, -110, -95, -80, -58,
  110979. -55, -49, -66, -68, -71, -78, -78, -80,
  110980. -88, -85, -89, -97, -100, -105, -110, -999,
  110981. -999, -999, -999, -999, -999, -999, -999, -999,
  110982. -999, -999, -999, -999, -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, -110, -95, -80, -53,
  110986. -52, -41, -59, -59, -49, -58, -56, -63,
  110987. -86, -79, -90, -93, -98, -103, -107, -112,
  110988. -999, -999, -999, -999, -999, -999, -999, -999,
  110989. -999, -999, -999, -999, -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, -110, -97, -91, -73, -45,
  110993. -40, -33, -53, -61, -49, -54, -50, -50,
  110994. -60, -52, -67, -74, -81, -92, -96, -100,
  110995. -105, -110, -999, -999, -999, -999, -999, -999,
  110996. -999, -999, -999, -999, -999, -999, -999, -999,
  110997. -999, -999, -999, -999, -999, -999, -999, -999}},
  110998. /* 5657 Hz */
  110999. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111000. -999, -999, -999, -113, -106, -99, -92, -77,
  111001. -80, -88, -97, -106, -115, -999, -999, -999,
  111002. -999, -999, -999, -999, -999, -999, -999, -999,
  111003. -999, -999, -999, -999, -999, -999, -999, -999,
  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, -116, -109, -102, -95, -89, -74,
  111008. -72, -88, -87, -95, -102, -109, -116, -999,
  111009. -999, -999, -999, -999, -999, -999, -999, -999,
  111010. -999, -999, -999, -999, -999, -999, -999, -999,
  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, -116, -109, -102, -95, -89, -75,
  111015. -66, -74, -77, -78, -86, -87, -90, -96,
  111016. -105, -115, -999, -999, -999, -999, -999, -999,
  111017. -999, -999, -999, -999, -999, -999, -999, -999,
  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, -115, -108, -101, -94, -88, -66,
  111022. -56, -61, -70, -65, -78, -72, -83, -84,
  111023. -93, -98, -105, -110, -999, -999, -999, -999,
  111024. -999, -999, -999, -999, -999, -999, -999, -999,
  111025. -999, -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, -110, -105, -95, -89, -82, -57,
  111029. -52, -52, -59, -56, -59, -58, -69, -67,
  111030. -88, -82, -82, -89, -94, -100, -108, -999,
  111031. -999, -999, -999, -999, -999, -999, -999, -999,
  111032. -999, -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, -110, -101, -96, -90, -83, -77, -54,
  111036. -43, -38, -50, -48, -52, -48, -42, -42,
  111037. -51, -52, -53, -59, -65, -71, -78, -85,
  111038. -95, -999, -999, -999, -999, -999, -999, -999,
  111039. -999, -999, -999, -999, -999, -999, -999, -999,
  111040. -999, -999, -999, -999, -999, -999, -999, -999}},
  111041. /* 8000 Hz */
  111042. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111043. -999, -999, -999, -999, -120, -105, -86, -68,
  111044. -78, -79, -90, -100, -110, -999, -999, -999,
  111045. -999, -999, -999, -999, -999, -999, -999, -999,
  111046. -999, -999, -999, -999, -999, -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, -120, -105, -86, -66,
  111051. -73, -77, -88, -96, -105, -115, -999, -999,
  111052. -999, -999, -999, -999, -999, -999, -999, -999,
  111053. -999, -999, -999, -999, -999, -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, -120, -105, -92, -80, -61,
  111058. -64, -68, -80, -87, -92, -100, -110, -999,
  111059. -999, -999, -999, -999, -999, -999, -999, -999,
  111060. -999, -999, -999, -999, -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, -120, -104, -91, -79, -52,
  111065. -60, -54, -64, -69, -77, -80, -82, -84,
  111066. -85, -87, -88, -90, -999, -999, -999, -999,
  111067. -999, -999, -999, -999, -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, -118, -100, -87, -77, -49,
  111072. -50, -44, -58, -61, -61, -67, -65, -62,
  111073. -62, -62, -65, -68, -999, -999, -999, -999,
  111074. -999, -999, -999, -999, -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, -115, -98, -84, -62, -49,
  111079. -44, -38, -46, -49, -49, -46, -39, -37,
  111080. -39, -40, -42, -43, -999, -999, -999, -999,
  111081. -999, -999, -999, -999, -999, -999, -999, -999,
  111082. -999, -999, -999, -999, -999, -999, -999, -999,
  111083. -999, -999, -999, -999, -999, -999, -999, -999}},
  111084. /* 11314 Hz */
  111085. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111086. -999, -999, -999, -999, -999, -110, -88, -74,
  111087. -77, -82, -82, -85, -90, -94, -99, -104,
  111088. -999, -999, -999, -999, -999, -999, -999, -999,
  111089. -999, -999, -999, -999, -999, -999, -999, -999,
  111090. -999, -999, -999, -999, -999, -999, -999, -999,
  111091. -999, -999, -999, -999, -999, -999, -999, -999},
  111092. {-999, -999, -999, -999, -999, -999, -999, -999,
  111093. -999, -999, -999, -999, -999, -110, -88, -66,
  111094. -70, -81, -80, -81, -84, -88, -91, -93,
  111095. -999, -999, -999, -999, -999, -999, -999, -999,
  111096. -999, -999, -999, -999, -999, -999, -999, -999,
  111097. -999, -999, -999, -999, -999, -999, -999, -999,
  111098. -999, -999, -999, -999, -999, -999, -999, -999},
  111099. {-999, -999, -999, -999, -999, -999, -999, -999,
  111100. -999, -999, -999, -999, -999, -110, -88, -61,
  111101. -63, -70, -71, -74, -77, -80, -83, -85,
  111102. -999, -999, -999, -999, -999, -999, -999, -999,
  111103. -999, -999, -999, -999, -999, -999, -999, -999,
  111104. -999, -999, -999, -999, -999, -999, -999, -999,
  111105. -999, -999, -999, -999, -999, -999, -999, -999},
  111106. {-999, -999, -999, -999, -999, -999, -999, -999,
  111107. -999, -999, -999, -999, -999, -110, -86, -62,
  111108. -63, -62, -62, -58, -52, -50, -50, -52,
  111109. -54, -999, -999, -999, -999, -999, -999, -999,
  111110. -999, -999, -999, -999, -999, -999, -999, -999,
  111111. -999, -999, -999, -999, -999, -999, -999, -999,
  111112. -999, -999, -999, -999, -999, -999, -999, -999},
  111113. {-999, -999, -999, -999, -999, -999, -999, -999,
  111114. -999, -999, -999, -999, -118, -108, -84, -53,
  111115. -50, -50, -50, -55, -47, -45, -40, -40,
  111116. -40, -999, -999, -999, -999, -999, -999, -999,
  111117. -999, -999, -999, -999, -999, -999, -999, -999,
  111118. -999, -999, -999, -999, -999, -999, -999, -999,
  111119. -999, -999, -999, -999, -999, -999, -999, -999},
  111120. {-999, -999, -999, -999, -999, -999, -999, -999,
  111121. -999, -999, -999, -999, -118, -100, -73, -43,
  111122. -37, -42, -43, -53, -38, -37, -35, -35,
  111123. -38, -999, -999, -999, -999, -999, -999, -999,
  111124. -999, -999, -999, -999, -999, -999, -999, -999,
  111125. -999, -999, -999, -999, -999, -999, -999, -999,
  111126. -999, -999, -999, -999, -999, -999, -999, -999}},
  111127. /* 16000 Hz */
  111128. {{-999, -999, -999, -999, -999, -999, -999, -999,
  111129. -999, -999, -999, -110, -100, -91, -84, -74,
  111130. -80, -80, -80, -80, -80, -999, -999, -999,
  111131. -999, -999, -999, -999, -999, -999, -999, -999,
  111132. -999, -999, -999, -999, -999, -999, -999, -999,
  111133. -999, -999, -999, -999, -999, -999, -999, -999,
  111134. -999, -999, -999, -999, -999, -999, -999, -999},
  111135. {-999, -999, -999, -999, -999, -999, -999, -999,
  111136. -999, -999, -999, -110, -100, -91, -84, -74,
  111137. -68, -68, -68, -68, -68, -999, -999, -999,
  111138. -999, -999, -999, -999, -999, -999, -999, -999,
  111139. -999, -999, -999, -999, -999, -999, -999, -999,
  111140. -999, -999, -999, -999, -999, -999, -999, -999,
  111141. -999, -999, -999, -999, -999, -999, -999, -999},
  111142. {-999, -999, -999, -999, -999, -999, -999, -999,
  111143. -999, -999, -999, -110, -100, -86, -78, -70,
  111144. -60, -45, -30, -21, -999, -999, -999, -999,
  111145. -999, -999, -999, -999, -999, -999, -999, -999,
  111146. -999, -999, -999, -999, -999, -999, -999, -999,
  111147. -999, -999, -999, -999, -999, -999, -999, -999,
  111148. -999, -999, -999, -999, -999, -999, -999, -999},
  111149. {-999, -999, -999, -999, -999, -999, -999, -999,
  111150. -999, -999, -999, -110, -100, -87, -78, -67,
  111151. -48, -38, -29, -21, -999, -999, -999, -999,
  111152. -999, -999, -999, -999, -999, -999, -999, -999,
  111153. -999, -999, -999, -999, -999, -999, -999, -999,
  111154. -999, -999, -999, -999, -999, -999, -999, -999,
  111155. -999, -999, -999, -999, -999, -999, -999, -999},
  111156. {-999, -999, -999, -999, -999, -999, -999, -999,
  111157. -999, -999, -999, -110, -100, -86, -69, -56,
  111158. -45, -35, -33, -29, -999, -999, -999, -999,
  111159. -999, -999, -999, -999, -999, -999, -999, -999,
  111160. -999, -999, -999, -999, -999, -999, -999, -999,
  111161. -999, -999, -999, -999, -999, -999, -999, -999,
  111162. -999, -999, -999, -999, -999, -999, -999, -999},
  111163. {-999, -999, -999, -999, -999, -999, -999, -999,
  111164. -999, -999, -999, -110, -100, -83, -71, -48,
  111165. -27, -38, -37, -34, -999, -999, -999, -999,
  111166. -999, -999, -999, -999, -999, -999, -999, -999,
  111167. -999, -999, -999, -999, -999, -999, -999, -999,
  111168. -999, -999, -999, -999, -999, -999, -999, -999,
  111169. -999, -999, -999, -999, -999, -999, -999, -999}}
  111170. };
  111171. #endif
  111172. /********* End of inlined file: masking.h *********/
  111173. #define NEGINF -9999.f
  111174. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  111175. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  111176. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  111177. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111178. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111179. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  111180. look->channels=vi->channels;
  111181. look->ampmax=-9999.;
  111182. look->gi=gi;
  111183. return(look);
  111184. }
  111185. void _vp_global_free(vorbis_look_psy_global *look){
  111186. if(look){
  111187. memset(look,0,sizeof(*look));
  111188. _ogg_free(look);
  111189. }
  111190. }
  111191. void _vi_gpsy_free(vorbis_info_psy_global *i){
  111192. if(i){
  111193. memset(i,0,sizeof(*i));
  111194. _ogg_free(i);
  111195. }
  111196. }
  111197. void _vi_psy_free(vorbis_info_psy *i){
  111198. if(i){
  111199. memset(i,0,sizeof(*i));
  111200. _ogg_free(i);
  111201. }
  111202. }
  111203. static void min_curve(float *c,
  111204. float *c2){
  111205. int i;
  111206. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  111207. }
  111208. static void max_curve(float *c,
  111209. float *c2){
  111210. int i;
  111211. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  111212. }
  111213. static void attenuate_curve(float *c,float att){
  111214. int i;
  111215. for(i=0;i<EHMER_MAX;i++)
  111216. c[i]+=att;
  111217. }
  111218. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  111219. float center_boost, float center_decay_rate){
  111220. int i,j,k,m;
  111221. float ath[EHMER_MAX];
  111222. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  111223. float athc[P_LEVELS][EHMER_MAX];
  111224. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  111225. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  111226. memset(workc,0,sizeof(workc));
  111227. for(i=0;i<P_BANDS;i++){
  111228. /* we add back in the ATH to avoid low level curves falling off to
  111229. -infinity and unnecessarily cutting off high level curves in the
  111230. curve limiting (last step). */
  111231. /* A half-band's settings must be valid over the whole band, and
  111232. it's better to mask too little than too much */
  111233. int ath_offset=i*4;
  111234. for(j=0;j<EHMER_MAX;j++){
  111235. float min=999.;
  111236. for(k=0;k<4;k++)
  111237. if(j+k+ath_offset<MAX_ATH){
  111238. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  111239. }else{
  111240. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  111241. }
  111242. ath[j]=min;
  111243. }
  111244. /* copy curves into working space, replicate the 50dB curve to 30
  111245. and 40, replicate the 100dB curve to 110 */
  111246. for(j=0;j<6;j++)
  111247. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  111248. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  111249. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  111250. /* apply centered curve boost/decay */
  111251. for(j=0;j<P_LEVELS;j++){
  111252. for(k=0;k<EHMER_MAX;k++){
  111253. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  111254. if(adj<0. && center_boost>0)adj=0.;
  111255. if(adj>0. && center_boost<0)adj=0.;
  111256. workc[i][j][k]+=adj;
  111257. }
  111258. }
  111259. /* normalize curves so the driving amplitude is 0dB */
  111260. /* make temp curves with the ATH overlayed */
  111261. for(j=0;j<P_LEVELS;j++){
  111262. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  111263. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  111264. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  111265. max_curve(athc[j],workc[i][j]);
  111266. }
  111267. /* Now limit the louder curves.
  111268. the idea is this: We don't know what the playback attenuation
  111269. will be; 0dB SL moves every time the user twiddles the volume
  111270. knob. So that means we have to use a single 'most pessimal' curve
  111271. for all masking amplitudes, right? Wrong. The *loudest* sound
  111272. can be in (we assume) a range of ...+100dB] SL. However, sounds
  111273. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  111274. etc... */
  111275. for(j=1;j<P_LEVELS;j++){
  111276. min_curve(athc[j],athc[j-1]);
  111277. min_curve(workc[i][j],athc[j]);
  111278. }
  111279. }
  111280. for(i=0;i<P_BANDS;i++){
  111281. int hi_curve,lo_curve,bin;
  111282. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  111283. /* low frequency curves are measured with greater resolution than
  111284. the MDCT/FFT will actually give us; we want the curve applied
  111285. to the tone data to be pessimistic and thus apply the minimum
  111286. masking possible for a given bin. That means that a single bin
  111287. could span more than one octave and that the curve will be a
  111288. composite of multiple octaves. It also may mean that a single
  111289. bin may span > an eighth of an octave and that the eighth
  111290. octave values may also be composited. */
  111291. /* which octave curves will we be compositing? */
  111292. bin=floor(fromOC(i*.5)/binHz);
  111293. lo_curve= ceil(toOC(bin*binHz+1)*2);
  111294. hi_curve= floor(toOC((bin+1)*binHz)*2);
  111295. if(lo_curve>i)lo_curve=i;
  111296. if(lo_curve<0)lo_curve=0;
  111297. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  111298. for(m=0;m<P_LEVELS;m++){
  111299. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  111300. for(j=0;j<n;j++)brute_buffer[j]=999.;
  111301. /* render the curve into bins, then pull values back into curve.
  111302. The point is that any inherent subsampling aliasing results in
  111303. a safe minimum */
  111304. for(k=lo_curve;k<=hi_curve;k++){
  111305. int l=0;
  111306. for(j=0;j<EHMER_MAX;j++){
  111307. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  111308. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  111309. if(lo_bin<0)lo_bin=0;
  111310. if(lo_bin>n)lo_bin=n;
  111311. if(lo_bin<l)l=lo_bin;
  111312. if(hi_bin<0)hi_bin=0;
  111313. if(hi_bin>n)hi_bin=n;
  111314. for(;l<hi_bin && l<n;l++)
  111315. if(brute_buffer[l]>workc[k][m][j])
  111316. brute_buffer[l]=workc[k][m][j];
  111317. }
  111318. for(;l<n;l++)
  111319. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  111320. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  111321. }
  111322. /* be equally paranoid about being valid up to next half ocatve */
  111323. if(i+1<P_BANDS){
  111324. int l=0;
  111325. k=i+1;
  111326. for(j=0;j<EHMER_MAX;j++){
  111327. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  111328. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  111329. if(lo_bin<0)lo_bin=0;
  111330. if(lo_bin>n)lo_bin=n;
  111331. if(lo_bin<l)l=lo_bin;
  111332. if(hi_bin<0)hi_bin=0;
  111333. if(hi_bin>n)hi_bin=n;
  111334. for(;l<hi_bin && l<n;l++)
  111335. if(brute_buffer[l]>workc[k][m][j])
  111336. brute_buffer[l]=workc[k][m][j];
  111337. }
  111338. for(;l<n;l++)
  111339. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  111340. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  111341. }
  111342. for(j=0;j<EHMER_MAX;j++){
  111343. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  111344. if(bin<0){
  111345. ret[i][m][j+2]=-999.;
  111346. }else{
  111347. if(bin>=n){
  111348. ret[i][m][j+2]=-999.;
  111349. }else{
  111350. ret[i][m][j+2]=brute_buffer[bin];
  111351. }
  111352. }
  111353. }
  111354. /* add fenceposts */
  111355. for(j=0;j<EHMER_OFFSET;j++)
  111356. if(ret[i][m][j+2]>-200.f)break;
  111357. ret[i][m][0]=j;
  111358. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  111359. if(ret[i][m][j+2]>-200.f)
  111360. break;
  111361. ret[i][m][1]=j;
  111362. }
  111363. }
  111364. return(ret);
  111365. }
  111366. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  111367. vorbis_info_psy_global *gi,int n,long rate){
  111368. long i,j,lo=-99,hi=1;
  111369. long maxoc;
  111370. memset(p,0,sizeof(*p));
  111371. p->eighth_octave_lines=gi->eighth_octave_lines;
  111372. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  111373. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  111374. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  111375. p->total_octave_lines=maxoc-p->firstoc+1;
  111376. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  111377. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  111378. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  111379. p->vi=vi;
  111380. p->n=n;
  111381. p->rate=rate;
  111382. /* AoTuV HF weighting */
  111383. p->m_val = 1.;
  111384. if(rate < 26000) p->m_val = 0;
  111385. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  111386. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  111387. /* set up the lookups for a given blocksize and sample rate */
  111388. for(i=0,j=0;i<MAX_ATH-1;i++){
  111389. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  111390. float base=ATH[i];
  111391. if(j<endpos){
  111392. float delta=(ATH[i+1]-base)/(endpos-j);
  111393. for(;j<endpos && j<n;j++){
  111394. p->ath[j]=base+100.;
  111395. base+=delta;
  111396. }
  111397. }
  111398. }
  111399. for(i=0;i<n;i++){
  111400. float bark=toBARK(rate/(2*n)*i);
  111401. for(;lo+vi->noisewindowlomin<i &&
  111402. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  111403. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  111404. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  111405. p->bark[i]=((lo-1)<<16)+(hi-1);
  111406. }
  111407. for(i=0;i<n;i++)
  111408. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  111409. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  111410. vi->tone_centerboost,vi->tone_decay);
  111411. /* set up rolling noise median */
  111412. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  111413. for(i=0;i<P_NOISECURVES;i++)
  111414. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  111415. for(i=0;i<n;i++){
  111416. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  111417. int inthalfoc;
  111418. float del;
  111419. if(halfoc<0)halfoc=0;
  111420. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  111421. inthalfoc=(int)halfoc;
  111422. del=halfoc-inthalfoc;
  111423. for(j=0;j<P_NOISECURVES;j++)
  111424. p->noiseoffset[j][i]=
  111425. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  111426. p->vi->noiseoff[j][inthalfoc+1]*del;
  111427. }
  111428. #if 0
  111429. {
  111430. static int ls=0;
  111431. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  111432. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  111433. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  111434. }
  111435. #endif
  111436. }
  111437. void _vp_psy_clear(vorbis_look_psy *p){
  111438. int i,j;
  111439. if(p){
  111440. if(p->ath)_ogg_free(p->ath);
  111441. if(p->octave)_ogg_free(p->octave);
  111442. if(p->bark)_ogg_free(p->bark);
  111443. if(p->tonecurves){
  111444. for(i=0;i<P_BANDS;i++){
  111445. for(j=0;j<P_LEVELS;j++){
  111446. _ogg_free(p->tonecurves[i][j]);
  111447. }
  111448. _ogg_free(p->tonecurves[i]);
  111449. }
  111450. _ogg_free(p->tonecurves);
  111451. }
  111452. if(p->noiseoffset){
  111453. for(i=0;i<P_NOISECURVES;i++){
  111454. _ogg_free(p->noiseoffset[i]);
  111455. }
  111456. _ogg_free(p->noiseoffset);
  111457. }
  111458. memset(p,0,sizeof(*p));
  111459. }
  111460. }
  111461. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  111462. static void seed_curve(float *seed,
  111463. const float **curves,
  111464. float amp,
  111465. int oc, int n,
  111466. int linesper,float dBoffset){
  111467. int i,post1;
  111468. int seedptr;
  111469. const float *posts,*curve;
  111470. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  111471. choice=max(choice,0);
  111472. choice=min(choice,P_LEVELS-1);
  111473. posts=curves[choice];
  111474. curve=posts+2;
  111475. post1=(int)posts[1];
  111476. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  111477. for(i=posts[0];i<post1;i++){
  111478. if(seedptr>0){
  111479. float lin=amp+curve[i];
  111480. if(seed[seedptr]<lin)seed[seedptr]=lin;
  111481. }
  111482. seedptr+=linesper;
  111483. if(seedptr>=n)break;
  111484. }
  111485. }
  111486. static void seed_loop(vorbis_look_psy *p,
  111487. const float ***curves,
  111488. const float *f,
  111489. const float *flr,
  111490. float *seed,
  111491. float specmax){
  111492. vorbis_info_psy *vi=p->vi;
  111493. long n=p->n,i;
  111494. float dBoffset=vi->max_curve_dB-specmax;
  111495. /* prime the working vector with peak values */
  111496. for(i=0;i<n;i++){
  111497. float max=f[i];
  111498. long oc=p->octave[i];
  111499. while(i+1<n && p->octave[i+1]==oc){
  111500. i++;
  111501. if(f[i]>max)max=f[i];
  111502. }
  111503. if(max+6.f>flr[i]){
  111504. oc=oc>>p->shiftoc;
  111505. if(oc>=P_BANDS)oc=P_BANDS-1;
  111506. if(oc<0)oc=0;
  111507. seed_curve(seed,
  111508. curves[oc],
  111509. max,
  111510. p->octave[i]-p->firstoc,
  111511. p->total_octave_lines,
  111512. p->eighth_octave_lines,
  111513. dBoffset);
  111514. }
  111515. }
  111516. }
  111517. static void seed_chase(float *seeds, int linesper, long n){
  111518. long *posstack=(long*)alloca(n*sizeof(*posstack));
  111519. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  111520. long stack=0;
  111521. long pos=0;
  111522. long i;
  111523. for(i=0;i<n;i++){
  111524. if(stack<2){
  111525. posstack[stack]=i;
  111526. ampstack[stack++]=seeds[i];
  111527. }else{
  111528. while(1){
  111529. if(seeds[i]<ampstack[stack-1]){
  111530. posstack[stack]=i;
  111531. ampstack[stack++]=seeds[i];
  111532. break;
  111533. }else{
  111534. if(i<posstack[stack-1]+linesper){
  111535. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  111536. i<posstack[stack-2]+linesper){
  111537. /* we completely overlap, making stack-1 irrelevant. pop it */
  111538. stack--;
  111539. continue;
  111540. }
  111541. }
  111542. posstack[stack]=i;
  111543. ampstack[stack++]=seeds[i];
  111544. break;
  111545. }
  111546. }
  111547. }
  111548. }
  111549. /* the stack now contains only the positions that are relevant. Scan
  111550. 'em straight through */
  111551. for(i=0;i<stack;i++){
  111552. long endpos;
  111553. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  111554. endpos=posstack[i+1];
  111555. }else{
  111556. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  111557. discarded in short frames */
  111558. }
  111559. if(endpos>n)endpos=n;
  111560. for(;pos<endpos;pos++)
  111561. seeds[pos]=ampstack[i];
  111562. }
  111563. /* there. Linear time. I now remember this was on a problem set I
  111564. had in Grad Skool... I didn't solve it at the time ;-) */
  111565. }
  111566. /* bleaugh, this is more complicated than it needs to be */
  111567. #include<stdio.h>
  111568. static void max_seeds(vorbis_look_psy *p,
  111569. float *seed,
  111570. float *flr){
  111571. long n=p->total_octave_lines;
  111572. int linesper=p->eighth_octave_lines;
  111573. long linpos=0;
  111574. long pos;
  111575. seed_chase(seed,linesper,n); /* for masking */
  111576. pos=p->octave[0]-p->firstoc-(linesper>>1);
  111577. while(linpos+1<p->n){
  111578. float minV=seed[pos];
  111579. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  111580. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  111581. while(pos+1<=end){
  111582. pos++;
  111583. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  111584. minV=seed[pos];
  111585. }
  111586. end=pos+p->firstoc;
  111587. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  111588. if(flr[linpos]<minV)flr[linpos]=minV;
  111589. }
  111590. {
  111591. float minV=seed[p->total_octave_lines-1];
  111592. for(;linpos<p->n;linpos++)
  111593. if(flr[linpos]<minV)flr[linpos]=minV;
  111594. }
  111595. }
  111596. static void bark_noise_hybridmp(int n,const long *b,
  111597. const float *f,
  111598. float *noise,
  111599. const float offset,
  111600. const int fixed){
  111601. float *N=(float*) alloca(n*sizeof(*N));
  111602. float *X=(float*) alloca(n*sizeof(*N));
  111603. float *XX=(float*) alloca(n*sizeof(*N));
  111604. float *Y=(float*) alloca(n*sizeof(*N));
  111605. float *XY=(float*) alloca(n*sizeof(*N));
  111606. float tN, tX, tXX, tY, tXY;
  111607. int i;
  111608. int lo, hi;
  111609. float R, A, B, D;
  111610. float w, x, y;
  111611. tN = tX = tXX = tY = tXY = 0.f;
  111612. y = f[0] + offset;
  111613. if (y < 1.f) y = 1.f;
  111614. w = y * y * .5;
  111615. tN += w;
  111616. tX += w;
  111617. tY += w * y;
  111618. N[0] = tN;
  111619. X[0] = tX;
  111620. XX[0] = tXX;
  111621. Y[0] = tY;
  111622. XY[0] = tXY;
  111623. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  111624. y = f[i] + offset;
  111625. if (y < 1.f) y = 1.f;
  111626. w = y * y;
  111627. tN += w;
  111628. tX += w * x;
  111629. tXX += w * x * x;
  111630. tY += w * y;
  111631. tXY += w * x * y;
  111632. N[i] = tN;
  111633. X[i] = tX;
  111634. XX[i] = tXX;
  111635. Y[i] = tY;
  111636. XY[i] = tXY;
  111637. }
  111638. for (i = 0, x = 0.f;; i++, x += 1.f) {
  111639. lo = b[i] >> 16;
  111640. if( lo>=0 ) break;
  111641. hi = b[i] & 0xffff;
  111642. tN = N[hi] + N[-lo];
  111643. tX = X[hi] - X[-lo];
  111644. tXX = XX[hi] + XX[-lo];
  111645. tY = Y[hi] + Y[-lo];
  111646. tXY = XY[hi] - XY[-lo];
  111647. A = tY * tXX - tX * tXY;
  111648. B = tN * tXY - tX * tY;
  111649. D = tN * tXX - tX * tX;
  111650. R = (A + x * B) / D;
  111651. if (R < 0.f)
  111652. R = 0.f;
  111653. noise[i] = R - offset;
  111654. }
  111655. for ( ;; i++, x += 1.f) {
  111656. lo = b[i] >> 16;
  111657. hi = b[i] & 0xffff;
  111658. if(hi>=n)break;
  111659. tN = N[hi] - N[lo];
  111660. tX = X[hi] - X[lo];
  111661. tXX = XX[hi] - XX[lo];
  111662. tY = Y[hi] - Y[lo];
  111663. tXY = XY[hi] - XY[lo];
  111664. A = tY * tXX - tX * tXY;
  111665. B = tN * tXY - tX * tY;
  111666. D = tN * tXX - tX * tX;
  111667. R = (A + x * B) / D;
  111668. if (R < 0.f) R = 0.f;
  111669. noise[i] = R - offset;
  111670. }
  111671. for ( ; i < n; i++, x += 1.f) {
  111672. R = (A + x * B) / D;
  111673. if (R < 0.f) R = 0.f;
  111674. noise[i] = R - offset;
  111675. }
  111676. if (fixed <= 0) return;
  111677. for (i = 0, x = 0.f;; i++, x += 1.f) {
  111678. hi = i + fixed / 2;
  111679. lo = hi - fixed;
  111680. if(lo>=0)break;
  111681. tN = N[hi] + N[-lo];
  111682. tX = X[hi] - X[-lo];
  111683. tXX = XX[hi] + XX[-lo];
  111684. tY = Y[hi] + Y[-lo];
  111685. tXY = XY[hi] - XY[-lo];
  111686. A = tY * tXX - tX * tXY;
  111687. B = tN * tXY - tX * tY;
  111688. D = tN * tXX - tX * tX;
  111689. R = (A + x * B) / D;
  111690. if (R - offset < noise[i]) noise[i] = R - offset;
  111691. }
  111692. for ( ;; i++, x += 1.f) {
  111693. hi = i + fixed / 2;
  111694. lo = hi - fixed;
  111695. if(hi>=n)break;
  111696. tN = N[hi] - N[lo];
  111697. tX = X[hi] - X[lo];
  111698. tXX = XX[hi] - XX[lo];
  111699. tY = Y[hi] - Y[lo];
  111700. tXY = XY[hi] - XY[lo];
  111701. A = tY * tXX - tX * tXY;
  111702. B = tN * tXY - tX * tY;
  111703. D = tN * tXX - tX * tX;
  111704. R = (A + x * B) / D;
  111705. if (R - offset < noise[i]) noise[i] = R - offset;
  111706. }
  111707. for ( ; i < n; i++, x += 1.f) {
  111708. R = (A + x * B) / D;
  111709. if (R - offset < noise[i]) noise[i] = R - offset;
  111710. }
  111711. }
  111712. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  111713. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  111714. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  111715. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  111716. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  111717. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  111718. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  111719. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  111720. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  111721. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  111722. 973377.F, 913981.F, 858210.F, 805842.F,
  111723. 756669.F, 710497.F, 667142.F, 626433.F,
  111724. 588208.F, 552316.F, 518613.F, 486967.F,
  111725. 457252.F, 429351.F, 403152.F, 378551.F,
  111726. 355452.F, 333762.F, 313396.F, 294273.F,
  111727. 276316.F, 259455.F, 243623.F, 228757.F,
  111728. 214798.F, 201691.F, 189384.F, 177828.F,
  111729. 166977.F, 156788.F, 147221.F, 138237.F,
  111730. 129802.F, 121881.F, 114444.F, 107461.F,
  111731. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  111732. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  111733. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  111734. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  111735. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  111736. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  111737. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  111738. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  111739. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  111740. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  111741. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  111742. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  111743. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  111744. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  111745. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  111746. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  111747. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  111748. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  111749. 1084.32F, 1018.15F, 956.024F, 897.687F,
  111750. 842.910F, 791.475F, 743.179F, 697.830F,
  111751. 655.249F, 615.265F, 577.722F, 542.469F,
  111752. 509.367F, 478.286F, 449.101F, 421.696F,
  111753. 395.964F, 371.803F, 349.115F, 327.812F,
  111754. 307.809F, 289.026F, 271.390F, 254.830F,
  111755. 239.280F, 224.679F, 210.969F, 198.096F,
  111756. 186.008F, 174.658F, 164.000F, 153.993F,
  111757. 144.596F, 135.773F, 127.488F, 119.708F,
  111758. 112.404F, 105.545F, 99.1046F, 93.0572F,
  111759. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  111760. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  111761. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  111762. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  111763. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  111764. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  111765. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  111766. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  111767. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  111768. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  111769. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  111770. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  111771. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  111772. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  111773. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  111774. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  111775. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  111776. 1.20790F, 1.13419F, 1.06499F, 1.F
  111777. };
  111778. void _vp_remove_floor(vorbis_look_psy *p,
  111779. float *mdct,
  111780. int *codedflr,
  111781. float *residue,
  111782. int sliding_lowpass){
  111783. int i,n=p->n;
  111784. if(sliding_lowpass>n)sliding_lowpass=n;
  111785. for(i=0;i<sliding_lowpass;i++){
  111786. residue[i]=
  111787. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  111788. }
  111789. for(;i<n;i++)
  111790. residue[i]=0.;
  111791. }
  111792. void _vp_noisemask(vorbis_look_psy *p,
  111793. float *logmdct,
  111794. float *logmask){
  111795. int i,n=p->n;
  111796. float *work=(float*) alloca(n*sizeof(*work));
  111797. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  111798. 140.,-1);
  111799. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  111800. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  111801. p->vi->noisewindowfixed);
  111802. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  111803. #if 0
  111804. {
  111805. static int seq=0;
  111806. float work2[n];
  111807. for(i=0;i<n;i++){
  111808. work2[i]=logmask[i]+work[i];
  111809. }
  111810. if(seq&1)
  111811. _analysis_output("median2R",seq/2,work,n,1,0,0);
  111812. else
  111813. _analysis_output("median2L",seq/2,work,n,1,0,0);
  111814. if(seq&1)
  111815. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  111816. else
  111817. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  111818. seq++;
  111819. }
  111820. #endif
  111821. for(i=0;i<n;i++){
  111822. int dB=logmask[i]+.5;
  111823. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  111824. if(dB<0)dB=0;
  111825. logmask[i]= work[i]+p->vi->noisecompand[dB];
  111826. }
  111827. }
  111828. void _vp_tonemask(vorbis_look_psy *p,
  111829. float *logfft,
  111830. float *logmask,
  111831. float global_specmax,
  111832. float local_specmax){
  111833. int i,n=p->n;
  111834. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  111835. float att=local_specmax+p->vi->ath_adjatt;
  111836. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  111837. /* set the ATH (floating below localmax, not global max by a
  111838. specified att) */
  111839. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  111840. for(i=0;i<n;i++)
  111841. logmask[i]=p->ath[i]+att;
  111842. /* tone masking */
  111843. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  111844. max_seeds(p,seed,logmask);
  111845. }
  111846. void _vp_offset_and_mix(vorbis_look_psy *p,
  111847. float *noise,
  111848. float *tone,
  111849. int offset_select,
  111850. float *logmask,
  111851. float *mdct,
  111852. float *logmdct){
  111853. int i,n=p->n;
  111854. float de, coeffi, cx;/* AoTuV */
  111855. float toneatt=p->vi->tone_masteratt[offset_select];
  111856. cx = p->m_val;
  111857. for(i=0;i<n;i++){
  111858. float val= noise[i]+p->noiseoffset[offset_select][i];
  111859. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  111860. logmask[i]=max(val,tone[i]+toneatt);
  111861. /* AoTuV */
  111862. /** @ M1 **
  111863. The following codes improve a noise problem.
  111864. A fundamental idea uses the value of masking and carries out
  111865. the relative compensation of the MDCT.
  111866. However, this code is not perfect and all noise problems cannot be solved.
  111867. by Aoyumi @ 2004/04/18
  111868. */
  111869. if(offset_select == 1) {
  111870. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  111871. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  111872. if(val > coeffi){
  111873. /* mdct value is > -17.2 dB below floor */
  111874. de = 1.0-((val-coeffi)*0.005*cx);
  111875. /* pro-rated attenuation:
  111876. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  111877. -0.77 dB boost if mdct value is 0dB (relative to floor)
  111878. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  111879. etc... */
  111880. if(de < 0) de = 0.0001;
  111881. }else
  111882. /* mdct value is <= -17.2 dB below floor */
  111883. de = 1.0-((val-coeffi)*0.0003*cx);
  111884. /* pro-rated attenuation:
  111885. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  111886. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  111887. etc... */
  111888. mdct[i] *= de;
  111889. }
  111890. }
  111891. }
  111892. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  111893. vorbis_info *vi=vd->vi;
  111894. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111895. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111896. int n=ci->blocksizes[vd->W]/2;
  111897. float secs=(float)n/vi->rate;
  111898. amp+=secs*gi->ampmax_att_per_sec;
  111899. if(amp<-9999)amp=-9999;
  111900. return(amp);
  111901. }
  111902. static void couple_lossless(float A, float B,
  111903. float *qA, float *qB){
  111904. int test1=fabs(*qA)>fabs(*qB);
  111905. test1-= fabs(*qA)<fabs(*qB);
  111906. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  111907. if(test1==1){
  111908. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  111909. }else{
  111910. float temp=*qB;
  111911. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  111912. *qA=temp;
  111913. }
  111914. if(*qB>fabs(*qA)*1.9999f){
  111915. *qB= -fabs(*qA)*2.f;
  111916. *qA= -*qA;
  111917. }
  111918. }
  111919. static float hypot_lookup[32]={
  111920. -0.009935, -0.011245, -0.012726, -0.014397,
  111921. -0.016282, -0.018407, -0.020800, -0.023494,
  111922. -0.026522, -0.029923, -0.033737, -0.038010,
  111923. -0.042787, -0.048121, -0.054064, -0.060671,
  111924. -0.068000, -0.076109, -0.085054, -0.094892,
  111925. -0.105675, -0.117451, -0.130260, -0.144134,
  111926. -0.159093, -0.175146, -0.192286, -0.210490,
  111927. -0.229718, -0.249913, -0.271001, -0.292893};
  111928. static void precomputed_couple_point(float premag,
  111929. int floorA,int floorB,
  111930. float *mag, float *ang){
  111931. int test=(floorA>floorB)-1;
  111932. int offset=31-abs(floorA-floorB);
  111933. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  111934. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  111935. *mag=premag*floormag;
  111936. *ang=0.f;
  111937. }
  111938. /* just like below, this is currently set up to only do
  111939. single-step-depth coupling. Otherwise, we'd have to do more
  111940. copying (which will be inevitable later) */
  111941. /* doing the real circular magnitude calculation is audibly superior
  111942. to (A+B)/sqrt(2) */
  111943. static float dipole_hypot(float a, float b){
  111944. if(a>0.){
  111945. if(b>0.)return sqrt(a*a+b*b);
  111946. if(a>-b)return sqrt(a*a-b*b);
  111947. return -sqrt(b*b-a*a);
  111948. }
  111949. if(b<0.)return -sqrt(a*a+b*b);
  111950. if(-a>b)return -sqrt(a*a-b*b);
  111951. return sqrt(b*b-a*a);
  111952. }
  111953. static float round_hypot(float a, float b){
  111954. if(a>0.){
  111955. if(b>0.)return sqrt(a*a+b*b);
  111956. if(a>-b)return sqrt(a*a+b*b);
  111957. return -sqrt(b*b+a*a);
  111958. }
  111959. if(b<0.)return -sqrt(a*a+b*b);
  111960. if(-a>b)return -sqrt(a*a+b*b);
  111961. return sqrt(b*b+a*a);
  111962. }
  111963. /* revert to round hypot for now */
  111964. float **_vp_quantize_couple_memo(vorbis_block *vb,
  111965. vorbis_info_psy_global *g,
  111966. vorbis_look_psy *p,
  111967. vorbis_info_mapping0 *vi,
  111968. float **mdct){
  111969. int i,j,n=p->n;
  111970. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  111971. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  111972. for(i=0;i<vi->coupling_steps;i++){
  111973. float *mdctM=mdct[vi->coupling_mag[i]];
  111974. float *mdctA=mdct[vi->coupling_ang[i]];
  111975. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  111976. for(j=0;j<limit;j++)
  111977. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  111978. for(;j<n;j++)
  111979. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  111980. }
  111981. return(ret);
  111982. }
  111983. /* this is for per-channel noise normalization */
  111984. static int apsort(const void *a, const void *b){
  111985. float f1=fabs(**(float**)a);
  111986. float f2=fabs(**(float**)b);
  111987. return (f1<f2)-(f1>f2);
  111988. }
  111989. int **_vp_quantize_couple_sort(vorbis_block *vb,
  111990. vorbis_look_psy *p,
  111991. vorbis_info_mapping0 *vi,
  111992. float **mags){
  111993. if(p->vi->normal_point_p){
  111994. int i,j,k,n=p->n;
  111995. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  111996. int partition=p->vi->normal_partition;
  111997. float **work=(float**) alloca(sizeof(*work)*partition);
  111998. for(i=0;i<vi->coupling_steps;i++){
  111999. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  112000. for(j=0;j<n;j+=partition){
  112001. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  112002. qsort(work,partition,sizeof(*work),apsort);
  112003. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  112004. }
  112005. }
  112006. return(ret);
  112007. }
  112008. return(NULL);
  112009. }
  112010. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  112011. float *magnitudes,int *sortedindex){
  112012. int i,j,n=p->n;
  112013. vorbis_info_psy *vi=p->vi;
  112014. int partition=vi->normal_partition;
  112015. float **work=(float**) alloca(sizeof(*work)*partition);
  112016. int start=vi->normal_start;
  112017. for(j=start;j<n;j+=partition){
  112018. if(j+partition>n)partition=n-j;
  112019. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  112020. qsort(work,partition,sizeof(*work),apsort);
  112021. for(i=0;i<partition;i++){
  112022. sortedindex[i+j-start]=work[i]-magnitudes;
  112023. }
  112024. }
  112025. }
  112026. void _vp_noise_normalize(vorbis_look_psy *p,
  112027. float *in,float *out,int *sortedindex){
  112028. int flag=0,i,j=0,n=p->n;
  112029. vorbis_info_psy *vi=p->vi;
  112030. int partition=vi->normal_partition;
  112031. int start=vi->normal_start;
  112032. if(start>n)start=n;
  112033. if(vi->normal_channel_p){
  112034. for(;j<start;j++)
  112035. out[j]=rint(in[j]);
  112036. for(;j+partition<=n;j+=partition){
  112037. float acc=0.;
  112038. int k;
  112039. for(i=j;i<j+partition;i++)
  112040. acc+=in[i]*in[i];
  112041. for(i=0;i<partition;i++){
  112042. k=sortedindex[i+j-start];
  112043. if(in[k]*in[k]>=.25f){
  112044. out[k]=rint(in[k]);
  112045. acc-=in[k]*in[k];
  112046. flag=1;
  112047. }else{
  112048. if(acc<vi->normal_thresh)break;
  112049. out[k]=unitnorm(in[k]);
  112050. acc-=1.;
  112051. }
  112052. }
  112053. for(;i<partition;i++){
  112054. k=sortedindex[i+j-start];
  112055. out[k]=0.;
  112056. }
  112057. }
  112058. }
  112059. for(;j<n;j++)
  112060. out[j]=rint(in[j]);
  112061. }
  112062. void _vp_couple(int blobno,
  112063. vorbis_info_psy_global *g,
  112064. vorbis_look_psy *p,
  112065. vorbis_info_mapping0 *vi,
  112066. float **res,
  112067. float **mag_memo,
  112068. int **mag_sort,
  112069. int **ifloor,
  112070. int *nonzero,
  112071. int sliding_lowpass){
  112072. int i,j,k,n=p->n;
  112073. /* perform any requested channel coupling */
  112074. /* point stereo can only be used in a first stage (in this encoder)
  112075. because of the dependency on floor lookups */
  112076. for(i=0;i<vi->coupling_steps;i++){
  112077. /* once we're doing multistage coupling in which a channel goes
  112078. through more than one coupling step, the floor vector
  112079. magnitudes will also have to be recalculated an propogated
  112080. along with PCM. Right now, we're not (that will wait until 5.1
  112081. most likely), so the code isn't here yet. The memory management
  112082. here is all assuming single depth couplings anyway. */
  112083. /* make sure coupling a zero and a nonzero channel results in two
  112084. nonzero channels. */
  112085. if(nonzero[vi->coupling_mag[i]] ||
  112086. nonzero[vi->coupling_ang[i]]){
  112087. float *rM=res[vi->coupling_mag[i]];
  112088. float *rA=res[vi->coupling_ang[i]];
  112089. float *qM=rM+n;
  112090. float *qA=rA+n;
  112091. int *floorM=ifloor[vi->coupling_mag[i]];
  112092. int *floorA=ifloor[vi->coupling_ang[i]];
  112093. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  112094. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  112095. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  112096. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  112097. int pointlimit=limit;
  112098. nonzero[vi->coupling_mag[i]]=1;
  112099. nonzero[vi->coupling_ang[i]]=1;
  112100. /* The threshold of a stereo is changed with the size of n */
  112101. if(n > 1000)
  112102. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  112103. for(j=0;j<p->n;j+=partition){
  112104. float acc=0.f;
  112105. for(k=0;k<partition;k++){
  112106. int l=k+j;
  112107. if(l<sliding_lowpass){
  112108. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  112109. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  112110. precomputed_couple_point(mag_memo[i][l],
  112111. floorM[l],floorA[l],
  112112. qM+l,qA+l);
  112113. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  112114. }else{
  112115. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  112116. }
  112117. }else{
  112118. qM[l]=0.;
  112119. qA[l]=0.;
  112120. }
  112121. }
  112122. if(p->vi->normal_point_p){
  112123. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  112124. int l=mag_sort[i][j+k];
  112125. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  112126. qM[l]=unitnorm(qM[l]);
  112127. acc-=1.f;
  112128. }
  112129. }
  112130. }
  112131. }
  112132. }
  112133. }
  112134. }
  112135. /* AoTuV */
  112136. /** @ M2 **
  112137. The boost problem by the combination of noise normalization and point stereo is eased.
  112138. However, this is a temporary patch.
  112139. by Aoyumi @ 2004/04/18
  112140. */
  112141. void hf_reduction(vorbis_info_psy_global *g,
  112142. vorbis_look_psy *p,
  112143. vorbis_info_mapping0 *vi,
  112144. float **mdct){
  112145. int i,j,n=p->n, de=0.3*p->m_val;
  112146. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  112147. for(i=0; i<vi->coupling_steps; i++){
  112148. /* for(j=start; j<limit; j++){} // ???*/
  112149. for(j=limit; j<n; j++)
  112150. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  112151. }
  112152. }
  112153. #endif
  112154. /********* End of inlined file: psy.c *********/
  112155. /********* Start of inlined file: registry.c *********/
  112156. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112157. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112158. // tasks..
  112159. #ifdef _MSC_VER
  112160. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112161. #endif
  112162. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112163. #if JUCE_USE_OGGVORBIS
  112164. /* seems like major overkill now; the backend numbers will grow into
  112165. the infrastructure soon enough */
  112166. extern vorbis_func_floor floor0_exportbundle;
  112167. extern vorbis_func_floor floor1_exportbundle;
  112168. extern vorbis_func_residue residue0_exportbundle;
  112169. extern vorbis_func_residue residue1_exportbundle;
  112170. extern vorbis_func_residue residue2_exportbundle;
  112171. extern vorbis_func_mapping mapping0_exportbundle;
  112172. vorbis_func_floor *_floor_P[]={
  112173. &floor0_exportbundle,
  112174. &floor1_exportbundle,
  112175. };
  112176. vorbis_func_residue *_residue_P[]={
  112177. &residue0_exportbundle,
  112178. &residue1_exportbundle,
  112179. &residue2_exportbundle,
  112180. };
  112181. vorbis_func_mapping *_mapping_P[]={
  112182. &mapping0_exportbundle,
  112183. };
  112184. #endif
  112185. /********* End of inlined file: registry.c *********/
  112186. /********* Start of inlined file: res0.c *********/
  112187. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  112188. encode/decode loops are coded for clarity and performance is not
  112189. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  112190. it's slow. */
  112191. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112192. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112193. // tasks..
  112194. #ifdef _MSC_VER
  112195. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112196. #endif
  112197. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112198. #if JUCE_USE_OGGVORBIS
  112199. #include <stdlib.h>
  112200. #include <string.h>
  112201. #include <math.h>
  112202. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  112203. #include <stdio.h>
  112204. #endif
  112205. typedef struct {
  112206. vorbis_info_residue0 *info;
  112207. int parts;
  112208. int stages;
  112209. codebook *fullbooks;
  112210. codebook *phrasebook;
  112211. codebook ***partbooks;
  112212. int partvals;
  112213. int **decodemap;
  112214. long postbits;
  112215. long phrasebits;
  112216. long frames;
  112217. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  112218. int train_seq;
  112219. long *training_data[8][64];
  112220. float training_max[8][64];
  112221. float training_min[8][64];
  112222. float tmin;
  112223. float tmax;
  112224. #endif
  112225. } vorbis_look_residue0;
  112226. void res0_free_info(vorbis_info_residue *i){
  112227. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  112228. if(info){
  112229. memset(info,0,sizeof(*info));
  112230. _ogg_free(info);
  112231. }
  112232. }
  112233. void res0_free_look(vorbis_look_residue *i){
  112234. int j;
  112235. if(i){
  112236. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  112237. #ifdef TRAIN_RES
  112238. {
  112239. int j,k,l;
  112240. for(j=0;j<look->parts;j++){
  112241. /*fprintf(stderr,"partition %d: ",j);*/
  112242. for(k=0;k<8;k++)
  112243. if(look->training_data[k][j]){
  112244. char buffer[80];
  112245. FILE *of;
  112246. codebook *statebook=look->partbooks[j][k];
  112247. /* long and short into the same bucket by current convention */
  112248. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  112249. of=fopen(buffer,"a");
  112250. for(l=0;l<statebook->entries;l++)
  112251. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  112252. fclose(of);
  112253. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  112254. look->training_min[k][j],look->training_max[k][j]);*/
  112255. _ogg_free(look->training_data[k][j]);
  112256. look->training_data[k][j]=NULL;
  112257. }
  112258. /*fprintf(stderr,"\n");*/
  112259. }
  112260. }
  112261. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  112262. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  112263. (float)look->phrasebits/look->frames,
  112264. (float)look->postbits/look->frames,
  112265. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112266. #endif
  112267. /*vorbis_info_residue0 *info=look->info;
  112268. fprintf(stderr,
  112269. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  112270. "(%g/frame) \n",look->frames,look->phrasebits,
  112271. look->resbitsflat,
  112272. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  112273. for(j=0;j<look->parts;j++){
  112274. long acc=0;
  112275. fprintf(stderr,"\t[%d] == ",j);
  112276. for(k=0;k<look->stages;k++)
  112277. if((info->secondstages[j]>>k)&1){
  112278. fprintf(stderr,"%ld,",look->resbits[j][k]);
  112279. acc+=look->resbits[j][k];
  112280. }
  112281. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  112282. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  112283. }
  112284. fprintf(stderr,"\n");*/
  112285. for(j=0;j<look->parts;j++)
  112286. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  112287. _ogg_free(look->partbooks);
  112288. for(j=0;j<look->partvals;j++)
  112289. _ogg_free(look->decodemap[j]);
  112290. _ogg_free(look->decodemap);
  112291. memset(look,0,sizeof(*look));
  112292. _ogg_free(look);
  112293. }
  112294. }
  112295. static int icount(unsigned int v){
  112296. int ret=0;
  112297. while(v){
  112298. ret+=v&1;
  112299. v>>=1;
  112300. }
  112301. return(ret);
  112302. }
  112303. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  112304. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  112305. int j,acc=0;
  112306. oggpack_write(opb,info->begin,24);
  112307. oggpack_write(opb,info->end,24);
  112308. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  112309. code with a partitioned book */
  112310. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  112311. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  112312. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  112313. bitmask of one indicates this partition class has bits to write
  112314. this pass */
  112315. for(j=0;j<info->partitions;j++){
  112316. if(ilog(info->secondstages[j])>3){
  112317. /* yes, this is a minor hack due to not thinking ahead */
  112318. oggpack_write(opb,info->secondstages[j],3);
  112319. oggpack_write(opb,1,1);
  112320. oggpack_write(opb,info->secondstages[j]>>3,5);
  112321. }else
  112322. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  112323. acc+=icount(info->secondstages[j]);
  112324. }
  112325. for(j=0;j<acc;j++)
  112326. oggpack_write(opb,info->booklist[j],8);
  112327. }
  112328. /* vorbis_info is for range checking */
  112329. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  112330. int j,acc=0;
  112331. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  112332. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  112333. info->begin=oggpack_read(opb,24);
  112334. info->end=oggpack_read(opb,24);
  112335. info->grouping=oggpack_read(opb,24)+1;
  112336. info->partitions=oggpack_read(opb,6)+1;
  112337. info->groupbook=oggpack_read(opb,8);
  112338. for(j=0;j<info->partitions;j++){
  112339. int cascade=oggpack_read(opb,3);
  112340. if(oggpack_read(opb,1))
  112341. cascade|=(oggpack_read(opb,5)<<3);
  112342. info->secondstages[j]=cascade;
  112343. acc+=icount(cascade);
  112344. }
  112345. for(j=0;j<acc;j++)
  112346. info->booklist[j]=oggpack_read(opb,8);
  112347. if(info->groupbook>=ci->books)goto errout;
  112348. for(j=0;j<acc;j++)
  112349. if(info->booklist[j]>=ci->books)goto errout;
  112350. return(info);
  112351. errout:
  112352. res0_free_info(info);
  112353. return(NULL);
  112354. }
  112355. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  112356. vorbis_info_residue *vr){
  112357. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  112358. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  112359. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  112360. int j,k,acc=0;
  112361. int dim;
  112362. int maxstage=0;
  112363. look->info=info;
  112364. look->parts=info->partitions;
  112365. look->fullbooks=ci->fullbooks;
  112366. look->phrasebook=ci->fullbooks+info->groupbook;
  112367. dim=look->phrasebook->dim;
  112368. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  112369. for(j=0;j<look->parts;j++){
  112370. int stages=ilog(info->secondstages[j]);
  112371. if(stages){
  112372. if(stages>maxstage)maxstage=stages;
  112373. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  112374. for(k=0;k<stages;k++)
  112375. if(info->secondstages[j]&(1<<k)){
  112376. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  112377. #ifdef TRAIN_RES
  112378. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  112379. sizeof(***look->training_data));
  112380. #endif
  112381. }
  112382. }
  112383. }
  112384. look->partvals=rint(pow((float)look->parts,(float)dim));
  112385. look->stages=maxstage;
  112386. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  112387. for(j=0;j<look->partvals;j++){
  112388. long val=j;
  112389. long mult=look->partvals/look->parts;
  112390. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  112391. for(k=0;k<dim;k++){
  112392. long deco=val/mult;
  112393. val-=deco*mult;
  112394. mult/=look->parts;
  112395. look->decodemap[j][k]=deco;
  112396. }
  112397. }
  112398. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  112399. {
  112400. static int train_seq=0;
  112401. look->train_seq=train_seq++;
  112402. }
  112403. #endif
  112404. return(look);
  112405. }
  112406. /* break an abstraction and copy some code for performance purposes */
  112407. static int local_book_besterror(codebook *book,float *a){
  112408. int dim=book->dim,i,k,o;
  112409. int best=0;
  112410. encode_aux_threshmatch *tt=book->c->thresh_tree;
  112411. /* find the quant val of each scalar */
  112412. for(k=0,o=dim;k<dim;++k){
  112413. float val=a[--o];
  112414. i=tt->threshvals>>1;
  112415. if(val<tt->quantthresh[i]){
  112416. if(val<tt->quantthresh[i-1]){
  112417. for(--i;i>0;--i)
  112418. if(val>=tt->quantthresh[i-1])
  112419. break;
  112420. }
  112421. }else{
  112422. for(++i;i<tt->threshvals-1;++i)
  112423. if(val<tt->quantthresh[i])break;
  112424. }
  112425. best=(best*tt->quantvals)+tt->quantmap[i];
  112426. }
  112427. /* regular lattices are easy :-) */
  112428. if(book->c->lengthlist[best]<=0){
  112429. const static_codebook *c=book->c;
  112430. int i,j;
  112431. float bestf=0.f;
  112432. float *e=book->valuelist;
  112433. best=-1;
  112434. for(i=0;i<book->entries;i++){
  112435. if(c->lengthlist[i]>0){
  112436. float thisx=0.f;
  112437. for(j=0;j<dim;j++){
  112438. float val=(e[j]-a[j]);
  112439. thisx+=val*val;
  112440. }
  112441. if(best==-1 || thisx<bestf){
  112442. bestf=thisx;
  112443. best=i;
  112444. }
  112445. }
  112446. e+=dim;
  112447. }
  112448. }
  112449. {
  112450. float *ptr=book->valuelist+best*dim;
  112451. for(i=0;i<dim;i++)
  112452. *a++ -= *ptr++;
  112453. }
  112454. return(best);
  112455. }
  112456. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  112457. codebook *book,long *acc){
  112458. int i,bits=0;
  112459. int dim=book->dim;
  112460. int step=n/dim;
  112461. for(i=0;i<step;i++){
  112462. int entry=local_book_besterror(book,vec+i*dim);
  112463. #ifdef TRAIN_RES
  112464. acc[entry]++;
  112465. #endif
  112466. bits+=vorbis_book_encode(book,entry,opb);
  112467. }
  112468. return(bits);
  112469. }
  112470. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  112471. float **in,int ch){
  112472. long i,j,k;
  112473. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112474. vorbis_info_residue0 *info=look->info;
  112475. /* move all this setup out later */
  112476. int samples_per_partition=info->grouping;
  112477. int possible_partitions=info->partitions;
  112478. int n=info->end-info->begin;
  112479. int partvals=n/samples_per_partition;
  112480. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  112481. float scale=100./samples_per_partition;
  112482. /* we find the partition type for each partition of each
  112483. channel. We'll go back and do the interleaved encoding in a
  112484. bit. For now, clarity */
  112485. for(i=0;i<ch;i++){
  112486. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  112487. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  112488. }
  112489. for(i=0;i<partvals;i++){
  112490. int offset=i*samples_per_partition+info->begin;
  112491. for(j=0;j<ch;j++){
  112492. float max=0.;
  112493. float ent=0.;
  112494. for(k=0;k<samples_per_partition;k++){
  112495. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  112496. ent+=fabs(rint(in[j][offset+k]));
  112497. }
  112498. ent*=scale;
  112499. for(k=0;k<possible_partitions-1;k++)
  112500. if(max<=info->classmetric1[k] &&
  112501. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  112502. break;
  112503. partword[j][i]=k;
  112504. }
  112505. }
  112506. #ifdef TRAIN_RESAUX
  112507. {
  112508. FILE *of;
  112509. char buffer[80];
  112510. for(i=0;i<ch;i++){
  112511. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  112512. of=fopen(buffer,"a");
  112513. for(j=0;j<partvals;j++)
  112514. fprintf(of,"%ld, ",partword[i][j]);
  112515. fprintf(of,"\n");
  112516. fclose(of);
  112517. }
  112518. }
  112519. #endif
  112520. look->frames++;
  112521. return(partword);
  112522. }
  112523. /* designed for stereo or other modes where the partition size is an
  112524. integer multiple of the number of channels encoded in the current
  112525. submap */
  112526. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  112527. int ch){
  112528. long i,j,k,l;
  112529. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112530. vorbis_info_residue0 *info=look->info;
  112531. /* move all this setup out later */
  112532. int samples_per_partition=info->grouping;
  112533. int possible_partitions=info->partitions;
  112534. int n=info->end-info->begin;
  112535. int partvals=n/samples_per_partition;
  112536. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  112537. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  112538. FILE *of;
  112539. char buffer[80];
  112540. #endif
  112541. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  112542. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  112543. for(i=0,l=info->begin/ch;i<partvals;i++){
  112544. float magmax=0.f;
  112545. float angmax=0.f;
  112546. for(j=0;j<samples_per_partition;j+=ch){
  112547. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  112548. for(k=1;k<ch;k++)
  112549. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  112550. l++;
  112551. }
  112552. for(j=0;j<possible_partitions-1;j++)
  112553. if(magmax<=info->classmetric1[j] &&
  112554. angmax<=info->classmetric2[j])
  112555. break;
  112556. partword[0][i]=j;
  112557. }
  112558. #ifdef TRAIN_RESAUX
  112559. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  112560. of=fopen(buffer,"a");
  112561. for(i=0;i<partvals;i++)
  112562. fprintf(of,"%ld, ",partword[0][i]);
  112563. fprintf(of,"\n");
  112564. fclose(of);
  112565. #endif
  112566. look->frames++;
  112567. return(partword);
  112568. }
  112569. static int _01forward(oggpack_buffer *opb,
  112570. vorbis_block *vb,vorbis_look_residue *vl,
  112571. float **in,int ch,
  112572. long **partword,
  112573. int (*encode)(oggpack_buffer *,float *,int,
  112574. codebook *,long *)){
  112575. long i,j,k,s;
  112576. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112577. vorbis_info_residue0 *info=look->info;
  112578. /* move all this setup out later */
  112579. int samples_per_partition=info->grouping;
  112580. int possible_partitions=info->partitions;
  112581. int partitions_per_word=look->phrasebook->dim;
  112582. int n=info->end-info->begin;
  112583. int partvals=n/samples_per_partition;
  112584. long resbits[128];
  112585. long resvals[128];
  112586. #ifdef TRAIN_RES
  112587. for(i=0;i<ch;i++)
  112588. for(j=info->begin;j<info->end;j++){
  112589. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  112590. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  112591. }
  112592. #endif
  112593. memset(resbits,0,sizeof(resbits));
  112594. memset(resvals,0,sizeof(resvals));
  112595. /* we code the partition words for each channel, then the residual
  112596. words for a partition per channel until we've written all the
  112597. residual words for that partition word. Then write the next
  112598. partition channel words... */
  112599. for(s=0;s<look->stages;s++){
  112600. for(i=0;i<partvals;){
  112601. /* first we encode a partition codeword for each channel */
  112602. if(s==0){
  112603. for(j=0;j<ch;j++){
  112604. long val=partword[j][i];
  112605. for(k=1;k<partitions_per_word;k++){
  112606. val*=possible_partitions;
  112607. if(i+k<partvals)
  112608. val+=partword[j][i+k];
  112609. }
  112610. /* training hack */
  112611. if(val<look->phrasebook->entries)
  112612. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  112613. #if 0 /*def TRAIN_RES*/
  112614. else
  112615. fprintf(stderr,"!");
  112616. #endif
  112617. }
  112618. }
  112619. /* now we encode interleaved residual values for the partitions */
  112620. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  112621. long offset=i*samples_per_partition+info->begin;
  112622. for(j=0;j<ch;j++){
  112623. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  112624. if(info->secondstages[partword[j][i]]&(1<<s)){
  112625. codebook *statebook=look->partbooks[partword[j][i]][s];
  112626. if(statebook){
  112627. int ret;
  112628. long *accumulator=NULL;
  112629. #ifdef TRAIN_RES
  112630. accumulator=look->training_data[s][partword[j][i]];
  112631. {
  112632. int l;
  112633. float *samples=in[j]+offset;
  112634. for(l=0;l<samples_per_partition;l++){
  112635. if(samples[l]<look->training_min[s][partword[j][i]])
  112636. look->training_min[s][partword[j][i]]=samples[l];
  112637. if(samples[l]>look->training_max[s][partword[j][i]])
  112638. look->training_max[s][partword[j][i]]=samples[l];
  112639. }
  112640. }
  112641. #endif
  112642. ret=encode(opb,in[j]+offset,samples_per_partition,
  112643. statebook,accumulator);
  112644. look->postbits+=ret;
  112645. resbits[partword[j][i]]+=ret;
  112646. }
  112647. }
  112648. }
  112649. }
  112650. }
  112651. }
  112652. /*{
  112653. long total=0;
  112654. long totalbits=0;
  112655. fprintf(stderr,"%d :: ",vb->mode);
  112656. for(k=0;k<possible_partitions;k++){
  112657. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  112658. total+=resvals[k];
  112659. totalbits+=resbits[k];
  112660. }
  112661. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  112662. }*/
  112663. return(0);
  112664. }
  112665. /* a truncated packet here just means 'stop working'; it's not an error */
  112666. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  112667. float **in,int ch,
  112668. long (*decodepart)(codebook *, float *,
  112669. oggpack_buffer *,int)){
  112670. long i,j,k,l,s;
  112671. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112672. vorbis_info_residue0 *info=look->info;
  112673. /* move all this setup out later */
  112674. int samples_per_partition=info->grouping;
  112675. int partitions_per_word=look->phrasebook->dim;
  112676. int n=info->end-info->begin;
  112677. int partvals=n/samples_per_partition;
  112678. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  112679. int ***partword=(int***)alloca(ch*sizeof(*partword));
  112680. for(j=0;j<ch;j++)
  112681. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  112682. for(s=0;s<look->stages;s++){
  112683. /* each loop decodes on partition codeword containing
  112684. partitions_pre_word partitions */
  112685. for(i=0,l=0;i<partvals;l++){
  112686. if(s==0){
  112687. /* fetch the partition word for each channel */
  112688. for(j=0;j<ch;j++){
  112689. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  112690. if(temp==-1)goto eopbreak;
  112691. partword[j][l]=look->decodemap[temp];
  112692. if(partword[j][l]==NULL)goto errout;
  112693. }
  112694. }
  112695. /* now we decode residual values for the partitions */
  112696. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  112697. for(j=0;j<ch;j++){
  112698. long offset=info->begin+i*samples_per_partition;
  112699. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  112700. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  112701. if(stagebook){
  112702. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  112703. samples_per_partition)==-1)goto eopbreak;
  112704. }
  112705. }
  112706. }
  112707. }
  112708. }
  112709. errout:
  112710. eopbreak:
  112711. return(0);
  112712. }
  112713. #if 0
  112714. /* residue 0 and 1 are just slight variants of one another. 0 is
  112715. interleaved, 1 is not */
  112716. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  112717. float **in,int *nonzero,int ch){
  112718. /* we encode only the nonzero parts of a bundle */
  112719. int i,used=0;
  112720. for(i=0;i<ch;i++)
  112721. if(nonzero[i])
  112722. in[used++]=in[i];
  112723. if(used)
  112724. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  112725. return(_01class(vb,vl,in,used));
  112726. else
  112727. return(0);
  112728. }
  112729. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  112730. float **in,float **out,int *nonzero,int ch,
  112731. long **partword){
  112732. /* we encode only the nonzero parts of a bundle */
  112733. int i,j,used=0,n=vb->pcmend/2;
  112734. for(i=0;i<ch;i++)
  112735. if(nonzero[i]){
  112736. if(out)
  112737. for(j=0;j<n;j++)
  112738. out[i][j]+=in[i][j];
  112739. in[used++]=in[i];
  112740. }
  112741. if(used){
  112742. int ret=_01forward(vb,vl,in,used,partword,
  112743. _interleaved_encodepart);
  112744. if(out){
  112745. used=0;
  112746. for(i=0;i<ch;i++)
  112747. if(nonzero[i]){
  112748. for(j=0;j<n;j++)
  112749. out[i][j]-=in[used][j];
  112750. used++;
  112751. }
  112752. }
  112753. return(ret);
  112754. }else{
  112755. return(0);
  112756. }
  112757. }
  112758. #endif
  112759. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  112760. float **in,int *nonzero,int ch){
  112761. int i,used=0;
  112762. for(i=0;i<ch;i++)
  112763. if(nonzero[i])
  112764. in[used++]=in[i];
  112765. if(used)
  112766. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  112767. else
  112768. return(0);
  112769. }
  112770. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  112771. float **in,float **out,int *nonzero,int ch,
  112772. long **partword){
  112773. int i,j,used=0,n=vb->pcmend/2;
  112774. for(i=0;i<ch;i++)
  112775. if(nonzero[i]){
  112776. if(out)
  112777. for(j=0;j<n;j++)
  112778. out[i][j]+=in[i][j];
  112779. in[used++]=in[i];
  112780. }
  112781. if(used){
  112782. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  112783. if(out){
  112784. used=0;
  112785. for(i=0;i<ch;i++)
  112786. if(nonzero[i]){
  112787. for(j=0;j<n;j++)
  112788. out[i][j]-=in[used][j];
  112789. used++;
  112790. }
  112791. }
  112792. return(ret);
  112793. }else{
  112794. return(0);
  112795. }
  112796. }
  112797. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  112798. float **in,int *nonzero,int ch){
  112799. int i,used=0;
  112800. for(i=0;i<ch;i++)
  112801. if(nonzero[i])
  112802. in[used++]=in[i];
  112803. if(used)
  112804. return(_01class(vb,vl,in,used));
  112805. else
  112806. return(0);
  112807. }
  112808. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  112809. float **in,int *nonzero,int ch){
  112810. int i,used=0;
  112811. for(i=0;i<ch;i++)
  112812. if(nonzero[i])
  112813. in[used++]=in[i];
  112814. if(used)
  112815. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  112816. else
  112817. return(0);
  112818. }
  112819. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  112820. float **in,int *nonzero,int ch){
  112821. int i,used=0;
  112822. for(i=0;i<ch;i++)
  112823. if(nonzero[i])used++;
  112824. if(used)
  112825. return(_2class(vb,vl,in,ch));
  112826. else
  112827. return(0);
  112828. }
  112829. /* res2 is slightly more different; all the channels are interleaved
  112830. into a single vector and encoded. */
  112831. int res2_forward(oggpack_buffer *opb,
  112832. vorbis_block *vb,vorbis_look_residue *vl,
  112833. float **in,float **out,int *nonzero,int ch,
  112834. long **partword){
  112835. long i,j,k,n=vb->pcmend/2,used=0;
  112836. /* don't duplicate the code; use a working vector hack for now and
  112837. reshape ourselves into a single channel res1 */
  112838. /* ugly; reallocs for each coupling pass :-( */
  112839. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  112840. for(i=0;i<ch;i++){
  112841. float *pcm=in[i];
  112842. if(nonzero[i])used++;
  112843. for(j=0,k=i;j<n;j++,k+=ch)
  112844. work[k]=pcm[j];
  112845. }
  112846. if(used){
  112847. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  112848. /* update the sofar vector */
  112849. if(out){
  112850. for(i=0;i<ch;i++){
  112851. float *pcm=in[i];
  112852. float *sofar=out[i];
  112853. for(j=0,k=i;j<n;j++,k+=ch)
  112854. sofar[j]+=pcm[j]-work[k];
  112855. }
  112856. }
  112857. return(ret);
  112858. }else{
  112859. return(0);
  112860. }
  112861. }
  112862. /* duplicate code here as speed is somewhat more important */
  112863. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  112864. float **in,int *nonzero,int ch){
  112865. long i,k,l,s;
  112866. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112867. vorbis_info_residue0 *info=look->info;
  112868. /* move all this setup out later */
  112869. int samples_per_partition=info->grouping;
  112870. int partitions_per_word=look->phrasebook->dim;
  112871. int n=info->end-info->begin;
  112872. int partvals=n/samples_per_partition;
  112873. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  112874. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  112875. for(i=0;i<ch;i++)if(nonzero[i])break;
  112876. if(i==ch)return(0); /* no nonzero vectors */
  112877. for(s=0;s<look->stages;s++){
  112878. for(i=0,l=0;i<partvals;l++){
  112879. if(s==0){
  112880. /* fetch the partition word */
  112881. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  112882. if(temp==-1)goto eopbreak;
  112883. partword[l]=look->decodemap[temp];
  112884. if(partword[l]==NULL)goto errout;
  112885. }
  112886. /* now we decode residual values for the partitions */
  112887. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  112888. if(info->secondstages[partword[l][k]]&(1<<s)){
  112889. codebook *stagebook=look->partbooks[partword[l][k]][s];
  112890. if(stagebook){
  112891. if(vorbis_book_decodevv_add(stagebook,in,
  112892. i*samples_per_partition+info->begin,ch,
  112893. &vb->opb,samples_per_partition)==-1)
  112894. goto eopbreak;
  112895. }
  112896. }
  112897. }
  112898. }
  112899. errout:
  112900. eopbreak:
  112901. return(0);
  112902. }
  112903. vorbis_func_residue residue0_exportbundle={
  112904. NULL,
  112905. &res0_unpack,
  112906. &res0_look,
  112907. &res0_free_info,
  112908. &res0_free_look,
  112909. NULL,
  112910. NULL,
  112911. &res0_inverse
  112912. };
  112913. vorbis_func_residue residue1_exportbundle={
  112914. &res0_pack,
  112915. &res0_unpack,
  112916. &res0_look,
  112917. &res0_free_info,
  112918. &res0_free_look,
  112919. &res1_class,
  112920. &res1_forward,
  112921. &res1_inverse
  112922. };
  112923. vorbis_func_residue residue2_exportbundle={
  112924. &res0_pack,
  112925. &res0_unpack,
  112926. &res0_look,
  112927. &res0_free_info,
  112928. &res0_free_look,
  112929. &res2_class,
  112930. &res2_forward,
  112931. &res2_inverse
  112932. };
  112933. #endif
  112934. /********* End of inlined file: res0.c *********/
  112935. /********* Start of inlined file: sharedbook.c *********/
  112936. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112937. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112938. // tasks..
  112939. #ifdef _MSC_VER
  112940. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112941. #endif
  112942. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112943. #if JUCE_USE_OGGVORBIS
  112944. #include <stdlib.h>
  112945. #include <math.h>
  112946. #include <string.h>
  112947. /**** pack/unpack helpers ******************************************/
  112948. int _ilog(unsigned int v){
  112949. int ret=0;
  112950. while(v){
  112951. ret++;
  112952. v>>=1;
  112953. }
  112954. return(ret);
  112955. }
  112956. /* 32 bit float (not IEEE; nonnormalized mantissa +
  112957. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  112958. Why not IEEE? It's just not that important here. */
  112959. #define VQ_FEXP 10
  112960. #define VQ_FMAN 21
  112961. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  112962. /* doesn't currently guard under/overflow */
  112963. long _float32_pack(float val){
  112964. int sign=0;
  112965. long exp;
  112966. long mant;
  112967. if(val<0){
  112968. sign=0x80000000;
  112969. val= -val;
  112970. }
  112971. exp= floor(log(val)/log(2.f));
  112972. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  112973. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  112974. return(sign|exp|mant);
  112975. }
  112976. float _float32_unpack(long val){
  112977. double mant=val&0x1fffff;
  112978. int sign=val&0x80000000;
  112979. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  112980. if(sign)mant= -mant;
  112981. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  112982. }
  112983. /* given a list of word lengths, generate a list of codewords. Works
  112984. for length ordered or unordered, always assigns the lowest valued
  112985. codewords first. Extended to handle unused entries (length 0) */
  112986. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  112987. long i,j,count=0;
  112988. ogg_uint32_t marker[33];
  112989. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  112990. memset(marker,0,sizeof(marker));
  112991. for(i=0;i<n;i++){
  112992. long length=l[i];
  112993. if(length>0){
  112994. ogg_uint32_t entry=marker[length];
  112995. /* when we claim a node for an entry, we also claim the nodes
  112996. below it (pruning off the imagined tree that may have dangled
  112997. from it) as well as blocking the use of any nodes directly
  112998. above for leaves */
  112999. /* update ourself */
  113000. if(length<32 && (entry>>length)){
  113001. /* error condition; the lengths must specify an overpopulated tree */
  113002. _ogg_free(r);
  113003. return(NULL);
  113004. }
  113005. r[count++]=entry;
  113006. /* Look to see if the next shorter marker points to the node
  113007. above. if so, update it and repeat. */
  113008. {
  113009. for(j=length;j>0;j--){
  113010. if(marker[j]&1){
  113011. /* have to jump branches */
  113012. if(j==1)
  113013. marker[1]++;
  113014. else
  113015. marker[j]=marker[j-1]<<1;
  113016. break; /* invariant says next upper marker would already
  113017. have been moved if it was on the same path */
  113018. }
  113019. marker[j]++;
  113020. }
  113021. }
  113022. /* prune the tree; the implicit invariant says all the longer
  113023. markers were dangling from our just-taken node. Dangle them
  113024. from our *new* node. */
  113025. for(j=length+1;j<33;j++)
  113026. if((marker[j]>>1) == entry){
  113027. entry=marker[j];
  113028. marker[j]=marker[j-1]<<1;
  113029. }else
  113030. break;
  113031. }else
  113032. if(sparsecount==0)count++;
  113033. }
  113034. /* bitreverse the words because our bitwise packer/unpacker is LSb
  113035. endian */
  113036. for(i=0,count=0;i<n;i++){
  113037. ogg_uint32_t temp=0;
  113038. for(j=0;j<l[i];j++){
  113039. temp<<=1;
  113040. temp|=(r[count]>>j)&1;
  113041. }
  113042. if(sparsecount){
  113043. if(l[i])
  113044. r[count++]=temp;
  113045. }else
  113046. r[count++]=temp;
  113047. }
  113048. return(r);
  113049. }
  113050. /* there might be a straightforward one-line way to do the below
  113051. that's portable and totally safe against roundoff, but I haven't
  113052. thought of it. Therefore, we opt on the side of caution */
  113053. long _book_maptype1_quantvals(const static_codebook *b){
  113054. long vals=floor(pow((float)b->entries,1.f/b->dim));
  113055. /* the above *should* be reliable, but we'll not assume that FP is
  113056. ever reliable when bitstream sync is at stake; verify via integer
  113057. means that vals really is the greatest value of dim for which
  113058. vals^b->bim <= b->entries */
  113059. /* treat the above as an initial guess */
  113060. while(1){
  113061. long acc=1;
  113062. long acc1=1;
  113063. int i;
  113064. for(i=0;i<b->dim;i++){
  113065. acc*=vals;
  113066. acc1*=vals+1;
  113067. }
  113068. if(acc<=b->entries && acc1>b->entries){
  113069. return(vals);
  113070. }else{
  113071. if(acc>b->entries){
  113072. vals--;
  113073. }else{
  113074. vals++;
  113075. }
  113076. }
  113077. }
  113078. }
  113079. /* unpack the quantized list of values for encode/decode ***********/
  113080. /* we need to deal with two map types: in map type 1, the values are
  113081. generated algorithmically (each column of the vector counts through
  113082. the values in the quant vector). in map type 2, all the values came
  113083. in in an explicit list. Both value lists must be unpacked */
  113084. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  113085. long j,k,count=0;
  113086. if(b->maptype==1 || b->maptype==2){
  113087. int quantvals;
  113088. float mindel=_float32_unpack(b->q_min);
  113089. float delta=_float32_unpack(b->q_delta);
  113090. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  113091. /* maptype 1 and 2 both use a quantized value vector, but
  113092. different sizes */
  113093. switch(b->maptype){
  113094. case 1:
  113095. /* most of the time, entries%dimensions == 0, but we need to be
  113096. well defined. We define that the possible vales at each
  113097. scalar is values == entries/dim. If entries%dim != 0, we'll
  113098. have 'too few' values (values*dim<entries), which means that
  113099. we'll have 'left over' entries; left over entries use zeroed
  113100. values (and are wasted). So don't generate codebooks like
  113101. that */
  113102. quantvals=_book_maptype1_quantvals(b);
  113103. for(j=0;j<b->entries;j++){
  113104. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  113105. float last=0.f;
  113106. int indexdiv=1;
  113107. for(k=0;k<b->dim;k++){
  113108. int index= (j/indexdiv)%quantvals;
  113109. float val=b->quantlist[index];
  113110. val=fabs(val)*delta+mindel+last;
  113111. if(b->q_sequencep)last=val;
  113112. if(sparsemap)
  113113. r[sparsemap[count]*b->dim+k]=val;
  113114. else
  113115. r[count*b->dim+k]=val;
  113116. indexdiv*=quantvals;
  113117. }
  113118. count++;
  113119. }
  113120. }
  113121. break;
  113122. case 2:
  113123. for(j=0;j<b->entries;j++){
  113124. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  113125. float last=0.f;
  113126. for(k=0;k<b->dim;k++){
  113127. float val=b->quantlist[j*b->dim+k];
  113128. val=fabs(val)*delta+mindel+last;
  113129. if(b->q_sequencep)last=val;
  113130. if(sparsemap)
  113131. r[sparsemap[count]*b->dim+k]=val;
  113132. else
  113133. r[count*b->dim+k]=val;
  113134. }
  113135. count++;
  113136. }
  113137. }
  113138. break;
  113139. }
  113140. return(r);
  113141. }
  113142. return(NULL);
  113143. }
  113144. void vorbis_staticbook_clear(static_codebook *b){
  113145. if(b->allocedp){
  113146. if(b->quantlist)_ogg_free(b->quantlist);
  113147. if(b->lengthlist)_ogg_free(b->lengthlist);
  113148. if(b->nearest_tree){
  113149. _ogg_free(b->nearest_tree->ptr0);
  113150. _ogg_free(b->nearest_tree->ptr1);
  113151. _ogg_free(b->nearest_tree->p);
  113152. _ogg_free(b->nearest_tree->q);
  113153. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  113154. _ogg_free(b->nearest_tree);
  113155. }
  113156. if(b->thresh_tree){
  113157. _ogg_free(b->thresh_tree->quantthresh);
  113158. _ogg_free(b->thresh_tree->quantmap);
  113159. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  113160. _ogg_free(b->thresh_tree);
  113161. }
  113162. memset(b,0,sizeof(*b));
  113163. }
  113164. }
  113165. void vorbis_staticbook_destroy(static_codebook *b){
  113166. if(b->allocedp){
  113167. vorbis_staticbook_clear(b);
  113168. _ogg_free(b);
  113169. }
  113170. }
  113171. void vorbis_book_clear(codebook *b){
  113172. /* static book is not cleared; we're likely called on the lookup and
  113173. the static codebook belongs to the info struct */
  113174. if(b->valuelist)_ogg_free(b->valuelist);
  113175. if(b->codelist)_ogg_free(b->codelist);
  113176. if(b->dec_index)_ogg_free(b->dec_index);
  113177. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  113178. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  113179. memset(b,0,sizeof(*b));
  113180. }
  113181. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  113182. memset(c,0,sizeof(*c));
  113183. c->c=s;
  113184. c->entries=s->entries;
  113185. c->used_entries=s->entries;
  113186. c->dim=s->dim;
  113187. c->codelist=_make_words(s->lengthlist,s->entries,0);
  113188. c->valuelist=_book_unquantize(s,s->entries,NULL);
  113189. return(0);
  113190. }
  113191. static int sort32a(const void *a,const void *b){
  113192. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  113193. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  113194. }
  113195. /* decode codebook arrangement is more heavily optimized than encode */
  113196. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  113197. int i,j,n=0,tabn;
  113198. int *sortindex;
  113199. memset(c,0,sizeof(*c));
  113200. /* count actually used entries */
  113201. for(i=0;i<s->entries;i++)
  113202. if(s->lengthlist[i]>0)
  113203. n++;
  113204. c->entries=s->entries;
  113205. c->used_entries=n;
  113206. c->dim=s->dim;
  113207. /* two different remappings go on here.
  113208. First, we collapse the likely sparse codebook down only to
  113209. actually represented values/words. This collapsing needs to be
  113210. indexed as map-valueless books are used to encode original entry
  113211. positions as integers.
  113212. Second, we reorder all vectors, including the entry index above,
  113213. by sorted bitreversed codeword to allow treeless decode. */
  113214. {
  113215. /* perform sort */
  113216. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  113217. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  113218. if(codes==NULL)goto err_out;
  113219. for(i=0;i<n;i++){
  113220. codes[i]=bitreverse(codes[i]);
  113221. codep[i]=codes+i;
  113222. }
  113223. qsort(codep,n,sizeof(*codep),sort32a);
  113224. sortindex=(int*)alloca(n*sizeof(*sortindex));
  113225. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  113226. /* the index is a reverse index */
  113227. for(i=0;i<n;i++){
  113228. int position=codep[i]-codes;
  113229. sortindex[position]=i;
  113230. }
  113231. for(i=0;i<n;i++)
  113232. c->codelist[sortindex[i]]=codes[i];
  113233. _ogg_free(codes);
  113234. }
  113235. c->valuelist=_book_unquantize(s,n,sortindex);
  113236. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  113237. for(n=0,i=0;i<s->entries;i++)
  113238. if(s->lengthlist[i]>0)
  113239. c->dec_index[sortindex[n++]]=i;
  113240. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  113241. for(n=0,i=0;i<s->entries;i++)
  113242. if(s->lengthlist[i]>0)
  113243. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  113244. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  113245. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  113246. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  113247. tabn=1<<c->dec_firsttablen;
  113248. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  113249. c->dec_maxlength=0;
  113250. for(i=0;i<n;i++){
  113251. if(c->dec_maxlength<c->dec_codelengths[i])
  113252. c->dec_maxlength=c->dec_codelengths[i];
  113253. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  113254. ogg_uint32_t orig=bitreverse(c->codelist[i]);
  113255. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  113256. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  113257. }
  113258. }
  113259. /* now fill in 'unused' entries in the firsttable with hi/lo search
  113260. hints for the non-direct-hits */
  113261. {
  113262. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  113263. long lo=0,hi=0;
  113264. for(i=0;i<tabn;i++){
  113265. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  113266. if(c->dec_firsttable[bitreverse(word)]==0){
  113267. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  113268. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  113269. /* we only actually have 15 bits per hint to play with here.
  113270. In order to overflow gracefully (nothing breaks, efficiency
  113271. just drops), encode as the difference from the extremes. */
  113272. {
  113273. unsigned long loval=lo;
  113274. unsigned long hival=n-hi;
  113275. if(loval>0x7fff)loval=0x7fff;
  113276. if(hival>0x7fff)hival=0x7fff;
  113277. c->dec_firsttable[bitreverse(word)]=
  113278. 0x80000000UL | (loval<<15) | hival;
  113279. }
  113280. }
  113281. }
  113282. }
  113283. return(0);
  113284. err_out:
  113285. vorbis_book_clear(c);
  113286. return(-1);
  113287. }
  113288. static float _dist(int el,float *ref, float *b,int step){
  113289. int i;
  113290. float acc=0.f;
  113291. for(i=0;i<el;i++){
  113292. float val=(ref[i]-b[i*step]);
  113293. acc+=val*val;
  113294. }
  113295. return(acc);
  113296. }
  113297. int _best(codebook *book, float *a, int step){
  113298. encode_aux_threshmatch *tt=book->c->thresh_tree;
  113299. #if 0
  113300. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  113301. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  113302. #endif
  113303. int dim=book->dim;
  113304. int k,o;
  113305. /*int savebest=-1;
  113306. float saverr;*/
  113307. /* do we have a threshhold encode hint? */
  113308. if(tt){
  113309. int index=0,i;
  113310. /* find the quant val of each scalar */
  113311. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  113312. i=tt->threshvals>>1;
  113313. if(a[o]<tt->quantthresh[i]){
  113314. for(;i>0;i--)
  113315. if(a[o]>=tt->quantthresh[i-1])
  113316. break;
  113317. }else{
  113318. for(i++;i<tt->threshvals-1;i++)
  113319. if(a[o]<tt->quantthresh[i])break;
  113320. }
  113321. index=(index*tt->quantvals)+tt->quantmap[i];
  113322. }
  113323. /* regular lattices are easy :-) */
  113324. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  113325. use a decision tree after all
  113326. and fall through*/
  113327. return(index);
  113328. }
  113329. #if 0
  113330. /* do we have a pigeonhole encode hint? */
  113331. if(pt){
  113332. const static_codebook *c=book->c;
  113333. int i,besti=-1;
  113334. float best=0.f;
  113335. int entry=0;
  113336. /* dealing with sequentialness is a pain in the ass */
  113337. if(c->q_sequencep){
  113338. int pv;
  113339. long mul=1;
  113340. float qlast=0;
  113341. for(k=0,o=0;k<dim;k++,o+=step){
  113342. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  113343. if(pv<0 || pv>=pt->mapentries)break;
  113344. entry+=pt->pigeonmap[pv]*mul;
  113345. mul*=pt->quantvals;
  113346. qlast+=pv*pt->del+pt->min;
  113347. }
  113348. }else{
  113349. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  113350. int pv=(int)((a[o]-pt->min)/pt->del);
  113351. if(pv<0 || pv>=pt->mapentries)break;
  113352. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  113353. }
  113354. }
  113355. /* must be within the pigeonholable range; if we quant outside (or
  113356. in an entry that we define no list for), brute force it */
  113357. if(k==dim && pt->fitlength[entry]){
  113358. /* search the abbreviated list */
  113359. long *list=pt->fitlist+pt->fitmap[entry];
  113360. for(i=0;i<pt->fitlength[entry];i++){
  113361. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  113362. if(besti==-1 || this<best){
  113363. best=this;
  113364. besti=list[i];
  113365. }
  113366. }
  113367. return(besti);
  113368. }
  113369. }
  113370. if(nt){
  113371. /* optimized using the decision tree */
  113372. while(1){
  113373. float c=0.f;
  113374. float *p=book->valuelist+nt->p[ptr];
  113375. float *q=book->valuelist+nt->q[ptr];
  113376. for(k=0,o=0;k<dim;k++,o+=step)
  113377. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  113378. if(c>0.f) /* in A */
  113379. ptr= -nt->ptr0[ptr];
  113380. else /* in B */
  113381. ptr= -nt->ptr1[ptr];
  113382. if(ptr<=0)break;
  113383. }
  113384. return(-ptr);
  113385. }
  113386. #endif
  113387. /* brute force it! */
  113388. {
  113389. const static_codebook *c=book->c;
  113390. int i,besti=-1;
  113391. float best=0.f;
  113392. float *e=book->valuelist;
  113393. for(i=0;i<book->entries;i++){
  113394. if(c->lengthlist[i]>0){
  113395. float thisx=_dist(dim,e,a,step);
  113396. if(besti==-1 || thisx<best){
  113397. best=thisx;
  113398. besti=i;
  113399. }
  113400. }
  113401. e+=dim;
  113402. }
  113403. /*if(savebest!=-1 && savebest!=besti){
  113404. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  113405. "original:");
  113406. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  113407. fprintf(stderr,"\n"
  113408. "pigeonhole (entry %d, err %g):",savebest,saverr);
  113409. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  113410. (book->valuelist+savebest*dim)[i]);
  113411. fprintf(stderr,"\n"
  113412. "bruteforce (entry %d, err %g):",besti,best);
  113413. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  113414. (book->valuelist+besti*dim)[i]);
  113415. fprintf(stderr,"\n");
  113416. }*/
  113417. return(besti);
  113418. }
  113419. }
  113420. long vorbis_book_codeword(codebook *book,int entry){
  113421. if(book->c) /* only use with encode; decode optimizations are
  113422. allowed to break this */
  113423. return book->codelist[entry];
  113424. return -1;
  113425. }
  113426. long vorbis_book_codelen(codebook *book,int entry){
  113427. if(book->c) /* only use with encode; decode optimizations are
  113428. allowed to break this */
  113429. return book->c->lengthlist[entry];
  113430. return -1;
  113431. }
  113432. #ifdef _V_SELFTEST
  113433. /* Unit tests of the dequantizer; this stuff will be OK
  113434. cross-platform, I simply want to be sure that special mapping cases
  113435. actually work properly; a bug could go unnoticed for a while */
  113436. #include <stdio.h>
  113437. /* cases:
  113438. no mapping
  113439. full, explicit mapping
  113440. algorithmic mapping
  113441. nonsequential
  113442. sequential
  113443. */
  113444. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  113445. static long partial_quantlist1[]={0,7,2};
  113446. /* no mapping */
  113447. static_codebook test1={
  113448. 4,16,
  113449. NULL,
  113450. 0,
  113451. 0,0,0,0,
  113452. NULL,
  113453. NULL,NULL
  113454. };
  113455. static float *test1_result=NULL;
  113456. /* linear, full mapping, nonsequential */
  113457. static_codebook test2={
  113458. 4,3,
  113459. NULL,
  113460. 2,
  113461. -533200896,1611661312,4,0,
  113462. full_quantlist1,
  113463. NULL,NULL
  113464. };
  113465. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  113466. /* linear, full mapping, sequential */
  113467. static_codebook test3={
  113468. 4,3,
  113469. NULL,
  113470. 2,
  113471. -533200896,1611661312,4,1,
  113472. full_quantlist1,
  113473. NULL,NULL
  113474. };
  113475. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  113476. /* linear, algorithmic mapping, nonsequential */
  113477. static_codebook test4={
  113478. 3,27,
  113479. NULL,
  113480. 1,
  113481. -533200896,1611661312,4,0,
  113482. partial_quantlist1,
  113483. NULL,NULL
  113484. };
  113485. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  113486. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  113487. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  113488. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  113489. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  113490. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  113491. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  113492. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  113493. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  113494. /* linear, algorithmic mapping, sequential */
  113495. static_codebook test5={
  113496. 3,27,
  113497. NULL,
  113498. 1,
  113499. -533200896,1611661312,4,1,
  113500. partial_quantlist1,
  113501. NULL,NULL
  113502. };
  113503. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  113504. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  113505. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  113506. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  113507. -3, 1, 5, 4, 8,12, -1, 3, 7,
  113508. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  113509. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  113510. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  113511. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  113512. void run_test(static_codebook *b,float *comp){
  113513. float *out=_book_unquantize(b,b->entries,NULL);
  113514. int i;
  113515. if(comp){
  113516. if(!out){
  113517. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  113518. exit(1);
  113519. }
  113520. for(i=0;i<b->entries*b->dim;i++)
  113521. if(fabs(out[i]-comp[i])>.0001){
  113522. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  113523. "position %d, %g != %g\n",i,out[i],comp[i]);
  113524. exit(1);
  113525. }
  113526. }else{
  113527. if(out){
  113528. fprintf(stderr,"_book_unquantize returned a value array: \n"
  113529. " correct result should have been NULL\n");
  113530. exit(1);
  113531. }
  113532. }
  113533. }
  113534. int main(){
  113535. /* run the nine dequant tests, and compare to the hand-rolled results */
  113536. fprintf(stderr,"Dequant test 1... ");
  113537. run_test(&test1,test1_result);
  113538. fprintf(stderr,"OK\nDequant test 2... ");
  113539. run_test(&test2,test2_result);
  113540. fprintf(stderr,"OK\nDequant test 3... ");
  113541. run_test(&test3,test3_result);
  113542. fprintf(stderr,"OK\nDequant test 4... ");
  113543. run_test(&test4,test4_result);
  113544. fprintf(stderr,"OK\nDequant test 5... ");
  113545. run_test(&test5,test5_result);
  113546. fprintf(stderr,"OK\n\n");
  113547. return(0);
  113548. }
  113549. #endif
  113550. #endif
  113551. /********* End of inlined file: sharedbook.c *********/
  113552. /********* Start of inlined file: smallft.c *********/
  113553. /* FFT implementation from OggSquish, minus cosine transforms,
  113554. * minus all but radix 2/4 case. In Vorbis we only need this
  113555. * cut-down version.
  113556. *
  113557. * To do more than just power-of-two sized vectors, see the full
  113558. * version I wrote for NetLib.
  113559. *
  113560. * Note that the packing is a little strange; rather than the FFT r/i
  113561. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  113562. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  113563. * FORTRAN version
  113564. */
  113565. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113566. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113567. // tasks..
  113568. #ifdef _MSC_VER
  113569. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113570. #endif
  113571. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113572. #if JUCE_USE_OGGVORBIS
  113573. #include <stdlib.h>
  113574. #include <string.h>
  113575. #include <math.h>
  113576. static void drfti1(int n, float *wa, int *ifac){
  113577. static int ntryh[4] = { 4,2,3,5 };
  113578. static float tpi = 6.28318530717958648f;
  113579. float arg,argh,argld,fi;
  113580. int ntry=0,i,j=-1;
  113581. int k1, l1, l2, ib;
  113582. int ld, ii, ip, is, nq, nr;
  113583. int ido, ipm, nfm1;
  113584. int nl=n;
  113585. int nf=0;
  113586. L101:
  113587. j++;
  113588. if (j < 4)
  113589. ntry=ntryh[j];
  113590. else
  113591. ntry+=2;
  113592. L104:
  113593. nq=nl/ntry;
  113594. nr=nl-ntry*nq;
  113595. if (nr!=0) goto L101;
  113596. nf++;
  113597. ifac[nf+1]=ntry;
  113598. nl=nq;
  113599. if(ntry!=2)goto L107;
  113600. if(nf==1)goto L107;
  113601. for (i=1;i<nf;i++){
  113602. ib=nf-i+1;
  113603. ifac[ib+1]=ifac[ib];
  113604. }
  113605. ifac[2] = 2;
  113606. L107:
  113607. if(nl!=1)goto L104;
  113608. ifac[0]=n;
  113609. ifac[1]=nf;
  113610. argh=tpi/n;
  113611. is=0;
  113612. nfm1=nf-1;
  113613. l1=1;
  113614. if(nfm1==0)return;
  113615. for (k1=0;k1<nfm1;k1++){
  113616. ip=ifac[k1+2];
  113617. ld=0;
  113618. l2=l1*ip;
  113619. ido=n/l2;
  113620. ipm=ip-1;
  113621. for (j=0;j<ipm;j++){
  113622. ld+=l1;
  113623. i=is;
  113624. argld=(float)ld*argh;
  113625. fi=0.f;
  113626. for (ii=2;ii<ido;ii+=2){
  113627. fi+=1.f;
  113628. arg=fi*argld;
  113629. wa[i++]=cos(arg);
  113630. wa[i++]=sin(arg);
  113631. }
  113632. is+=ido;
  113633. }
  113634. l1=l2;
  113635. }
  113636. }
  113637. static void fdrffti(int n, float *wsave, int *ifac){
  113638. if (n == 1) return;
  113639. drfti1(n, wsave+n, ifac);
  113640. }
  113641. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  113642. int i,k;
  113643. float ti2,tr2;
  113644. int t0,t1,t2,t3,t4,t5,t6;
  113645. t1=0;
  113646. t0=(t2=l1*ido);
  113647. t3=ido<<1;
  113648. for(k=0;k<l1;k++){
  113649. ch[t1<<1]=cc[t1]+cc[t2];
  113650. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  113651. t1+=ido;
  113652. t2+=ido;
  113653. }
  113654. if(ido<2)return;
  113655. if(ido==2)goto L105;
  113656. t1=0;
  113657. t2=t0;
  113658. for(k=0;k<l1;k++){
  113659. t3=t2;
  113660. t4=(t1<<1)+(ido<<1);
  113661. t5=t1;
  113662. t6=t1+t1;
  113663. for(i=2;i<ido;i+=2){
  113664. t3+=2;
  113665. t4-=2;
  113666. t5+=2;
  113667. t6+=2;
  113668. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  113669. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  113670. ch[t6]=cc[t5]+ti2;
  113671. ch[t4]=ti2-cc[t5];
  113672. ch[t6-1]=cc[t5-1]+tr2;
  113673. ch[t4-1]=cc[t5-1]-tr2;
  113674. }
  113675. t1+=ido;
  113676. t2+=ido;
  113677. }
  113678. if(ido%2==1)return;
  113679. L105:
  113680. t3=(t2=(t1=ido)-1);
  113681. t2+=t0;
  113682. for(k=0;k<l1;k++){
  113683. ch[t1]=-cc[t2];
  113684. ch[t1-1]=cc[t3];
  113685. t1+=ido<<1;
  113686. t2+=ido;
  113687. t3+=ido;
  113688. }
  113689. }
  113690. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  113691. float *wa2,float *wa3){
  113692. static float hsqt2 = .70710678118654752f;
  113693. int i,k,t0,t1,t2,t3,t4,t5,t6;
  113694. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  113695. t0=l1*ido;
  113696. t1=t0;
  113697. t4=t1<<1;
  113698. t2=t1+(t1<<1);
  113699. t3=0;
  113700. for(k=0;k<l1;k++){
  113701. tr1=cc[t1]+cc[t2];
  113702. tr2=cc[t3]+cc[t4];
  113703. ch[t5=t3<<2]=tr1+tr2;
  113704. ch[(ido<<2)+t5-1]=tr2-tr1;
  113705. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  113706. ch[t5]=cc[t2]-cc[t1];
  113707. t1+=ido;
  113708. t2+=ido;
  113709. t3+=ido;
  113710. t4+=ido;
  113711. }
  113712. if(ido<2)return;
  113713. if(ido==2)goto L105;
  113714. t1=0;
  113715. for(k=0;k<l1;k++){
  113716. t2=t1;
  113717. t4=t1<<2;
  113718. t5=(t6=ido<<1)+t4;
  113719. for(i=2;i<ido;i+=2){
  113720. t3=(t2+=2);
  113721. t4+=2;
  113722. t5-=2;
  113723. t3+=t0;
  113724. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  113725. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  113726. t3+=t0;
  113727. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  113728. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  113729. t3+=t0;
  113730. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  113731. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  113732. tr1=cr2+cr4;
  113733. tr4=cr4-cr2;
  113734. ti1=ci2+ci4;
  113735. ti4=ci2-ci4;
  113736. ti2=cc[t2]+ci3;
  113737. ti3=cc[t2]-ci3;
  113738. tr2=cc[t2-1]+cr3;
  113739. tr3=cc[t2-1]-cr3;
  113740. ch[t4-1]=tr1+tr2;
  113741. ch[t4]=ti1+ti2;
  113742. ch[t5-1]=tr3-ti4;
  113743. ch[t5]=tr4-ti3;
  113744. ch[t4+t6-1]=ti4+tr3;
  113745. ch[t4+t6]=tr4+ti3;
  113746. ch[t5+t6-1]=tr2-tr1;
  113747. ch[t5+t6]=ti1-ti2;
  113748. }
  113749. t1+=ido;
  113750. }
  113751. if(ido&1)return;
  113752. L105:
  113753. t2=(t1=t0+ido-1)+(t0<<1);
  113754. t3=ido<<2;
  113755. t4=ido;
  113756. t5=ido<<1;
  113757. t6=ido;
  113758. for(k=0;k<l1;k++){
  113759. ti1=-hsqt2*(cc[t1]+cc[t2]);
  113760. tr1=hsqt2*(cc[t1]-cc[t2]);
  113761. ch[t4-1]=tr1+cc[t6-1];
  113762. ch[t4+t5-1]=cc[t6-1]-tr1;
  113763. ch[t4]=ti1-cc[t1+t0];
  113764. ch[t4+t5]=ti1+cc[t1+t0];
  113765. t1+=ido;
  113766. t2+=ido;
  113767. t4+=t3;
  113768. t6+=ido;
  113769. }
  113770. }
  113771. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  113772. float *c2,float *ch,float *ch2,float *wa){
  113773. static float tpi=6.283185307179586f;
  113774. int idij,ipph,i,j,k,l,ic,ik,is;
  113775. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  113776. float dc2,ai1,ai2,ar1,ar2,ds2;
  113777. int nbd;
  113778. float dcp,arg,dsp,ar1h,ar2h;
  113779. int idp2,ipp2;
  113780. arg=tpi/(float)ip;
  113781. dcp=cos(arg);
  113782. dsp=sin(arg);
  113783. ipph=(ip+1)>>1;
  113784. ipp2=ip;
  113785. idp2=ido;
  113786. nbd=(ido-1)>>1;
  113787. t0=l1*ido;
  113788. t10=ip*ido;
  113789. if(ido==1)goto L119;
  113790. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  113791. t1=0;
  113792. for(j=1;j<ip;j++){
  113793. t1+=t0;
  113794. t2=t1;
  113795. for(k=0;k<l1;k++){
  113796. ch[t2]=c1[t2];
  113797. t2+=ido;
  113798. }
  113799. }
  113800. is=-ido;
  113801. t1=0;
  113802. if(nbd>l1){
  113803. for(j=1;j<ip;j++){
  113804. t1+=t0;
  113805. is+=ido;
  113806. t2= -ido+t1;
  113807. for(k=0;k<l1;k++){
  113808. idij=is-1;
  113809. t2+=ido;
  113810. t3=t2;
  113811. for(i=2;i<ido;i+=2){
  113812. idij+=2;
  113813. t3+=2;
  113814. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  113815. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  113816. }
  113817. }
  113818. }
  113819. }else{
  113820. for(j=1;j<ip;j++){
  113821. is+=ido;
  113822. idij=is-1;
  113823. t1+=t0;
  113824. t2=t1;
  113825. for(i=2;i<ido;i+=2){
  113826. idij+=2;
  113827. t2+=2;
  113828. t3=t2;
  113829. for(k=0;k<l1;k++){
  113830. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  113831. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  113832. t3+=ido;
  113833. }
  113834. }
  113835. }
  113836. }
  113837. t1=0;
  113838. t2=ipp2*t0;
  113839. if(nbd<l1){
  113840. for(j=1;j<ipph;j++){
  113841. t1+=t0;
  113842. t2-=t0;
  113843. t3=t1;
  113844. t4=t2;
  113845. for(i=2;i<ido;i+=2){
  113846. t3+=2;
  113847. t4+=2;
  113848. t5=t3-ido;
  113849. t6=t4-ido;
  113850. for(k=0;k<l1;k++){
  113851. t5+=ido;
  113852. t6+=ido;
  113853. c1[t5-1]=ch[t5-1]+ch[t6-1];
  113854. c1[t6-1]=ch[t5]-ch[t6];
  113855. c1[t5]=ch[t5]+ch[t6];
  113856. c1[t6]=ch[t6-1]-ch[t5-1];
  113857. }
  113858. }
  113859. }
  113860. }else{
  113861. for(j=1;j<ipph;j++){
  113862. t1+=t0;
  113863. t2-=t0;
  113864. t3=t1;
  113865. t4=t2;
  113866. for(k=0;k<l1;k++){
  113867. t5=t3;
  113868. t6=t4;
  113869. for(i=2;i<ido;i+=2){
  113870. t5+=2;
  113871. t6+=2;
  113872. c1[t5-1]=ch[t5-1]+ch[t6-1];
  113873. c1[t6-1]=ch[t5]-ch[t6];
  113874. c1[t5]=ch[t5]+ch[t6];
  113875. c1[t6]=ch[t6-1]-ch[t5-1];
  113876. }
  113877. t3+=ido;
  113878. t4+=ido;
  113879. }
  113880. }
  113881. }
  113882. L119:
  113883. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  113884. t1=0;
  113885. t2=ipp2*idl1;
  113886. for(j=1;j<ipph;j++){
  113887. t1+=t0;
  113888. t2-=t0;
  113889. t3=t1-ido;
  113890. t4=t2-ido;
  113891. for(k=0;k<l1;k++){
  113892. t3+=ido;
  113893. t4+=ido;
  113894. c1[t3]=ch[t3]+ch[t4];
  113895. c1[t4]=ch[t4]-ch[t3];
  113896. }
  113897. }
  113898. ar1=1.f;
  113899. ai1=0.f;
  113900. t1=0;
  113901. t2=ipp2*idl1;
  113902. t3=(ip-1)*idl1;
  113903. for(l=1;l<ipph;l++){
  113904. t1+=idl1;
  113905. t2-=idl1;
  113906. ar1h=dcp*ar1-dsp*ai1;
  113907. ai1=dcp*ai1+dsp*ar1;
  113908. ar1=ar1h;
  113909. t4=t1;
  113910. t5=t2;
  113911. t6=t3;
  113912. t7=idl1;
  113913. for(ik=0;ik<idl1;ik++){
  113914. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  113915. ch2[t5++]=ai1*c2[t6++];
  113916. }
  113917. dc2=ar1;
  113918. ds2=ai1;
  113919. ar2=ar1;
  113920. ai2=ai1;
  113921. t4=idl1;
  113922. t5=(ipp2-1)*idl1;
  113923. for(j=2;j<ipph;j++){
  113924. t4+=idl1;
  113925. t5-=idl1;
  113926. ar2h=dc2*ar2-ds2*ai2;
  113927. ai2=dc2*ai2+ds2*ar2;
  113928. ar2=ar2h;
  113929. t6=t1;
  113930. t7=t2;
  113931. t8=t4;
  113932. t9=t5;
  113933. for(ik=0;ik<idl1;ik++){
  113934. ch2[t6++]+=ar2*c2[t8++];
  113935. ch2[t7++]+=ai2*c2[t9++];
  113936. }
  113937. }
  113938. }
  113939. t1=0;
  113940. for(j=1;j<ipph;j++){
  113941. t1+=idl1;
  113942. t2=t1;
  113943. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  113944. }
  113945. if(ido<l1)goto L132;
  113946. t1=0;
  113947. t2=0;
  113948. for(k=0;k<l1;k++){
  113949. t3=t1;
  113950. t4=t2;
  113951. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  113952. t1+=ido;
  113953. t2+=t10;
  113954. }
  113955. goto L135;
  113956. L132:
  113957. for(i=0;i<ido;i++){
  113958. t1=i;
  113959. t2=i;
  113960. for(k=0;k<l1;k++){
  113961. cc[t2]=ch[t1];
  113962. t1+=ido;
  113963. t2+=t10;
  113964. }
  113965. }
  113966. L135:
  113967. t1=0;
  113968. t2=ido<<1;
  113969. t3=0;
  113970. t4=ipp2*t0;
  113971. for(j=1;j<ipph;j++){
  113972. t1+=t2;
  113973. t3+=t0;
  113974. t4-=t0;
  113975. t5=t1;
  113976. t6=t3;
  113977. t7=t4;
  113978. for(k=0;k<l1;k++){
  113979. cc[t5-1]=ch[t6];
  113980. cc[t5]=ch[t7];
  113981. t5+=t10;
  113982. t6+=ido;
  113983. t7+=ido;
  113984. }
  113985. }
  113986. if(ido==1)return;
  113987. if(nbd<l1)goto L141;
  113988. t1=-ido;
  113989. t3=0;
  113990. t4=0;
  113991. t5=ipp2*t0;
  113992. for(j=1;j<ipph;j++){
  113993. t1+=t2;
  113994. t3+=t2;
  113995. t4+=t0;
  113996. t5-=t0;
  113997. t6=t1;
  113998. t7=t3;
  113999. t8=t4;
  114000. t9=t5;
  114001. for(k=0;k<l1;k++){
  114002. for(i=2;i<ido;i+=2){
  114003. ic=idp2-i;
  114004. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  114005. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  114006. cc[i+t7]=ch[i+t8]+ch[i+t9];
  114007. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  114008. }
  114009. t6+=t10;
  114010. t7+=t10;
  114011. t8+=ido;
  114012. t9+=ido;
  114013. }
  114014. }
  114015. return;
  114016. L141:
  114017. t1=-ido;
  114018. t3=0;
  114019. t4=0;
  114020. t5=ipp2*t0;
  114021. for(j=1;j<ipph;j++){
  114022. t1+=t2;
  114023. t3+=t2;
  114024. t4+=t0;
  114025. t5-=t0;
  114026. for(i=2;i<ido;i+=2){
  114027. t6=idp2+t1-i;
  114028. t7=i+t3;
  114029. t8=i+t4;
  114030. t9=i+t5;
  114031. for(k=0;k<l1;k++){
  114032. cc[t7-1]=ch[t8-1]+ch[t9-1];
  114033. cc[t6-1]=ch[t8-1]-ch[t9-1];
  114034. cc[t7]=ch[t8]+ch[t9];
  114035. cc[t6]=ch[t9]-ch[t8];
  114036. t6+=t10;
  114037. t7+=t10;
  114038. t8+=ido;
  114039. t9+=ido;
  114040. }
  114041. }
  114042. }
  114043. }
  114044. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  114045. int i,k1,l1,l2;
  114046. int na,kh,nf;
  114047. int ip,iw,ido,idl1,ix2,ix3;
  114048. nf=ifac[1];
  114049. na=1;
  114050. l2=n;
  114051. iw=n;
  114052. for(k1=0;k1<nf;k1++){
  114053. kh=nf-k1;
  114054. ip=ifac[kh+1];
  114055. l1=l2/ip;
  114056. ido=n/l2;
  114057. idl1=ido*l1;
  114058. iw-=(ip-1)*ido;
  114059. na=1-na;
  114060. if(ip!=4)goto L102;
  114061. ix2=iw+ido;
  114062. ix3=ix2+ido;
  114063. if(na!=0)
  114064. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  114065. else
  114066. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  114067. goto L110;
  114068. L102:
  114069. if(ip!=2)goto L104;
  114070. if(na!=0)goto L103;
  114071. dradf2(ido,l1,c,ch,wa+iw-1);
  114072. goto L110;
  114073. L103:
  114074. dradf2(ido,l1,ch,c,wa+iw-1);
  114075. goto L110;
  114076. L104:
  114077. if(ido==1)na=1-na;
  114078. if(na!=0)goto L109;
  114079. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  114080. na=1;
  114081. goto L110;
  114082. L109:
  114083. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  114084. na=0;
  114085. L110:
  114086. l2=l1;
  114087. }
  114088. if(na==1)return;
  114089. for(i=0;i<n;i++)c[i]=ch[i];
  114090. }
  114091. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  114092. int i,k,t0,t1,t2,t3,t4,t5,t6;
  114093. float ti2,tr2;
  114094. t0=l1*ido;
  114095. t1=0;
  114096. t2=0;
  114097. t3=(ido<<1)-1;
  114098. for(k=0;k<l1;k++){
  114099. ch[t1]=cc[t2]+cc[t3+t2];
  114100. ch[t1+t0]=cc[t2]-cc[t3+t2];
  114101. t2=(t1+=ido)<<1;
  114102. }
  114103. if(ido<2)return;
  114104. if(ido==2)goto L105;
  114105. t1=0;
  114106. t2=0;
  114107. for(k=0;k<l1;k++){
  114108. t3=t1;
  114109. t5=(t4=t2)+(ido<<1);
  114110. t6=t0+t1;
  114111. for(i=2;i<ido;i+=2){
  114112. t3+=2;
  114113. t4+=2;
  114114. t5-=2;
  114115. t6+=2;
  114116. ch[t3-1]=cc[t4-1]+cc[t5-1];
  114117. tr2=cc[t4-1]-cc[t5-1];
  114118. ch[t3]=cc[t4]-cc[t5];
  114119. ti2=cc[t4]+cc[t5];
  114120. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  114121. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  114122. }
  114123. t2=(t1+=ido)<<1;
  114124. }
  114125. if(ido%2==1)return;
  114126. L105:
  114127. t1=ido-1;
  114128. t2=ido-1;
  114129. for(k=0;k<l1;k++){
  114130. ch[t1]=cc[t2]+cc[t2];
  114131. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  114132. t1+=ido;
  114133. t2+=ido<<1;
  114134. }
  114135. }
  114136. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  114137. float *wa2){
  114138. static float taur = -.5f;
  114139. static float taui = .8660254037844386f;
  114140. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  114141. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  114142. t0=l1*ido;
  114143. t1=0;
  114144. t2=t0<<1;
  114145. t3=ido<<1;
  114146. t4=ido+(ido<<1);
  114147. t5=0;
  114148. for(k=0;k<l1;k++){
  114149. tr2=cc[t3-1]+cc[t3-1];
  114150. cr2=cc[t5]+(taur*tr2);
  114151. ch[t1]=cc[t5]+tr2;
  114152. ci3=taui*(cc[t3]+cc[t3]);
  114153. ch[t1+t0]=cr2-ci3;
  114154. ch[t1+t2]=cr2+ci3;
  114155. t1+=ido;
  114156. t3+=t4;
  114157. t5+=t4;
  114158. }
  114159. if(ido==1)return;
  114160. t1=0;
  114161. t3=ido<<1;
  114162. for(k=0;k<l1;k++){
  114163. t7=t1+(t1<<1);
  114164. t6=(t5=t7+t3);
  114165. t8=t1;
  114166. t10=(t9=t1+t0)+t0;
  114167. for(i=2;i<ido;i+=2){
  114168. t5+=2;
  114169. t6-=2;
  114170. t7+=2;
  114171. t8+=2;
  114172. t9+=2;
  114173. t10+=2;
  114174. tr2=cc[t5-1]+cc[t6-1];
  114175. cr2=cc[t7-1]+(taur*tr2);
  114176. ch[t8-1]=cc[t7-1]+tr2;
  114177. ti2=cc[t5]-cc[t6];
  114178. ci2=cc[t7]+(taur*ti2);
  114179. ch[t8]=cc[t7]+ti2;
  114180. cr3=taui*(cc[t5-1]-cc[t6-1]);
  114181. ci3=taui*(cc[t5]+cc[t6]);
  114182. dr2=cr2-ci3;
  114183. dr3=cr2+ci3;
  114184. di2=ci2+cr3;
  114185. di3=ci2-cr3;
  114186. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  114187. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  114188. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  114189. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  114190. }
  114191. t1+=ido;
  114192. }
  114193. }
  114194. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  114195. float *wa2,float *wa3){
  114196. static float sqrt2=1.414213562373095f;
  114197. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  114198. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  114199. t0=l1*ido;
  114200. t1=0;
  114201. t2=ido<<2;
  114202. t3=0;
  114203. t6=ido<<1;
  114204. for(k=0;k<l1;k++){
  114205. t4=t3+t6;
  114206. t5=t1;
  114207. tr3=cc[t4-1]+cc[t4-1];
  114208. tr4=cc[t4]+cc[t4];
  114209. tr1=cc[t3]-cc[(t4+=t6)-1];
  114210. tr2=cc[t3]+cc[t4-1];
  114211. ch[t5]=tr2+tr3;
  114212. ch[t5+=t0]=tr1-tr4;
  114213. ch[t5+=t0]=tr2-tr3;
  114214. ch[t5+=t0]=tr1+tr4;
  114215. t1+=ido;
  114216. t3+=t2;
  114217. }
  114218. if(ido<2)return;
  114219. if(ido==2)goto L105;
  114220. t1=0;
  114221. for(k=0;k<l1;k++){
  114222. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  114223. t7=t1;
  114224. for(i=2;i<ido;i+=2){
  114225. t2+=2;
  114226. t3+=2;
  114227. t4-=2;
  114228. t5-=2;
  114229. t7+=2;
  114230. ti1=cc[t2]+cc[t5];
  114231. ti2=cc[t2]-cc[t5];
  114232. ti3=cc[t3]-cc[t4];
  114233. tr4=cc[t3]+cc[t4];
  114234. tr1=cc[t2-1]-cc[t5-1];
  114235. tr2=cc[t2-1]+cc[t5-1];
  114236. ti4=cc[t3-1]-cc[t4-1];
  114237. tr3=cc[t3-1]+cc[t4-1];
  114238. ch[t7-1]=tr2+tr3;
  114239. cr3=tr2-tr3;
  114240. ch[t7]=ti2+ti3;
  114241. ci3=ti2-ti3;
  114242. cr2=tr1-tr4;
  114243. cr4=tr1+tr4;
  114244. ci2=ti1+ti4;
  114245. ci4=ti1-ti4;
  114246. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  114247. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  114248. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  114249. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  114250. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  114251. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  114252. }
  114253. t1+=ido;
  114254. }
  114255. if(ido%2 == 1)return;
  114256. L105:
  114257. t1=ido;
  114258. t2=ido<<2;
  114259. t3=ido-1;
  114260. t4=ido+(ido<<1);
  114261. for(k=0;k<l1;k++){
  114262. t5=t3;
  114263. ti1=cc[t1]+cc[t4];
  114264. ti2=cc[t4]-cc[t1];
  114265. tr1=cc[t1-1]-cc[t4-1];
  114266. tr2=cc[t1-1]+cc[t4-1];
  114267. ch[t5]=tr2+tr2;
  114268. ch[t5+=t0]=sqrt2*(tr1-ti1);
  114269. ch[t5+=t0]=ti2+ti2;
  114270. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  114271. t3+=ido;
  114272. t1+=t2;
  114273. t4+=t2;
  114274. }
  114275. }
  114276. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  114277. float *c2,float *ch,float *ch2,float *wa){
  114278. static float tpi=6.283185307179586f;
  114279. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  114280. t11,t12;
  114281. float dc2,ai1,ai2,ar1,ar2,ds2;
  114282. int nbd;
  114283. float dcp,arg,dsp,ar1h,ar2h;
  114284. int ipp2;
  114285. t10=ip*ido;
  114286. t0=l1*ido;
  114287. arg=tpi/(float)ip;
  114288. dcp=cos(arg);
  114289. dsp=sin(arg);
  114290. nbd=(ido-1)>>1;
  114291. ipp2=ip;
  114292. ipph=(ip+1)>>1;
  114293. if(ido<l1)goto L103;
  114294. t1=0;
  114295. t2=0;
  114296. for(k=0;k<l1;k++){
  114297. t3=t1;
  114298. t4=t2;
  114299. for(i=0;i<ido;i++){
  114300. ch[t3]=cc[t4];
  114301. t3++;
  114302. t4++;
  114303. }
  114304. t1+=ido;
  114305. t2+=t10;
  114306. }
  114307. goto L106;
  114308. L103:
  114309. t1=0;
  114310. for(i=0;i<ido;i++){
  114311. t2=t1;
  114312. t3=t1;
  114313. for(k=0;k<l1;k++){
  114314. ch[t2]=cc[t3];
  114315. t2+=ido;
  114316. t3+=t10;
  114317. }
  114318. t1++;
  114319. }
  114320. L106:
  114321. t1=0;
  114322. t2=ipp2*t0;
  114323. t7=(t5=ido<<1);
  114324. for(j=1;j<ipph;j++){
  114325. t1+=t0;
  114326. t2-=t0;
  114327. t3=t1;
  114328. t4=t2;
  114329. t6=t5;
  114330. for(k=0;k<l1;k++){
  114331. ch[t3]=cc[t6-1]+cc[t6-1];
  114332. ch[t4]=cc[t6]+cc[t6];
  114333. t3+=ido;
  114334. t4+=ido;
  114335. t6+=t10;
  114336. }
  114337. t5+=t7;
  114338. }
  114339. if (ido == 1)goto L116;
  114340. if(nbd<l1)goto L112;
  114341. t1=0;
  114342. t2=ipp2*t0;
  114343. t7=0;
  114344. for(j=1;j<ipph;j++){
  114345. t1+=t0;
  114346. t2-=t0;
  114347. t3=t1;
  114348. t4=t2;
  114349. t7+=(ido<<1);
  114350. t8=t7;
  114351. for(k=0;k<l1;k++){
  114352. t5=t3;
  114353. t6=t4;
  114354. t9=t8;
  114355. t11=t8;
  114356. for(i=2;i<ido;i+=2){
  114357. t5+=2;
  114358. t6+=2;
  114359. t9+=2;
  114360. t11-=2;
  114361. ch[t5-1]=cc[t9-1]+cc[t11-1];
  114362. ch[t6-1]=cc[t9-1]-cc[t11-1];
  114363. ch[t5]=cc[t9]-cc[t11];
  114364. ch[t6]=cc[t9]+cc[t11];
  114365. }
  114366. t3+=ido;
  114367. t4+=ido;
  114368. t8+=t10;
  114369. }
  114370. }
  114371. goto L116;
  114372. L112:
  114373. t1=0;
  114374. t2=ipp2*t0;
  114375. t7=0;
  114376. for(j=1;j<ipph;j++){
  114377. t1+=t0;
  114378. t2-=t0;
  114379. t3=t1;
  114380. t4=t2;
  114381. t7+=(ido<<1);
  114382. t8=t7;
  114383. t9=t7;
  114384. for(i=2;i<ido;i+=2){
  114385. t3+=2;
  114386. t4+=2;
  114387. t8+=2;
  114388. t9-=2;
  114389. t5=t3;
  114390. t6=t4;
  114391. t11=t8;
  114392. t12=t9;
  114393. for(k=0;k<l1;k++){
  114394. ch[t5-1]=cc[t11-1]+cc[t12-1];
  114395. ch[t6-1]=cc[t11-1]-cc[t12-1];
  114396. ch[t5]=cc[t11]-cc[t12];
  114397. ch[t6]=cc[t11]+cc[t12];
  114398. t5+=ido;
  114399. t6+=ido;
  114400. t11+=t10;
  114401. t12+=t10;
  114402. }
  114403. }
  114404. }
  114405. L116:
  114406. ar1=1.f;
  114407. ai1=0.f;
  114408. t1=0;
  114409. t9=(t2=ipp2*idl1);
  114410. t3=(ip-1)*idl1;
  114411. for(l=1;l<ipph;l++){
  114412. t1+=idl1;
  114413. t2-=idl1;
  114414. ar1h=dcp*ar1-dsp*ai1;
  114415. ai1=dcp*ai1+dsp*ar1;
  114416. ar1=ar1h;
  114417. t4=t1;
  114418. t5=t2;
  114419. t6=0;
  114420. t7=idl1;
  114421. t8=t3;
  114422. for(ik=0;ik<idl1;ik++){
  114423. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  114424. c2[t5++]=ai1*ch2[t8++];
  114425. }
  114426. dc2=ar1;
  114427. ds2=ai1;
  114428. ar2=ar1;
  114429. ai2=ai1;
  114430. t6=idl1;
  114431. t7=t9-idl1;
  114432. for(j=2;j<ipph;j++){
  114433. t6+=idl1;
  114434. t7-=idl1;
  114435. ar2h=dc2*ar2-ds2*ai2;
  114436. ai2=dc2*ai2+ds2*ar2;
  114437. ar2=ar2h;
  114438. t4=t1;
  114439. t5=t2;
  114440. t11=t6;
  114441. t12=t7;
  114442. for(ik=0;ik<idl1;ik++){
  114443. c2[t4++]+=ar2*ch2[t11++];
  114444. c2[t5++]+=ai2*ch2[t12++];
  114445. }
  114446. }
  114447. }
  114448. t1=0;
  114449. for(j=1;j<ipph;j++){
  114450. t1+=idl1;
  114451. t2=t1;
  114452. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  114453. }
  114454. t1=0;
  114455. t2=ipp2*t0;
  114456. for(j=1;j<ipph;j++){
  114457. t1+=t0;
  114458. t2-=t0;
  114459. t3=t1;
  114460. t4=t2;
  114461. for(k=0;k<l1;k++){
  114462. ch[t3]=c1[t3]-c1[t4];
  114463. ch[t4]=c1[t3]+c1[t4];
  114464. t3+=ido;
  114465. t4+=ido;
  114466. }
  114467. }
  114468. if(ido==1)goto L132;
  114469. if(nbd<l1)goto L128;
  114470. t1=0;
  114471. t2=ipp2*t0;
  114472. for(j=1;j<ipph;j++){
  114473. t1+=t0;
  114474. t2-=t0;
  114475. t3=t1;
  114476. t4=t2;
  114477. for(k=0;k<l1;k++){
  114478. t5=t3;
  114479. t6=t4;
  114480. for(i=2;i<ido;i+=2){
  114481. t5+=2;
  114482. t6+=2;
  114483. ch[t5-1]=c1[t5-1]-c1[t6];
  114484. ch[t6-1]=c1[t5-1]+c1[t6];
  114485. ch[t5]=c1[t5]+c1[t6-1];
  114486. ch[t6]=c1[t5]-c1[t6-1];
  114487. }
  114488. t3+=ido;
  114489. t4+=ido;
  114490. }
  114491. }
  114492. goto L132;
  114493. L128:
  114494. t1=0;
  114495. t2=ipp2*t0;
  114496. for(j=1;j<ipph;j++){
  114497. t1+=t0;
  114498. t2-=t0;
  114499. t3=t1;
  114500. t4=t2;
  114501. for(i=2;i<ido;i+=2){
  114502. t3+=2;
  114503. t4+=2;
  114504. t5=t3;
  114505. t6=t4;
  114506. for(k=0;k<l1;k++){
  114507. ch[t5-1]=c1[t5-1]-c1[t6];
  114508. ch[t6-1]=c1[t5-1]+c1[t6];
  114509. ch[t5]=c1[t5]+c1[t6-1];
  114510. ch[t6]=c1[t5]-c1[t6-1];
  114511. t5+=ido;
  114512. t6+=ido;
  114513. }
  114514. }
  114515. }
  114516. L132:
  114517. if(ido==1)return;
  114518. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  114519. t1=0;
  114520. for(j=1;j<ip;j++){
  114521. t2=(t1+=t0);
  114522. for(k=0;k<l1;k++){
  114523. c1[t2]=ch[t2];
  114524. t2+=ido;
  114525. }
  114526. }
  114527. if(nbd>l1)goto L139;
  114528. is= -ido-1;
  114529. t1=0;
  114530. for(j=1;j<ip;j++){
  114531. is+=ido;
  114532. t1+=t0;
  114533. idij=is;
  114534. t2=t1;
  114535. for(i=2;i<ido;i+=2){
  114536. t2+=2;
  114537. idij+=2;
  114538. t3=t2;
  114539. for(k=0;k<l1;k++){
  114540. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  114541. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  114542. t3+=ido;
  114543. }
  114544. }
  114545. }
  114546. return;
  114547. L139:
  114548. is= -ido-1;
  114549. t1=0;
  114550. for(j=1;j<ip;j++){
  114551. is+=ido;
  114552. t1+=t0;
  114553. t2=t1;
  114554. for(k=0;k<l1;k++){
  114555. idij=is;
  114556. t3=t2;
  114557. for(i=2;i<ido;i+=2){
  114558. idij+=2;
  114559. t3+=2;
  114560. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  114561. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  114562. }
  114563. t2+=ido;
  114564. }
  114565. }
  114566. }
  114567. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  114568. int i,k1,l1,l2;
  114569. int na;
  114570. int nf,ip,iw,ix2,ix3,ido,idl1;
  114571. nf=ifac[1];
  114572. na=0;
  114573. l1=1;
  114574. iw=1;
  114575. for(k1=0;k1<nf;k1++){
  114576. ip=ifac[k1 + 2];
  114577. l2=ip*l1;
  114578. ido=n/l2;
  114579. idl1=ido*l1;
  114580. if(ip!=4)goto L103;
  114581. ix2=iw+ido;
  114582. ix3=ix2+ido;
  114583. if(na!=0)
  114584. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  114585. else
  114586. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  114587. na=1-na;
  114588. goto L115;
  114589. L103:
  114590. if(ip!=2)goto L106;
  114591. if(na!=0)
  114592. dradb2(ido,l1,ch,c,wa+iw-1);
  114593. else
  114594. dradb2(ido,l1,c,ch,wa+iw-1);
  114595. na=1-na;
  114596. goto L115;
  114597. L106:
  114598. if(ip!=3)goto L109;
  114599. ix2=iw+ido;
  114600. if(na!=0)
  114601. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  114602. else
  114603. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  114604. na=1-na;
  114605. goto L115;
  114606. L109:
  114607. /* The radix five case can be translated later..... */
  114608. /* if(ip!=5)goto L112;
  114609. ix2=iw+ido;
  114610. ix3=ix2+ido;
  114611. ix4=ix3+ido;
  114612. if(na!=0)
  114613. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  114614. else
  114615. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  114616. na=1-na;
  114617. goto L115;
  114618. L112:*/
  114619. if(na!=0)
  114620. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  114621. else
  114622. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  114623. if(ido==1)na=1-na;
  114624. L115:
  114625. l1=l2;
  114626. iw+=(ip-1)*ido;
  114627. }
  114628. if(na==0)return;
  114629. for(i=0;i<n;i++)c[i]=ch[i];
  114630. }
  114631. void drft_forward(drft_lookup *l,float *data){
  114632. if(l->n==1)return;
  114633. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  114634. }
  114635. void drft_backward(drft_lookup *l,float *data){
  114636. if (l->n==1)return;
  114637. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  114638. }
  114639. void drft_init(drft_lookup *l,int n){
  114640. l->n=n;
  114641. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  114642. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  114643. fdrffti(n, l->trigcache, l->splitcache);
  114644. }
  114645. void drft_clear(drft_lookup *l){
  114646. if(l){
  114647. if(l->trigcache)_ogg_free(l->trigcache);
  114648. if(l->splitcache)_ogg_free(l->splitcache);
  114649. memset(l,0,sizeof(*l));
  114650. }
  114651. }
  114652. #endif
  114653. /********* End of inlined file: smallft.c *********/
  114654. /********* Start of inlined file: synthesis.c *********/
  114655. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  114656. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114657. // tasks..
  114658. #ifdef _MSC_VER
  114659. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114660. #endif
  114661. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  114662. #if JUCE_USE_OGGVORBIS
  114663. #include <stdio.h>
  114664. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  114665. vorbis_dsp_state *vd=vb->vd;
  114666. private_state *b=(private_state*)vd->backend_state;
  114667. vorbis_info *vi=vd->vi;
  114668. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  114669. oggpack_buffer *opb=&vb->opb;
  114670. int type,mode,i;
  114671. /* first things first. Make sure decode is ready */
  114672. _vorbis_block_ripcord(vb);
  114673. oggpack_readinit(opb,op->packet,op->bytes);
  114674. /* Check the packet type */
  114675. if(oggpack_read(opb,1)!=0){
  114676. /* Oops. This is not an audio data packet */
  114677. return(OV_ENOTAUDIO);
  114678. }
  114679. /* read our mode and pre/post windowsize */
  114680. mode=oggpack_read(opb,b->modebits);
  114681. if(mode==-1)return(OV_EBADPACKET);
  114682. vb->mode=mode;
  114683. vb->W=ci->mode_param[mode]->blockflag;
  114684. if(vb->W){
  114685. /* this doesn;t get mapped through mode selection as it's used
  114686. only for window selection */
  114687. vb->lW=oggpack_read(opb,1);
  114688. vb->nW=oggpack_read(opb,1);
  114689. if(vb->nW==-1) return(OV_EBADPACKET);
  114690. }else{
  114691. vb->lW=0;
  114692. vb->nW=0;
  114693. }
  114694. /* more setup */
  114695. vb->granulepos=op->granulepos;
  114696. vb->sequence=op->packetno;
  114697. vb->eofflag=op->e_o_s;
  114698. /* alloc pcm passback storage */
  114699. vb->pcmend=ci->blocksizes[vb->W];
  114700. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  114701. for(i=0;i<vi->channels;i++)
  114702. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  114703. /* unpack_header enforces range checking */
  114704. type=ci->map_type[ci->mode_param[mode]->mapping];
  114705. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  114706. mapping]));
  114707. }
  114708. /* used to track pcm position without actually performing decode.
  114709. Useful for sequential 'fast forward' */
  114710. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  114711. vorbis_dsp_state *vd=vb->vd;
  114712. private_state *b=(private_state*)vd->backend_state;
  114713. vorbis_info *vi=vd->vi;
  114714. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114715. oggpack_buffer *opb=&vb->opb;
  114716. int mode;
  114717. /* first things first. Make sure decode is ready */
  114718. _vorbis_block_ripcord(vb);
  114719. oggpack_readinit(opb,op->packet,op->bytes);
  114720. /* Check the packet type */
  114721. if(oggpack_read(opb,1)!=0){
  114722. /* Oops. This is not an audio data packet */
  114723. return(OV_ENOTAUDIO);
  114724. }
  114725. /* read our mode and pre/post windowsize */
  114726. mode=oggpack_read(opb,b->modebits);
  114727. if(mode==-1)return(OV_EBADPACKET);
  114728. vb->mode=mode;
  114729. vb->W=ci->mode_param[mode]->blockflag;
  114730. if(vb->W){
  114731. vb->lW=oggpack_read(opb,1);
  114732. vb->nW=oggpack_read(opb,1);
  114733. if(vb->nW==-1) return(OV_EBADPACKET);
  114734. }else{
  114735. vb->lW=0;
  114736. vb->nW=0;
  114737. }
  114738. /* more setup */
  114739. vb->granulepos=op->granulepos;
  114740. vb->sequence=op->packetno;
  114741. vb->eofflag=op->e_o_s;
  114742. /* no pcm */
  114743. vb->pcmend=0;
  114744. vb->pcm=NULL;
  114745. return(0);
  114746. }
  114747. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  114748. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114749. oggpack_buffer opb;
  114750. int mode;
  114751. oggpack_readinit(&opb,op->packet,op->bytes);
  114752. /* Check the packet type */
  114753. if(oggpack_read(&opb,1)!=0){
  114754. /* Oops. This is not an audio data packet */
  114755. return(OV_ENOTAUDIO);
  114756. }
  114757. {
  114758. int modebits=0;
  114759. int v=ci->modes;
  114760. while(v>1){
  114761. modebits++;
  114762. v>>=1;
  114763. }
  114764. /* read our mode and pre/post windowsize */
  114765. mode=oggpack_read(&opb,modebits);
  114766. }
  114767. if(mode==-1)return(OV_EBADPACKET);
  114768. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  114769. }
  114770. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  114771. /* set / clear half-sample-rate mode */
  114772. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114773. /* right now, our MDCT can't handle < 64 sample windows. */
  114774. if(ci->blocksizes[0]<=64 && flag)return -1;
  114775. ci->halfrate_flag=(flag?1:0);
  114776. return 0;
  114777. }
  114778. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  114779. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114780. return ci->halfrate_flag;
  114781. }
  114782. #endif
  114783. /********* End of inlined file: synthesis.c *********/
  114784. /********* Start of inlined file: vorbisenc.c *********/
  114785. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  114786. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114787. // tasks..
  114788. #ifdef _MSC_VER
  114789. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114790. #endif
  114791. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  114792. #if JUCE_USE_OGGVORBIS
  114793. #include <stdlib.h>
  114794. #include <string.h>
  114795. #include <math.h>
  114796. /* careful with this; it's using static array sizing to make managing
  114797. all the modes a little less annoying. If we use a residue backend
  114798. with > 12 partition types, or a different division of iteration,
  114799. this needs to be updated. */
  114800. typedef struct {
  114801. static_codebook *books[12][3];
  114802. } static_bookblock;
  114803. typedef struct {
  114804. int res_type;
  114805. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  114806. vorbis_info_residue0 *res;
  114807. static_codebook *book_aux;
  114808. static_codebook *book_aux_managed;
  114809. static_bookblock *books_base;
  114810. static_bookblock *books_base_managed;
  114811. } vorbis_residue_template;
  114812. typedef struct {
  114813. vorbis_info_mapping0 *map;
  114814. vorbis_residue_template *res;
  114815. } vorbis_mapping_template;
  114816. typedef struct vp_adjblock{
  114817. int block[P_BANDS];
  114818. } vp_adjblock;
  114819. typedef struct {
  114820. int data[NOISE_COMPAND_LEVELS];
  114821. } compandblock;
  114822. /* high level configuration information for setting things up
  114823. step-by-step with the detailed vorbis_encode_ctl interface.
  114824. There's a fair amount of redundancy such that interactive setup
  114825. does not directly deal with any vorbis_info or codec_setup_info
  114826. initialization; it's all stored (until full init) in this highlevel
  114827. setup, then flushed out to the real codec setup structs later. */
  114828. typedef struct {
  114829. int att[P_NOISECURVES];
  114830. float boost;
  114831. float decay;
  114832. } att3;
  114833. typedef struct { int data[P_NOISECURVES]; } adj3;
  114834. typedef struct {
  114835. int pre[PACKETBLOBS];
  114836. int post[PACKETBLOBS];
  114837. float kHz[PACKETBLOBS];
  114838. float lowpasskHz[PACKETBLOBS];
  114839. } adj_stereo;
  114840. typedef struct {
  114841. int lo;
  114842. int hi;
  114843. int fixed;
  114844. } noiseguard;
  114845. typedef struct {
  114846. int data[P_NOISECURVES][17];
  114847. } noise3;
  114848. typedef struct {
  114849. int mappings;
  114850. double *rate_mapping;
  114851. double *quality_mapping;
  114852. int coupling_restriction;
  114853. long samplerate_min_restriction;
  114854. long samplerate_max_restriction;
  114855. int *blocksize_short;
  114856. int *blocksize_long;
  114857. att3 *psy_tone_masteratt;
  114858. int *psy_tone_0dB;
  114859. int *psy_tone_dBsuppress;
  114860. vp_adjblock *psy_tone_adj_impulse;
  114861. vp_adjblock *psy_tone_adj_long;
  114862. vp_adjblock *psy_tone_adj_other;
  114863. noiseguard *psy_noiseguards;
  114864. noise3 *psy_noise_bias_impulse;
  114865. noise3 *psy_noise_bias_padding;
  114866. noise3 *psy_noise_bias_trans;
  114867. noise3 *psy_noise_bias_long;
  114868. int *psy_noise_dBsuppress;
  114869. compandblock *psy_noise_compand;
  114870. double *psy_noise_compand_short_mapping;
  114871. double *psy_noise_compand_long_mapping;
  114872. int *psy_noise_normal_start[2];
  114873. int *psy_noise_normal_partition[2];
  114874. double *psy_noise_normal_thresh;
  114875. int *psy_ath_float;
  114876. int *psy_ath_abs;
  114877. double *psy_lowpass;
  114878. vorbis_info_psy_global *global_params;
  114879. double *global_mapping;
  114880. adj_stereo *stereo_modes;
  114881. static_codebook ***floor_books;
  114882. vorbis_info_floor1 *floor_params;
  114883. int *floor_short_mapping;
  114884. int *floor_long_mapping;
  114885. vorbis_mapping_template *maps;
  114886. } ve_setup_data_template;
  114887. /* a few static coder conventions */
  114888. static vorbis_info_mode _mode_template[2]={
  114889. {0,0,0,0},
  114890. {1,0,0,1}
  114891. };
  114892. static vorbis_info_mapping0 _map_nominal[2]={
  114893. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  114894. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  114895. };
  114896. /********* Start of inlined file: setup_44.h *********/
  114897. /********* Start of inlined file: floor_all.h *********/
  114898. /********* Start of inlined file: floor_books.h *********/
  114899. static long _huff_lengthlist_line_256x7_0sub1[] = {
  114900. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  114901. };
  114902. static static_codebook _huff_book_line_256x7_0sub1 = {
  114903. 1, 9,
  114904. _huff_lengthlist_line_256x7_0sub1,
  114905. 0, 0, 0, 0, 0,
  114906. NULL,
  114907. NULL,
  114908. NULL,
  114909. NULL,
  114910. 0
  114911. };
  114912. static long _huff_lengthlist_line_256x7_0sub2[] = {
  114913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  114914. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  114915. };
  114916. static static_codebook _huff_book_line_256x7_0sub2 = {
  114917. 1, 25,
  114918. _huff_lengthlist_line_256x7_0sub2,
  114919. 0, 0, 0, 0, 0,
  114920. NULL,
  114921. NULL,
  114922. NULL,
  114923. NULL,
  114924. 0
  114925. };
  114926. static long _huff_lengthlist_line_256x7_0sub3[] = {
  114927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  114929. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  114930. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  114931. };
  114932. static static_codebook _huff_book_line_256x7_0sub3 = {
  114933. 1, 64,
  114934. _huff_lengthlist_line_256x7_0sub3,
  114935. 0, 0, 0, 0, 0,
  114936. NULL,
  114937. NULL,
  114938. NULL,
  114939. NULL,
  114940. 0
  114941. };
  114942. static long _huff_lengthlist_line_256x7_1sub1[] = {
  114943. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  114944. };
  114945. static static_codebook _huff_book_line_256x7_1sub1 = {
  114946. 1, 9,
  114947. _huff_lengthlist_line_256x7_1sub1,
  114948. 0, 0, 0, 0, 0,
  114949. NULL,
  114950. NULL,
  114951. NULL,
  114952. NULL,
  114953. 0
  114954. };
  114955. static long _huff_lengthlist_line_256x7_1sub2[] = {
  114956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  114957. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  114958. };
  114959. static static_codebook _huff_book_line_256x7_1sub2 = {
  114960. 1, 25,
  114961. _huff_lengthlist_line_256x7_1sub2,
  114962. 0, 0, 0, 0, 0,
  114963. NULL,
  114964. NULL,
  114965. NULL,
  114966. NULL,
  114967. 0
  114968. };
  114969. static long _huff_lengthlist_line_256x7_1sub3[] = {
  114970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  114972. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  114973. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  114974. };
  114975. static static_codebook _huff_book_line_256x7_1sub3 = {
  114976. 1, 64,
  114977. _huff_lengthlist_line_256x7_1sub3,
  114978. 0, 0, 0, 0, 0,
  114979. NULL,
  114980. NULL,
  114981. NULL,
  114982. NULL,
  114983. 0
  114984. };
  114985. static long _huff_lengthlist_line_256x7_class0[] = {
  114986. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  114987. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  114988. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  114989. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  114990. };
  114991. static static_codebook _huff_book_line_256x7_class0 = {
  114992. 1, 64,
  114993. _huff_lengthlist_line_256x7_class0,
  114994. 0, 0, 0, 0, 0,
  114995. NULL,
  114996. NULL,
  114997. NULL,
  114998. NULL,
  114999. 0
  115000. };
  115001. static long _huff_lengthlist_line_256x7_class1[] = {
  115002. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  115003. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  115004. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  115005. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  115006. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  115007. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  115008. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  115009. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  115010. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  115011. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  115012. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  115013. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  115014. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  115015. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  115016. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  115017. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  115018. };
  115019. static static_codebook _huff_book_line_256x7_class1 = {
  115020. 1, 256,
  115021. _huff_lengthlist_line_256x7_class1,
  115022. 0, 0, 0, 0, 0,
  115023. NULL,
  115024. NULL,
  115025. NULL,
  115026. NULL,
  115027. 0
  115028. };
  115029. static long _huff_lengthlist_line_512x17_0sub0[] = {
  115030. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  115031. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  115032. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  115033. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  115034. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  115035. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  115036. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  115037. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  115038. };
  115039. static static_codebook _huff_book_line_512x17_0sub0 = {
  115040. 1, 128,
  115041. _huff_lengthlist_line_512x17_0sub0,
  115042. 0, 0, 0, 0, 0,
  115043. NULL,
  115044. NULL,
  115045. NULL,
  115046. NULL,
  115047. 0
  115048. };
  115049. static long _huff_lengthlist_line_512x17_1sub0[] = {
  115050. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  115051. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  115052. };
  115053. static static_codebook _huff_book_line_512x17_1sub0 = {
  115054. 1, 32,
  115055. _huff_lengthlist_line_512x17_1sub0,
  115056. 0, 0, 0, 0, 0,
  115057. NULL,
  115058. NULL,
  115059. NULL,
  115060. NULL,
  115061. 0
  115062. };
  115063. static long _huff_lengthlist_line_512x17_1sub1[] = {
  115064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115066. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  115067. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  115068. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  115069. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  115070. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  115071. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  115072. };
  115073. static static_codebook _huff_book_line_512x17_1sub1 = {
  115074. 1, 128,
  115075. _huff_lengthlist_line_512x17_1sub1,
  115076. 0, 0, 0, 0, 0,
  115077. NULL,
  115078. NULL,
  115079. NULL,
  115080. NULL,
  115081. 0
  115082. };
  115083. static long _huff_lengthlist_line_512x17_2sub1[] = {
  115084. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  115085. 5, 3,
  115086. };
  115087. static static_codebook _huff_book_line_512x17_2sub1 = {
  115088. 1, 18,
  115089. _huff_lengthlist_line_512x17_2sub1,
  115090. 0, 0, 0, 0, 0,
  115091. NULL,
  115092. NULL,
  115093. NULL,
  115094. NULL,
  115095. 0
  115096. };
  115097. static long _huff_lengthlist_line_512x17_2sub2[] = {
  115098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115099. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  115100. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  115101. 9, 8,
  115102. };
  115103. static static_codebook _huff_book_line_512x17_2sub2 = {
  115104. 1, 50,
  115105. _huff_lengthlist_line_512x17_2sub2,
  115106. 0, 0, 0, 0, 0,
  115107. NULL,
  115108. NULL,
  115109. NULL,
  115110. NULL,
  115111. 0
  115112. };
  115113. static long _huff_lengthlist_line_512x17_2sub3[] = {
  115114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115117. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  115118. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  115119. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115120. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115121. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115122. };
  115123. static static_codebook _huff_book_line_512x17_2sub3 = {
  115124. 1, 128,
  115125. _huff_lengthlist_line_512x17_2sub3,
  115126. 0, 0, 0, 0, 0,
  115127. NULL,
  115128. NULL,
  115129. NULL,
  115130. NULL,
  115131. 0
  115132. };
  115133. static long _huff_lengthlist_line_512x17_3sub1[] = {
  115134. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  115135. 5, 5,
  115136. };
  115137. static static_codebook _huff_book_line_512x17_3sub1 = {
  115138. 1, 18,
  115139. _huff_lengthlist_line_512x17_3sub1,
  115140. 0, 0, 0, 0, 0,
  115141. NULL,
  115142. NULL,
  115143. NULL,
  115144. NULL,
  115145. 0
  115146. };
  115147. static long _huff_lengthlist_line_512x17_3sub2[] = {
  115148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115149. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  115150. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  115151. 11,14,
  115152. };
  115153. static static_codebook _huff_book_line_512x17_3sub2 = {
  115154. 1, 50,
  115155. _huff_lengthlist_line_512x17_3sub2,
  115156. 0, 0, 0, 0, 0,
  115157. NULL,
  115158. NULL,
  115159. NULL,
  115160. NULL,
  115161. 0
  115162. };
  115163. static long _huff_lengthlist_line_512x17_3sub3[] = {
  115164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115167. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  115168. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115169. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115170. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115171. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115172. };
  115173. static static_codebook _huff_book_line_512x17_3sub3 = {
  115174. 1, 128,
  115175. _huff_lengthlist_line_512x17_3sub3,
  115176. 0, 0, 0, 0, 0,
  115177. NULL,
  115178. NULL,
  115179. NULL,
  115180. NULL,
  115181. 0
  115182. };
  115183. static long _huff_lengthlist_line_512x17_class1[] = {
  115184. 1, 2, 3, 6, 5, 4, 7, 7,
  115185. };
  115186. static static_codebook _huff_book_line_512x17_class1 = {
  115187. 1, 8,
  115188. _huff_lengthlist_line_512x17_class1,
  115189. 0, 0, 0, 0, 0,
  115190. NULL,
  115191. NULL,
  115192. NULL,
  115193. NULL,
  115194. 0
  115195. };
  115196. static long _huff_lengthlist_line_512x17_class2[] = {
  115197. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  115198. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  115199. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  115200. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  115201. };
  115202. static static_codebook _huff_book_line_512x17_class2 = {
  115203. 1, 64,
  115204. _huff_lengthlist_line_512x17_class2,
  115205. 0, 0, 0, 0, 0,
  115206. NULL,
  115207. NULL,
  115208. NULL,
  115209. NULL,
  115210. 0
  115211. };
  115212. static long _huff_lengthlist_line_512x17_class3[] = {
  115213. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  115214. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  115215. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  115216. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  115217. };
  115218. static static_codebook _huff_book_line_512x17_class3 = {
  115219. 1, 64,
  115220. _huff_lengthlist_line_512x17_class3,
  115221. 0, 0, 0, 0, 0,
  115222. NULL,
  115223. NULL,
  115224. NULL,
  115225. NULL,
  115226. 0
  115227. };
  115228. static long _huff_lengthlist_line_128x4_class0[] = {
  115229. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  115230. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  115231. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  115232. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  115233. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  115234. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  115235. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  115236. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  115237. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  115238. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  115239. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  115240. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  115241. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  115242. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  115243. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  115244. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  115245. };
  115246. static static_codebook _huff_book_line_128x4_class0 = {
  115247. 1, 256,
  115248. _huff_lengthlist_line_128x4_class0,
  115249. 0, 0, 0, 0, 0,
  115250. NULL,
  115251. NULL,
  115252. NULL,
  115253. NULL,
  115254. 0
  115255. };
  115256. static long _huff_lengthlist_line_128x4_0sub0[] = {
  115257. 2, 2, 2, 2,
  115258. };
  115259. static static_codebook _huff_book_line_128x4_0sub0 = {
  115260. 1, 4,
  115261. _huff_lengthlist_line_128x4_0sub0,
  115262. 0, 0, 0, 0, 0,
  115263. NULL,
  115264. NULL,
  115265. NULL,
  115266. NULL,
  115267. 0
  115268. };
  115269. static long _huff_lengthlist_line_128x4_0sub1[] = {
  115270. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  115271. };
  115272. static static_codebook _huff_book_line_128x4_0sub1 = {
  115273. 1, 10,
  115274. _huff_lengthlist_line_128x4_0sub1,
  115275. 0, 0, 0, 0, 0,
  115276. NULL,
  115277. NULL,
  115278. NULL,
  115279. NULL,
  115280. 0
  115281. };
  115282. static long _huff_lengthlist_line_128x4_0sub2[] = {
  115283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  115284. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  115285. };
  115286. static static_codebook _huff_book_line_128x4_0sub2 = {
  115287. 1, 25,
  115288. _huff_lengthlist_line_128x4_0sub2,
  115289. 0, 0, 0, 0, 0,
  115290. NULL,
  115291. NULL,
  115292. NULL,
  115293. NULL,
  115294. 0
  115295. };
  115296. static long _huff_lengthlist_line_128x4_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. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  115300. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  115301. };
  115302. static static_codebook _huff_book_line_128x4_0sub3 = {
  115303. 1, 64,
  115304. _huff_lengthlist_line_128x4_0sub3,
  115305. 0, 0, 0, 0, 0,
  115306. NULL,
  115307. NULL,
  115308. NULL,
  115309. NULL,
  115310. 0
  115311. };
  115312. static long _huff_lengthlist_line_256x4_class0[] = {
  115313. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  115314. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  115315. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  115316. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  115317. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  115318. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  115319. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  115320. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  115321. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  115322. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  115323. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  115324. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  115325. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  115326. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  115327. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  115328. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  115329. };
  115330. static static_codebook _huff_book_line_256x4_class0 = {
  115331. 1, 256,
  115332. _huff_lengthlist_line_256x4_class0,
  115333. 0, 0, 0, 0, 0,
  115334. NULL,
  115335. NULL,
  115336. NULL,
  115337. NULL,
  115338. 0
  115339. };
  115340. static long _huff_lengthlist_line_256x4_0sub0[] = {
  115341. 2, 2, 2, 2,
  115342. };
  115343. static static_codebook _huff_book_line_256x4_0sub0 = {
  115344. 1, 4,
  115345. _huff_lengthlist_line_256x4_0sub0,
  115346. 0, 0, 0, 0, 0,
  115347. NULL,
  115348. NULL,
  115349. NULL,
  115350. NULL,
  115351. 0
  115352. };
  115353. static long _huff_lengthlist_line_256x4_0sub1[] = {
  115354. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  115355. };
  115356. static static_codebook _huff_book_line_256x4_0sub1 = {
  115357. 1, 10,
  115358. _huff_lengthlist_line_256x4_0sub1,
  115359. 0, 0, 0, 0, 0,
  115360. NULL,
  115361. NULL,
  115362. NULL,
  115363. NULL,
  115364. 0
  115365. };
  115366. static long _huff_lengthlist_line_256x4_0sub2[] = {
  115367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  115368. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  115369. };
  115370. static static_codebook _huff_book_line_256x4_0sub2 = {
  115371. 1, 25,
  115372. _huff_lengthlist_line_256x4_0sub2,
  115373. 0, 0, 0, 0, 0,
  115374. NULL,
  115375. NULL,
  115376. NULL,
  115377. NULL,
  115378. 0
  115379. };
  115380. static long _huff_lengthlist_line_256x4_0sub3[] = {
  115381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  115383. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  115384. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  115385. };
  115386. static static_codebook _huff_book_line_256x4_0sub3 = {
  115387. 1, 64,
  115388. _huff_lengthlist_line_256x4_0sub3,
  115389. 0, 0, 0, 0, 0,
  115390. NULL,
  115391. NULL,
  115392. NULL,
  115393. NULL,
  115394. 0
  115395. };
  115396. static long _huff_lengthlist_line_128x7_class0[] = {
  115397. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  115398. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  115399. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  115400. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  115401. };
  115402. static static_codebook _huff_book_line_128x7_class0 = {
  115403. 1, 64,
  115404. _huff_lengthlist_line_128x7_class0,
  115405. 0, 0, 0, 0, 0,
  115406. NULL,
  115407. NULL,
  115408. NULL,
  115409. NULL,
  115410. 0
  115411. };
  115412. static long _huff_lengthlist_line_128x7_class1[] = {
  115413. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  115414. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  115415. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  115416. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  115417. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  115418. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  115419. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  115420. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  115421. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  115422. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  115423. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  115424. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  115425. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  115426. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  115427. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  115428. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  115429. };
  115430. static static_codebook _huff_book_line_128x7_class1 = {
  115431. 1, 256,
  115432. _huff_lengthlist_line_128x7_class1,
  115433. 0, 0, 0, 0, 0,
  115434. NULL,
  115435. NULL,
  115436. NULL,
  115437. NULL,
  115438. 0
  115439. };
  115440. static long _huff_lengthlist_line_128x7_0sub1[] = {
  115441. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  115442. };
  115443. static static_codebook _huff_book_line_128x7_0sub1 = {
  115444. 1, 9,
  115445. _huff_lengthlist_line_128x7_0sub1,
  115446. 0, 0, 0, 0, 0,
  115447. NULL,
  115448. NULL,
  115449. NULL,
  115450. NULL,
  115451. 0
  115452. };
  115453. static long _huff_lengthlist_line_128x7_0sub2[] = {
  115454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  115455. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  115456. };
  115457. static static_codebook _huff_book_line_128x7_0sub2 = {
  115458. 1, 25,
  115459. _huff_lengthlist_line_128x7_0sub2,
  115460. 0, 0, 0, 0, 0,
  115461. NULL,
  115462. NULL,
  115463. NULL,
  115464. NULL,
  115465. 0
  115466. };
  115467. static long _huff_lengthlist_line_128x7_0sub3[] = {
  115468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  115470. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115471. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  115472. };
  115473. static static_codebook _huff_book_line_128x7_0sub3 = {
  115474. 1, 64,
  115475. _huff_lengthlist_line_128x7_0sub3,
  115476. 0, 0, 0, 0, 0,
  115477. NULL,
  115478. NULL,
  115479. NULL,
  115480. NULL,
  115481. 0
  115482. };
  115483. static long _huff_lengthlist_line_128x7_1sub1[] = {
  115484. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  115485. };
  115486. static static_codebook _huff_book_line_128x7_1sub1 = {
  115487. 1, 9,
  115488. _huff_lengthlist_line_128x7_1sub1,
  115489. 0, 0, 0, 0, 0,
  115490. NULL,
  115491. NULL,
  115492. NULL,
  115493. NULL,
  115494. 0
  115495. };
  115496. static long _huff_lengthlist_line_128x7_1sub2[] = {
  115497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  115498. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  115499. };
  115500. static static_codebook _huff_book_line_128x7_1sub2 = {
  115501. 1, 25,
  115502. _huff_lengthlist_line_128x7_1sub2,
  115503. 0, 0, 0, 0, 0,
  115504. NULL,
  115505. NULL,
  115506. NULL,
  115507. NULL,
  115508. 0
  115509. };
  115510. static long _huff_lengthlist_line_128x7_1sub3[] = {
  115511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  115513. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  115514. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  115515. };
  115516. static static_codebook _huff_book_line_128x7_1sub3 = {
  115517. 1, 64,
  115518. _huff_lengthlist_line_128x7_1sub3,
  115519. 0, 0, 0, 0, 0,
  115520. NULL,
  115521. NULL,
  115522. NULL,
  115523. NULL,
  115524. 0
  115525. };
  115526. static long _huff_lengthlist_line_128x11_class1[] = {
  115527. 1, 6, 3, 7, 2, 4, 5, 7,
  115528. };
  115529. static static_codebook _huff_book_line_128x11_class1 = {
  115530. 1, 8,
  115531. _huff_lengthlist_line_128x11_class1,
  115532. 0, 0, 0, 0, 0,
  115533. NULL,
  115534. NULL,
  115535. NULL,
  115536. NULL,
  115537. 0
  115538. };
  115539. static long _huff_lengthlist_line_128x11_class2[] = {
  115540. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  115541. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  115542. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  115543. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  115544. };
  115545. static static_codebook _huff_book_line_128x11_class2 = {
  115546. 1, 64,
  115547. _huff_lengthlist_line_128x11_class2,
  115548. 0, 0, 0, 0, 0,
  115549. NULL,
  115550. NULL,
  115551. NULL,
  115552. NULL,
  115553. 0
  115554. };
  115555. static long _huff_lengthlist_line_128x11_class3[] = {
  115556. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  115557. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  115558. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  115559. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  115560. };
  115561. static static_codebook _huff_book_line_128x11_class3 = {
  115562. 1, 64,
  115563. _huff_lengthlist_line_128x11_class3,
  115564. 0, 0, 0, 0, 0,
  115565. NULL,
  115566. NULL,
  115567. NULL,
  115568. NULL,
  115569. 0
  115570. };
  115571. static long _huff_lengthlist_line_128x11_0sub0[] = {
  115572. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115573. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  115574. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  115575. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  115576. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  115577. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  115578. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  115579. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  115580. };
  115581. static static_codebook _huff_book_line_128x11_0sub0 = {
  115582. 1, 128,
  115583. _huff_lengthlist_line_128x11_0sub0,
  115584. 0, 0, 0, 0, 0,
  115585. NULL,
  115586. NULL,
  115587. NULL,
  115588. NULL,
  115589. 0
  115590. };
  115591. static long _huff_lengthlist_line_128x11_1sub0[] = {
  115592. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  115593. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  115594. };
  115595. static static_codebook _huff_book_line_128x11_1sub0 = {
  115596. 1, 32,
  115597. _huff_lengthlist_line_128x11_1sub0,
  115598. 0, 0, 0, 0, 0,
  115599. NULL,
  115600. NULL,
  115601. NULL,
  115602. NULL,
  115603. 0
  115604. };
  115605. static long _huff_lengthlist_line_128x11_1sub1[] = {
  115606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115608. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  115609. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  115610. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  115611. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  115612. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  115613. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  115614. };
  115615. static static_codebook _huff_book_line_128x11_1sub1 = {
  115616. 1, 128,
  115617. _huff_lengthlist_line_128x11_1sub1,
  115618. 0, 0, 0, 0, 0,
  115619. NULL,
  115620. NULL,
  115621. NULL,
  115622. NULL,
  115623. 0
  115624. };
  115625. static long _huff_lengthlist_line_128x11_2sub1[] = {
  115626. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  115627. 5, 5,
  115628. };
  115629. static static_codebook _huff_book_line_128x11_2sub1 = {
  115630. 1, 18,
  115631. _huff_lengthlist_line_128x11_2sub1,
  115632. 0, 0, 0, 0, 0,
  115633. NULL,
  115634. NULL,
  115635. NULL,
  115636. NULL,
  115637. 0
  115638. };
  115639. static long _huff_lengthlist_line_128x11_2sub2[] = {
  115640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115641. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  115642. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  115643. 8,11,
  115644. };
  115645. static static_codebook _huff_book_line_128x11_2sub2 = {
  115646. 1, 50,
  115647. _huff_lengthlist_line_128x11_2sub2,
  115648. 0, 0, 0, 0, 0,
  115649. NULL,
  115650. NULL,
  115651. NULL,
  115652. NULL,
  115653. 0
  115654. };
  115655. static long _huff_lengthlist_line_128x11_2sub3[] = {
  115656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115659. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  115660. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115661. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115662. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115663. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115664. };
  115665. static static_codebook _huff_book_line_128x11_2sub3 = {
  115666. 1, 128,
  115667. _huff_lengthlist_line_128x11_2sub3,
  115668. 0, 0, 0, 0, 0,
  115669. NULL,
  115670. NULL,
  115671. NULL,
  115672. NULL,
  115673. 0
  115674. };
  115675. static long _huff_lengthlist_line_128x11_3sub1[] = {
  115676. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  115677. 5, 4,
  115678. };
  115679. static static_codebook _huff_book_line_128x11_3sub1 = {
  115680. 1, 18,
  115681. _huff_lengthlist_line_128x11_3sub1,
  115682. 0, 0, 0, 0, 0,
  115683. NULL,
  115684. NULL,
  115685. NULL,
  115686. NULL,
  115687. 0
  115688. };
  115689. static long _huff_lengthlist_line_128x11_3sub2[] = {
  115690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115691. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  115692. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  115693. 12, 6,
  115694. };
  115695. static static_codebook _huff_book_line_128x11_3sub2 = {
  115696. 1, 50,
  115697. _huff_lengthlist_line_128x11_3sub2,
  115698. 0, 0, 0, 0, 0,
  115699. NULL,
  115700. NULL,
  115701. NULL,
  115702. NULL,
  115703. 0
  115704. };
  115705. static long _huff_lengthlist_line_128x11_3sub3[] = {
  115706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115709. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  115710. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  115711. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115712. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  115713. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  115714. };
  115715. static static_codebook _huff_book_line_128x11_3sub3 = {
  115716. 1, 128,
  115717. _huff_lengthlist_line_128x11_3sub3,
  115718. 0, 0, 0, 0, 0,
  115719. NULL,
  115720. NULL,
  115721. NULL,
  115722. NULL,
  115723. 0
  115724. };
  115725. static long _huff_lengthlist_line_128x17_class1[] = {
  115726. 1, 3, 4, 7, 2, 5, 6, 7,
  115727. };
  115728. static static_codebook _huff_book_line_128x17_class1 = {
  115729. 1, 8,
  115730. _huff_lengthlist_line_128x17_class1,
  115731. 0, 0, 0, 0, 0,
  115732. NULL,
  115733. NULL,
  115734. NULL,
  115735. NULL,
  115736. 0
  115737. };
  115738. static long _huff_lengthlist_line_128x17_class2[] = {
  115739. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  115740. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  115741. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  115742. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  115743. };
  115744. static static_codebook _huff_book_line_128x17_class2 = {
  115745. 1, 64,
  115746. _huff_lengthlist_line_128x17_class2,
  115747. 0, 0, 0, 0, 0,
  115748. NULL,
  115749. NULL,
  115750. NULL,
  115751. NULL,
  115752. 0
  115753. };
  115754. static long _huff_lengthlist_line_128x17_class3[] = {
  115755. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  115756. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  115757. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  115758. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  115759. };
  115760. static static_codebook _huff_book_line_128x17_class3 = {
  115761. 1, 64,
  115762. _huff_lengthlist_line_128x17_class3,
  115763. 0, 0, 0, 0, 0,
  115764. NULL,
  115765. NULL,
  115766. NULL,
  115767. NULL,
  115768. 0
  115769. };
  115770. static long _huff_lengthlist_line_128x17_0sub0[] = {
  115771. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115772. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  115773. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  115774. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  115775. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  115776. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  115777. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  115778. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  115779. };
  115780. static static_codebook _huff_book_line_128x17_0sub0 = {
  115781. 1, 128,
  115782. _huff_lengthlist_line_128x17_0sub0,
  115783. 0, 0, 0, 0, 0,
  115784. NULL,
  115785. NULL,
  115786. NULL,
  115787. NULL,
  115788. 0
  115789. };
  115790. static long _huff_lengthlist_line_128x17_1sub0[] = {
  115791. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  115792. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  115793. };
  115794. static static_codebook _huff_book_line_128x17_1sub0 = {
  115795. 1, 32,
  115796. _huff_lengthlist_line_128x17_1sub0,
  115797. 0, 0, 0, 0, 0,
  115798. NULL,
  115799. NULL,
  115800. NULL,
  115801. NULL,
  115802. 0
  115803. };
  115804. static long _huff_lengthlist_line_128x17_1sub1[] = {
  115805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115807. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  115808. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  115809. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  115810. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  115811. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  115812. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  115813. };
  115814. static static_codebook _huff_book_line_128x17_1sub1 = {
  115815. 1, 128,
  115816. _huff_lengthlist_line_128x17_1sub1,
  115817. 0, 0, 0, 0, 0,
  115818. NULL,
  115819. NULL,
  115820. NULL,
  115821. NULL,
  115822. 0
  115823. };
  115824. static long _huff_lengthlist_line_128x17_2sub1[] = {
  115825. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  115826. 9, 4,
  115827. };
  115828. static static_codebook _huff_book_line_128x17_2sub1 = {
  115829. 1, 18,
  115830. _huff_lengthlist_line_128x17_2sub1,
  115831. 0, 0, 0, 0, 0,
  115832. NULL,
  115833. NULL,
  115834. NULL,
  115835. NULL,
  115836. 0
  115837. };
  115838. static long _huff_lengthlist_line_128x17_2sub2[] = {
  115839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115840. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  115841. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  115842. 13,13,
  115843. };
  115844. static static_codebook _huff_book_line_128x17_2sub2 = {
  115845. 1, 50,
  115846. _huff_lengthlist_line_128x17_2sub2,
  115847. 0, 0, 0, 0, 0,
  115848. NULL,
  115849. NULL,
  115850. NULL,
  115851. NULL,
  115852. 0
  115853. };
  115854. static long _huff_lengthlist_line_128x17_2sub3[] = {
  115855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115858. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115859. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  115860. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115861. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115862. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115863. };
  115864. static static_codebook _huff_book_line_128x17_2sub3 = {
  115865. 1, 128,
  115866. _huff_lengthlist_line_128x17_2sub3,
  115867. 0, 0, 0, 0, 0,
  115868. NULL,
  115869. NULL,
  115870. NULL,
  115871. NULL,
  115872. 0
  115873. };
  115874. static long _huff_lengthlist_line_128x17_3sub1[] = {
  115875. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  115876. 6, 4,
  115877. };
  115878. static static_codebook _huff_book_line_128x17_3sub1 = {
  115879. 1, 18,
  115880. _huff_lengthlist_line_128x17_3sub1,
  115881. 0, 0, 0, 0, 0,
  115882. NULL,
  115883. NULL,
  115884. NULL,
  115885. NULL,
  115886. 0
  115887. };
  115888. static long _huff_lengthlist_line_128x17_3sub2[] = {
  115889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115890. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  115891. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  115892. 10, 8,
  115893. };
  115894. static static_codebook _huff_book_line_128x17_3sub2 = {
  115895. 1, 50,
  115896. _huff_lengthlist_line_128x17_3sub2,
  115897. 0, 0, 0, 0, 0,
  115898. NULL,
  115899. NULL,
  115900. NULL,
  115901. NULL,
  115902. 0
  115903. };
  115904. static long _huff_lengthlist_line_128x17_3sub3[] = {
  115905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115908. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  115909. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  115910. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115911. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115912. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115913. };
  115914. static static_codebook _huff_book_line_128x17_3sub3 = {
  115915. 1, 128,
  115916. _huff_lengthlist_line_128x17_3sub3,
  115917. 0, 0, 0, 0, 0,
  115918. NULL,
  115919. NULL,
  115920. NULL,
  115921. NULL,
  115922. 0
  115923. };
  115924. static long _huff_lengthlist_line_1024x27_class1[] = {
  115925. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  115926. };
  115927. static static_codebook _huff_book_line_1024x27_class1 = {
  115928. 1, 16,
  115929. _huff_lengthlist_line_1024x27_class1,
  115930. 0, 0, 0, 0, 0,
  115931. NULL,
  115932. NULL,
  115933. NULL,
  115934. NULL,
  115935. 0
  115936. };
  115937. static long _huff_lengthlist_line_1024x27_class2[] = {
  115938. 1, 4, 2, 6, 3, 7, 5, 7,
  115939. };
  115940. static static_codebook _huff_book_line_1024x27_class2 = {
  115941. 1, 8,
  115942. _huff_lengthlist_line_1024x27_class2,
  115943. 0, 0, 0, 0, 0,
  115944. NULL,
  115945. NULL,
  115946. NULL,
  115947. NULL,
  115948. 0
  115949. };
  115950. static long _huff_lengthlist_line_1024x27_class3[] = {
  115951. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  115952. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  115953. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  115954. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  115955. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  115956. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  115957. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  115958. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  115959. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  115960. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  115961. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  115962. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  115963. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  115964. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  115965. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  115966. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  115967. };
  115968. static static_codebook _huff_book_line_1024x27_class3 = {
  115969. 1, 256,
  115970. _huff_lengthlist_line_1024x27_class3,
  115971. 0, 0, 0, 0, 0,
  115972. NULL,
  115973. NULL,
  115974. NULL,
  115975. NULL,
  115976. 0
  115977. };
  115978. static long _huff_lengthlist_line_1024x27_class4[] = {
  115979. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  115980. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  115981. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  115982. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  115983. };
  115984. static static_codebook _huff_book_line_1024x27_class4 = {
  115985. 1, 64,
  115986. _huff_lengthlist_line_1024x27_class4,
  115987. 0, 0, 0, 0, 0,
  115988. NULL,
  115989. NULL,
  115990. NULL,
  115991. NULL,
  115992. 0
  115993. };
  115994. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  115995. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115996. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  115997. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  115998. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  115999. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  116000. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  116001. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  116002. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  116003. };
  116004. static static_codebook _huff_book_line_1024x27_0sub0 = {
  116005. 1, 128,
  116006. _huff_lengthlist_line_1024x27_0sub0,
  116007. 0, 0, 0, 0, 0,
  116008. NULL,
  116009. NULL,
  116010. NULL,
  116011. NULL,
  116012. 0
  116013. };
  116014. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  116015. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  116016. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  116017. };
  116018. static static_codebook _huff_book_line_1024x27_1sub0 = {
  116019. 1, 32,
  116020. _huff_lengthlist_line_1024x27_1sub0,
  116021. 0, 0, 0, 0, 0,
  116022. NULL,
  116023. NULL,
  116024. NULL,
  116025. NULL,
  116026. 0
  116027. };
  116028. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  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. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  116032. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  116033. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  116034. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  116035. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  116036. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  116037. };
  116038. static static_codebook _huff_book_line_1024x27_1sub1 = {
  116039. 1, 128,
  116040. _huff_lengthlist_line_1024x27_1sub1,
  116041. 0, 0, 0, 0, 0,
  116042. NULL,
  116043. NULL,
  116044. NULL,
  116045. NULL,
  116046. 0
  116047. };
  116048. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  116049. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  116050. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  116051. };
  116052. static static_codebook _huff_book_line_1024x27_2sub0 = {
  116053. 1, 32,
  116054. _huff_lengthlist_line_1024x27_2sub0,
  116055. 0, 0, 0, 0, 0,
  116056. NULL,
  116057. NULL,
  116058. NULL,
  116059. NULL,
  116060. 0
  116061. };
  116062. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  116063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116065. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  116066. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  116067. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  116068. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  116069. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  116070. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  116071. };
  116072. static static_codebook _huff_book_line_1024x27_2sub1 = {
  116073. 1, 128,
  116074. _huff_lengthlist_line_1024x27_2sub1,
  116075. 0, 0, 0, 0, 0,
  116076. NULL,
  116077. NULL,
  116078. NULL,
  116079. NULL,
  116080. 0
  116081. };
  116082. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  116083. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  116084. 5, 5,
  116085. };
  116086. static static_codebook _huff_book_line_1024x27_3sub1 = {
  116087. 1, 18,
  116088. _huff_lengthlist_line_1024x27_3sub1,
  116089. 0, 0, 0, 0, 0,
  116090. NULL,
  116091. NULL,
  116092. NULL,
  116093. NULL,
  116094. 0
  116095. };
  116096. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  116097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116098. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  116099. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  116100. 9,11,
  116101. };
  116102. static static_codebook _huff_book_line_1024x27_3sub2 = {
  116103. 1, 50,
  116104. _huff_lengthlist_line_1024x27_3sub2,
  116105. 0, 0, 0, 0, 0,
  116106. NULL,
  116107. NULL,
  116108. NULL,
  116109. NULL,
  116110. 0
  116111. };
  116112. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  116113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116116. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  116117. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  116118. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  116119. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  116120. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  116121. };
  116122. static static_codebook _huff_book_line_1024x27_3sub3 = {
  116123. 1, 128,
  116124. _huff_lengthlist_line_1024x27_3sub3,
  116125. 0, 0, 0, 0, 0,
  116126. NULL,
  116127. NULL,
  116128. NULL,
  116129. NULL,
  116130. 0
  116131. };
  116132. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  116133. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  116134. 5, 4,
  116135. };
  116136. static static_codebook _huff_book_line_1024x27_4sub1 = {
  116137. 1, 18,
  116138. _huff_lengthlist_line_1024x27_4sub1,
  116139. 0, 0, 0, 0, 0,
  116140. NULL,
  116141. NULL,
  116142. NULL,
  116143. NULL,
  116144. 0
  116145. };
  116146. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  116147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116148. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  116149. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  116150. 9,12,
  116151. };
  116152. static static_codebook _huff_book_line_1024x27_4sub2 = {
  116153. 1, 50,
  116154. _huff_lengthlist_line_1024x27_4sub2,
  116155. 0, 0, 0, 0, 0,
  116156. NULL,
  116157. NULL,
  116158. NULL,
  116159. NULL,
  116160. 0
  116161. };
  116162. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  116163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116166. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  116167. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  116168. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  116169. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  116170. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  116171. };
  116172. static static_codebook _huff_book_line_1024x27_4sub3 = {
  116173. 1, 128,
  116174. _huff_lengthlist_line_1024x27_4sub3,
  116175. 0, 0, 0, 0, 0,
  116176. NULL,
  116177. NULL,
  116178. NULL,
  116179. NULL,
  116180. 0
  116181. };
  116182. static long _huff_lengthlist_line_2048x27_class1[] = {
  116183. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  116184. };
  116185. static static_codebook _huff_book_line_2048x27_class1 = {
  116186. 1, 16,
  116187. _huff_lengthlist_line_2048x27_class1,
  116188. 0, 0, 0, 0, 0,
  116189. NULL,
  116190. NULL,
  116191. NULL,
  116192. NULL,
  116193. 0
  116194. };
  116195. static long _huff_lengthlist_line_2048x27_class2[] = {
  116196. 1, 2, 3, 6, 4, 7, 5, 7,
  116197. };
  116198. static static_codebook _huff_book_line_2048x27_class2 = {
  116199. 1, 8,
  116200. _huff_lengthlist_line_2048x27_class2,
  116201. 0, 0, 0, 0, 0,
  116202. NULL,
  116203. NULL,
  116204. NULL,
  116205. NULL,
  116206. 0
  116207. };
  116208. static long _huff_lengthlist_line_2048x27_class3[] = {
  116209. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  116210. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  116211. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  116212. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  116213. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  116214. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  116215. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  116216. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  116217. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  116218. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  116219. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  116220. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  116221. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  116222. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  116223. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  116224. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  116225. };
  116226. static static_codebook _huff_book_line_2048x27_class3 = {
  116227. 1, 256,
  116228. _huff_lengthlist_line_2048x27_class3,
  116229. 0, 0, 0, 0, 0,
  116230. NULL,
  116231. NULL,
  116232. NULL,
  116233. NULL,
  116234. 0
  116235. };
  116236. static long _huff_lengthlist_line_2048x27_class4[] = {
  116237. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  116238. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  116239. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  116240. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  116241. };
  116242. static static_codebook _huff_book_line_2048x27_class4 = {
  116243. 1, 64,
  116244. _huff_lengthlist_line_2048x27_class4,
  116245. 0, 0, 0, 0, 0,
  116246. NULL,
  116247. NULL,
  116248. NULL,
  116249. NULL,
  116250. 0
  116251. };
  116252. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  116253. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  116254. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  116255. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  116256. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  116257. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  116258. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  116259. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  116260. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  116261. };
  116262. static static_codebook _huff_book_line_2048x27_0sub0 = {
  116263. 1, 128,
  116264. _huff_lengthlist_line_2048x27_0sub0,
  116265. 0, 0, 0, 0, 0,
  116266. NULL,
  116267. NULL,
  116268. NULL,
  116269. NULL,
  116270. 0
  116271. };
  116272. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  116273. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  116274. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  116275. };
  116276. static static_codebook _huff_book_line_2048x27_1sub0 = {
  116277. 1, 32,
  116278. _huff_lengthlist_line_2048x27_1sub0,
  116279. 0, 0, 0, 0, 0,
  116280. NULL,
  116281. NULL,
  116282. NULL,
  116283. NULL,
  116284. 0
  116285. };
  116286. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  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. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  116290. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  116291. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  116292. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  116293. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  116294. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  116295. };
  116296. static static_codebook _huff_book_line_2048x27_1sub1 = {
  116297. 1, 128,
  116298. _huff_lengthlist_line_2048x27_1sub1,
  116299. 0, 0, 0, 0, 0,
  116300. NULL,
  116301. NULL,
  116302. NULL,
  116303. NULL,
  116304. 0
  116305. };
  116306. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  116307. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  116308. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  116309. };
  116310. static static_codebook _huff_book_line_2048x27_2sub0 = {
  116311. 1, 32,
  116312. _huff_lengthlist_line_2048x27_2sub0,
  116313. 0, 0, 0, 0, 0,
  116314. NULL,
  116315. NULL,
  116316. NULL,
  116317. NULL,
  116318. 0
  116319. };
  116320. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  116321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116323. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  116324. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  116325. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  116326. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  116327. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  116328. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  116329. };
  116330. static static_codebook _huff_book_line_2048x27_2sub1 = {
  116331. 1, 128,
  116332. _huff_lengthlist_line_2048x27_2sub1,
  116333. 0, 0, 0, 0, 0,
  116334. NULL,
  116335. NULL,
  116336. NULL,
  116337. NULL,
  116338. 0
  116339. };
  116340. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  116341. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  116342. 5, 5,
  116343. };
  116344. static static_codebook _huff_book_line_2048x27_3sub1 = {
  116345. 1, 18,
  116346. _huff_lengthlist_line_2048x27_3sub1,
  116347. 0, 0, 0, 0, 0,
  116348. NULL,
  116349. NULL,
  116350. NULL,
  116351. NULL,
  116352. 0
  116353. };
  116354. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  116355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116356. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  116357. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  116358. 10,12,
  116359. };
  116360. static static_codebook _huff_book_line_2048x27_3sub2 = {
  116361. 1, 50,
  116362. _huff_lengthlist_line_2048x27_3sub2,
  116363. 0, 0, 0, 0, 0,
  116364. NULL,
  116365. NULL,
  116366. NULL,
  116367. NULL,
  116368. 0
  116369. };
  116370. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  116371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116374. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  116375. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116376. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116377. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116378. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116379. };
  116380. static static_codebook _huff_book_line_2048x27_3sub3 = {
  116381. 1, 128,
  116382. _huff_lengthlist_line_2048x27_3sub3,
  116383. 0, 0, 0, 0, 0,
  116384. NULL,
  116385. NULL,
  116386. NULL,
  116387. NULL,
  116388. 0
  116389. };
  116390. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  116391. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  116392. 4, 5,
  116393. };
  116394. static static_codebook _huff_book_line_2048x27_4sub1 = {
  116395. 1, 18,
  116396. _huff_lengthlist_line_2048x27_4sub1,
  116397. 0, 0, 0, 0, 0,
  116398. NULL,
  116399. NULL,
  116400. NULL,
  116401. NULL,
  116402. 0
  116403. };
  116404. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  116405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116406. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  116407. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  116408. 10,10,
  116409. };
  116410. static static_codebook _huff_book_line_2048x27_4sub2 = {
  116411. 1, 50,
  116412. _huff_lengthlist_line_2048x27_4sub2,
  116413. 0, 0, 0, 0, 0,
  116414. NULL,
  116415. NULL,
  116416. NULL,
  116417. NULL,
  116418. 0
  116419. };
  116420. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  116421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116424. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  116425. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  116426. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116427. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116428. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  116429. };
  116430. static static_codebook _huff_book_line_2048x27_4sub3 = {
  116431. 1, 128,
  116432. _huff_lengthlist_line_2048x27_4sub3,
  116433. 0, 0, 0, 0, 0,
  116434. NULL,
  116435. NULL,
  116436. NULL,
  116437. NULL,
  116438. 0
  116439. };
  116440. static long _huff_lengthlist_line_256x4low_class0[] = {
  116441. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  116442. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  116443. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  116444. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  116445. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  116446. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  116447. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  116448. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  116449. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  116450. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  116451. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  116452. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  116453. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  116454. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  116455. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  116456. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  116457. };
  116458. static static_codebook _huff_book_line_256x4low_class0 = {
  116459. 1, 256,
  116460. _huff_lengthlist_line_256x4low_class0,
  116461. 0, 0, 0, 0, 0,
  116462. NULL,
  116463. NULL,
  116464. NULL,
  116465. NULL,
  116466. 0
  116467. };
  116468. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  116469. 1, 3, 2, 3,
  116470. };
  116471. static static_codebook _huff_book_line_256x4low_0sub0 = {
  116472. 1, 4,
  116473. _huff_lengthlist_line_256x4low_0sub0,
  116474. 0, 0, 0, 0, 0,
  116475. NULL,
  116476. NULL,
  116477. NULL,
  116478. NULL,
  116479. 0
  116480. };
  116481. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  116482. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  116483. };
  116484. static static_codebook _huff_book_line_256x4low_0sub1 = {
  116485. 1, 10,
  116486. _huff_lengthlist_line_256x4low_0sub1,
  116487. 0, 0, 0, 0, 0,
  116488. NULL,
  116489. NULL,
  116490. NULL,
  116491. NULL,
  116492. 0
  116493. };
  116494. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  116495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  116496. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  116497. };
  116498. static static_codebook _huff_book_line_256x4low_0sub2 = {
  116499. 1, 25,
  116500. _huff_lengthlist_line_256x4low_0sub2,
  116501. 0, 0, 0, 0, 0,
  116502. NULL,
  116503. NULL,
  116504. NULL,
  116505. NULL,
  116506. 0
  116507. };
  116508. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  116509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  116511. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  116512. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  116513. };
  116514. static static_codebook _huff_book_line_256x4low_0sub3 = {
  116515. 1, 64,
  116516. _huff_lengthlist_line_256x4low_0sub3,
  116517. 0, 0, 0, 0, 0,
  116518. NULL,
  116519. NULL,
  116520. NULL,
  116521. NULL,
  116522. 0
  116523. };
  116524. /********* End of inlined file: floor_books.h *********/
  116525. static static_codebook *_floor_128x4_books[]={
  116526. &_huff_book_line_128x4_class0,
  116527. &_huff_book_line_128x4_0sub0,
  116528. &_huff_book_line_128x4_0sub1,
  116529. &_huff_book_line_128x4_0sub2,
  116530. &_huff_book_line_128x4_0sub3,
  116531. };
  116532. static static_codebook *_floor_256x4_books[]={
  116533. &_huff_book_line_256x4_class0,
  116534. &_huff_book_line_256x4_0sub0,
  116535. &_huff_book_line_256x4_0sub1,
  116536. &_huff_book_line_256x4_0sub2,
  116537. &_huff_book_line_256x4_0sub3,
  116538. };
  116539. static static_codebook *_floor_128x7_books[]={
  116540. &_huff_book_line_128x7_class0,
  116541. &_huff_book_line_128x7_class1,
  116542. &_huff_book_line_128x7_0sub1,
  116543. &_huff_book_line_128x7_0sub2,
  116544. &_huff_book_line_128x7_0sub3,
  116545. &_huff_book_line_128x7_1sub1,
  116546. &_huff_book_line_128x7_1sub2,
  116547. &_huff_book_line_128x7_1sub3,
  116548. };
  116549. static static_codebook *_floor_256x7_books[]={
  116550. &_huff_book_line_256x7_class0,
  116551. &_huff_book_line_256x7_class1,
  116552. &_huff_book_line_256x7_0sub1,
  116553. &_huff_book_line_256x7_0sub2,
  116554. &_huff_book_line_256x7_0sub3,
  116555. &_huff_book_line_256x7_1sub1,
  116556. &_huff_book_line_256x7_1sub2,
  116557. &_huff_book_line_256x7_1sub3,
  116558. };
  116559. static static_codebook *_floor_128x11_books[]={
  116560. &_huff_book_line_128x11_class1,
  116561. &_huff_book_line_128x11_class2,
  116562. &_huff_book_line_128x11_class3,
  116563. &_huff_book_line_128x11_0sub0,
  116564. &_huff_book_line_128x11_1sub0,
  116565. &_huff_book_line_128x11_1sub1,
  116566. &_huff_book_line_128x11_2sub1,
  116567. &_huff_book_line_128x11_2sub2,
  116568. &_huff_book_line_128x11_2sub3,
  116569. &_huff_book_line_128x11_3sub1,
  116570. &_huff_book_line_128x11_3sub2,
  116571. &_huff_book_line_128x11_3sub3,
  116572. };
  116573. static static_codebook *_floor_128x17_books[]={
  116574. &_huff_book_line_128x17_class1,
  116575. &_huff_book_line_128x17_class2,
  116576. &_huff_book_line_128x17_class3,
  116577. &_huff_book_line_128x17_0sub0,
  116578. &_huff_book_line_128x17_1sub0,
  116579. &_huff_book_line_128x17_1sub1,
  116580. &_huff_book_line_128x17_2sub1,
  116581. &_huff_book_line_128x17_2sub2,
  116582. &_huff_book_line_128x17_2sub3,
  116583. &_huff_book_line_128x17_3sub1,
  116584. &_huff_book_line_128x17_3sub2,
  116585. &_huff_book_line_128x17_3sub3,
  116586. };
  116587. static static_codebook *_floor_256x4low_books[]={
  116588. &_huff_book_line_256x4low_class0,
  116589. &_huff_book_line_256x4low_0sub0,
  116590. &_huff_book_line_256x4low_0sub1,
  116591. &_huff_book_line_256x4low_0sub2,
  116592. &_huff_book_line_256x4low_0sub3,
  116593. };
  116594. static static_codebook *_floor_1024x27_books[]={
  116595. &_huff_book_line_1024x27_class1,
  116596. &_huff_book_line_1024x27_class2,
  116597. &_huff_book_line_1024x27_class3,
  116598. &_huff_book_line_1024x27_class4,
  116599. &_huff_book_line_1024x27_0sub0,
  116600. &_huff_book_line_1024x27_1sub0,
  116601. &_huff_book_line_1024x27_1sub1,
  116602. &_huff_book_line_1024x27_2sub0,
  116603. &_huff_book_line_1024x27_2sub1,
  116604. &_huff_book_line_1024x27_3sub1,
  116605. &_huff_book_line_1024x27_3sub2,
  116606. &_huff_book_line_1024x27_3sub3,
  116607. &_huff_book_line_1024x27_4sub1,
  116608. &_huff_book_line_1024x27_4sub2,
  116609. &_huff_book_line_1024x27_4sub3,
  116610. };
  116611. static static_codebook *_floor_2048x27_books[]={
  116612. &_huff_book_line_2048x27_class1,
  116613. &_huff_book_line_2048x27_class2,
  116614. &_huff_book_line_2048x27_class3,
  116615. &_huff_book_line_2048x27_class4,
  116616. &_huff_book_line_2048x27_0sub0,
  116617. &_huff_book_line_2048x27_1sub0,
  116618. &_huff_book_line_2048x27_1sub1,
  116619. &_huff_book_line_2048x27_2sub0,
  116620. &_huff_book_line_2048x27_2sub1,
  116621. &_huff_book_line_2048x27_3sub1,
  116622. &_huff_book_line_2048x27_3sub2,
  116623. &_huff_book_line_2048x27_3sub3,
  116624. &_huff_book_line_2048x27_4sub1,
  116625. &_huff_book_line_2048x27_4sub2,
  116626. &_huff_book_line_2048x27_4sub3,
  116627. };
  116628. static static_codebook *_floor_512x17_books[]={
  116629. &_huff_book_line_512x17_class1,
  116630. &_huff_book_line_512x17_class2,
  116631. &_huff_book_line_512x17_class3,
  116632. &_huff_book_line_512x17_0sub0,
  116633. &_huff_book_line_512x17_1sub0,
  116634. &_huff_book_line_512x17_1sub1,
  116635. &_huff_book_line_512x17_2sub1,
  116636. &_huff_book_line_512x17_2sub2,
  116637. &_huff_book_line_512x17_2sub3,
  116638. &_huff_book_line_512x17_3sub1,
  116639. &_huff_book_line_512x17_3sub2,
  116640. &_huff_book_line_512x17_3sub3,
  116641. };
  116642. static static_codebook **_floor_books[10]={
  116643. _floor_128x4_books,
  116644. _floor_256x4_books,
  116645. _floor_128x7_books,
  116646. _floor_256x7_books,
  116647. _floor_128x11_books,
  116648. _floor_128x17_books,
  116649. _floor_256x4low_books,
  116650. _floor_1024x27_books,
  116651. _floor_2048x27_books,
  116652. _floor_512x17_books,
  116653. };
  116654. static vorbis_info_floor1 _floor[10]={
  116655. /* 128 x 4 */
  116656. {
  116657. 1,{0},{4},{2},{0},
  116658. {{1,2,3,4}},
  116659. 4,{0,128, 33,8,16,70},
  116660. 60,30,500, 1.,18., -1
  116661. },
  116662. /* 256 x 4 */
  116663. {
  116664. 1,{0},{4},{2},{0},
  116665. {{1,2,3,4}},
  116666. 4,{0,256, 66,16,32,140},
  116667. 60,30,500, 1.,18., -1
  116668. },
  116669. /* 128 x 7 */
  116670. {
  116671. 2,{0,1},{3,4},{2,2},{0,1},
  116672. {{-1,2,3,4},{-1,5,6,7}},
  116673. 4,{0,128, 14,4,58, 2,8,28,90},
  116674. 60,30,500, 1.,18., -1
  116675. },
  116676. /* 256 x 7 */
  116677. {
  116678. 2,{0,1},{3,4},{2,2},{0,1},
  116679. {{-1,2,3,4},{-1,5,6,7}},
  116680. 4,{0,256, 28,8,116, 4,16,56,180},
  116681. 60,30,500, 1.,18., -1
  116682. },
  116683. /* 128 x 11 */
  116684. {
  116685. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  116686. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  116687. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  116688. 60,30,500, 1,18., -1
  116689. },
  116690. /* 128 x 17 */
  116691. {
  116692. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  116693. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  116694. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  116695. 60,30,500, 1,18., -1
  116696. },
  116697. /* 256 x 4 (low bitrate version) */
  116698. {
  116699. 1,{0},{4},{2},{0},
  116700. {{1,2,3,4}},
  116701. 4,{0,256, 66,16,32,140},
  116702. 60,30,500, 1.,18., -1
  116703. },
  116704. /* 1024 x 27 */
  116705. {
  116706. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  116707. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  116708. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  116709. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  116710. 60,30,500, 3,18., -1 /* lowpass */
  116711. },
  116712. /* 2048 x 27 */
  116713. {
  116714. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  116715. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  116716. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  116717. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  116718. 60,30,500, 3,18., -1 /* lowpass */
  116719. },
  116720. /* 512 x 17 */
  116721. {
  116722. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  116723. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  116724. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  116725. 7,23,39, 55,79,110, 156,232,360},
  116726. 60,30,500, 1,18., -1 /* lowpass! */
  116727. },
  116728. };
  116729. /********* End of inlined file: floor_all.h *********/
  116730. /********* Start of inlined file: residue_44.h *********/
  116731. /********* Start of inlined file: res_books_stereo.h *********/
  116732. static long _vq_quantlist__16c0_s_p1_0[] = {
  116733. 1,
  116734. 0,
  116735. 2,
  116736. };
  116737. static long _vq_lengthlist__16c0_s_p1_0[] = {
  116738. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  116739. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  116744. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116746. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  116749. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116751. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  116784. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0,
  116789. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 7,10,10, 0, 0,
  116794. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  116830. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  116835. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  116840. 0, 0, 0, 0, 0, 0, 9,12, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117148. 0,
  117149. };
  117150. static float _vq_quantthresh__16c0_s_p1_0[] = {
  117151. -0.5, 0.5,
  117152. };
  117153. static long _vq_quantmap__16c0_s_p1_0[] = {
  117154. 1, 0, 2,
  117155. };
  117156. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  117157. _vq_quantthresh__16c0_s_p1_0,
  117158. _vq_quantmap__16c0_s_p1_0,
  117159. 3,
  117160. 3
  117161. };
  117162. static static_codebook _16c0_s_p1_0 = {
  117163. 8, 6561,
  117164. _vq_lengthlist__16c0_s_p1_0,
  117165. 1, -535822336, 1611661312, 2, 0,
  117166. _vq_quantlist__16c0_s_p1_0,
  117167. NULL,
  117168. &_vq_auxt__16c0_s_p1_0,
  117169. NULL,
  117170. 0
  117171. };
  117172. static long _vq_quantlist__16c0_s_p2_0[] = {
  117173. 2,
  117174. 1,
  117175. 3,
  117176. 0,
  117177. 4,
  117178. };
  117179. static long _vq_lengthlist__16c0_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117219. 0,
  117220. };
  117221. static float _vq_quantthresh__16c0_s_p2_0[] = {
  117222. -1.5, -0.5, 0.5, 1.5,
  117223. };
  117224. static long _vq_quantmap__16c0_s_p2_0[] = {
  117225. 3, 1, 0, 2, 4,
  117226. };
  117227. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  117228. _vq_quantthresh__16c0_s_p2_0,
  117229. _vq_quantmap__16c0_s_p2_0,
  117230. 5,
  117231. 5
  117232. };
  117233. static static_codebook _16c0_s_p2_0 = {
  117234. 4, 625,
  117235. _vq_lengthlist__16c0_s_p2_0,
  117236. 1, -533725184, 1611661312, 3, 0,
  117237. _vq_quantlist__16c0_s_p2_0,
  117238. NULL,
  117239. &_vq_auxt__16c0_s_p2_0,
  117240. NULL,
  117241. 0
  117242. };
  117243. static long _vq_quantlist__16c0_s_p3_0[] = {
  117244. 2,
  117245. 1,
  117246. 3,
  117247. 0,
  117248. 4,
  117249. };
  117250. static long _vq_lengthlist__16c0_s_p3_0[] = {
  117251. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  117253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117254. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  117256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117257. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  117258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117290. 0,
  117291. };
  117292. static float _vq_quantthresh__16c0_s_p3_0[] = {
  117293. -1.5, -0.5, 0.5, 1.5,
  117294. };
  117295. static long _vq_quantmap__16c0_s_p3_0[] = {
  117296. 3, 1, 0, 2, 4,
  117297. };
  117298. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  117299. _vq_quantthresh__16c0_s_p3_0,
  117300. _vq_quantmap__16c0_s_p3_0,
  117301. 5,
  117302. 5
  117303. };
  117304. static static_codebook _16c0_s_p3_0 = {
  117305. 4, 625,
  117306. _vq_lengthlist__16c0_s_p3_0,
  117307. 1, -533725184, 1611661312, 3, 0,
  117308. _vq_quantlist__16c0_s_p3_0,
  117309. NULL,
  117310. &_vq_auxt__16c0_s_p3_0,
  117311. NULL,
  117312. 0
  117313. };
  117314. static long _vq_quantlist__16c0_s_p4_0[] = {
  117315. 4,
  117316. 3,
  117317. 5,
  117318. 2,
  117319. 6,
  117320. 1,
  117321. 7,
  117322. 0,
  117323. 8,
  117324. };
  117325. static long _vq_lengthlist__16c0_s_p4_0[] = {
  117326. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  117327. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  117328. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  117329. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  117330. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117331. 0,
  117332. };
  117333. static float _vq_quantthresh__16c0_s_p4_0[] = {
  117334. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  117335. };
  117336. static long _vq_quantmap__16c0_s_p4_0[] = {
  117337. 7, 5, 3, 1, 0, 2, 4, 6,
  117338. 8,
  117339. };
  117340. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  117341. _vq_quantthresh__16c0_s_p4_0,
  117342. _vq_quantmap__16c0_s_p4_0,
  117343. 9,
  117344. 9
  117345. };
  117346. static static_codebook _16c0_s_p4_0 = {
  117347. 2, 81,
  117348. _vq_lengthlist__16c0_s_p4_0,
  117349. 1, -531628032, 1611661312, 4, 0,
  117350. _vq_quantlist__16c0_s_p4_0,
  117351. NULL,
  117352. &_vq_auxt__16c0_s_p4_0,
  117353. NULL,
  117354. 0
  117355. };
  117356. static long _vq_quantlist__16c0_s_p5_0[] = {
  117357. 4,
  117358. 3,
  117359. 5,
  117360. 2,
  117361. 6,
  117362. 1,
  117363. 7,
  117364. 0,
  117365. 8,
  117366. };
  117367. static long _vq_lengthlist__16c0_s_p5_0[] = {
  117368. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  117369. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  117370. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  117371. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  117372. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  117373. 10,
  117374. };
  117375. static float _vq_quantthresh__16c0_s_p5_0[] = {
  117376. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  117377. };
  117378. static long _vq_quantmap__16c0_s_p5_0[] = {
  117379. 7, 5, 3, 1, 0, 2, 4, 6,
  117380. 8,
  117381. };
  117382. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  117383. _vq_quantthresh__16c0_s_p5_0,
  117384. _vq_quantmap__16c0_s_p5_0,
  117385. 9,
  117386. 9
  117387. };
  117388. static static_codebook _16c0_s_p5_0 = {
  117389. 2, 81,
  117390. _vq_lengthlist__16c0_s_p5_0,
  117391. 1, -531628032, 1611661312, 4, 0,
  117392. _vq_quantlist__16c0_s_p5_0,
  117393. NULL,
  117394. &_vq_auxt__16c0_s_p5_0,
  117395. NULL,
  117396. 0
  117397. };
  117398. static long _vq_quantlist__16c0_s_p6_0[] = {
  117399. 8,
  117400. 7,
  117401. 9,
  117402. 6,
  117403. 10,
  117404. 5,
  117405. 11,
  117406. 4,
  117407. 12,
  117408. 3,
  117409. 13,
  117410. 2,
  117411. 14,
  117412. 1,
  117413. 15,
  117414. 0,
  117415. 16,
  117416. };
  117417. static long _vq_lengthlist__16c0_s_p6_0[] = {
  117418. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  117419. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  117420. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  117421. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  117422. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  117423. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  117424. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  117425. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  117426. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  117427. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  117428. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  117429. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  117430. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  117431. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  117432. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  117433. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  117434. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  117435. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  117436. 14,
  117437. };
  117438. static float _vq_quantthresh__16c0_s_p6_0[] = {
  117439. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  117440. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  117441. };
  117442. static long _vq_quantmap__16c0_s_p6_0[] = {
  117443. 15, 13, 11, 9, 7, 5, 3, 1,
  117444. 0, 2, 4, 6, 8, 10, 12, 14,
  117445. 16,
  117446. };
  117447. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  117448. _vq_quantthresh__16c0_s_p6_0,
  117449. _vq_quantmap__16c0_s_p6_0,
  117450. 17,
  117451. 17
  117452. };
  117453. static static_codebook _16c0_s_p6_0 = {
  117454. 2, 289,
  117455. _vq_lengthlist__16c0_s_p6_0,
  117456. 1, -529530880, 1611661312, 5, 0,
  117457. _vq_quantlist__16c0_s_p6_0,
  117458. NULL,
  117459. &_vq_auxt__16c0_s_p6_0,
  117460. NULL,
  117461. 0
  117462. };
  117463. static long _vq_quantlist__16c0_s_p7_0[] = {
  117464. 1,
  117465. 0,
  117466. 2,
  117467. };
  117468. static long _vq_lengthlist__16c0_s_p7_0[] = {
  117469. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  117470. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  117471. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  117472. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  117473. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  117474. 13,
  117475. };
  117476. static float _vq_quantthresh__16c0_s_p7_0[] = {
  117477. -5.5, 5.5,
  117478. };
  117479. static long _vq_quantmap__16c0_s_p7_0[] = {
  117480. 1, 0, 2,
  117481. };
  117482. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  117483. _vq_quantthresh__16c0_s_p7_0,
  117484. _vq_quantmap__16c0_s_p7_0,
  117485. 3,
  117486. 3
  117487. };
  117488. static static_codebook _16c0_s_p7_0 = {
  117489. 4, 81,
  117490. _vq_lengthlist__16c0_s_p7_0,
  117491. 1, -529137664, 1618345984, 2, 0,
  117492. _vq_quantlist__16c0_s_p7_0,
  117493. NULL,
  117494. &_vq_auxt__16c0_s_p7_0,
  117495. NULL,
  117496. 0
  117497. };
  117498. static long _vq_quantlist__16c0_s_p7_1[] = {
  117499. 5,
  117500. 4,
  117501. 6,
  117502. 3,
  117503. 7,
  117504. 2,
  117505. 8,
  117506. 1,
  117507. 9,
  117508. 0,
  117509. 10,
  117510. };
  117511. static long _vq_lengthlist__16c0_s_p7_1[] = {
  117512. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  117513. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  117514. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  117515. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  117516. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  117517. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  117518. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  117519. 11,11,11, 9, 9, 9, 9,10,10,
  117520. };
  117521. static float _vq_quantthresh__16c0_s_p7_1[] = {
  117522. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  117523. 3.5, 4.5,
  117524. };
  117525. static long _vq_quantmap__16c0_s_p7_1[] = {
  117526. 9, 7, 5, 3, 1, 0, 2, 4,
  117527. 6, 8, 10,
  117528. };
  117529. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  117530. _vq_quantthresh__16c0_s_p7_1,
  117531. _vq_quantmap__16c0_s_p7_1,
  117532. 11,
  117533. 11
  117534. };
  117535. static static_codebook _16c0_s_p7_1 = {
  117536. 2, 121,
  117537. _vq_lengthlist__16c0_s_p7_1,
  117538. 1, -531365888, 1611661312, 4, 0,
  117539. _vq_quantlist__16c0_s_p7_1,
  117540. NULL,
  117541. &_vq_auxt__16c0_s_p7_1,
  117542. NULL,
  117543. 0
  117544. };
  117545. static long _vq_quantlist__16c0_s_p8_0[] = {
  117546. 6,
  117547. 5,
  117548. 7,
  117549. 4,
  117550. 8,
  117551. 3,
  117552. 9,
  117553. 2,
  117554. 10,
  117555. 1,
  117556. 11,
  117557. 0,
  117558. 12,
  117559. };
  117560. static long _vq_lengthlist__16c0_s_p8_0[] = {
  117561. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  117562. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  117563. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  117564. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  117565. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  117566. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  117567. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  117568. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  117569. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  117570. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  117571. 0,12,13,13,12,13,14,14,14,
  117572. };
  117573. static float _vq_quantthresh__16c0_s_p8_0[] = {
  117574. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  117575. 12.5, 17.5, 22.5, 27.5,
  117576. };
  117577. static long _vq_quantmap__16c0_s_p8_0[] = {
  117578. 11, 9, 7, 5, 3, 1, 0, 2,
  117579. 4, 6, 8, 10, 12,
  117580. };
  117581. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  117582. _vq_quantthresh__16c0_s_p8_0,
  117583. _vq_quantmap__16c0_s_p8_0,
  117584. 13,
  117585. 13
  117586. };
  117587. static static_codebook _16c0_s_p8_0 = {
  117588. 2, 169,
  117589. _vq_lengthlist__16c0_s_p8_0,
  117590. 1, -526516224, 1616117760, 4, 0,
  117591. _vq_quantlist__16c0_s_p8_0,
  117592. NULL,
  117593. &_vq_auxt__16c0_s_p8_0,
  117594. NULL,
  117595. 0
  117596. };
  117597. static long _vq_quantlist__16c0_s_p8_1[] = {
  117598. 2,
  117599. 1,
  117600. 3,
  117601. 0,
  117602. 4,
  117603. };
  117604. static long _vq_lengthlist__16c0_s_p8_1[] = {
  117605. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  117606. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  117607. };
  117608. static float _vq_quantthresh__16c0_s_p8_1[] = {
  117609. -1.5, -0.5, 0.5, 1.5,
  117610. };
  117611. static long _vq_quantmap__16c0_s_p8_1[] = {
  117612. 3, 1, 0, 2, 4,
  117613. };
  117614. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  117615. _vq_quantthresh__16c0_s_p8_1,
  117616. _vq_quantmap__16c0_s_p8_1,
  117617. 5,
  117618. 5
  117619. };
  117620. static static_codebook _16c0_s_p8_1 = {
  117621. 2, 25,
  117622. _vq_lengthlist__16c0_s_p8_1,
  117623. 1, -533725184, 1611661312, 3, 0,
  117624. _vq_quantlist__16c0_s_p8_1,
  117625. NULL,
  117626. &_vq_auxt__16c0_s_p8_1,
  117627. NULL,
  117628. 0
  117629. };
  117630. static long _vq_quantlist__16c0_s_p9_0[] = {
  117631. 1,
  117632. 0,
  117633. 2,
  117634. };
  117635. static long _vq_lengthlist__16c0_s_p9_0[] = {
  117636. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117637. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117638. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117639. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117640. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117641. 7,
  117642. };
  117643. static float _vq_quantthresh__16c0_s_p9_0[] = {
  117644. -157.5, 157.5,
  117645. };
  117646. static long _vq_quantmap__16c0_s_p9_0[] = {
  117647. 1, 0, 2,
  117648. };
  117649. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  117650. _vq_quantthresh__16c0_s_p9_0,
  117651. _vq_quantmap__16c0_s_p9_0,
  117652. 3,
  117653. 3
  117654. };
  117655. static static_codebook _16c0_s_p9_0 = {
  117656. 4, 81,
  117657. _vq_lengthlist__16c0_s_p9_0,
  117658. 1, -518803456, 1628680192, 2, 0,
  117659. _vq_quantlist__16c0_s_p9_0,
  117660. NULL,
  117661. &_vq_auxt__16c0_s_p9_0,
  117662. NULL,
  117663. 0
  117664. };
  117665. static long _vq_quantlist__16c0_s_p9_1[] = {
  117666. 7,
  117667. 6,
  117668. 8,
  117669. 5,
  117670. 9,
  117671. 4,
  117672. 10,
  117673. 3,
  117674. 11,
  117675. 2,
  117676. 12,
  117677. 1,
  117678. 13,
  117679. 0,
  117680. 14,
  117681. };
  117682. static long _vq_lengthlist__16c0_s_p9_1[] = {
  117683. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  117684. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  117685. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  117686. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  117687. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117688. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117689. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117690. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117691. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117692. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117693. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117694. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117695. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117696. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117697. 10,
  117698. };
  117699. static float _vq_quantthresh__16c0_s_p9_1[] = {
  117700. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  117701. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  117702. };
  117703. static long _vq_quantmap__16c0_s_p9_1[] = {
  117704. 13, 11, 9, 7, 5, 3, 1, 0,
  117705. 2, 4, 6, 8, 10, 12, 14,
  117706. };
  117707. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  117708. _vq_quantthresh__16c0_s_p9_1,
  117709. _vq_quantmap__16c0_s_p9_1,
  117710. 15,
  117711. 15
  117712. };
  117713. static static_codebook _16c0_s_p9_1 = {
  117714. 2, 225,
  117715. _vq_lengthlist__16c0_s_p9_1,
  117716. 1, -520986624, 1620377600, 4, 0,
  117717. _vq_quantlist__16c0_s_p9_1,
  117718. NULL,
  117719. &_vq_auxt__16c0_s_p9_1,
  117720. NULL,
  117721. 0
  117722. };
  117723. static long _vq_quantlist__16c0_s_p9_2[] = {
  117724. 10,
  117725. 9,
  117726. 11,
  117727. 8,
  117728. 12,
  117729. 7,
  117730. 13,
  117731. 6,
  117732. 14,
  117733. 5,
  117734. 15,
  117735. 4,
  117736. 16,
  117737. 3,
  117738. 17,
  117739. 2,
  117740. 18,
  117741. 1,
  117742. 19,
  117743. 0,
  117744. 20,
  117745. };
  117746. static long _vq_lengthlist__16c0_s_p9_2[] = {
  117747. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  117748. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  117749. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  117750. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  117751. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  117752. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  117753. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  117754. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  117755. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  117756. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  117757. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  117758. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  117759. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  117760. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  117761. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  117762. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  117763. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  117764. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  117765. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  117766. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  117767. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  117768. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  117769. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  117770. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  117771. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  117772. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  117773. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  117774. 10,11,10,10,11, 9,10,10,10,
  117775. };
  117776. static float _vq_quantthresh__16c0_s_p9_2[] = {
  117777. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  117778. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  117779. 6.5, 7.5, 8.5, 9.5,
  117780. };
  117781. static long _vq_quantmap__16c0_s_p9_2[] = {
  117782. 19, 17, 15, 13, 11, 9, 7, 5,
  117783. 3, 1, 0, 2, 4, 6, 8, 10,
  117784. 12, 14, 16, 18, 20,
  117785. };
  117786. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  117787. _vq_quantthresh__16c0_s_p9_2,
  117788. _vq_quantmap__16c0_s_p9_2,
  117789. 21,
  117790. 21
  117791. };
  117792. static static_codebook _16c0_s_p9_2 = {
  117793. 2, 441,
  117794. _vq_lengthlist__16c0_s_p9_2,
  117795. 1, -529268736, 1611661312, 5, 0,
  117796. _vq_quantlist__16c0_s_p9_2,
  117797. NULL,
  117798. &_vq_auxt__16c0_s_p9_2,
  117799. NULL,
  117800. 0
  117801. };
  117802. static long _huff_lengthlist__16c0_s_single[] = {
  117803. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  117804. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  117805. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  117806. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  117807. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  117808. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  117809. 16,16,18,18,
  117810. };
  117811. static static_codebook _huff_book__16c0_s_single = {
  117812. 2, 100,
  117813. _huff_lengthlist__16c0_s_single,
  117814. 0, 0, 0, 0, 0,
  117815. NULL,
  117816. NULL,
  117817. NULL,
  117818. NULL,
  117819. 0
  117820. };
  117821. static long _huff_lengthlist__16c1_s_long[] = {
  117822. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  117823. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  117824. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  117825. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  117826. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  117827. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  117828. 12,11,11,13,
  117829. };
  117830. static static_codebook _huff_book__16c1_s_long = {
  117831. 2, 100,
  117832. _huff_lengthlist__16c1_s_long,
  117833. 0, 0, 0, 0, 0,
  117834. NULL,
  117835. NULL,
  117836. NULL,
  117837. NULL,
  117838. 0
  117839. };
  117840. static long _vq_quantlist__16c1_s_p1_0[] = {
  117841. 1,
  117842. 0,
  117843. 2,
  117844. };
  117845. static long _vq_lengthlist__16c1_s_p1_0[] = {
  117846. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  117847. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  117852. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117854. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  117857. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117859. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0,
  117892. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  117897. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  117902. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  117938. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  117943. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  117948. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118256. 0,
  118257. };
  118258. static float _vq_quantthresh__16c1_s_p1_0[] = {
  118259. -0.5, 0.5,
  118260. };
  118261. static long _vq_quantmap__16c1_s_p1_0[] = {
  118262. 1, 0, 2,
  118263. };
  118264. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  118265. _vq_quantthresh__16c1_s_p1_0,
  118266. _vq_quantmap__16c1_s_p1_0,
  118267. 3,
  118268. 3
  118269. };
  118270. static static_codebook _16c1_s_p1_0 = {
  118271. 8, 6561,
  118272. _vq_lengthlist__16c1_s_p1_0,
  118273. 1, -535822336, 1611661312, 2, 0,
  118274. _vq_quantlist__16c1_s_p1_0,
  118275. NULL,
  118276. &_vq_auxt__16c1_s_p1_0,
  118277. NULL,
  118278. 0
  118279. };
  118280. static long _vq_quantlist__16c1_s_p2_0[] = {
  118281. 2,
  118282. 1,
  118283. 3,
  118284. 0,
  118285. 4,
  118286. };
  118287. static long _vq_lengthlist__16c1_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118327. 0,
  118328. };
  118329. static float _vq_quantthresh__16c1_s_p2_0[] = {
  118330. -1.5, -0.5, 0.5, 1.5,
  118331. };
  118332. static long _vq_quantmap__16c1_s_p2_0[] = {
  118333. 3, 1, 0, 2, 4,
  118334. };
  118335. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  118336. _vq_quantthresh__16c1_s_p2_0,
  118337. _vq_quantmap__16c1_s_p2_0,
  118338. 5,
  118339. 5
  118340. };
  118341. static static_codebook _16c1_s_p2_0 = {
  118342. 4, 625,
  118343. _vq_lengthlist__16c1_s_p2_0,
  118344. 1, -533725184, 1611661312, 3, 0,
  118345. _vq_quantlist__16c1_s_p2_0,
  118346. NULL,
  118347. &_vq_auxt__16c1_s_p2_0,
  118348. NULL,
  118349. 0
  118350. };
  118351. static long _vq_quantlist__16c1_s_p3_0[] = {
  118352. 2,
  118353. 1,
  118354. 3,
  118355. 0,
  118356. 4,
  118357. };
  118358. static long _vq_lengthlist__16c1_s_p3_0[] = {
  118359. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  118361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118362. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  118364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118365. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  118366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118398. 0,
  118399. };
  118400. static float _vq_quantthresh__16c1_s_p3_0[] = {
  118401. -1.5, -0.5, 0.5, 1.5,
  118402. };
  118403. static long _vq_quantmap__16c1_s_p3_0[] = {
  118404. 3, 1, 0, 2, 4,
  118405. };
  118406. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  118407. _vq_quantthresh__16c1_s_p3_0,
  118408. _vq_quantmap__16c1_s_p3_0,
  118409. 5,
  118410. 5
  118411. };
  118412. static static_codebook _16c1_s_p3_0 = {
  118413. 4, 625,
  118414. _vq_lengthlist__16c1_s_p3_0,
  118415. 1, -533725184, 1611661312, 3, 0,
  118416. _vq_quantlist__16c1_s_p3_0,
  118417. NULL,
  118418. &_vq_auxt__16c1_s_p3_0,
  118419. NULL,
  118420. 0
  118421. };
  118422. static long _vq_quantlist__16c1_s_p4_0[] = {
  118423. 4,
  118424. 3,
  118425. 5,
  118426. 2,
  118427. 6,
  118428. 1,
  118429. 7,
  118430. 0,
  118431. 8,
  118432. };
  118433. static long _vq_lengthlist__16c1_s_p4_0[] = {
  118434. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  118435. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  118436. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  118437. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  118438. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118439. 0,
  118440. };
  118441. static float _vq_quantthresh__16c1_s_p4_0[] = {
  118442. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118443. };
  118444. static long _vq_quantmap__16c1_s_p4_0[] = {
  118445. 7, 5, 3, 1, 0, 2, 4, 6,
  118446. 8,
  118447. };
  118448. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  118449. _vq_quantthresh__16c1_s_p4_0,
  118450. _vq_quantmap__16c1_s_p4_0,
  118451. 9,
  118452. 9
  118453. };
  118454. static static_codebook _16c1_s_p4_0 = {
  118455. 2, 81,
  118456. _vq_lengthlist__16c1_s_p4_0,
  118457. 1, -531628032, 1611661312, 4, 0,
  118458. _vq_quantlist__16c1_s_p4_0,
  118459. NULL,
  118460. &_vq_auxt__16c1_s_p4_0,
  118461. NULL,
  118462. 0
  118463. };
  118464. static long _vq_quantlist__16c1_s_p5_0[] = {
  118465. 4,
  118466. 3,
  118467. 5,
  118468. 2,
  118469. 6,
  118470. 1,
  118471. 7,
  118472. 0,
  118473. 8,
  118474. };
  118475. static long _vq_lengthlist__16c1_s_p5_0[] = {
  118476. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  118477. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  118478. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  118479. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  118480. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  118481. 10,
  118482. };
  118483. static float _vq_quantthresh__16c1_s_p5_0[] = {
  118484. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118485. };
  118486. static long _vq_quantmap__16c1_s_p5_0[] = {
  118487. 7, 5, 3, 1, 0, 2, 4, 6,
  118488. 8,
  118489. };
  118490. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  118491. _vq_quantthresh__16c1_s_p5_0,
  118492. _vq_quantmap__16c1_s_p5_0,
  118493. 9,
  118494. 9
  118495. };
  118496. static static_codebook _16c1_s_p5_0 = {
  118497. 2, 81,
  118498. _vq_lengthlist__16c1_s_p5_0,
  118499. 1, -531628032, 1611661312, 4, 0,
  118500. _vq_quantlist__16c1_s_p5_0,
  118501. NULL,
  118502. &_vq_auxt__16c1_s_p5_0,
  118503. NULL,
  118504. 0
  118505. };
  118506. static long _vq_quantlist__16c1_s_p6_0[] = {
  118507. 8,
  118508. 7,
  118509. 9,
  118510. 6,
  118511. 10,
  118512. 5,
  118513. 11,
  118514. 4,
  118515. 12,
  118516. 3,
  118517. 13,
  118518. 2,
  118519. 14,
  118520. 1,
  118521. 15,
  118522. 0,
  118523. 16,
  118524. };
  118525. static long _vq_lengthlist__16c1_s_p6_0[] = {
  118526. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  118527. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  118528. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  118529. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  118530. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  118531. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  118532. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  118533. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  118534. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  118535. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  118536. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  118537. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  118538. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  118539. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  118540. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  118541. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  118542. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  118543. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  118544. 14,
  118545. };
  118546. static float _vq_quantthresh__16c1_s_p6_0[] = {
  118547. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  118548. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  118549. };
  118550. static long _vq_quantmap__16c1_s_p6_0[] = {
  118551. 15, 13, 11, 9, 7, 5, 3, 1,
  118552. 0, 2, 4, 6, 8, 10, 12, 14,
  118553. 16,
  118554. };
  118555. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  118556. _vq_quantthresh__16c1_s_p6_0,
  118557. _vq_quantmap__16c1_s_p6_0,
  118558. 17,
  118559. 17
  118560. };
  118561. static static_codebook _16c1_s_p6_0 = {
  118562. 2, 289,
  118563. _vq_lengthlist__16c1_s_p6_0,
  118564. 1, -529530880, 1611661312, 5, 0,
  118565. _vq_quantlist__16c1_s_p6_0,
  118566. NULL,
  118567. &_vq_auxt__16c1_s_p6_0,
  118568. NULL,
  118569. 0
  118570. };
  118571. static long _vq_quantlist__16c1_s_p7_0[] = {
  118572. 1,
  118573. 0,
  118574. 2,
  118575. };
  118576. static long _vq_lengthlist__16c1_s_p7_0[] = {
  118577. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  118578. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  118579. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  118580. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  118581. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  118582. 11,
  118583. };
  118584. static float _vq_quantthresh__16c1_s_p7_0[] = {
  118585. -5.5, 5.5,
  118586. };
  118587. static long _vq_quantmap__16c1_s_p7_0[] = {
  118588. 1, 0, 2,
  118589. };
  118590. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  118591. _vq_quantthresh__16c1_s_p7_0,
  118592. _vq_quantmap__16c1_s_p7_0,
  118593. 3,
  118594. 3
  118595. };
  118596. static static_codebook _16c1_s_p7_0 = {
  118597. 4, 81,
  118598. _vq_lengthlist__16c1_s_p7_0,
  118599. 1, -529137664, 1618345984, 2, 0,
  118600. _vq_quantlist__16c1_s_p7_0,
  118601. NULL,
  118602. &_vq_auxt__16c1_s_p7_0,
  118603. NULL,
  118604. 0
  118605. };
  118606. static long _vq_quantlist__16c1_s_p7_1[] = {
  118607. 5,
  118608. 4,
  118609. 6,
  118610. 3,
  118611. 7,
  118612. 2,
  118613. 8,
  118614. 1,
  118615. 9,
  118616. 0,
  118617. 10,
  118618. };
  118619. static long _vq_lengthlist__16c1_s_p7_1[] = {
  118620. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  118621. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  118622. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  118623. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  118624. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  118625. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  118626. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  118627. 10,10,10, 8, 8, 8, 8, 9, 9,
  118628. };
  118629. static float _vq_quantthresh__16c1_s_p7_1[] = {
  118630. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  118631. 3.5, 4.5,
  118632. };
  118633. static long _vq_quantmap__16c1_s_p7_1[] = {
  118634. 9, 7, 5, 3, 1, 0, 2, 4,
  118635. 6, 8, 10,
  118636. };
  118637. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  118638. _vq_quantthresh__16c1_s_p7_1,
  118639. _vq_quantmap__16c1_s_p7_1,
  118640. 11,
  118641. 11
  118642. };
  118643. static static_codebook _16c1_s_p7_1 = {
  118644. 2, 121,
  118645. _vq_lengthlist__16c1_s_p7_1,
  118646. 1, -531365888, 1611661312, 4, 0,
  118647. _vq_quantlist__16c1_s_p7_1,
  118648. NULL,
  118649. &_vq_auxt__16c1_s_p7_1,
  118650. NULL,
  118651. 0
  118652. };
  118653. static long _vq_quantlist__16c1_s_p8_0[] = {
  118654. 6,
  118655. 5,
  118656. 7,
  118657. 4,
  118658. 8,
  118659. 3,
  118660. 9,
  118661. 2,
  118662. 10,
  118663. 1,
  118664. 11,
  118665. 0,
  118666. 12,
  118667. };
  118668. static long _vq_lengthlist__16c1_s_p8_0[] = {
  118669. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  118670. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  118671. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  118672. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  118673. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  118674. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  118675. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  118676. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  118677. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  118678. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  118679. 0,12,12,12,12,13,13,14,15,
  118680. };
  118681. static float _vq_quantthresh__16c1_s_p8_0[] = {
  118682. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  118683. 12.5, 17.5, 22.5, 27.5,
  118684. };
  118685. static long _vq_quantmap__16c1_s_p8_0[] = {
  118686. 11, 9, 7, 5, 3, 1, 0, 2,
  118687. 4, 6, 8, 10, 12,
  118688. };
  118689. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  118690. _vq_quantthresh__16c1_s_p8_0,
  118691. _vq_quantmap__16c1_s_p8_0,
  118692. 13,
  118693. 13
  118694. };
  118695. static static_codebook _16c1_s_p8_0 = {
  118696. 2, 169,
  118697. _vq_lengthlist__16c1_s_p8_0,
  118698. 1, -526516224, 1616117760, 4, 0,
  118699. _vq_quantlist__16c1_s_p8_0,
  118700. NULL,
  118701. &_vq_auxt__16c1_s_p8_0,
  118702. NULL,
  118703. 0
  118704. };
  118705. static long _vq_quantlist__16c1_s_p8_1[] = {
  118706. 2,
  118707. 1,
  118708. 3,
  118709. 0,
  118710. 4,
  118711. };
  118712. static long _vq_lengthlist__16c1_s_p8_1[] = {
  118713. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  118714. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  118715. };
  118716. static float _vq_quantthresh__16c1_s_p8_1[] = {
  118717. -1.5, -0.5, 0.5, 1.5,
  118718. };
  118719. static long _vq_quantmap__16c1_s_p8_1[] = {
  118720. 3, 1, 0, 2, 4,
  118721. };
  118722. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  118723. _vq_quantthresh__16c1_s_p8_1,
  118724. _vq_quantmap__16c1_s_p8_1,
  118725. 5,
  118726. 5
  118727. };
  118728. static static_codebook _16c1_s_p8_1 = {
  118729. 2, 25,
  118730. _vq_lengthlist__16c1_s_p8_1,
  118731. 1, -533725184, 1611661312, 3, 0,
  118732. _vq_quantlist__16c1_s_p8_1,
  118733. NULL,
  118734. &_vq_auxt__16c1_s_p8_1,
  118735. NULL,
  118736. 0
  118737. };
  118738. static long _vq_quantlist__16c1_s_p9_0[] = {
  118739. 6,
  118740. 5,
  118741. 7,
  118742. 4,
  118743. 8,
  118744. 3,
  118745. 9,
  118746. 2,
  118747. 10,
  118748. 1,
  118749. 11,
  118750. 0,
  118751. 12,
  118752. };
  118753. static long _vq_lengthlist__16c1_s_p9_0[] = {
  118754. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118755. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118756. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118757. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118758. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118759. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118760. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118761. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118762. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118763. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118764. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118765. };
  118766. static float _vq_quantthresh__16c1_s_p9_0[] = {
  118767. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  118768. 787.5, 1102.5, 1417.5, 1732.5,
  118769. };
  118770. static long _vq_quantmap__16c1_s_p9_0[] = {
  118771. 11, 9, 7, 5, 3, 1, 0, 2,
  118772. 4, 6, 8, 10, 12,
  118773. };
  118774. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  118775. _vq_quantthresh__16c1_s_p9_0,
  118776. _vq_quantmap__16c1_s_p9_0,
  118777. 13,
  118778. 13
  118779. };
  118780. static static_codebook _16c1_s_p9_0 = {
  118781. 2, 169,
  118782. _vq_lengthlist__16c1_s_p9_0,
  118783. 1, -513964032, 1628680192, 4, 0,
  118784. _vq_quantlist__16c1_s_p9_0,
  118785. NULL,
  118786. &_vq_auxt__16c1_s_p9_0,
  118787. NULL,
  118788. 0
  118789. };
  118790. static long _vq_quantlist__16c1_s_p9_1[] = {
  118791. 7,
  118792. 6,
  118793. 8,
  118794. 5,
  118795. 9,
  118796. 4,
  118797. 10,
  118798. 3,
  118799. 11,
  118800. 2,
  118801. 12,
  118802. 1,
  118803. 13,
  118804. 0,
  118805. 14,
  118806. };
  118807. static long _vq_lengthlist__16c1_s_p9_1[] = {
  118808. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  118809. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  118810. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  118811. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  118812. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  118813. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  118814. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  118815. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  118816. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118817. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  118818. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118819. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118820. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  118821. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118822. 13,
  118823. };
  118824. static float _vq_quantthresh__16c1_s_p9_1[] = {
  118825. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  118826. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  118827. };
  118828. static long _vq_quantmap__16c1_s_p9_1[] = {
  118829. 13, 11, 9, 7, 5, 3, 1, 0,
  118830. 2, 4, 6, 8, 10, 12, 14,
  118831. };
  118832. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  118833. _vq_quantthresh__16c1_s_p9_1,
  118834. _vq_quantmap__16c1_s_p9_1,
  118835. 15,
  118836. 15
  118837. };
  118838. static static_codebook _16c1_s_p9_1 = {
  118839. 2, 225,
  118840. _vq_lengthlist__16c1_s_p9_1,
  118841. 1, -520986624, 1620377600, 4, 0,
  118842. _vq_quantlist__16c1_s_p9_1,
  118843. NULL,
  118844. &_vq_auxt__16c1_s_p9_1,
  118845. NULL,
  118846. 0
  118847. };
  118848. static long _vq_quantlist__16c1_s_p9_2[] = {
  118849. 10,
  118850. 9,
  118851. 11,
  118852. 8,
  118853. 12,
  118854. 7,
  118855. 13,
  118856. 6,
  118857. 14,
  118858. 5,
  118859. 15,
  118860. 4,
  118861. 16,
  118862. 3,
  118863. 17,
  118864. 2,
  118865. 18,
  118866. 1,
  118867. 19,
  118868. 0,
  118869. 20,
  118870. };
  118871. static long _vq_lengthlist__16c1_s_p9_2[] = {
  118872. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  118873. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  118874. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  118875. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  118876. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  118877. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  118878. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  118879. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  118880. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  118881. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  118882. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  118883. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  118884. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  118885. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  118886. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  118887. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  118888. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  118889. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  118890. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  118891. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  118892. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  118893. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  118894. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  118895. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  118896. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  118897. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  118898. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  118899. 11,11,11,11,12,11,11,12,11,
  118900. };
  118901. static float _vq_quantthresh__16c1_s_p9_2[] = {
  118902. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  118903. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  118904. 6.5, 7.5, 8.5, 9.5,
  118905. };
  118906. static long _vq_quantmap__16c1_s_p9_2[] = {
  118907. 19, 17, 15, 13, 11, 9, 7, 5,
  118908. 3, 1, 0, 2, 4, 6, 8, 10,
  118909. 12, 14, 16, 18, 20,
  118910. };
  118911. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  118912. _vq_quantthresh__16c1_s_p9_2,
  118913. _vq_quantmap__16c1_s_p9_2,
  118914. 21,
  118915. 21
  118916. };
  118917. static static_codebook _16c1_s_p9_2 = {
  118918. 2, 441,
  118919. _vq_lengthlist__16c1_s_p9_2,
  118920. 1, -529268736, 1611661312, 5, 0,
  118921. _vq_quantlist__16c1_s_p9_2,
  118922. NULL,
  118923. &_vq_auxt__16c1_s_p9_2,
  118924. NULL,
  118925. 0
  118926. };
  118927. static long _huff_lengthlist__16c1_s_short[] = {
  118928. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  118929. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  118930. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  118931. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  118932. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  118933. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  118934. 9, 9,10,13,
  118935. };
  118936. static static_codebook _huff_book__16c1_s_short = {
  118937. 2, 100,
  118938. _huff_lengthlist__16c1_s_short,
  118939. 0, 0, 0, 0, 0,
  118940. NULL,
  118941. NULL,
  118942. NULL,
  118943. NULL,
  118944. 0
  118945. };
  118946. static long _huff_lengthlist__16c2_s_long[] = {
  118947. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  118948. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  118949. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  118950. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  118951. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  118952. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  118953. 14,14,16,18,
  118954. };
  118955. static static_codebook _huff_book__16c2_s_long = {
  118956. 2, 100,
  118957. _huff_lengthlist__16c2_s_long,
  118958. 0, 0, 0, 0, 0,
  118959. NULL,
  118960. NULL,
  118961. NULL,
  118962. NULL,
  118963. 0
  118964. };
  118965. static long _vq_quantlist__16c2_s_p1_0[] = {
  118966. 1,
  118967. 0,
  118968. 2,
  118969. };
  118970. static long _vq_lengthlist__16c2_s_p1_0[] = {
  118971. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  118972. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118976. 0,
  118977. };
  118978. static float _vq_quantthresh__16c2_s_p1_0[] = {
  118979. -0.5, 0.5,
  118980. };
  118981. static long _vq_quantmap__16c2_s_p1_0[] = {
  118982. 1, 0, 2,
  118983. };
  118984. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  118985. _vq_quantthresh__16c2_s_p1_0,
  118986. _vq_quantmap__16c2_s_p1_0,
  118987. 3,
  118988. 3
  118989. };
  118990. static static_codebook _16c2_s_p1_0 = {
  118991. 4, 81,
  118992. _vq_lengthlist__16c2_s_p1_0,
  118993. 1, -535822336, 1611661312, 2, 0,
  118994. _vq_quantlist__16c2_s_p1_0,
  118995. NULL,
  118996. &_vq_auxt__16c2_s_p1_0,
  118997. NULL,
  118998. 0
  118999. };
  119000. static long _vq_quantlist__16c2_s_p2_0[] = {
  119001. 2,
  119002. 1,
  119003. 3,
  119004. 0,
  119005. 4,
  119006. };
  119007. static long _vq_lengthlist__16c2_s_p2_0[] = {
  119008. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  119009. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  119010. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  119011. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  119012. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  119013. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  119014. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  119015. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  119016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119020. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  119021. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  119022. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  119023. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  119024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119028. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  119029. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  119030. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  119031. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119036. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  119037. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  119038. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  119039. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  119044. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  119045. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  119046. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  119047. 13,
  119048. };
  119049. static float _vq_quantthresh__16c2_s_p2_0[] = {
  119050. -1.5, -0.5, 0.5, 1.5,
  119051. };
  119052. static long _vq_quantmap__16c2_s_p2_0[] = {
  119053. 3, 1, 0, 2, 4,
  119054. };
  119055. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  119056. _vq_quantthresh__16c2_s_p2_0,
  119057. _vq_quantmap__16c2_s_p2_0,
  119058. 5,
  119059. 5
  119060. };
  119061. static static_codebook _16c2_s_p2_0 = {
  119062. 4, 625,
  119063. _vq_lengthlist__16c2_s_p2_0,
  119064. 1, -533725184, 1611661312, 3, 0,
  119065. _vq_quantlist__16c2_s_p2_0,
  119066. NULL,
  119067. &_vq_auxt__16c2_s_p2_0,
  119068. NULL,
  119069. 0
  119070. };
  119071. static long _vq_quantlist__16c2_s_p3_0[] = {
  119072. 4,
  119073. 3,
  119074. 5,
  119075. 2,
  119076. 6,
  119077. 1,
  119078. 7,
  119079. 0,
  119080. 8,
  119081. };
  119082. static long _vq_lengthlist__16c2_s_p3_0[] = {
  119083. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  119084. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  119085. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  119086. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  119087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119088. 0,
  119089. };
  119090. static float _vq_quantthresh__16c2_s_p3_0[] = {
  119091. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119092. };
  119093. static long _vq_quantmap__16c2_s_p3_0[] = {
  119094. 7, 5, 3, 1, 0, 2, 4, 6,
  119095. 8,
  119096. };
  119097. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  119098. _vq_quantthresh__16c2_s_p3_0,
  119099. _vq_quantmap__16c2_s_p3_0,
  119100. 9,
  119101. 9
  119102. };
  119103. static static_codebook _16c2_s_p3_0 = {
  119104. 2, 81,
  119105. _vq_lengthlist__16c2_s_p3_0,
  119106. 1, -531628032, 1611661312, 4, 0,
  119107. _vq_quantlist__16c2_s_p3_0,
  119108. NULL,
  119109. &_vq_auxt__16c2_s_p3_0,
  119110. NULL,
  119111. 0
  119112. };
  119113. static long _vq_quantlist__16c2_s_p4_0[] = {
  119114. 8,
  119115. 7,
  119116. 9,
  119117. 6,
  119118. 10,
  119119. 5,
  119120. 11,
  119121. 4,
  119122. 12,
  119123. 3,
  119124. 13,
  119125. 2,
  119126. 14,
  119127. 1,
  119128. 15,
  119129. 0,
  119130. 16,
  119131. };
  119132. static long _vq_lengthlist__16c2_s_p4_0[] = {
  119133. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  119134. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  119135. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  119136. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  119137. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  119138. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  119139. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  119140. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  119141. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  119142. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  119143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119151. 0,
  119152. };
  119153. static float _vq_quantthresh__16c2_s_p4_0[] = {
  119154. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  119155. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  119156. };
  119157. static long _vq_quantmap__16c2_s_p4_0[] = {
  119158. 15, 13, 11, 9, 7, 5, 3, 1,
  119159. 0, 2, 4, 6, 8, 10, 12, 14,
  119160. 16,
  119161. };
  119162. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  119163. _vq_quantthresh__16c2_s_p4_0,
  119164. _vq_quantmap__16c2_s_p4_0,
  119165. 17,
  119166. 17
  119167. };
  119168. static static_codebook _16c2_s_p4_0 = {
  119169. 2, 289,
  119170. _vq_lengthlist__16c2_s_p4_0,
  119171. 1, -529530880, 1611661312, 5, 0,
  119172. _vq_quantlist__16c2_s_p4_0,
  119173. NULL,
  119174. &_vq_auxt__16c2_s_p4_0,
  119175. NULL,
  119176. 0
  119177. };
  119178. static long _vq_quantlist__16c2_s_p5_0[] = {
  119179. 1,
  119180. 0,
  119181. 2,
  119182. };
  119183. static long _vq_lengthlist__16c2_s_p5_0[] = {
  119184. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  119185. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  119186. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  119187. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  119188. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  119189. 12,
  119190. };
  119191. static float _vq_quantthresh__16c2_s_p5_0[] = {
  119192. -5.5, 5.5,
  119193. };
  119194. static long _vq_quantmap__16c2_s_p5_0[] = {
  119195. 1, 0, 2,
  119196. };
  119197. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  119198. _vq_quantthresh__16c2_s_p5_0,
  119199. _vq_quantmap__16c2_s_p5_0,
  119200. 3,
  119201. 3
  119202. };
  119203. static static_codebook _16c2_s_p5_0 = {
  119204. 4, 81,
  119205. _vq_lengthlist__16c2_s_p5_0,
  119206. 1, -529137664, 1618345984, 2, 0,
  119207. _vq_quantlist__16c2_s_p5_0,
  119208. NULL,
  119209. &_vq_auxt__16c2_s_p5_0,
  119210. NULL,
  119211. 0
  119212. };
  119213. static long _vq_quantlist__16c2_s_p5_1[] = {
  119214. 5,
  119215. 4,
  119216. 6,
  119217. 3,
  119218. 7,
  119219. 2,
  119220. 8,
  119221. 1,
  119222. 9,
  119223. 0,
  119224. 10,
  119225. };
  119226. static long _vq_lengthlist__16c2_s_p5_1[] = {
  119227. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  119228. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  119229. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  119230. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  119231. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  119232. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  119233. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  119234. 11,11,11, 7, 7, 8, 8, 8, 8,
  119235. };
  119236. static float _vq_quantthresh__16c2_s_p5_1[] = {
  119237. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119238. 3.5, 4.5,
  119239. };
  119240. static long _vq_quantmap__16c2_s_p5_1[] = {
  119241. 9, 7, 5, 3, 1, 0, 2, 4,
  119242. 6, 8, 10,
  119243. };
  119244. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  119245. _vq_quantthresh__16c2_s_p5_1,
  119246. _vq_quantmap__16c2_s_p5_1,
  119247. 11,
  119248. 11
  119249. };
  119250. static static_codebook _16c2_s_p5_1 = {
  119251. 2, 121,
  119252. _vq_lengthlist__16c2_s_p5_1,
  119253. 1, -531365888, 1611661312, 4, 0,
  119254. _vq_quantlist__16c2_s_p5_1,
  119255. NULL,
  119256. &_vq_auxt__16c2_s_p5_1,
  119257. NULL,
  119258. 0
  119259. };
  119260. static long _vq_quantlist__16c2_s_p6_0[] = {
  119261. 6,
  119262. 5,
  119263. 7,
  119264. 4,
  119265. 8,
  119266. 3,
  119267. 9,
  119268. 2,
  119269. 10,
  119270. 1,
  119271. 11,
  119272. 0,
  119273. 12,
  119274. };
  119275. static long _vq_lengthlist__16c2_s_p6_0[] = {
  119276. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  119277. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  119278. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  119279. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  119280. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  119281. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  119282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119286. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119287. };
  119288. static float _vq_quantthresh__16c2_s_p6_0[] = {
  119289. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  119290. 12.5, 17.5, 22.5, 27.5,
  119291. };
  119292. static long _vq_quantmap__16c2_s_p6_0[] = {
  119293. 11, 9, 7, 5, 3, 1, 0, 2,
  119294. 4, 6, 8, 10, 12,
  119295. };
  119296. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  119297. _vq_quantthresh__16c2_s_p6_0,
  119298. _vq_quantmap__16c2_s_p6_0,
  119299. 13,
  119300. 13
  119301. };
  119302. static static_codebook _16c2_s_p6_0 = {
  119303. 2, 169,
  119304. _vq_lengthlist__16c2_s_p6_0,
  119305. 1, -526516224, 1616117760, 4, 0,
  119306. _vq_quantlist__16c2_s_p6_0,
  119307. NULL,
  119308. &_vq_auxt__16c2_s_p6_0,
  119309. NULL,
  119310. 0
  119311. };
  119312. static long _vq_quantlist__16c2_s_p6_1[] = {
  119313. 2,
  119314. 1,
  119315. 3,
  119316. 0,
  119317. 4,
  119318. };
  119319. static long _vq_lengthlist__16c2_s_p6_1[] = {
  119320. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  119321. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  119322. };
  119323. static float _vq_quantthresh__16c2_s_p6_1[] = {
  119324. -1.5, -0.5, 0.5, 1.5,
  119325. };
  119326. static long _vq_quantmap__16c2_s_p6_1[] = {
  119327. 3, 1, 0, 2, 4,
  119328. };
  119329. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  119330. _vq_quantthresh__16c2_s_p6_1,
  119331. _vq_quantmap__16c2_s_p6_1,
  119332. 5,
  119333. 5
  119334. };
  119335. static static_codebook _16c2_s_p6_1 = {
  119336. 2, 25,
  119337. _vq_lengthlist__16c2_s_p6_1,
  119338. 1, -533725184, 1611661312, 3, 0,
  119339. _vq_quantlist__16c2_s_p6_1,
  119340. NULL,
  119341. &_vq_auxt__16c2_s_p6_1,
  119342. NULL,
  119343. 0
  119344. };
  119345. static long _vq_quantlist__16c2_s_p7_0[] = {
  119346. 6,
  119347. 5,
  119348. 7,
  119349. 4,
  119350. 8,
  119351. 3,
  119352. 9,
  119353. 2,
  119354. 10,
  119355. 1,
  119356. 11,
  119357. 0,
  119358. 12,
  119359. };
  119360. static long _vq_lengthlist__16c2_s_p7_0[] = {
  119361. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  119362. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  119363. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  119364. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  119365. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  119366. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  119367. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  119368. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  119369. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  119370. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  119371. 18,13,14,13,13,14,13,15,14,
  119372. };
  119373. static float _vq_quantthresh__16c2_s_p7_0[] = {
  119374. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  119375. 27.5, 38.5, 49.5, 60.5,
  119376. };
  119377. static long _vq_quantmap__16c2_s_p7_0[] = {
  119378. 11, 9, 7, 5, 3, 1, 0, 2,
  119379. 4, 6, 8, 10, 12,
  119380. };
  119381. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  119382. _vq_quantthresh__16c2_s_p7_0,
  119383. _vq_quantmap__16c2_s_p7_0,
  119384. 13,
  119385. 13
  119386. };
  119387. static static_codebook _16c2_s_p7_0 = {
  119388. 2, 169,
  119389. _vq_lengthlist__16c2_s_p7_0,
  119390. 1, -523206656, 1618345984, 4, 0,
  119391. _vq_quantlist__16c2_s_p7_0,
  119392. NULL,
  119393. &_vq_auxt__16c2_s_p7_0,
  119394. NULL,
  119395. 0
  119396. };
  119397. static long _vq_quantlist__16c2_s_p7_1[] = {
  119398. 5,
  119399. 4,
  119400. 6,
  119401. 3,
  119402. 7,
  119403. 2,
  119404. 8,
  119405. 1,
  119406. 9,
  119407. 0,
  119408. 10,
  119409. };
  119410. static long _vq_lengthlist__16c2_s_p7_1[] = {
  119411. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  119412. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  119413. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  119414. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  119415. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  119416. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  119417. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  119418. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  119419. };
  119420. static float _vq_quantthresh__16c2_s_p7_1[] = {
  119421. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119422. 3.5, 4.5,
  119423. };
  119424. static long _vq_quantmap__16c2_s_p7_1[] = {
  119425. 9, 7, 5, 3, 1, 0, 2, 4,
  119426. 6, 8, 10,
  119427. };
  119428. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  119429. _vq_quantthresh__16c2_s_p7_1,
  119430. _vq_quantmap__16c2_s_p7_1,
  119431. 11,
  119432. 11
  119433. };
  119434. static static_codebook _16c2_s_p7_1 = {
  119435. 2, 121,
  119436. _vq_lengthlist__16c2_s_p7_1,
  119437. 1, -531365888, 1611661312, 4, 0,
  119438. _vq_quantlist__16c2_s_p7_1,
  119439. NULL,
  119440. &_vq_auxt__16c2_s_p7_1,
  119441. NULL,
  119442. 0
  119443. };
  119444. static long _vq_quantlist__16c2_s_p8_0[] = {
  119445. 7,
  119446. 6,
  119447. 8,
  119448. 5,
  119449. 9,
  119450. 4,
  119451. 10,
  119452. 3,
  119453. 11,
  119454. 2,
  119455. 12,
  119456. 1,
  119457. 13,
  119458. 0,
  119459. 14,
  119460. };
  119461. static long _vq_lengthlist__16c2_s_p8_0[] = {
  119462. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  119463. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  119464. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  119465. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  119466. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  119467. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  119468. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  119469. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  119470. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  119471. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  119472. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  119473. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  119474. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  119475. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  119476. 13,
  119477. };
  119478. static float _vq_quantthresh__16c2_s_p8_0[] = {
  119479. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  119480. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  119481. };
  119482. static long _vq_quantmap__16c2_s_p8_0[] = {
  119483. 13, 11, 9, 7, 5, 3, 1, 0,
  119484. 2, 4, 6, 8, 10, 12, 14,
  119485. };
  119486. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  119487. _vq_quantthresh__16c2_s_p8_0,
  119488. _vq_quantmap__16c2_s_p8_0,
  119489. 15,
  119490. 15
  119491. };
  119492. static static_codebook _16c2_s_p8_0 = {
  119493. 2, 225,
  119494. _vq_lengthlist__16c2_s_p8_0,
  119495. 1, -520986624, 1620377600, 4, 0,
  119496. _vq_quantlist__16c2_s_p8_0,
  119497. NULL,
  119498. &_vq_auxt__16c2_s_p8_0,
  119499. NULL,
  119500. 0
  119501. };
  119502. static long _vq_quantlist__16c2_s_p8_1[] = {
  119503. 10,
  119504. 9,
  119505. 11,
  119506. 8,
  119507. 12,
  119508. 7,
  119509. 13,
  119510. 6,
  119511. 14,
  119512. 5,
  119513. 15,
  119514. 4,
  119515. 16,
  119516. 3,
  119517. 17,
  119518. 2,
  119519. 18,
  119520. 1,
  119521. 19,
  119522. 0,
  119523. 20,
  119524. };
  119525. static long _vq_lengthlist__16c2_s_p8_1[] = {
  119526. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  119527. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  119528. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  119529. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  119530. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  119531. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  119532. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  119533. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  119534. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  119535. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  119536. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  119537. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  119538. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  119539. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  119540. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  119541. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  119542. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  119543. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  119544. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  119545. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  119546. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  119547. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  119548. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  119549. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  119550. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  119551. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  119552. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  119553. 10,11,10,10,10,10,10,10,10,
  119554. };
  119555. static float _vq_quantthresh__16c2_s_p8_1[] = {
  119556. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  119557. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  119558. 6.5, 7.5, 8.5, 9.5,
  119559. };
  119560. static long _vq_quantmap__16c2_s_p8_1[] = {
  119561. 19, 17, 15, 13, 11, 9, 7, 5,
  119562. 3, 1, 0, 2, 4, 6, 8, 10,
  119563. 12, 14, 16, 18, 20,
  119564. };
  119565. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  119566. _vq_quantthresh__16c2_s_p8_1,
  119567. _vq_quantmap__16c2_s_p8_1,
  119568. 21,
  119569. 21
  119570. };
  119571. static static_codebook _16c2_s_p8_1 = {
  119572. 2, 441,
  119573. _vq_lengthlist__16c2_s_p8_1,
  119574. 1, -529268736, 1611661312, 5, 0,
  119575. _vq_quantlist__16c2_s_p8_1,
  119576. NULL,
  119577. &_vq_auxt__16c2_s_p8_1,
  119578. NULL,
  119579. 0
  119580. };
  119581. static long _vq_quantlist__16c2_s_p9_0[] = {
  119582. 6,
  119583. 5,
  119584. 7,
  119585. 4,
  119586. 8,
  119587. 3,
  119588. 9,
  119589. 2,
  119590. 10,
  119591. 1,
  119592. 11,
  119593. 0,
  119594. 12,
  119595. };
  119596. static long _vq_lengthlist__16c2_s_p9_0[] = {
  119597. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119598. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119599. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119600. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119601. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  119602. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119603. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119604. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119605. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119606. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119607. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119608. };
  119609. static float _vq_quantthresh__16c2_s_p9_0[] = {
  119610. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  119611. 2327.5, 3258.5, 4189.5, 5120.5,
  119612. };
  119613. static long _vq_quantmap__16c2_s_p9_0[] = {
  119614. 11, 9, 7, 5, 3, 1, 0, 2,
  119615. 4, 6, 8, 10, 12,
  119616. };
  119617. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  119618. _vq_quantthresh__16c2_s_p9_0,
  119619. _vq_quantmap__16c2_s_p9_0,
  119620. 13,
  119621. 13
  119622. };
  119623. static static_codebook _16c2_s_p9_0 = {
  119624. 2, 169,
  119625. _vq_lengthlist__16c2_s_p9_0,
  119626. 1, -510275072, 1631393792, 4, 0,
  119627. _vq_quantlist__16c2_s_p9_0,
  119628. NULL,
  119629. &_vq_auxt__16c2_s_p9_0,
  119630. NULL,
  119631. 0
  119632. };
  119633. static long _vq_quantlist__16c2_s_p9_1[] = {
  119634. 8,
  119635. 7,
  119636. 9,
  119637. 6,
  119638. 10,
  119639. 5,
  119640. 11,
  119641. 4,
  119642. 12,
  119643. 3,
  119644. 13,
  119645. 2,
  119646. 14,
  119647. 1,
  119648. 15,
  119649. 0,
  119650. 16,
  119651. };
  119652. static long _vq_lengthlist__16c2_s_p9_1[] = {
  119653. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  119654. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  119655. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  119656. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  119657. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  119658. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  119659. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  119660. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  119661. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  119662. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  119663. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119664. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119665. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119666. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119667. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119668. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  119669. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  119670. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119671. 10,
  119672. };
  119673. static float _vq_quantthresh__16c2_s_p9_1[] = {
  119674. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  119675. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  119676. };
  119677. static long _vq_quantmap__16c2_s_p9_1[] = {
  119678. 15, 13, 11, 9, 7, 5, 3, 1,
  119679. 0, 2, 4, 6, 8, 10, 12, 14,
  119680. 16,
  119681. };
  119682. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  119683. _vq_quantthresh__16c2_s_p9_1,
  119684. _vq_quantmap__16c2_s_p9_1,
  119685. 17,
  119686. 17
  119687. };
  119688. static static_codebook _16c2_s_p9_1 = {
  119689. 2, 289,
  119690. _vq_lengthlist__16c2_s_p9_1,
  119691. 1, -518488064, 1622704128, 5, 0,
  119692. _vq_quantlist__16c2_s_p9_1,
  119693. NULL,
  119694. &_vq_auxt__16c2_s_p9_1,
  119695. NULL,
  119696. 0
  119697. };
  119698. static long _vq_quantlist__16c2_s_p9_2[] = {
  119699. 13,
  119700. 12,
  119701. 14,
  119702. 11,
  119703. 15,
  119704. 10,
  119705. 16,
  119706. 9,
  119707. 17,
  119708. 8,
  119709. 18,
  119710. 7,
  119711. 19,
  119712. 6,
  119713. 20,
  119714. 5,
  119715. 21,
  119716. 4,
  119717. 22,
  119718. 3,
  119719. 23,
  119720. 2,
  119721. 24,
  119722. 1,
  119723. 25,
  119724. 0,
  119725. 26,
  119726. };
  119727. static long _vq_lengthlist__16c2_s_p9_2[] = {
  119728. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  119729. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  119730. };
  119731. static float _vq_quantthresh__16c2_s_p9_2[] = {
  119732. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  119733. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119734. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  119735. 11.5, 12.5,
  119736. };
  119737. static long _vq_quantmap__16c2_s_p9_2[] = {
  119738. 25, 23, 21, 19, 17, 15, 13, 11,
  119739. 9, 7, 5, 3, 1, 0, 2, 4,
  119740. 6, 8, 10, 12, 14, 16, 18, 20,
  119741. 22, 24, 26,
  119742. };
  119743. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  119744. _vq_quantthresh__16c2_s_p9_2,
  119745. _vq_quantmap__16c2_s_p9_2,
  119746. 27,
  119747. 27
  119748. };
  119749. static static_codebook _16c2_s_p9_2 = {
  119750. 1, 27,
  119751. _vq_lengthlist__16c2_s_p9_2,
  119752. 1, -528875520, 1611661312, 5, 0,
  119753. _vq_quantlist__16c2_s_p9_2,
  119754. NULL,
  119755. &_vq_auxt__16c2_s_p9_2,
  119756. NULL,
  119757. 0
  119758. };
  119759. static long _huff_lengthlist__16c2_s_short[] = {
  119760. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  119761. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  119762. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  119763. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  119764. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  119765. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  119766. 15,12,14,14,
  119767. };
  119768. static static_codebook _huff_book__16c2_s_short = {
  119769. 2, 100,
  119770. _huff_lengthlist__16c2_s_short,
  119771. 0, 0, 0, 0, 0,
  119772. NULL,
  119773. NULL,
  119774. NULL,
  119775. NULL,
  119776. 0
  119777. };
  119778. static long _vq_quantlist__8c0_s_p1_0[] = {
  119779. 1,
  119780. 0,
  119781. 2,
  119782. };
  119783. static long _vq_lengthlist__8c0_s_p1_0[] = {
  119784. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  119785. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  119790. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119792. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119795. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119797. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  119830. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  119835. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  119840. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  119876. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  119881. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  119886. 0, 0, 0, 0, 0, 0, 8,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120194. 0,
  120195. };
  120196. static float _vq_quantthresh__8c0_s_p1_0[] = {
  120197. -0.5, 0.5,
  120198. };
  120199. static long _vq_quantmap__8c0_s_p1_0[] = {
  120200. 1, 0, 2,
  120201. };
  120202. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  120203. _vq_quantthresh__8c0_s_p1_0,
  120204. _vq_quantmap__8c0_s_p1_0,
  120205. 3,
  120206. 3
  120207. };
  120208. static static_codebook _8c0_s_p1_0 = {
  120209. 8, 6561,
  120210. _vq_lengthlist__8c0_s_p1_0,
  120211. 1, -535822336, 1611661312, 2, 0,
  120212. _vq_quantlist__8c0_s_p1_0,
  120213. NULL,
  120214. &_vq_auxt__8c0_s_p1_0,
  120215. NULL,
  120216. 0
  120217. };
  120218. static long _vq_quantlist__8c0_s_p2_0[] = {
  120219. 2,
  120220. 1,
  120221. 3,
  120222. 0,
  120223. 4,
  120224. };
  120225. static long _vq_lengthlist__8c0_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120265. 0,
  120266. };
  120267. static float _vq_quantthresh__8c0_s_p2_0[] = {
  120268. -1.5, -0.5, 0.5, 1.5,
  120269. };
  120270. static long _vq_quantmap__8c0_s_p2_0[] = {
  120271. 3, 1, 0, 2, 4,
  120272. };
  120273. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  120274. _vq_quantthresh__8c0_s_p2_0,
  120275. _vq_quantmap__8c0_s_p2_0,
  120276. 5,
  120277. 5
  120278. };
  120279. static static_codebook _8c0_s_p2_0 = {
  120280. 4, 625,
  120281. _vq_lengthlist__8c0_s_p2_0,
  120282. 1, -533725184, 1611661312, 3, 0,
  120283. _vq_quantlist__8c0_s_p2_0,
  120284. NULL,
  120285. &_vq_auxt__8c0_s_p2_0,
  120286. NULL,
  120287. 0
  120288. };
  120289. static long _vq_quantlist__8c0_s_p3_0[] = {
  120290. 2,
  120291. 1,
  120292. 3,
  120293. 0,
  120294. 4,
  120295. };
  120296. static long _vq_lengthlist__8c0_s_p3_0[] = {
  120297. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  120299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120300. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  120302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120303. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  120304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120336. 0,
  120337. };
  120338. static float _vq_quantthresh__8c0_s_p3_0[] = {
  120339. -1.5, -0.5, 0.5, 1.5,
  120340. };
  120341. static long _vq_quantmap__8c0_s_p3_0[] = {
  120342. 3, 1, 0, 2, 4,
  120343. };
  120344. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  120345. _vq_quantthresh__8c0_s_p3_0,
  120346. _vq_quantmap__8c0_s_p3_0,
  120347. 5,
  120348. 5
  120349. };
  120350. static static_codebook _8c0_s_p3_0 = {
  120351. 4, 625,
  120352. _vq_lengthlist__8c0_s_p3_0,
  120353. 1, -533725184, 1611661312, 3, 0,
  120354. _vq_quantlist__8c0_s_p3_0,
  120355. NULL,
  120356. &_vq_auxt__8c0_s_p3_0,
  120357. NULL,
  120358. 0
  120359. };
  120360. static long _vq_quantlist__8c0_s_p4_0[] = {
  120361. 4,
  120362. 3,
  120363. 5,
  120364. 2,
  120365. 6,
  120366. 1,
  120367. 7,
  120368. 0,
  120369. 8,
  120370. };
  120371. static long _vq_lengthlist__8c0_s_p4_0[] = {
  120372. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  120373. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  120374. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  120375. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  120376. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120377. 0,
  120378. };
  120379. static float _vq_quantthresh__8c0_s_p4_0[] = {
  120380. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120381. };
  120382. static long _vq_quantmap__8c0_s_p4_0[] = {
  120383. 7, 5, 3, 1, 0, 2, 4, 6,
  120384. 8,
  120385. };
  120386. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  120387. _vq_quantthresh__8c0_s_p4_0,
  120388. _vq_quantmap__8c0_s_p4_0,
  120389. 9,
  120390. 9
  120391. };
  120392. static static_codebook _8c0_s_p4_0 = {
  120393. 2, 81,
  120394. _vq_lengthlist__8c0_s_p4_0,
  120395. 1, -531628032, 1611661312, 4, 0,
  120396. _vq_quantlist__8c0_s_p4_0,
  120397. NULL,
  120398. &_vq_auxt__8c0_s_p4_0,
  120399. NULL,
  120400. 0
  120401. };
  120402. static long _vq_quantlist__8c0_s_p5_0[] = {
  120403. 4,
  120404. 3,
  120405. 5,
  120406. 2,
  120407. 6,
  120408. 1,
  120409. 7,
  120410. 0,
  120411. 8,
  120412. };
  120413. static long _vq_lengthlist__8c0_s_p5_0[] = {
  120414. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  120415. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  120416. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  120417. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  120418. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  120419. 10,
  120420. };
  120421. static float _vq_quantthresh__8c0_s_p5_0[] = {
  120422. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120423. };
  120424. static long _vq_quantmap__8c0_s_p5_0[] = {
  120425. 7, 5, 3, 1, 0, 2, 4, 6,
  120426. 8,
  120427. };
  120428. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  120429. _vq_quantthresh__8c0_s_p5_0,
  120430. _vq_quantmap__8c0_s_p5_0,
  120431. 9,
  120432. 9
  120433. };
  120434. static static_codebook _8c0_s_p5_0 = {
  120435. 2, 81,
  120436. _vq_lengthlist__8c0_s_p5_0,
  120437. 1, -531628032, 1611661312, 4, 0,
  120438. _vq_quantlist__8c0_s_p5_0,
  120439. NULL,
  120440. &_vq_auxt__8c0_s_p5_0,
  120441. NULL,
  120442. 0
  120443. };
  120444. static long _vq_quantlist__8c0_s_p6_0[] = {
  120445. 8,
  120446. 7,
  120447. 9,
  120448. 6,
  120449. 10,
  120450. 5,
  120451. 11,
  120452. 4,
  120453. 12,
  120454. 3,
  120455. 13,
  120456. 2,
  120457. 14,
  120458. 1,
  120459. 15,
  120460. 0,
  120461. 16,
  120462. };
  120463. static long _vq_lengthlist__8c0_s_p6_0[] = {
  120464. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  120465. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  120466. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  120467. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  120468. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  120469. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  120470. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  120471. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  120472. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  120473. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  120474. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  120475. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  120476. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  120477. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  120478. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  120479. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  120480. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  120481. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  120482. 14,
  120483. };
  120484. static float _vq_quantthresh__8c0_s_p6_0[] = {
  120485. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120486. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120487. };
  120488. static long _vq_quantmap__8c0_s_p6_0[] = {
  120489. 15, 13, 11, 9, 7, 5, 3, 1,
  120490. 0, 2, 4, 6, 8, 10, 12, 14,
  120491. 16,
  120492. };
  120493. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  120494. _vq_quantthresh__8c0_s_p6_0,
  120495. _vq_quantmap__8c0_s_p6_0,
  120496. 17,
  120497. 17
  120498. };
  120499. static static_codebook _8c0_s_p6_0 = {
  120500. 2, 289,
  120501. _vq_lengthlist__8c0_s_p6_0,
  120502. 1, -529530880, 1611661312, 5, 0,
  120503. _vq_quantlist__8c0_s_p6_0,
  120504. NULL,
  120505. &_vq_auxt__8c0_s_p6_0,
  120506. NULL,
  120507. 0
  120508. };
  120509. static long _vq_quantlist__8c0_s_p7_0[] = {
  120510. 1,
  120511. 0,
  120512. 2,
  120513. };
  120514. static long _vq_lengthlist__8c0_s_p7_0[] = {
  120515. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  120516. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  120517. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  120518. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  120519. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  120520. 10,
  120521. };
  120522. static float _vq_quantthresh__8c0_s_p7_0[] = {
  120523. -5.5, 5.5,
  120524. };
  120525. static long _vq_quantmap__8c0_s_p7_0[] = {
  120526. 1, 0, 2,
  120527. };
  120528. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  120529. _vq_quantthresh__8c0_s_p7_0,
  120530. _vq_quantmap__8c0_s_p7_0,
  120531. 3,
  120532. 3
  120533. };
  120534. static static_codebook _8c0_s_p7_0 = {
  120535. 4, 81,
  120536. _vq_lengthlist__8c0_s_p7_0,
  120537. 1, -529137664, 1618345984, 2, 0,
  120538. _vq_quantlist__8c0_s_p7_0,
  120539. NULL,
  120540. &_vq_auxt__8c0_s_p7_0,
  120541. NULL,
  120542. 0
  120543. };
  120544. static long _vq_quantlist__8c0_s_p7_1[] = {
  120545. 5,
  120546. 4,
  120547. 6,
  120548. 3,
  120549. 7,
  120550. 2,
  120551. 8,
  120552. 1,
  120553. 9,
  120554. 0,
  120555. 10,
  120556. };
  120557. static long _vq_lengthlist__8c0_s_p7_1[] = {
  120558. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  120559. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  120560. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  120561. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  120562. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  120563. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  120564. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  120565. 10,10,10, 9, 9, 9,10,10,10,
  120566. };
  120567. static float _vq_quantthresh__8c0_s_p7_1[] = {
  120568. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120569. 3.5, 4.5,
  120570. };
  120571. static long _vq_quantmap__8c0_s_p7_1[] = {
  120572. 9, 7, 5, 3, 1, 0, 2, 4,
  120573. 6, 8, 10,
  120574. };
  120575. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  120576. _vq_quantthresh__8c0_s_p7_1,
  120577. _vq_quantmap__8c0_s_p7_1,
  120578. 11,
  120579. 11
  120580. };
  120581. static static_codebook _8c0_s_p7_1 = {
  120582. 2, 121,
  120583. _vq_lengthlist__8c0_s_p7_1,
  120584. 1, -531365888, 1611661312, 4, 0,
  120585. _vq_quantlist__8c0_s_p7_1,
  120586. NULL,
  120587. &_vq_auxt__8c0_s_p7_1,
  120588. NULL,
  120589. 0
  120590. };
  120591. static long _vq_quantlist__8c0_s_p8_0[] = {
  120592. 6,
  120593. 5,
  120594. 7,
  120595. 4,
  120596. 8,
  120597. 3,
  120598. 9,
  120599. 2,
  120600. 10,
  120601. 1,
  120602. 11,
  120603. 0,
  120604. 12,
  120605. };
  120606. static long _vq_lengthlist__8c0_s_p8_0[] = {
  120607. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  120608. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  120609. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  120610. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  120611. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  120612. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  120613. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  120614. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  120615. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  120616. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  120617. 0, 0,13,13,11,13,13,11,12,
  120618. };
  120619. static float _vq_quantthresh__8c0_s_p8_0[] = {
  120620. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120621. 12.5, 17.5, 22.5, 27.5,
  120622. };
  120623. static long _vq_quantmap__8c0_s_p8_0[] = {
  120624. 11, 9, 7, 5, 3, 1, 0, 2,
  120625. 4, 6, 8, 10, 12,
  120626. };
  120627. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  120628. _vq_quantthresh__8c0_s_p8_0,
  120629. _vq_quantmap__8c0_s_p8_0,
  120630. 13,
  120631. 13
  120632. };
  120633. static static_codebook _8c0_s_p8_0 = {
  120634. 2, 169,
  120635. _vq_lengthlist__8c0_s_p8_0,
  120636. 1, -526516224, 1616117760, 4, 0,
  120637. _vq_quantlist__8c0_s_p8_0,
  120638. NULL,
  120639. &_vq_auxt__8c0_s_p8_0,
  120640. NULL,
  120641. 0
  120642. };
  120643. static long _vq_quantlist__8c0_s_p8_1[] = {
  120644. 2,
  120645. 1,
  120646. 3,
  120647. 0,
  120648. 4,
  120649. };
  120650. static long _vq_lengthlist__8c0_s_p8_1[] = {
  120651. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  120652. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  120653. };
  120654. static float _vq_quantthresh__8c0_s_p8_1[] = {
  120655. -1.5, -0.5, 0.5, 1.5,
  120656. };
  120657. static long _vq_quantmap__8c0_s_p8_1[] = {
  120658. 3, 1, 0, 2, 4,
  120659. };
  120660. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  120661. _vq_quantthresh__8c0_s_p8_1,
  120662. _vq_quantmap__8c0_s_p8_1,
  120663. 5,
  120664. 5
  120665. };
  120666. static static_codebook _8c0_s_p8_1 = {
  120667. 2, 25,
  120668. _vq_lengthlist__8c0_s_p8_1,
  120669. 1, -533725184, 1611661312, 3, 0,
  120670. _vq_quantlist__8c0_s_p8_1,
  120671. NULL,
  120672. &_vq_auxt__8c0_s_p8_1,
  120673. NULL,
  120674. 0
  120675. };
  120676. static long _vq_quantlist__8c0_s_p9_0[] = {
  120677. 1,
  120678. 0,
  120679. 2,
  120680. };
  120681. static long _vq_lengthlist__8c0_s_p9_0[] = {
  120682. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120683. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120684. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120685. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120686. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120687. 7,
  120688. };
  120689. static float _vq_quantthresh__8c0_s_p9_0[] = {
  120690. -157.5, 157.5,
  120691. };
  120692. static long _vq_quantmap__8c0_s_p9_0[] = {
  120693. 1, 0, 2,
  120694. };
  120695. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  120696. _vq_quantthresh__8c0_s_p9_0,
  120697. _vq_quantmap__8c0_s_p9_0,
  120698. 3,
  120699. 3
  120700. };
  120701. static static_codebook _8c0_s_p9_0 = {
  120702. 4, 81,
  120703. _vq_lengthlist__8c0_s_p9_0,
  120704. 1, -518803456, 1628680192, 2, 0,
  120705. _vq_quantlist__8c0_s_p9_0,
  120706. NULL,
  120707. &_vq_auxt__8c0_s_p9_0,
  120708. NULL,
  120709. 0
  120710. };
  120711. static long _vq_quantlist__8c0_s_p9_1[] = {
  120712. 7,
  120713. 6,
  120714. 8,
  120715. 5,
  120716. 9,
  120717. 4,
  120718. 10,
  120719. 3,
  120720. 11,
  120721. 2,
  120722. 12,
  120723. 1,
  120724. 13,
  120725. 0,
  120726. 14,
  120727. };
  120728. static long _vq_lengthlist__8c0_s_p9_1[] = {
  120729. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  120730. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  120731. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  120732. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  120733. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  120734. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  120735. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120736. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120737. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120738. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120739. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120740. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120741. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120742. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120743. 11,
  120744. };
  120745. static float _vq_quantthresh__8c0_s_p9_1[] = {
  120746. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  120747. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  120748. };
  120749. static long _vq_quantmap__8c0_s_p9_1[] = {
  120750. 13, 11, 9, 7, 5, 3, 1, 0,
  120751. 2, 4, 6, 8, 10, 12, 14,
  120752. };
  120753. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  120754. _vq_quantthresh__8c0_s_p9_1,
  120755. _vq_quantmap__8c0_s_p9_1,
  120756. 15,
  120757. 15
  120758. };
  120759. static static_codebook _8c0_s_p9_1 = {
  120760. 2, 225,
  120761. _vq_lengthlist__8c0_s_p9_1,
  120762. 1, -520986624, 1620377600, 4, 0,
  120763. _vq_quantlist__8c0_s_p9_1,
  120764. NULL,
  120765. &_vq_auxt__8c0_s_p9_1,
  120766. NULL,
  120767. 0
  120768. };
  120769. static long _vq_quantlist__8c0_s_p9_2[] = {
  120770. 10,
  120771. 9,
  120772. 11,
  120773. 8,
  120774. 12,
  120775. 7,
  120776. 13,
  120777. 6,
  120778. 14,
  120779. 5,
  120780. 15,
  120781. 4,
  120782. 16,
  120783. 3,
  120784. 17,
  120785. 2,
  120786. 18,
  120787. 1,
  120788. 19,
  120789. 0,
  120790. 20,
  120791. };
  120792. static long _vq_lengthlist__8c0_s_p9_2[] = {
  120793. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  120794. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  120795. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  120796. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  120797. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  120798. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  120799. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  120800. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  120801. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  120802. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  120803. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  120804. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  120805. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  120806. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  120807. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  120808. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  120809. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  120810. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  120811. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  120812. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  120813. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  120814. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  120815. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  120816. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  120817. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  120818. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  120819. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  120820. 10,11, 9,11,10, 9,10, 9,10,
  120821. };
  120822. static float _vq_quantthresh__8c0_s_p9_2[] = {
  120823. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  120824. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  120825. 6.5, 7.5, 8.5, 9.5,
  120826. };
  120827. static long _vq_quantmap__8c0_s_p9_2[] = {
  120828. 19, 17, 15, 13, 11, 9, 7, 5,
  120829. 3, 1, 0, 2, 4, 6, 8, 10,
  120830. 12, 14, 16, 18, 20,
  120831. };
  120832. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  120833. _vq_quantthresh__8c0_s_p9_2,
  120834. _vq_quantmap__8c0_s_p9_2,
  120835. 21,
  120836. 21
  120837. };
  120838. static static_codebook _8c0_s_p9_2 = {
  120839. 2, 441,
  120840. _vq_lengthlist__8c0_s_p9_2,
  120841. 1, -529268736, 1611661312, 5, 0,
  120842. _vq_quantlist__8c0_s_p9_2,
  120843. NULL,
  120844. &_vq_auxt__8c0_s_p9_2,
  120845. NULL,
  120846. 0
  120847. };
  120848. static long _huff_lengthlist__8c0_s_single[] = {
  120849. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  120850. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  120851. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  120852. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  120853. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  120854. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  120855. 17,16,17,17,
  120856. };
  120857. static static_codebook _huff_book__8c0_s_single = {
  120858. 2, 100,
  120859. _huff_lengthlist__8c0_s_single,
  120860. 0, 0, 0, 0, 0,
  120861. NULL,
  120862. NULL,
  120863. NULL,
  120864. NULL,
  120865. 0
  120866. };
  120867. static long _vq_quantlist__8c1_s_p1_0[] = {
  120868. 1,
  120869. 0,
  120870. 2,
  120871. };
  120872. static long _vq_lengthlist__8c1_s_p1_0[] = {
  120873. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  120874. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  120879. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120881. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  120884. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120886. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  120919. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  120924. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  120929. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  120965. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  120970. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  120975. 0, 0, 0, 0, 0, 0, 8,10, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121283. 0,
  121284. };
  121285. static float _vq_quantthresh__8c1_s_p1_0[] = {
  121286. -0.5, 0.5,
  121287. };
  121288. static long _vq_quantmap__8c1_s_p1_0[] = {
  121289. 1, 0, 2,
  121290. };
  121291. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  121292. _vq_quantthresh__8c1_s_p1_0,
  121293. _vq_quantmap__8c1_s_p1_0,
  121294. 3,
  121295. 3
  121296. };
  121297. static static_codebook _8c1_s_p1_0 = {
  121298. 8, 6561,
  121299. _vq_lengthlist__8c1_s_p1_0,
  121300. 1, -535822336, 1611661312, 2, 0,
  121301. _vq_quantlist__8c1_s_p1_0,
  121302. NULL,
  121303. &_vq_auxt__8c1_s_p1_0,
  121304. NULL,
  121305. 0
  121306. };
  121307. static long _vq_quantlist__8c1_s_p2_0[] = {
  121308. 2,
  121309. 1,
  121310. 3,
  121311. 0,
  121312. 4,
  121313. };
  121314. static long _vq_lengthlist__8c1_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121354. 0,
  121355. };
  121356. static float _vq_quantthresh__8c1_s_p2_0[] = {
  121357. -1.5, -0.5, 0.5, 1.5,
  121358. };
  121359. static long _vq_quantmap__8c1_s_p2_0[] = {
  121360. 3, 1, 0, 2, 4,
  121361. };
  121362. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  121363. _vq_quantthresh__8c1_s_p2_0,
  121364. _vq_quantmap__8c1_s_p2_0,
  121365. 5,
  121366. 5
  121367. };
  121368. static static_codebook _8c1_s_p2_0 = {
  121369. 4, 625,
  121370. _vq_lengthlist__8c1_s_p2_0,
  121371. 1, -533725184, 1611661312, 3, 0,
  121372. _vq_quantlist__8c1_s_p2_0,
  121373. NULL,
  121374. &_vq_auxt__8c1_s_p2_0,
  121375. NULL,
  121376. 0
  121377. };
  121378. static long _vq_quantlist__8c1_s_p3_0[] = {
  121379. 2,
  121380. 1,
  121381. 3,
  121382. 0,
  121383. 4,
  121384. };
  121385. static long _vq_lengthlist__8c1_s_p3_0[] = {
  121386. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  121388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121389. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  121391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121392. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  121393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121425. 0,
  121426. };
  121427. static float _vq_quantthresh__8c1_s_p3_0[] = {
  121428. -1.5, -0.5, 0.5, 1.5,
  121429. };
  121430. static long _vq_quantmap__8c1_s_p3_0[] = {
  121431. 3, 1, 0, 2, 4,
  121432. };
  121433. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  121434. _vq_quantthresh__8c1_s_p3_0,
  121435. _vq_quantmap__8c1_s_p3_0,
  121436. 5,
  121437. 5
  121438. };
  121439. static static_codebook _8c1_s_p3_0 = {
  121440. 4, 625,
  121441. _vq_lengthlist__8c1_s_p3_0,
  121442. 1, -533725184, 1611661312, 3, 0,
  121443. _vq_quantlist__8c1_s_p3_0,
  121444. NULL,
  121445. &_vq_auxt__8c1_s_p3_0,
  121446. NULL,
  121447. 0
  121448. };
  121449. static long _vq_quantlist__8c1_s_p4_0[] = {
  121450. 4,
  121451. 3,
  121452. 5,
  121453. 2,
  121454. 6,
  121455. 1,
  121456. 7,
  121457. 0,
  121458. 8,
  121459. };
  121460. static long _vq_lengthlist__8c1_s_p4_0[] = {
  121461. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  121462. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  121463. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  121464. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  121465. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121466. 0,
  121467. };
  121468. static float _vq_quantthresh__8c1_s_p4_0[] = {
  121469. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121470. };
  121471. static long _vq_quantmap__8c1_s_p4_0[] = {
  121472. 7, 5, 3, 1, 0, 2, 4, 6,
  121473. 8,
  121474. };
  121475. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  121476. _vq_quantthresh__8c1_s_p4_0,
  121477. _vq_quantmap__8c1_s_p4_0,
  121478. 9,
  121479. 9
  121480. };
  121481. static static_codebook _8c1_s_p4_0 = {
  121482. 2, 81,
  121483. _vq_lengthlist__8c1_s_p4_0,
  121484. 1, -531628032, 1611661312, 4, 0,
  121485. _vq_quantlist__8c1_s_p4_0,
  121486. NULL,
  121487. &_vq_auxt__8c1_s_p4_0,
  121488. NULL,
  121489. 0
  121490. };
  121491. static long _vq_quantlist__8c1_s_p5_0[] = {
  121492. 4,
  121493. 3,
  121494. 5,
  121495. 2,
  121496. 6,
  121497. 1,
  121498. 7,
  121499. 0,
  121500. 8,
  121501. };
  121502. static long _vq_lengthlist__8c1_s_p5_0[] = {
  121503. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  121504. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  121505. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  121506. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  121507. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  121508. 10,
  121509. };
  121510. static float _vq_quantthresh__8c1_s_p5_0[] = {
  121511. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121512. };
  121513. static long _vq_quantmap__8c1_s_p5_0[] = {
  121514. 7, 5, 3, 1, 0, 2, 4, 6,
  121515. 8,
  121516. };
  121517. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  121518. _vq_quantthresh__8c1_s_p5_0,
  121519. _vq_quantmap__8c1_s_p5_0,
  121520. 9,
  121521. 9
  121522. };
  121523. static static_codebook _8c1_s_p5_0 = {
  121524. 2, 81,
  121525. _vq_lengthlist__8c1_s_p5_0,
  121526. 1, -531628032, 1611661312, 4, 0,
  121527. _vq_quantlist__8c1_s_p5_0,
  121528. NULL,
  121529. &_vq_auxt__8c1_s_p5_0,
  121530. NULL,
  121531. 0
  121532. };
  121533. static long _vq_quantlist__8c1_s_p6_0[] = {
  121534. 8,
  121535. 7,
  121536. 9,
  121537. 6,
  121538. 10,
  121539. 5,
  121540. 11,
  121541. 4,
  121542. 12,
  121543. 3,
  121544. 13,
  121545. 2,
  121546. 14,
  121547. 1,
  121548. 15,
  121549. 0,
  121550. 16,
  121551. };
  121552. static long _vq_lengthlist__8c1_s_p6_0[] = {
  121553. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  121554. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  121555. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  121556. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  121557. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  121558. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  121559. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  121560. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  121561. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  121562. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  121563. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  121564. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  121565. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  121566. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  121567. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  121568. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  121569. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  121570. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  121571. 14,
  121572. };
  121573. static float _vq_quantthresh__8c1_s_p6_0[] = {
  121574. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  121575. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  121576. };
  121577. static long _vq_quantmap__8c1_s_p6_0[] = {
  121578. 15, 13, 11, 9, 7, 5, 3, 1,
  121579. 0, 2, 4, 6, 8, 10, 12, 14,
  121580. 16,
  121581. };
  121582. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  121583. _vq_quantthresh__8c1_s_p6_0,
  121584. _vq_quantmap__8c1_s_p6_0,
  121585. 17,
  121586. 17
  121587. };
  121588. static static_codebook _8c1_s_p6_0 = {
  121589. 2, 289,
  121590. _vq_lengthlist__8c1_s_p6_0,
  121591. 1, -529530880, 1611661312, 5, 0,
  121592. _vq_quantlist__8c1_s_p6_0,
  121593. NULL,
  121594. &_vq_auxt__8c1_s_p6_0,
  121595. NULL,
  121596. 0
  121597. };
  121598. static long _vq_quantlist__8c1_s_p7_0[] = {
  121599. 1,
  121600. 0,
  121601. 2,
  121602. };
  121603. static long _vq_lengthlist__8c1_s_p7_0[] = {
  121604. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  121605. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  121606. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  121607. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  121608. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  121609. 9,
  121610. };
  121611. static float _vq_quantthresh__8c1_s_p7_0[] = {
  121612. -5.5, 5.5,
  121613. };
  121614. static long _vq_quantmap__8c1_s_p7_0[] = {
  121615. 1, 0, 2,
  121616. };
  121617. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  121618. _vq_quantthresh__8c1_s_p7_0,
  121619. _vq_quantmap__8c1_s_p7_0,
  121620. 3,
  121621. 3
  121622. };
  121623. static static_codebook _8c1_s_p7_0 = {
  121624. 4, 81,
  121625. _vq_lengthlist__8c1_s_p7_0,
  121626. 1, -529137664, 1618345984, 2, 0,
  121627. _vq_quantlist__8c1_s_p7_0,
  121628. NULL,
  121629. &_vq_auxt__8c1_s_p7_0,
  121630. NULL,
  121631. 0
  121632. };
  121633. static long _vq_quantlist__8c1_s_p7_1[] = {
  121634. 5,
  121635. 4,
  121636. 6,
  121637. 3,
  121638. 7,
  121639. 2,
  121640. 8,
  121641. 1,
  121642. 9,
  121643. 0,
  121644. 10,
  121645. };
  121646. static long _vq_lengthlist__8c1_s_p7_1[] = {
  121647. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  121648. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  121649. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  121650. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  121651. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  121652. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  121653. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  121654. 10,10,10, 8, 8, 8, 8, 8, 8,
  121655. };
  121656. static float _vq_quantthresh__8c1_s_p7_1[] = {
  121657. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121658. 3.5, 4.5,
  121659. };
  121660. static long _vq_quantmap__8c1_s_p7_1[] = {
  121661. 9, 7, 5, 3, 1, 0, 2, 4,
  121662. 6, 8, 10,
  121663. };
  121664. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  121665. _vq_quantthresh__8c1_s_p7_1,
  121666. _vq_quantmap__8c1_s_p7_1,
  121667. 11,
  121668. 11
  121669. };
  121670. static static_codebook _8c1_s_p7_1 = {
  121671. 2, 121,
  121672. _vq_lengthlist__8c1_s_p7_1,
  121673. 1, -531365888, 1611661312, 4, 0,
  121674. _vq_quantlist__8c1_s_p7_1,
  121675. NULL,
  121676. &_vq_auxt__8c1_s_p7_1,
  121677. NULL,
  121678. 0
  121679. };
  121680. static long _vq_quantlist__8c1_s_p8_0[] = {
  121681. 6,
  121682. 5,
  121683. 7,
  121684. 4,
  121685. 8,
  121686. 3,
  121687. 9,
  121688. 2,
  121689. 10,
  121690. 1,
  121691. 11,
  121692. 0,
  121693. 12,
  121694. };
  121695. static long _vq_lengthlist__8c1_s_p8_0[] = {
  121696. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  121697. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  121698. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  121699. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  121700. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  121701. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  121702. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  121703. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  121704. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  121705. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  121706. 0,12,12,11,10,12,11,13,12,
  121707. };
  121708. static float _vq_quantthresh__8c1_s_p8_0[] = {
  121709. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  121710. 12.5, 17.5, 22.5, 27.5,
  121711. };
  121712. static long _vq_quantmap__8c1_s_p8_0[] = {
  121713. 11, 9, 7, 5, 3, 1, 0, 2,
  121714. 4, 6, 8, 10, 12,
  121715. };
  121716. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  121717. _vq_quantthresh__8c1_s_p8_0,
  121718. _vq_quantmap__8c1_s_p8_0,
  121719. 13,
  121720. 13
  121721. };
  121722. static static_codebook _8c1_s_p8_0 = {
  121723. 2, 169,
  121724. _vq_lengthlist__8c1_s_p8_0,
  121725. 1, -526516224, 1616117760, 4, 0,
  121726. _vq_quantlist__8c1_s_p8_0,
  121727. NULL,
  121728. &_vq_auxt__8c1_s_p8_0,
  121729. NULL,
  121730. 0
  121731. };
  121732. static long _vq_quantlist__8c1_s_p8_1[] = {
  121733. 2,
  121734. 1,
  121735. 3,
  121736. 0,
  121737. 4,
  121738. };
  121739. static long _vq_lengthlist__8c1_s_p8_1[] = {
  121740. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  121741. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  121742. };
  121743. static float _vq_quantthresh__8c1_s_p8_1[] = {
  121744. -1.5, -0.5, 0.5, 1.5,
  121745. };
  121746. static long _vq_quantmap__8c1_s_p8_1[] = {
  121747. 3, 1, 0, 2, 4,
  121748. };
  121749. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  121750. _vq_quantthresh__8c1_s_p8_1,
  121751. _vq_quantmap__8c1_s_p8_1,
  121752. 5,
  121753. 5
  121754. };
  121755. static static_codebook _8c1_s_p8_1 = {
  121756. 2, 25,
  121757. _vq_lengthlist__8c1_s_p8_1,
  121758. 1, -533725184, 1611661312, 3, 0,
  121759. _vq_quantlist__8c1_s_p8_1,
  121760. NULL,
  121761. &_vq_auxt__8c1_s_p8_1,
  121762. NULL,
  121763. 0
  121764. };
  121765. static long _vq_quantlist__8c1_s_p9_0[] = {
  121766. 6,
  121767. 5,
  121768. 7,
  121769. 4,
  121770. 8,
  121771. 3,
  121772. 9,
  121773. 2,
  121774. 10,
  121775. 1,
  121776. 11,
  121777. 0,
  121778. 12,
  121779. };
  121780. static long _vq_lengthlist__8c1_s_p9_0[] = {
  121781. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  121782. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  121783. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121784. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121785. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121786. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121787. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121788. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121789. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121790. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121791. 10,10,10,10,10, 9, 9, 9, 9,
  121792. };
  121793. static float _vq_quantthresh__8c1_s_p9_0[] = {
  121794. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  121795. 787.5, 1102.5, 1417.5, 1732.5,
  121796. };
  121797. static long _vq_quantmap__8c1_s_p9_0[] = {
  121798. 11, 9, 7, 5, 3, 1, 0, 2,
  121799. 4, 6, 8, 10, 12,
  121800. };
  121801. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  121802. _vq_quantthresh__8c1_s_p9_0,
  121803. _vq_quantmap__8c1_s_p9_0,
  121804. 13,
  121805. 13
  121806. };
  121807. static static_codebook _8c1_s_p9_0 = {
  121808. 2, 169,
  121809. _vq_lengthlist__8c1_s_p9_0,
  121810. 1, -513964032, 1628680192, 4, 0,
  121811. _vq_quantlist__8c1_s_p9_0,
  121812. NULL,
  121813. &_vq_auxt__8c1_s_p9_0,
  121814. NULL,
  121815. 0
  121816. };
  121817. static long _vq_quantlist__8c1_s_p9_1[] = {
  121818. 7,
  121819. 6,
  121820. 8,
  121821. 5,
  121822. 9,
  121823. 4,
  121824. 10,
  121825. 3,
  121826. 11,
  121827. 2,
  121828. 12,
  121829. 1,
  121830. 13,
  121831. 0,
  121832. 14,
  121833. };
  121834. static long _vq_lengthlist__8c1_s_p9_1[] = {
  121835. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  121836. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  121837. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  121838. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  121839. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  121840. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  121841. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  121842. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  121843. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  121844. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  121845. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  121846. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  121847. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  121848. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  121849. 15,
  121850. };
  121851. static float _vq_quantthresh__8c1_s_p9_1[] = {
  121852. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  121853. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  121854. };
  121855. static long _vq_quantmap__8c1_s_p9_1[] = {
  121856. 13, 11, 9, 7, 5, 3, 1, 0,
  121857. 2, 4, 6, 8, 10, 12, 14,
  121858. };
  121859. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  121860. _vq_quantthresh__8c1_s_p9_1,
  121861. _vq_quantmap__8c1_s_p9_1,
  121862. 15,
  121863. 15
  121864. };
  121865. static static_codebook _8c1_s_p9_1 = {
  121866. 2, 225,
  121867. _vq_lengthlist__8c1_s_p9_1,
  121868. 1, -520986624, 1620377600, 4, 0,
  121869. _vq_quantlist__8c1_s_p9_1,
  121870. NULL,
  121871. &_vq_auxt__8c1_s_p9_1,
  121872. NULL,
  121873. 0
  121874. };
  121875. static long _vq_quantlist__8c1_s_p9_2[] = {
  121876. 10,
  121877. 9,
  121878. 11,
  121879. 8,
  121880. 12,
  121881. 7,
  121882. 13,
  121883. 6,
  121884. 14,
  121885. 5,
  121886. 15,
  121887. 4,
  121888. 16,
  121889. 3,
  121890. 17,
  121891. 2,
  121892. 18,
  121893. 1,
  121894. 19,
  121895. 0,
  121896. 20,
  121897. };
  121898. static long _vq_lengthlist__8c1_s_p9_2[] = {
  121899. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  121900. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  121901. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  121902. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  121903. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  121904. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  121905. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  121906. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  121907. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  121908. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  121909. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  121910. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  121911. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  121912. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  121913. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  121914. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  121915. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121916. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  121917. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  121918. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  121919. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121920. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  121921. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  121922. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  121923. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  121924. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  121925. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  121926. 10,10,10,10,10,10,10,10,10,
  121927. };
  121928. static float _vq_quantthresh__8c1_s_p9_2[] = {
  121929. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  121930. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  121931. 6.5, 7.5, 8.5, 9.5,
  121932. };
  121933. static long _vq_quantmap__8c1_s_p9_2[] = {
  121934. 19, 17, 15, 13, 11, 9, 7, 5,
  121935. 3, 1, 0, 2, 4, 6, 8, 10,
  121936. 12, 14, 16, 18, 20,
  121937. };
  121938. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  121939. _vq_quantthresh__8c1_s_p9_2,
  121940. _vq_quantmap__8c1_s_p9_2,
  121941. 21,
  121942. 21
  121943. };
  121944. static static_codebook _8c1_s_p9_2 = {
  121945. 2, 441,
  121946. _vq_lengthlist__8c1_s_p9_2,
  121947. 1, -529268736, 1611661312, 5, 0,
  121948. _vq_quantlist__8c1_s_p9_2,
  121949. NULL,
  121950. &_vq_auxt__8c1_s_p9_2,
  121951. NULL,
  121952. 0
  121953. };
  121954. static long _huff_lengthlist__8c1_s_single[] = {
  121955. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  121956. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  121957. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  121958. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  121959. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  121960. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  121961. 9, 7, 7, 8,
  121962. };
  121963. static static_codebook _huff_book__8c1_s_single = {
  121964. 2, 100,
  121965. _huff_lengthlist__8c1_s_single,
  121966. 0, 0, 0, 0, 0,
  121967. NULL,
  121968. NULL,
  121969. NULL,
  121970. NULL,
  121971. 0
  121972. };
  121973. static long _huff_lengthlist__44c2_s_long[] = {
  121974. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  121975. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  121976. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  121977. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  121978. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  121979. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  121980. 10, 8, 8, 9,
  121981. };
  121982. static static_codebook _huff_book__44c2_s_long = {
  121983. 2, 100,
  121984. _huff_lengthlist__44c2_s_long,
  121985. 0, 0, 0, 0, 0,
  121986. NULL,
  121987. NULL,
  121988. NULL,
  121989. NULL,
  121990. 0
  121991. };
  121992. static long _vq_quantlist__44c2_s_p1_0[] = {
  121993. 1,
  121994. 0,
  121995. 2,
  121996. };
  121997. static long _vq_lengthlist__44c2_s_p1_0[] = {
  121998. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  121999. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  122004. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122006. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  122009. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122011. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  122044. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  122049. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  122054. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  122090. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  122095. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  122100. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122360. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122368. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122408. 0,
  122409. };
  122410. static float _vq_quantthresh__44c2_s_p1_0[] = {
  122411. -0.5, 0.5,
  122412. };
  122413. static long _vq_quantmap__44c2_s_p1_0[] = {
  122414. 1, 0, 2,
  122415. };
  122416. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  122417. _vq_quantthresh__44c2_s_p1_0,
  122418. _vq_quantmap__44c2_s_p1_0,
  122419. 3,
  122420. 3
  122421. };
  122422. static static_codebook _44c2_s_p1_0 = {
  122423. 8, 6561,
  122424. _vq_lengthlist__44c2_s_p1_0,
  122425. 1, -535822336, 1611661312, 2, 0,
  122426. _vq_quantlist__44c2_s_p1_0,
  122427. NULL,
  122428. &_vq_auxt__44c2_s_p1_0,
  122429. NULL,
  122430. 0
  122431. };
  122432. static long _vq_quantlist__44c2_s_p2_0[] = {
  122433. 2,
  122434. 1,
  122435. 3,
  122436. 0,
  122437. 4,
  122438. };
  122439. static long _vq_lengthlist__44c2_s_p2_0[] = {
  122440. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  122441. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  122442. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  122443. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  122444. 0, 0, 9, 9, 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, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  122450. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  122451. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  122452. 12, 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, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  122458. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  122459. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 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. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  122466. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  122467. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  122468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122479. 0,
  122480. };
  122481. static float _vq_quantthresh__44c2_s_p2_0[] = {
  122482. -1.5, -0.5, 0.5, 1.5,
  122483. };
  122484. static long _vq_quantmap__44c2_s_p2_0[] = {
  122485. 3, 1, 0, 2, 4,
  122486. };
  122487. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  122488. _vq_quantthresh__44c2_s_p2_0,
  122489. _vq_quantmap__44c2_s_p2_0,
  122490. 5,
  122491. 5
  122492. };
  122493. static static_codebook _44c2_s_p2_0 = {
  122494. 4, 625,
  122495. _vq_lengthlist__44c2_s_p2_0,
  122496. 1, -533725184, 1611661312, 3, 0,
  122497. _vq_quantlist__44c2_s_p2_0,
  122498. NULL,
  122499. &_vq_auxt__44c2_s_p2_0,
  122500. NULL,
  122501. 0
  122502. };
  122503. static long _vq_quantlist__44c2_s_p3_0[] = {
  122504. 2,
  122505. 1,
  122506. 3,
  122507. 0,
  122508. 4,
  122509. };
  122510. static long _vq_lengthlist__44c2_s_p3_0[] = {
  122511. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  122513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122514. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122517. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  122518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122550. 0,
  122551. };
  122552. static float _vq_quantthresh__44c2_s_p3_0[] = {
  122553. -1.5, -0.5, 0.5, 1.5,
  122554. };
  122555. static long _vq_quantmap__44c2_s_p3_0[] = {
  122556. 3, 1, 0, 2, 4,
  122557. };
  122558. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  122559. _vq_quantthresh__44c2_s_p3_0,
  122560. _vq_quantmap__44c2_s_p3_0,
  122561. 5,
  122562. 5
  122563. };
  122564. static static_codebook _44c2_s_p3_0 = {
  122565. 4, 625,
  122566. _vq_lengthlist__44c2_s_p3_0,
  122567. 1, -533725184, 1611661312, 3, 0,
  122568. _vq_quantlist__44c2_s_p3_0,
  122569. NULL,
  122570. &_vq_auxt__44c2_s_p3_0,
  122571. NULL,
  122572. 0
  122573. };
  122574. static long _vq_quantlist__44c2_s_p4_0[] = {
  122575. 4,
  122576. 3,
  122577. 5,
  122578. 2,
  122579. 6,
  122580. 1,
  122581. 7,
  122582. 0,
  122583. 8,
  122584. };
  122585. static long _vq_lengthlist__44c2_s_p4_0[] = {
  122586. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  122587. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  122588. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  122589. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  122590. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122591. 0,
  122592. };
  122593. static float _vq_quantthresh__44c2_s_p4_0[] = {
  122594. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122595. };
  122596. static long _vq_quantmap__44c2_s_p4_0[] = {
  122597. 7, 5, 3, 1, 0, 2, 4, 6,
  122598. 8,
  122599. };
  122600. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  122601. _vq_quantthresh__44c2_s_p4_0,
  122602. _vq_quantmap__44c2_s_p4_0,
  122603. 9,
  122604. 9
  122605. };
  122606. static static_codebook _44c2_s_p4_0 = {
  122607. 2, 81,
  122608. _vq_lengthlist__44c2_s_p4_0,
  122609. 1, -531628032, 1611661312, 4, 0,
  122610. _vq_quantlist__44c2_s_p4_0,
  122611. NULL,
  122612. &_vq_auxt__44c2_s_p4_0,
  122613. NULL,
  122614. 0
  122615. };
  122616. static long _vq_quantlist__44c2_s_p5_0[] = {
  122617. 4,
  122618. 3,
  122619. 5,
  122620. 2,
  122621. 6,
  122622. 1,
  122623. 7,
  122624. 0,
  122625. 8,
  122626. };
  122627. static long _vq_lengthlist__44c2_s_p5_0[] = {
  122628. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  122629. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  122630. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  122631. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  122632. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  122633. 11,
  122634. };
  122635. static float _vq_quantthresh__44c2_s_p5_0[] = {
  122636. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122637. };
  122638. static long _vq_quantmap__44c2_s_p5_0[] = {
  122639. 7, 5, 3, 1, 0, 2, 4, 6,
  122640. 8,
  122641. };
  122642. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  122643. _vq_quantthresh__44c2_s_p5_0,
  122644. _vq_quantmap__44c2_s_p5_0,
  122645. 9,
  122646. 9
  122647. };
  122648. static static_codebook _44c2_s_p5_0 = {
  122649. 2, 81,
  122650. _vq_lengthlist__44c2_s_p5_0,
  122651. 1, -531628032, 1611661312, 4, 0,
  122652. _vq_quantlist__44c2_s_p5_0,
  122653. NULL,
  122654. &_vq_auxt__44c2_s_p5_0,
  122655. NULL,
  122656. 0
  122657. };
  122658. static long _vq_quantlist__44c2_s_p6_0[] = {
  122659. 8,
  122660. 7,
  122661. 9,
  122662. 6,
  122663. 10,
  122664. 5,
  122665. 11,
  122666. 4,
  122667. 12,
  122668. 3,
  122669. 13,
  122670. 2,
  122671. 14,
  122672. 1,
  122673. 15,
  122674. 0,
  122675. 16,
  122676. };
  122677. static long _vq_lengthlist__44c2_s_p6_0[] = {
  122678. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  122679. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  122680. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  122681. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  122682. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  122683. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  122684. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  122685. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  122686. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  122687. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122688. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  122689. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  122690. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  122691. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  122692. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  122693. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  122694. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  122696. 14,
  122697. };
  122698. static float _vq_quantthresh__44c2_s_p6_0[] = {
  122699. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122700. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122701. };
  122702. static long _vq_quantmap__44c2_s_p6_0[] = {
  122703. 15, 13, 11, 9, 7, 5, 3, 1,
  122704. 0, 2, 4, 6, 8, 10, 12, 14,
  122705. 16,
  122706. };
  122707. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  122708. _vq_quantthresh__44c2_s_p6_0,
  122709. _vq_quantmap__44c2_s_p6_0,
  122710. 17,
  122711. 17
  122712. };
  122713. static static_codebook _44c2_s_p6_0 = {
  122714. 2, 289,
  122715. _vq_lengthlist__44c2_s_p6_0,
  122716. 1, -529530880, 1611661312, 5, 0,
  122717. _vq_quantlist__44c2_s_p6_0,
  122718. NULL,
  122719. &_vq_auxt__44c2_s_p6_0,
  122720. NULL,
  122721. 0
  122722. };
  122723. static long _vq_quantlist__44c2_s_p7_0[] = {
  122724. 1,
  122725. 0,
  122726. 2,
  122727. };
  122728. static long _vq_lengthlist__44c2_s_p7_0[] = {
  122729. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  122730. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  122731. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  122732. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  122733. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  122734. 11,
  122735. };
  122736. static float _vq_quantthresh__44c2_s_p7_0[] = {
  122737. -5.5, 5.5,
  122738. };
  122739. static long _vq_quantmap__44c2_s_p7_0[] = {
  122740. 1, 0, 2,
  122741. };
  122742. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  122743. _vq_quantthresh__44c2_s_p7_0,
  122744. _vq_quantmap__44c2_s_p7_0,
  122745. 3,
  122746. 3
  122747. };
  122748. static static_codebook _44c2_s_p7_0 = {
  122749. 4, 81,
  122750. _vq_lengthlist__44c2_s_p7_0,
  122751. 1, -529137664, 1618345984, 2, 0,
  122752. _vq_quantlist__44c2_s_p7_0,
  122753. NULL,
  122754. &_vq_auxt__44c2_s_p7_0,
  122755. NULL,
  122756. 0
  122757. };
  122758. static long _vq_quantlist__44c2_s_p7_1[] = {
  122759. 5,
  122760. 4,
  122761. 6,
  122762. 3,
  122763. 7,
  122764. 2,
  122765. 8,
  122766. 1,
  122767. 9,
  122768. 0,
  122769. 10,
  122770. };
  122771. static long _vq_lengthlist__44c2_s_p7_1[] = {
  122772. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  122773. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  122774. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  122775. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  122776. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  122777. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  122778. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  122779. 10,10,10, 8, 8, 8, 8, 8, 8,
  122780. };
  122781. static float _vq_quantthresh__44c2_s_p7_1[] = {
  122782. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122783. 3.5, 4.5,
  122784. };
  122785. static long _vq_quantmap__44c2_s_p7_1[] = {
  122786. 9, 7, 5, 3, 1, 0, 2, 4,
  122787. 6, 8, 10,
  122788. };
  122789. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  122790. _vq_quantthresh__44c2_s_p7_1,
  122791. _vq_quantmap__44c2_s_p7_1,
  122792. 11,
  122793. 11
  122794. };
  122795. static static_codebook _44c2_s_p7_1 = {
  122796. 2, 121,
  122797. _vq_lengthlist__44c2_s_p7_1,
  122798. 1, -531365888, 1611661312, 4, 0,
  122799. _vq_quantlist__44c2_s_p7_1,
  122800. NULL,
  122801. &_vq_auxt__44c2_s_p7_1,
  122802. NULL,
  122803. 0
  122804. };
  122805. static long _vq_quantlist__44c2_s_p8_0[] = {
  122806. 6,
  122807. 5,
  122808. 7,
  122809. 4,
  122810. 8,
  122811. 3,
  122812. 9,
  122813. 2,
  122814. 10,
  122815. 1,
  122816. 11,
  122817. 0,
  122818. 12,
  122819. };
  122820. static long _vq_lengthlist__44c2_s_p8_0[] = {
  122821. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  122822. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  122823. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  122824. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  122825. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  122826. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  122827. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  122828. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  122829. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  122830. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  122831. 0,12,12,12,12,13,12,14,14,
  122832. };
  122833. static float _vq_quantthresh__44c2_s_p8_0[] = {
  122834. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122835. 12.5, 17.5, 22.5, 27.5,
  122836. };
  122837. static long _vq_quantmap__44c2_s_p8_0[] = {
  122838. 11, 9, 7, 5, 3, 1, 0, 2,
  122839. 4, 6, 8, 10, 12,
  122840. };
  122841. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  122842. _vq_quantthresh__44c2_s_p8_0,
  122843. _vq_quantmap__44c2_s_p8_0,
  122844. 13,
  122845. 13
  122846. };
  122847. static static_codebook _44c2_s_p8_0 = {
  122848. 2, 169,
  122849. _vq_lengthlist__44c2_s_p8_0,
  122850. 1, -526516224, 1616117760, 4, 0,
  122851. _vq_quantlist__44c2_s_p8_0,
  122852. NULL,
  122853. &_vq_auxt__44c2_s_p8_0,
  122854. NULL,
  122855. 0
  122856. };
  122857. static long _vq_quantlist__44c2_s_p8_1[] = {
  122858. 2,
  122859. 1,
  122860. 3,
  122861. 0,
  122862. 4,
  122863. };
  122864. static long _vq_lengthlist__44c2_s_p8_1[] = {
  122865. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  122866. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  122867. };
  122868. static float _vq_quantthresh__44c2_s_p8_1[] = {
  122869. -1.5, -0.5, 0.5, 1.5,
  122870. };
  122871. static long _vq_quantmap__44c2_s_p8_1[] = {
  122872. 3, 1, 0, 2, 4,
  122873. };
  122874. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  122875. _vq_quantthresh__44c2_s_p8_1,
  122876. _vq_quantmap__44c2_s_p8_1,
  122877. 5,
  122878. 5
  122879. };
  122880. static static_codebook _44c2_s_p8_1 = {
  122881. 2, 25,
  122882. _vq_lengthlist__44c2_s_p8_1,
  122883. 1, -533725184, 1611661312, 3, 0,
  122884. _vq_quantlist__44c2_s_p8_1,
  122885. NULL,
  122886. &_vq_auxt__44c2_s_p8_1,
  122887. NULL,
  122888. 0
  122889. };
  122890. static long _vq_quantlist__44c2_s_p9_0[] = {
  122891. 6,
  122892. 5,
  122893. 7,
  122894. 4,
  122895. 8,
  122896. 3,
  122897. 9,
  122898. 2,
  122899. 10,
  122900. 1,
  122901. 11,
  122902. 0,
  122903. 12,
  122904. };
  122905. static long _vq_lengthlist__44c2_s_p9_0[] = {
  122906. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  122907. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  122908. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122909. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  122910. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122911. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122912. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122913. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122914. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122915. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122916. 11,11,11,11,11,11,11,11,11,
  122917. };
  122918. static float _vq_quantthresh__44c2_s_p9_0[] = {
  122919. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  122920. 552.5, 773.5, 994.5, 1215.5,
  122921. };
  122922. static long _vq_quantmap__44c2_s_p9_0[] = {
  122923. 11, 9, 7, 5, 3, 1, 0, 2,
  122924. 4, 6, 8, 10, 12,
  122925. };
  122926. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  122927. _vq_quantthresh__44c2_s_p9_0,
  122928. _vq_quantmap__44c2_s_p9_0,
  122929. 13,
  122930. 13
  122931. };
  122932. static static_codebook _44c2_s_p9_0 = {
  122933. 2, 169,
  122934. _vq_lengthlist__44c2_s_p9_0,
  122935. 1, -514541568, 1627103232, 4, 0,
  122936. _vq_quantlist__44c2_s_p9_0,
  122937. NULL,
  122938. &_vq_auxt__44c2_s_p9_0,
  122939. NULL,
  122940. 0
  122941. };
  122942. static long _vq_quantlist__44c2_s_p9_1[] = {
  122943. 6,
  122944. 5,
  122945. 7,
  122946. 4,
  122947. 8,
  122948. 3,
  122949. 9,
  122950. 2,
  122951. 10,
  122952. 1,
  122953. 11,
  122954. 0,
  122955. 12,
  122956. };
  122957. static long _vq_lengthlist__44c2_s_p9_1[] = {
  122958. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  122959. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  122960. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  122961. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  122962. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  122963. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  122964. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  122965. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  122966. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  122967. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  122968. 17,13,12,12,10,13,11,14,14,
  122969. };
  122970. static float _vq_quantthresh__44c2_s_p9_1[] = {
  122971. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  122972. 42.5, 59.5, 76.5, 93.5,
  122973. };
  122974. static long _vq_quantmap__44c2_s_p9_1[] = {
  122975. 11, 9, 7, 5, 3, 1, 0, 2,
  122976. 4, 6, 8, 10, 12,
  122977. };
  122978. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  122979. _vq_quantthresh__44c2_s_p9_1,
  122980. _vq_quantmap__44c2_s_p9_1,
  122981. 13,
  122982. 13
  122983. };
  122984. static static_codebook _44c2_s_p9_1 = {
  122985. 2, 169,
  122986. _vq_lengthlist__44c2_s_p9_1,
  122987. 1, -522616832, 1620115456, 4, 0,
  122988. _vq_quantlist__44c2_s_p9_1,
  122989. NULL,
  122990. &_vq_auxt__44c2_s_p9_1,
  122991. NULL,
  122992. 0
  122993. };
  122994. static long _vq_quantlist__44c2_s_p9_2[] = {
  122995. 8,
  122996. 7,
  122997. 9,
  122998. 6,
  122999. 10,
  123000. 5,
  123001. 11,
  123002. 4,
  123003. 12,
  123004. 3,
  123005. 13,
  123006. 2,
  123007. 14,
  123008. 1,
  123009. 15,
  123010. 0,
  123011. 16,
  123012. };
  123013. static long _vq_lengthlist__44c2_s_p9_2[] = {
  123014. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  123015. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  123016. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  123017. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  123018. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  123019. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  123020. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  123021. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  123022. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  123023. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  123024. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  123025. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  123026. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  123027. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  123028. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  123029. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  123030. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  123031. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  123032. 10,
  123033. };
  123034. static float _vq_quantthresh__44c2_s_p9_2[] = {
  123035. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123036. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123037. };
  123038. static long _vq_quantmap__44c2_s_p9_2[] = {
  123039. 15, 13, 11, 9, 7, 5, 3, 1,
  123040. 0, 2, 4, 6, 8, 10, 12, 14,
  123041. 16,
  123042. };
  123043. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  123044. _vq_quantthresh__44c2_s_p9_2,
  123045. _vq_quantmap__44c2_s_p9_2,
  123046. 17,
  123047. 17
  123048. };
  123049. static static_codebook _44c2_s_p9_2 = {
  123050. 2, 289,
  123051. _vq_lengthlist__44c2_s_p9_2,
  123052. 1, -529530880, 1611661312, 5, 0,
  123053. _vq_quantlist__44c2_s_p9_2,
  123054. NULL,
  123055. &_vq_auxt__44c2_s_p9_2,
  123056. NULL,
  123057. 0
  123058. };
  123059. static long _huff_lengthlist__44c2_s_short[] = {
  123060. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  123061. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  123062. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  123063. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  123064. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  123065. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  123066. 6, 8, 9,12,
  123067. };
  123068. static static_codebook _huff_book__44c2_s_short = {
  123069. 2, 100,
  123070. _huff_lengthlist__44c2_s_short,
  123071. 0, 0, 0, 0, 0,
  123072. NULL,
  123073. NULL,
  123074. NULL,
  123075. NULL,
  123076. 0
  123077. };
  123078. static long _huff_lengthlist__44c3_s_long[] = {
  123079. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  123080. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  123081. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  123082. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  123083. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  123084. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  123085. 9, 8, 8, 8,
  123086. };
  123087. static static_codebook _huff_book__44c3_s_long = {
  123088. 2, 100,
  123089. _huff_lengthlist__44c3_s_long,
  123090. 0, 0, 0, 0, 0,
  123091. NULL,
  123092. NULL,
  123093. NULL,
  123094. NULL,
  123095. 0
  123096. };
  123097. static long _vq_quantlist__44c3_s_p1_0[] = {
  123098. 1,
  123099. 0,
  123100. 2,
  123101. };
  123102. static long _vq_lengthlist__44c3_s_p1_0[] = {
  123103. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  123104. 0, 0, 5, 6, 6, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123109. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123111. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  123114. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123116. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  123149. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  123154. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  123159. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123195. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123200. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123205. 0, 0, 0, 0, 0, 0, 8, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123465. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123473. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123513. 0,
  123514. };
  123515. static float _vq_quantthresh__44c3_s_p1_0[] = {
  123516. -0.5, 0.5,
  123517. };
  123518. static long _vq_quantmap__44c3_s_p1_0[] = {
  123519. 1, 0, 2,
  123520. };
  123521. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  123522. _vq_quantthresh__44c3_s_p1_0,
  123523. _vq_quantmap__44c3_s_p1_0,
  123524. 3,
  123525. 3
  123526. };
  123527. static static_codebook _44c3_s_p1_0 = {
  123528. 8, 6561,
  123529. _vq_lengthlist__44c3_s_p1_0,
  123530. 1, -535822336, 1611661312, 2, 0,
  123531. _vq_quantlist__44c3_s_p1_0,
  123532. NULL,
  123533. &_vq_auxt__44c3_s_p1_0,
  123534. NULL,
  123535. 0
  123536. };
  123537. static long _vq_quantlist__44c3_s_p2_0[] = {
  123538. 2,
  123539. 1,
  123540. 3,
  123541. 0,
  123542. 4,
  123543. };
  123544. static long _vq_lengthlist__44c3_s_p2_0[] = {
  123545. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  123546. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  123547. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  123548. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  123549. 0, 0,10,10, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  123555. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  123556. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  123557. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  123563. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  123564. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  123571. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  123572. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  123573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123584. 0,
  123585. };
  123586. static float _vq_quantthresh__44c3_s_p2_0[] = {
  123587. -1.5, -0.5, 0.5, 1.5,
  123588. };
  123589. static long _vq_quantmap__44c3_s_p2_0[] = {
  123590. 3, 1, 0, 2, 4,
  123591. };
  123592. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  123593. _vq_quantthresh__44c3_s_p2_0,
  123594. _vq_quantmap__44c3_s_p2_0,
  123595. 5,
  123596. 5
  123597. };
  123598. static static_codebook _44c3_s_p2_0 = {
  123599. 4, 625,
  123600. _vq_lengthlist__44c3_s_p2_0,
  123601. 1, -533725184, 1611661312, 3, 0,
  123602. _vq_quantlist__44c3_s_p2_0,
  123603. NULL,
  123604. &_vq_auxt__44c3_s_p2_0,
  123605. NULL,
  123606. 0
  123607. };
  123608. static long _vq_quantlist__44c3_s_p3_0[] = {
  123609. 2,
  123610. 1,
  123611. 3,
  123612. 0,
  123613. 4,
  123614. };
  123615. static long _vq_lengthlist__44c3_s_p3_0[] = {
  123616. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  123618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123619. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123622. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123655. 0,
  123656. };
  123657. static float _vq_quantthresh__44c3_s_p3_0[] = {
  123658. -1.5, -0.5, 0.5, 1.5,
  123659. };
  123660. static long _vq_quantmap__44c3_s_p3_0[] = {
  123661. 3, 1, 0, 2, 4,
  123662. };
  123663. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  123664. _vq_quantthresh__44c3_s_p3_0,
  123665. _vq_quantmap__44c3_s_p3_0,
  123666. 5,
  123667. 5
  123668. };
  123669. static static_codebook _44c3_s_p3_0 = {
  123670. 4, 625,
  123671. _vq_lengthlist__44c3_s_p3_0,
  123672. 1, -533725184, 1611661312, 3, 0,
  123673. _vq_quantlist__44c3_s_p3_0,
  123674. NULL,
  123675. &_vq_auxt__44c3_s_p3_0,
  123676. NULL,
  123677. 0
  123678. };
  123679. static long _vq_quantlist__44c3_s_p4_0[] = {
  123680. 4,
  123681. 3,
  123682. 5,
  123683. 2,
  123684. 6,
  123685. 1,
  123686. 7,
  123687. 0,
  123688. 8,
  123689. };
  123690. static long _vq_lengthlist__44c3_s_p4_0[] = {
  123691. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  123692. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  123693. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  123694. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  123695. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123696. 0,
  123697. };
  123698. static float _vq_quantthresh__44c3_s_p4_0[] = {
  123699. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123700. };
  123701. static long _vq_quantmap__44c3_s_p4_0[] = {
  123702. 7, 5, 3, 1, 0, 2, 4, 6,
  123703. 8,
  123704. };
  123705. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  123706. _vq_quantthresh__44c3_s_p4_0,
  123707. _vq_quantmap__44c3_s_p4_0,
  123708. 9,
  123709. 9
  123710. };
  123711. static static_codebook _44c3_s_p4_0 = {
  123712. 2, 81,
  123713. _vq_lengthlist__44c3_s_p4_0,
  123714. 1, -531628032, 1611661312, 4, 0,
  123715. _vq_quantlist__44c3_s_p4_0,
  123716. NULL,
  123717. &_vq_auxt__44c3_s_p4_0,
  123718. NULL,
  123719. 0
  123720. };
  123721. static long _vq_quantlist__44c3_s_p5_0[] = {
  123722. 4,
  123723. 3,
  123724. 5,
  123725. 2,
  123726. 6,
  123727. 1,
  123728. 7,
  123729. 0,
  123730. 8,
  123731. };
  123732. static long _vq_lengthlist__44c3_s_p5_0[] = {
  123733. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  123734. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  123735. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  123736. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  123737. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  123738. 11,
  123739. };
  123740. static float _vq_quantthresh__44c3_s_p5_0[] = {
  123741. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123742. };
  123743. static long _vq_quantmap__44c3_s_p5_0[] = {
  123744. 7, 5, 3, 1, 0, 2, 4, 6,
  123745. 8,
  123746. };
  123747. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  123748. _vq_quantthresh__44c3_s_p5_0,
  123749. _vq_quantmap__44c3_s_p5_0,
  123750. 9,
  123751. 9
  123752. };
  123753. static static_codebook _44c3_s_p5_0 = {
  123754. 2, 81,
  123755. _vq_lengthlist__44c3_s_p5_0,
  123756. 1, -531628032, 1611661312, 4, 0,
  123757. _vq_quantlist__44c3_s_p5_0,
  123758. NULL,
  123759. &_vq_auxt__44c3_s_p5_0,
  123760. NULL,
  123761. 0
  123762. };
  123763. static long _vq_quantlist__44c3_s_p6_0[] = {
  123764. 8,
  123765. 7,
  123766. 9,
  123767. 6,
  123768. 10,
  123769. 5,
  123770. 11,
  123771. 4,
  123772. 12,
  123773. 3,
  123774. 13,
  123775. 2,
  123776. 14,
  123777. 1,
  123778. 15,
  123779. 0,
  123780. 16,
  123781. };
  123782. static long _vq_lengthlist__44c3_s_p6_0[] = {
  123783. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123784. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  123785. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  123786. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123787. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123788. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  123789. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  123790. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  123791. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  123792. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  123793. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  123794. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  123795. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  123796. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  123797. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  123798. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  123799. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  123801. 13,
  123802. };
  123803. static float _vq_quantthresh__44c3_s_p6_0[] = {
  123804. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123805. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123806. };
  123807. static long _vq_quantmap__44c3_s_p6_0[] = {
  123808. 15, 13, 11, 9, 7, 5, 3, 1,
  123809. 0, 2, 4, 6, 8, 10, 12, 14,
  123810. 16,
  123811. };
  123812. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  123813. _vq_quantthresh__44c3_s_p6_0,
  123814. _vq_quantmap__44c3_s_p6_0,
  123815. 17,
  123816. 17
  123817. };
  123818. static static_codebook _44c3_s_p6_0 = {
  123819. 2, 289,
  123820. _vq_lengthlist__44c3_s_p6_0,
  123821. 1, -529530880, 1611661312, 5, 0,
  123822. _vq_quantlist__44c3_s_p6_0,
  123823. NULL,
  123824. &_vq_auxt__44c3_s_p6_0,
  123825. NULL,
  123826. 0
  123827. };
  123828. static long _vq_quantlist__44c3_s_p7_0[] = {
  123829. 1,
  123830. 0,
  123831. 2,
  123832. };
  123833. static long _vq_lengthlist__44c3_s_p7_0[] = {
  123834. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  123835. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  123836. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  123837. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  123838. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  123839. 10,
  123840. };
  123841. static float _vq_quantthresh__44c3_s_p7_0[] = {
  123842. -5.5, 5.5,
  123843. };
  123844. static long _vq_quantmap__44c3_s_p7_0[] = {
  123845. 1, 0, 2,
  123846. };
  123847. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  123848. _vq_quantthresh__44c3_s_p7_0,
  123849. _vq_quantmap__44c3_s_p7_0,
  123850. 3,
  123851. 3
  123852. };
  123853. static static_codebook _44c3_s_p7_0 = {
  123854. 4, 81,
  123855. _vq_lengthlist__44c3_s_p7_0,
  123856. 1, -529137664, 1618345984, 2, 0,
  123857. _vq_quantlist__44c3_s_p7_0,
  123858. NULL,
  123859. &_vq_auxt__44c3_s_p7_0,
  123860. NULL,
  123861. 0
  123862. };
  123863. static long _vq_quantlist__44c3_s_p7_1[] = {
  123864. 5,
  123865. 4,
  123866. 6,
  123867. 3,
  123868. 7,
  123869. 2,
  123870. 8,
  123871. 1,
  123872. 9,
  123873. 0,
  123874. 10,
  123875. };
  123876. static long _vq_lengthlist__44c3_s_p7_1[] = {
  123877. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  123878. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  123879. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  123880. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  123881. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  123882. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  123883. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  123884. 10,10,10, 8, 8, 8, 8, 8, 8,
  123885. };
  123886. static float _vq_quantthresh__44c3_s_p7_1[] = {
  123887. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123888. 3.5, 4.5,
  123889. };
  123890. static long _vq_quantmap__44c3_s_p7_1[] = {
  123891. 9, 7, 5, 3, 1, 0, 2, 4,
  123892. 6, 8, 10,
  123893. };
  123894. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  123895. _vq_quantthresh__44c3_s_p7_1,
  123896. _vq_quantmap__44c3_s_p7_1,
  123897. 11,
  123898. 11
  123899. };
  123900. static static_codebook _44c3_s_p7_1 = {
  123901. 2, 121,
  123902. _vq_lengthlist__44c3_s_p7_1,
  123903. 1, -531365888, 1611661312, 4, 0,
  123904. _vq_quantlist__44c3_s_p7_1,
  123905. NULL,
  123906. &_vq_auxt__44c3_s_p7_1,
  123907. NULL,
  123908. 0
  123909. };
  123910. static long _vq_quantlist__44c3_s_p8_0[] = {
  123911. 6,
  123912. 5,
  123913. 7,
  123914. 4,
  123915. 8,
  123916. 3,
  123917. 9,
  123918. 2,
  123919. 10,
  123920. 1,
  123921. 11,
  123922. 0,
  123923. 12,
  123924. };
  123925. static long _vq_lengthlist__44c3_s_p8_0[] = {
  123926. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  123927. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  123928. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  123929. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  123930. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  123931. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  123932. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  123933. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  123934. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  123935. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  123936. 0,13,13,12,12,13,12,14,13,
  123937. };
  123938. static float _vq_quantthresh__44c3_s_p8_0[] = {
  123939. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123940. 12.5, 17.5, 22.5, 27.5,
  123941. };
  123942. static long _vq_quantmap__44c3_s_p8_0[] = {
  123943. 11, 9, 7, 5, 3, 1, 0, 2,
  123944. 4, 6, 8, 10, 12,
  123945. };
  123946. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  123947. _vq_quantthresh__44c3_s_p8_0,
  123948. _vq_quantmap__44c3_s_p8_0,
  123949. 13,
  123950. 13
  123951. };
  123952. static static_codebook _44c3_s_p8_0 = {
  123953. 2, 169,
  123954. _vq_lengthlist__44c3_s_p8_0,
  123955. 1, -526516224, 1616117760, 4, 0,
  123956. _vq_quantlist__44c3_s_p8_0,
  123957. NULL,
  123958. &_vq_auxt__44c3_s_p8_0,
  123959. NULL,
  123960. 0
  123961. };
  123962. static long _vq_quantlist__44c3_s_p8_1[] = {
  123963. 2,
  123964. 1,
  123965. 3,
  123966. 0,
  123967. 4,
  123968. };
  123969. static long _vq_lengthlist__44c3_s_p8_1[] = {
  123970. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  123971. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  123972. };
  123973. static float _vq_quantthresh__44c3_s_p8_1[] = {
  123974. -1.5, -0.5, 0.5, 1.5,
  123975. };
  123976. static long _vq_quantmap__44c3_s_p8_1[] = {
  123977. 3, 1, 0, 2, 4,
  123978. };
  123979. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  123980. _vq_quantthresh__44c3_s_p8_1,
  123981. _vq_quantmap__44c3_s_p8_1,
  123982. 5,
  123983. 5
  123984. };
  123985. static static_codebook _44c3_s_p8_1 = {
  123986. 2, 25,
  123987. _vq_lengthlist__44c3_s_p8_1,
  123988. 1, -533725184, 1611661312, 3, 0,
  123989. _vq_quantlist__44c3_s_p8_1,
  123990. NULL,
  123991. &_vq_auxt__44c3_s_p8_1,
  123992. NULL,
  123993. 0
  123994. };
  123995. static long _vq_quantlist__44c3_s_p9_0[] = {
  123996. 6,
  123997. 5,
  123998. 7,
  123999. 4,
  124000. 8,
  124001. 3,
  124002. 9,
  124003. 2,
  124004. 10,
  124005. 1,
  124006. 11,
  124007. 0,
  124008. 12,
  124009. };
  124010. static long _vq_lengthlist__44c3_s_p9_0[] = {
  124011. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  124012. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  124013. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124014. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  124015. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124016. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124017. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124018. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124019. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  124020. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124021. 11,11,11,11,11,11,11,11,11,
  124022. };
  124023. static float _vq_quantthresh__44c3_s_p9_0[] = {
  124024. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  124025. 637.5, 892.5, 1147.5, 1402.5,
  124026. };
  124027. static long _vq_quantmap__44c3_s_p9_0[] = {
  124028. 11, 9, 7, 5, 3, 1, 0, 2,
  124029. 4, 6, 8, 10, 12,
  124030. };
  124031. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  124032. _vq_quantthresh__44c3_s_p9_0,
  124033. _vq_quantmap__44c3_s_p9_0,
  124034. 13,
  124035. 13
  124036. };
  124037. static static_codebook _44c3_s_p9_0 = {
  124038. 2, 169,
  124039. _vq_lengthlist__44c3_s_p9_0,
  124040. 1, -514332672, 1627381760, 4, 0,
  124041. _vq_quantlist__44c3_s_p9_0,
  124042. NULL,
  124043. &_vq_auxt__44c3_s_p9_0,
  124044. NULL,
  124045. 0
  124046. };
  124047. static long _vq_quantlist__44c3_s_p9_1[] = {
  124048. 7,
  124049. 6,
  124050. 8,
  124051. 5,
  124052. 9,
  124053. 4,
  124054. 10,
  124055. 3,
  124056. 11,
  124057. 2,
  124058. 12,
  124059. 1,
  124060. 13,
  124061. 0,
  124062. 14,
  124063. };
  124064. static long _vq_lengthlist__44c3_s_p9_1[] = {
  124065. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  124066. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  124067. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  124068. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  124069. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  124070. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  124071. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  124072. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  124073. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  124074. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  124075. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  124076. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  124077. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  124078. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  124079. 15,
  124080. };
  124081. static float _vq_quantthresh__44c3_s_p9_1[] = {
  124082. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  124083. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  124084. };
  124085. static long _vq_quantmap__44c3_s_p9_1[] = {
  124086. 13, 11, 9, 7, 5, 3, 1, 0,
  124087. 2, 4, 6, 8, 10, 12, 14,
  124088. };
  124089. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  124090. _vq_quantthresh__44c3_s_p9_1,
  124091. _vq_quantmap__44c3_s_p9_1,
  124092. 15,
  124093. 15
  124094. };
  124095. static static_codebook _44c3_s_p9_1 = {
  124096. 2, 225,
  124097. _vq_lengthlist__44c3_s_p9_1,
  124098. 1, -522338304, 1620115456, 4, 0,
  124099. _vq_quantlist__44c3_s_p9_1,
  124100. NULL,
  124101. &_vq_auxt__44c3_s_p9_1,
  124102. NULL,
  124103. 0
  124104. };
  124105. static long _vq_quantlist__44c3_s_p9_2[] = {
  124106. 8,
  124107. 7,
  124108. 9,
  124109. 6,
  124110. 10,
  124111. 5,
  124112. 11,
  124113. 4,
  124114. 12,
  124115. 3,
  124116. 13,
  124117. 2,
  124118. 14,
  124119. 1,
  124120. 15,
  124121. 0,
  124122. 16,
  124123. };
  124124. static long _vq_lengthlist__44c3_s_p9_2[] = {
  124125. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  124126. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  124127. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  124128. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  124129. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  124130. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  124131. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  124132. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  124133. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  124134. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  124135. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  124136. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  124137. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  124138. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  124139. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  124140. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  124141. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  124142. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  124143. 10,
  124144. };
  124145. static float _vq_quantthresh__44c3_s_p9_2[] = {
  124146. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124147. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124148. };
  124149. static long _vq_quantmap__44c3_s_p9_2[] = {
  124150. 15, 13, 11, 9, 7, 5, 3, 1,
  124151. 0, 2, 4, 6, 8, 10, 12, 14,
  124152. 16,
  124153. };
  124154. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  124155. _vq_quantthresh__44c3_s_p9_2,
  124156. _vq_quantmap__44c3_s_p9_2,
  124157. 17,
  124158. 17
  124159. };
  124160. static static_codebook _44c3_s_p9_2 = {
  124161. 2, 289,
  124162. _vq_lengthlist__44c3_s_p9_2,
  124163. 1, -529530880, 1611661312, 5, 0,
  124164. _vq_quantlist__44c3_s_p9_2,
  124165. NULL,
  124166. &_vq_auxt__44c3_s_p9_2,
  124167. NULL,
  124168. 0
  124169. };
  124170. static long _huff_lengthlist__44c3_s_short[] = {
  124171. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  124172. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  124173. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  124174. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  124175. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  124176. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  124177. 6, 8, 9,11,
  124178. };
  124179. static static_codebook _huff_book__44c3_s_short = {
  124180. 2, 100,
  124181. _huff_lengthlist__44c3_s_short,
  124182. 0, 0, 0, 0, 0,
  124183. NULL,
  124184. NULL,
  124185. NULL,
  124186. NULL,
  124187. 0
  124188. };
  124189. static long _huff_lengthlist__44c4_s_long[] = {
  124190. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  124191. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  124192. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  124193. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  124194. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  124195. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  124196. 9, 8, 7, 7,
  124197. };
  124198. static static_codebook _huff_book__44c4_s_long = {
  124199. 2, 100,
  124200. _huff_lengthlist__44c4_s_long,
  124201. 0, 0, 0, 0, 0,
  124202. NULL,
  124203. NULL,
  124204. NULL,
  124205. NULL,
  124206. 0
  124207. };
  124208. static long _vq_quantlist__44c4_s_p1_0[] = {
  124209. 1,
  124210. 0,
  124211. 2,
  124212. };
  124213. static long _vq_lengthlist__44c4_s_p1_0[] = {
  124214. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  124215. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124220. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124222. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  124225. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124227. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  124260. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  124265. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  124270. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124306. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124311. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124316. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124576. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124584. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124624. 0,
  124625. };
  124626. static float _vq_quantthresh__44c4_s_p1_0[] = {
  124627. -0.5, 0.5,
  124628. };
  124629. static long _vq_quantmap__44c4_s_p1_0[] = {
  124630. 1, 0, 2,
  124631. };
  124632. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  124633. _vq_quantthresh__44c4_s_p1_0,
  124634. _vq_quantmap__44c4_s_p1_0,
  124635. 3,
  124636. 3
  124637. };
  124638. static static_codebook _44c4_s_p1_0 = {
  124639. 8, 6561,
  124640. _vq_lengthlist__44c4_s_p1_0,
  124641. 1, -535822336, 1611661312, 2, 0,
  124642. _vq_quantlist__44c4_s_p1_0,
  124643. NULL,
  124644. &_vq_auxt__44c4_s_p1_0,
  124645. NULL,
  124646. 0
  124647. };
  124648. static long _vq_quantlist__44c4_s_p2_0[] = {
  124649. 2,
  124650. 1,
  124651. 3,
  124652. 0,
  124653. 4,
  124654. };
  124655. static long _vq_lengthlist__44c4_s_p2_0[] = {
  124656. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  124657. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  124658. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  124659. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  124660. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  124666. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  124667. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  124668. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  124674. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  124675. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  124682. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  124683. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  124684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124695. 0,
  124696. };
  124697. static float _vq_quantthresh__44c4_s_p2_0[] = {
  124698. -1.5, -0.5, 0.5, 1.5,
  124699. };
  124700. static long _vq_quantmap__44c4_s_p2_0[] = {
  124701. 3, 1, 0, 2, 4,
  124702. };
  124703. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  124704. _vq_quantthresh__44c4_s_p2_0,
  124705. _vq_quantmap__44c4_s_p2_0,
  124706. 5,
  124707. 5
  124708. };
  124709. static static_codebook _44c4_s_p2_0 = {
  124710. 4, 625,
  124711. _vq_lengthlist__44c4_s_p2_0,
  124712. 1, -533725184, 1611661312, 3, 0,
  124713. _vq_quantlist__44c4_s_p2_0,
  124714. NULL,
  124715. &_vq_auxt__44c4_s_p2_0,
  124716. NULL,
  124717. 0
  124718. };
  124719. static long _vq_quantlist__44c4_s_p3_0[] = {
  124720. 2,
  124721. 1,
  124722. 3,
  124723. 0,
  124724. 4,
  124725. };
  124726. static long _vq_lengthlist__44c4_s_p3_0[] = {
  124727. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  124729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124730. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  124732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124733. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124766. 0,
  124767. };
  124768. static float _vq_quantthresh__44c4_s_p3_0[] = {
  124769. -1.5, -0.5, 0.5, 1.5,
  124770. };
  124771. static long _vq_quantmap__44c4_s_p3_0[] = {
  124772. 3, 1, 0, 2, 4,
  124773. };
  124774. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  124775. _vq_quantthresh__44c4_s_p3_0,
  124776. _vq_quantmap__44c4_s_p3_0,
  124777. 5,
  124778. 5
  124779. };
  124780. static static_codebook _44c4_s_p3_0 = {
  124781. 4, 625,
  124782. _vq_lengthlist__44c4_s_p3_0,
  124783. 1, -533725184, 1611661312, 3, 0,
  124784. _vq_quantlist__44c4_s_p3_0,
  124785. NULL,
  124786. &_vq_auxt__44c4_s_p3_0,
  124787. NULL,
  124788. 0
  124789. };
  124790. static long _vq_quantlist__44c4_s_p4_0[] = {
  124791. 4,
  124792. 3,
  124793. 5,
  124794. 2,
  124795. 6,
  124796. 1,
  124797. 7,
  124798. 0,
  124799. 8,
  124800. };
  124801. static long _vq_lengthlist__44c4_s_p4_0[] = {
  124802. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  124803. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  124804. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  124805. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  124806. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124807. 0,
  124808. };
  124809. static float _vq_quantthresh__44c4_s_p4_0[] = {
  124810. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124811. };
  124812. static long _vq_quantmap__44c4_s_p4_0[] = {
  124813. 7, 5, 3, 1, 0, 2, 4, 6,
  124814. 8,
  124815. };
  124816. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  124817. _vq_quantthresh__44c4_s_p4_0,
  124818. _vq_quantmap__44c4_s_p4_0,
  124819. 9,
  124820. 9
  124821. };
  124822. static static_codebook _44c4_s_p4_0 = {
  124823. 2, 81,
  124824. _vq_lengthlist__44c4_s_p4_0,
  124825. 1, -531628032, 1611661312, 4, 0,
  124826. _vq_quantlist__44c4_s_p4_0,
  124827. NULL,
  124828. &_vq_auxt__44c4_s_p4_0,
  124829. NULL,
  124830. 0
  124831. };
  124832. static long _vq_quantlist__44c4_s_p5_0[] = {
  124833. 4,
  124834. 3,
  124835. 5,
  124836. 2,
  124837. 6,
  124838. 1,
  124839. 7,
  124840. 0,
  124841. 8,
  124842. };
  124843. static long _vq_lengthlist__44c4_s_p5_0[] = {
  124844. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  124845. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  124846. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  124847. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  124848. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  124849. 10,
  124850. };
  124851. static float _vq_quantthresh__44c4_s_p5_0[] = {
  124852. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124853. };
  124854. static long _vq_quantmap__44c4_s_p5_0[] = {
  124855. 7, 5, 3, 1, 0, 2, 4, 6,
  124856. 8,
  124857. };
  124858. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  124859. _vq_quantthresh__44c4_s_p5_0,
  124860. _vq_quantmap__44c4_s_p5_0,
  124861. 9,
  124862. 9
  124863. };
  124864. static static_codebook _44c4_s_p5_0 = {
  124865. 2, 81,
  124866. _vq_lengthlist__44c4_s_p5_0,
  124867. 1, -531628032, 1611661312, 4, 0,
  124868. _vq_quantlist__44c4_s_p5_0,
  124869. NULL,
  124870. &_vq_auxt__44c4_s_p5_0,
  124871. NULL,
  124872. 0
  124873. };
  124874. static long _vq_quantlist__44c4_s_p6_0[] = {
  124875. 8,
  124876. 7,
  124877. 9,
  124878. 6,
  124879. 10,
  124880. 5,
  124881. 11,
  124882. 4,
  124883. 12,
  124884. 3,
  124885. 13,
  124886. 2,
  124887. 14,
  124888. 1,
  124889. 15,
  124890. 0,
  124891. 16,
  124892. };
  124893. static long _vq_lengthlist__44c4_s_p6_0[] = {
  124894. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  124895. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124896. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  124897. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  124898. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  124899. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124900. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  124901. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  124902. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  124903. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  124904. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  124905. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  124906. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  124907. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  124908. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  124909. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  124910. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  124911. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  124912. 13,
  124913. };
  124914. static float _vq_quantthresh__44c4_s_p6_0[] = {
  124915. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124916. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124917. };
  124918. static long _vq_quantmap__44c4_s_p6_0[] = {
  124919. 15, 13, 11, 9, 7, 5, 3, 1,
  124920. 0, 2, 4, 6, 8, 10, 12, 14,
  124921. 16,
  124922. };
  124923. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  124924. _vq_quantthresh__44c4_s_p6_0,
  124925. _vq_quantmap__44c4_s_p6_0,
  124926. 17,
  124927. 17
  124928. };
  124929. static static_codebook _44c4_s_p6_0 = {
  124930. 2, 289,
  124931. _vq_lengthlist__44c4_s_p6_0,
  124932. 1, -529530880, 1611661312, 5, 0,
  124933. _vq_quantlist__44c4_s_p6_0,
  124934. NULL,
  124935. &_vq_auxt__44c4_s_p6_0,
  124936. NULL,
  124937. 0
  124938. };
  124939. static long _vq_quantlist__44c4_s_p7_0[] = {
  124940. 1,
  124941. 0,
  124942. 2,
  124943. };
  124944. static long _vq_lengthlist__44c4_s_p7_0[] = {
  124945. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  124946. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  124947. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  124948. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  124949. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  124950. 10,
  124951. };
  124952. static float _vq_quantthresh__44c4_s_p7_0[] = {
  124953. -5.5, 5.5,
  124954. };
  124955. static long _vq_quantmap__44c4_s_p7_0[] = {
  124956. 1, 0, 2,
  124957. };
  124958. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  124959. _vq_quantthresh__44c4_s_p7_0,
  124960. _vq_quantmap__44c4_s_p7_0,
  124961. 3,
  124962. 3
  124963. };
  124964. static static_codebook _44c4_s_p7_0 = {
  124965. 4, 81,
  124966. _vq_lengthlist__44c4_s_p7_0,
  124967. 1, -529137664, 1618345984, 2, 0,
  124968. _vq_quantlist__44c4_s_p7_0,
  124969. NULL,
  124970. &_vq_auxt__44c4_s_p7_0,
  124971. NULL,
  124972. 0
  124973. };
  124974. static long _vq_quantlist__44c4_s_p7_1[] = {
  124975. 5,
  124976. 4,
  124977. 6,
  124978. 3,
  124979. 7,
  124980. 2,
  124981. 8,
  124982. 1,
  124983. 9,
  124984. 0,
  124985. 10,
  124986. };
  124987. static long _vq_lengthlist__44c4_s_p7_1[] = {
  124988. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  124989. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  124990. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  124991. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  124992. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124993. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  124994. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  124995. 10,10,10, 8, 8, 8, 8, 9, 9,
  124996. };
  124997. static float _vq_quantthresh__44c4_s_p7_1[] = {
  124998. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124999. 3.5, 4.5,
  125000. };
  125001. static long _vq_quantmap__44c4_s_p7_1[] = {
  125002. 9, 7, 5, 3, 1, 0, 2, 4,
  125003. 6, 8, 10,
  125004. };
  125005. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  125006. _vq_quantthresh__44c4_s_p7_1,
  125007. _vq_quantmap__44c4_s_p7_1,
  125008. 11,
  125009. 11
  125010. };
  125011. static static_codebook _44c4_s_p7_1 = {
  125012. 2, 121,
  125013. _vq_lengthlist__44c4_s_p7_1,
  125014. 1, -531365888, 1611661312, 4, 0,
  125015. _vq_quantlist__44c4_s_p7_1,
  125016. NULL,
  125017. &_vq_auxt__44c4_s_p7_1,
  125018. NULL,
  125019. 0
  125020. };
  125021. static long _vq_quantlist__44c4_s_p8_0[] = {
  125022. 6,
  125023. 5,
  125024. 7,
  125025. 4,
  125026. 8,
  125027. 3,
  125028. 9,
  125029. 2,
  125030. 10,
  125031. 1,
  125032. 11,
  125033. 0,
  125034. 12,
  125035. };
  125036. static long _vq_lengthlist__44c4_s_p8_0[] = {
  125037. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  125038. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  125039. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125040. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  125041. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  125042. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  125043. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  125044. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  125045. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  125046. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  125047. 0,13,12,12,12,12,12,13,13,
  125048. };
  125049. static float _vq_quantthresh__44c4_s_p8_0[] = {
  125050. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125051. 12.5, 17.5, 22.5, 27.5,
  125052. };
  125053. static long _vq_quantmap__44c4_s_p8_0[] = {
  125054. 11, 9, 7, 5, 3, 1, 0, 2,
  125055. 4, 6, 8, 10, 12,
  125056. };
  125057. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  125058. _vq_quantthresh__44c4_s_p8_0,
  125059. _vq_quantmap__44c4_s_p8_0,
  125060. 13,
  125061. 13
  125062. };
  125063. static static_codebook _44c4_s_p8_0 = {
  125064. 2, 169,
  125065. _vq_lengthlist__44c4_s_p8_0,
  125066. 1, -526516224, 1616117760, 4, 0,
  125067. _vq_quantlist__44c4_s_p8_0,
  125068. NULL,
  125069. &_vq_auxt__44c4_s_p8_0,
  125070. NULL,
  125071. 0
  125072. };
  125073. static long _vq_quantlist__44c4_s_p8_1[] = {
  125074. 2,
  125075. 1,
  125076. 3,
  125077. 0,
  125078. 4,
  125079. };
  125080. static long _vq_lengthlist__44c4_s_p8_1[] = {
  125081. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  125082. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  125083. };
  125084. static float _vq_quantthresh__44c4_s_p8_1[] = {
  125085. -1.5, -0.5, 0.5, 1.5,
  125086. };
  125087. static long _vq_quantmap__44c4_s_p8_1[] = {
  125088. 3, 1, 0, 2, 4,
  125089. };
  125090. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  125091. _vq_quantthresh__44c4_s_p8_1,
  125092. _vq_quantmap__44c4_s_p8_1,
  125093. 5,
  125094. 5
  125095. };
  125096. static static_codebook _44c4_s_p8_1 = {
  125097. 2, 25,
  125098. _vq_lengthlist__44c4_s_p8_1,
  125099. 1, -533725184, 1611661312, 3, 0,
  125100. _vq_quantlist__44c4_s_p8_1,
  125101. NULL,
  125102. &_vq_auxt__44c4_s_p8_1,
  125103. NULL,
  125104. 0
  125105. };
  125106. static long _vq_quantlist__44c4_s_p9_0[] = {
  125107. 6,
  125108. 5,
  125109. 7,
  125110. 4,
  125111. 8,
  125112. 3,
  125113. 9,
  125114. 2,
  125115. 10,
  125116. 1,
  125117. 11,
  125118. 0,
  125119. 12,
  125120. };
  125121. static long _vq_lengthlist__44c4_s_p9_0[] = {
  125122. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  125123. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  125124. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125125. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125126. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125127. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125128. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125129. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125130. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125131. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125132. 12,12,12,12,12,12,12,12,12,
  125133. };
  125134. static float _vq_quantthresh__44c4_s_p9_0[] = {
  125135. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  125136. 787.5, 1102.5, 1417.5, 1732.5,
  125137. };
  125138. static long _vq_quantmap__44c4_s_p9_0[] = {
  125139. 11, 9, 7, 5, 3, 1, 0, 2,
  125140. 4, 6, 8, 10, 12,
  125141. };
  125142. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  125143. _vq_quantthresh__44c4_s_p9_0,
  125144. _vq_quantmap__44c4_s_p9_0,
  125145. 13,
  125146. 13
  125147. };
  125148. static static_codebook _44c4_s_p9_0 = {
  125149. 2, 169,
  125150. _vq_lengthlist__44c4_s_p9_0,
  125151. 1, -513964032, 1628680192, 4, 0,
  125152. _vq_quantlist__44c4_s_p9_0,
  125153. NULL,
  125154. &_vq_auxt__44c4_s_p9_0,
  125155. NULL,
  125156. 0
  125157. };
  125158. static long _vq_quantlist__44c4_s_p9_1[] = {
  125159. 7,
  125160. 6,
  125161. 8,
  125162. 5,
  125163. 9,
  125164. 4,
  125165. 10,
  125166. 3,
  125167. 11,
  125168. 2,
  125169. 12,
  125170. 1,
  125171. 13,
  125172. 0,
  125173. 14,
  125174. };
  125175. static long _vq_lengthlist__44c4_s_p9_1[] = {
  125176. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  125177. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  125178. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  125179. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  125180. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  125181. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  125182. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  125183. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  125184. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  125185. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  125186. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  125187. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  125188. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  125189. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  125190. 15,
  125191. };
  125192. static float _vq_quantthresh__44c4_s_p9_1[] = {
  125193. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125194. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125195. };
  125196. static long _vq_quantmap__44c4_s_p9_1[] = {
  125197. 13, 11, 9, 7, 5, 3, 1, 0,
  125198. 2, 4, 6, 8, 10, 12, 14,
  125199. };
  125200. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  125201. _vq_quantthresh__44c4_s_p9_1,
  125202. _vq_quantmap__44c4_s_p9_1,
  125203. 15,
  125204. 15
  125205. };
  125206. static static_codebook _44c4_s_p9_1 = {
  125207. 2, 225,
  125208. _vq_lengthlist__44c4_s_p9_1,
  125209. 1, -520986624, 1620377600, 4, 0,
  125210. _vq_quantlist__44c4_s_p9_1,
  125211. NULL,
  125212. &_vq_auxt__44c4_s_p9_1,
  125213. NULL,
  125214. 0
  125215. };
  125216. static long _vq_quantlist__44c4_s_p9_2[] = {
  125217. 10,
  125218. 9,
  125219. 11,
  125220. 8,
  125221. 12,
  125222. 7,
  125223. 13,
  125224. 6,
  125225. 14,
  125226. 5,
  125227. 15,
  125228. 4,
  125229. 16,
  125230. 3,
  125231. 17,
  125232. 2,
  125233. 18,
  125234. 1,
  125235. 19,
  125236. 0,
  125237. 20,
  125238. };
  125239. static long _vq_lengthlist__44c4_s_p9_2[] = {
  125240. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  125241. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  125242. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  125243. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  125244. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  125245. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  125246. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  125247. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125248. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  125249. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  125250. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  125251. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  125252. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  125253. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  125254. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  125255. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  125256. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  125257. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  125258. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  125259. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  125260. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125261. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  125262. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  125263. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  125264. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  125265. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  125266. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  125267. 10,10,10,10,10,10,10,10,10,
  125268. };
  125269. static float _vq_quantthresh__44c4_s_p9_2[] = {
  125270. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125271. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125272. 6.5, 7.5, 8.5, 9.5,
  125273. };
  125274. static long _vq_quantmap__44c4_s_p9_2[] = {
  125275. 19, 17, 15, 13, 11, 9, 7, 5,
  125276. 3, 1, 0, 2, 4, 6, 8, 10,
  125277. 12, 14, 16, 18, 20,
  125278. };
  125279. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  125280. _vq_quantthresh__44c4_s_p9_2,
  125281. _vq_quantmap__44c4_s_p9_2,
  125282. 21,
  125283. 21
  125284. };
  125285. static static_codebook _44c4_s_p9_2 = {
  125286. 2, 441,
  125287. _vq_lengthlist__44c4_s_p9_2,
  125288. 1, -529268736, 1611661312, 5, 0,
  125289. _vq_quantlist__44c4_s_p9_2,
  125290. NULL,
  125291. &_vq_auxt__44c4_s_p9_2,
  125292. NULL,
  125293. 0
  125294. };
  125295. static long _huff_lengthlist__44c4_s_short[] = {
  125296. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  125297. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  125298. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  125299. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  125300. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  125301. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  125302. 7, 9,12,17,
  125303. };
  125304. static static_codebook _huff_book__44c4_s_short = {
  125305. 2, 100,
  125306. _huff_lengthlist__44c4_s_short,
  125307. 0, 0, 0, 0, 0,
  125308. NULL,
  125309. NULL,
  125310. NULL,
  125311. NULL,
  125312. 0
  125313. };
  125314. static long _huff_lengthlist__44c5_s_long[] = {
  125315. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  125316. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  125317. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  125318. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  125319. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  125320. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  125321. 9, 8, 7, 7,
  125322. };
  125323. static static_codebook _huff_book__44c5_s_long = {
  125324. 2, 100,
  125325. _huff_lengthlist__44c5_s_long,
  125326. 0, 0, 0, 0, 0,
  125327. NULL,
  125328. NULL,
  125329. NULL,
  125330. NULL,
  125331. 0
  125332. };
  125333. static long _vq_quantlist__44c5_s_p1_0[] = {
  125334. 1,
  125335. 0,
  125336. 2,
  125337. };
  125338. static long _vq_lengthlist__44c5_s_p1_0[] = {
  125339. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  125340. 0, 0, 4, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  125345. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125347. 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  125350. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125352. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0,
  125385. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  125390. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  125395. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125431. 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  125436. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  125441. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125701. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125709. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125749. 0,
  125750. };
  125751. static float _vq_quantthresh__44c5_s_p1_0[] = {
  125752. -0.5, 0.5,
  125753. };
  125754. static long _vq_quantmap__44c5_s_p1_0[] = {
  125755. 1, 0, 2,
  125756. };
  125757. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  125758. _vq_quantthresh__44c5_s_p1_0,
  125759. _vq_quantmap__44c5_s_p1_0,
  125760. 3,
  125761. 3
  125762. };
  125763. static static_codebook _44c5_s_p1_0 = {
  125764. 8, 6561,
  125765. _vq_lengthlist__44c5_s_p1_0,
  125766. 1, -535822336, 1611661312, 2, 0,
  125767. _vq_quantlist__44c5_s_p1_0,
  125768. NULL,
  125769. &_vq_auxt__44c5_s_p1_0,
  125770. NULL,
  125771. 0
  125772. };
  125773. static long _vq_quantlist__44c5_s_p2_0[] = {
  125774. 2,
  125775. 1,
  125776. 3,
  125777. 0,
  125778. 4,
  125779. };
  125780. static long _vq_lengthlist__44c5_s_p2_0[] = {
  125781. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  125782. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  125783. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125784. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  125785. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  125791. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  125792. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  125793. 10, 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, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  125799. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  125800. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 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. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  125807. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  125808. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  125809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0,
  125821. };
  125822. static float _vq_quantthresh__44c5_s_p2_0[] = {
  125823. -1.5, -0.5, 0.5, 1.5,
  125824. };
  125825. static long _vq_quantmap__44c5_s_p2_0[] = {
  125826. 3, 1, 0, 2, 4,
  125827. };
  125828. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  125829. _vq_quantthresh__44c5_s_p2_0,
  125830. _vq_quantmap__44c5_s_p2_0,
  125831. 5,
  125832. 5
  125833. };
  125834. static static_codebook _44c5_s_p2_0 = {
  125835. 4, 625,
  125836. _vq_lengthlist__44c5_s_p2_0,
  125837. 1, -533725184, 1611661312, 3, 0,
  125838. _vq_quantlist__44c5_s_p2_0,
  125839. NULL,
  125840. &_vq_auxt__44c5_s_p2_0,
  125841. NULL,
  125842. 0
  125843. };
  125844. static long _vq_quantlist__44c5_s_p3_0[] = {
  125845. 2,
  125846. 1,
  125847. 3,
  125848. 0,
  125849. 4,
  125850. };
  125851. static long _vq_lengthlist__44c5_s_p3_0[] = {
  125852. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  125854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125855. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  125857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0,
  125892. };
  125893. static float _vq_quantthresh__44c5_s_p3_0[] = {
  125894. -1.5, -0.5, 0.5, 1.5,
  125895. };
  125896. static long _vq_quantmap__44c5_s_p3_0[] = {
  125897. 3, 1, 0, 2, 4,
  125898. };
  125899. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  125900. _vq_quantthresh__44c5_s_p3_0,
  125901. _vq_quantmap__44c5_s_p3_0,
  125902. 5,
  125903. 5
  125904. };
  125905. static static_codebook _44c5_s_p3_0 = {
  125906. 4, 625,
  125907. _vq_lengthlist__44c5_s_p3_0,
  125908. 1, -533725184, 1611661312, 3, 0,
  125909. _vq_quantlist__44c5_s_p3_0,
  125910. NULL,
  125911. &_vq_auxt__44c5_s_p3_0,
  125912. NULL,
  125913. 0
  125914. };
  125915. static long _vq_quantlist__44c5_s_p4_0[] = {
  125916. 4,
  125917. 3,
  125918. 5,
  125919. 2,
  125920. 6,
  125921. 1,
  125922. 7,
  125923. 0,
  125924. 8,
  125925. };
  125926. static long _vq_lengthlist__44c5_s_p4_0[] = {
  125927. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  125928. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  125929. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  125930. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  125931. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0,
  125933. };
  125934. static float _vq_quantthresh__44c5_s_p4_0[] = {
  125935. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125936. };
  125937. static long _vq_quantmap__44c5_s_p4_0[] = {
  125938. 7, 5, 3, 1, 0, 2, 4, 6,
  125939. 8,
  125940. };
  125941. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  125942. _vq_quantthresh__44c5_s_p4_0,
  125943. _vq_quantmap__44c5_s_p4_0,
  125944. 9,
  125945. 9
  125946. };
  125947. static static_codebook _44c5_s_p4_0 = {
  125948. 2, 81,
  125949. _vq_lengthlist__44c5_s_p4_0,
  125950. 1, -531628032, 1611661312, 4, 0,
  125951. _vq_quantlist__44c5_s_p4_0,
  125952. NULL,
  125953. &_vq_auxt__44c5_s_p4_0,
  125954. NULL,
  125955. 0
  125956. };
  125957. static long _vq_quantlist__44c5_s_p5_0[] = {
  125958. 4,
  125959. 3,
  125960. 5,
  125961. 2,
  125962. 6,
  125963. 1,
  125964. 7,
  125965. 0,
  125966. 8,
  125967. };
  125968. static long _vq_lengthlist__44c5_s_p5_0[] = {
  125969. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  125970. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  125971. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  125972. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  125973. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125974. 10,
  125975. };
  125976. static float _vq_quantthresh__44c5_s_p5_0[] = {
  125977. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125978. };
  125979. static long _vq_quantmap__44c5_s_p5_0[] = {
  125980. 7, 5, 3, 1, 0, 2, 4, 6,
  125981. 8,
  125982. };
  125983. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  125984. _vq_quantthresh__44c5_s_p5_0,
  125985. _vq_quantmap__44c5_s_p5_0,
  125986. 9,
  125987. 9
  125988. };
  125989. static static_codebook _44c5_s_p5_0 = {
  125990. 2, 81,
  125991. _vq_lengthlist__44c5_s_p5_0,
  125992. 1, -531628032, 1611661312, 4, 0,
  125993. _vq_quantlist__44c5_s_p5_0,
  125994. NULL,
  125995. &_vq_auxt__44c5_s_p5_0,
  125996. NULL,
  125997. 0
  125998. };
  125999. static long _vq_quantlist__44c5_s_p6_0[] = {
  126000. 8,
  126001. 7,
  126002. 9,
  126003. 6,
  126004. 10,
  126005. 5,
  126006. 11,
  126007. 4,
  126008. 12,
  126009. 3,
  126010. 13,
  126011. 2,
  126012. 14,
  126013. 1,
  126014. 15,
  126015. 0,
  126016. 16,
  126017. };
  126018. static long _vq_lengthlist__44c5_s_p6_0[] = {
  126019. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  126020. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126021. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  126022. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  126023. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  126024. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  126025. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  126026. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  126027. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  126028. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  126029. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  126030. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  126031. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  126032. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  126033. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  126034. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  126035. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  126037. 13,
  126038. };
  126039. static float _vq_quantthresh__44c5_s_p6_0[] = {
  126040. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126041. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126042. };
  126043. static long _vq_quantmap__44c5_s_p6_0[] = {
  126044. 15, 13, 11, 9, 7, 5, 3, 1,
  126045. 0, 2, 4, 6, 8, 10, 12, 14,
  126046. 16,
  126047. };
  126048. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  126049. _vq_quantthresh__44c5_s_p6_0,
  126050. _vq_quantmap__44c5_s_p6_0,
  126051. 17,
  126052. 17
  126053. };
  126054. static static_codebook _44c5_s_p6_0 = {
  126055. 2, 289,
  126056. _vq_lengthlist__44c5_s_p6_0,
  126057. 1, -529530880, 1611661312, 5, 0,
  126058. _vq_quantlist__44c5_s_p6_0,
  126059. NULL,
  126060. &_vq_auxt__44c5_s_p6_0,
  126061. NULL,
  126062. 0
  126063. };
  126064. static long _vq_quantlist__44c5_s_p7_0[] = {
  126065. 1,
  126066. 0,
  126067. 2,
  126068. };
  126069. static long _vq_lengthlist__44c5_s_p7_0[] = {
  126070. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  126071. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  126072. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  126073. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  126074. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  126075. 10,
  126076. };
  126077. static float _vq_quantthresh__44c5_s_p7_0[] = {
  126078. -5.5, 5.5,
  126079. };
  126080. static long _vq_quantmap__44c5_s_p7_0[] = {
  126081. 1, 0, 2,
  126082. };
  126083. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  126084. _vq_quantthresh__44c5_s_p7_0,
  126085. _vq_quantmap__44c5_s_p7_0,
  126086. 3,
  126087. 3
  126088. };
  126089. static static_codebook _44c5_s_p7_0 = {
  126090. 4, 81,
  126091. _vq_lengthlist__44c5_s_p7_0,
  126092. 1, -529137664, 1618345984, 2, 0,
  126093. _vq_quantlist__44c5_s_p7_0,
  126094. NULL,
  126095. &_vq_auxt__44c5_s_p7_0,
  126096. NULL,
  126097. 0
  126098. };
  126099. static long _vq_quantlist__44c5_s_p7_1[] = {
  126100. 5,
  126101. 4,
  126102. 6,
  126103. 3,
  126104. 7,
  126105. 2,
  126106. 8,
  126107. 1,
  126108. 9,
  126109. 0,
  126110. 10,
  126111. };
  126112. static long _vq_lengthlist__44c5_s_p7_1[] = {
  126113. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  126114. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  126115. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  126116. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  126117. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  126118. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  126119. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  126120. 10,10,10, 8, 8, 8, 8, 8, 8,
  126121. };
  126122. static float _vq_quantthresh__44c5_s_p7_1[] = {
  126123. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126124. 3.5, 4.5,
  126125. };
  126126. static long _vq_quantmap__44c5_s_p7_1[] = {
  126127. 9, 7, 5, 3, 1, 0, 2, 4,
  126128. 6, 8, 10,
  126129. };
  126130. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  126131. _vq_quantthresh__44c5_s_p7_1,
  126132. _vq_quantmap__44c5_s_p7_1,
  126133. 11,
  126134. 11
  126135. };
  126136. static static_codebook _44c5_s_p7_1 = {
  126137. 2, 121,
  126138. _vq_lengthlist__44c5_s_p7_1,
  126139. 1, -531365888, 1611661312, 4, 0,
  126140. _vq_quantlist__44c5_s_p7_1,
  126141. NULL,
  126142. &_vq_auxt__44c5_s_p7_1,
  126143. NULL,
  126144. 0
  126145. };
  126146. static long _vq_quantlist__44c5_s_p8_0[] = {
  126147. 6,
  126148. 5,
  126149. 7,
  126150. 4,
  126151. 8,
  126152. 3,
  126153. 9,
  126154. 2,
  126155. 10,
  126156. 1,
  126157. 11,
  126158. 0,
  126159. 12,
  126160. };
  126161. static long _vq_lengthlist__44c5_s_p8_0[] = {
  126162. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  126163. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  126164. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126165. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126166. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  126167. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  126168. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  126169. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  126170. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  126171. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  126172. 0,12,12,12,12,12,12,13,13,
  126173. };
  126174. static float _vq_quantthresh__44c5_s_p8_0[] = {
  126175. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126176. 12.5, 17.5, 22.5, 27.5,
  126177. };
  126178. static long _vq_quantmap__44c5_s_p8_0[] = {
  126179. 11, 9, 7, 5, 3, 1, 0, 2,
  126180. 4, 6, 8, 10, 12,
  126181. };
  126182. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  126183. _vq_quantthresh__44c5_s_p8_0,
  126184. _vq_quantmap__44c5_s_p8_0,
  126185. 13,
  126186. 13
  126187. };
  126188. static static_codebook _44c5_s_p8_0 = {
  126189. 2, 169,
  126190. _vq_lengthlist__44c5_s_p8_0,
  126191. 1, -526516224, 1616117760, 4, 0,
  126192. _vq_quantlist__44c5_s_p8_0,
  126193. NULL,
  126194. &_vq_auxt__44c5_s_p8_0,
  126195. NULL,
  126196. 0
  126197. };
  126198. static long _vq_quantlist__44c5_s_p8_1[] = {
  126199. 2,
  126200. 1,
  126201. 3,
  126202. 0,
  126203. 4,
  126204. };
  126205. static long _vq_lengthlist__44c5_s_p8_1[] = {
  126206. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  126207. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126208. };
  126209. static float _vq_quantthresh__44c5_s_p8_1[] = {
  126210. -1.5, -0.5, 0.5, 1.5,
  126211. };
  126212. static long _vq_quantmap__44c5_s_p8_1[] = {
  126213. 3, 1, 0, 2, 4,
  126214. };
  126215. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  126216. _vq_quantthresh__44c5_s_p8_1,
  126217. _vq_quantmap__44c5_s_p8_1,
  126218. 5,
  126219. 5
  126220. };
  126221. static static_codebook _44c5_s_p8_1 = {
  126222. 2, 25,
  126223. _vq_lengthlist__44c5_s_p8_1,
  126224. 1, -533725184, 1611661312, 3, 0,
  126225. _vq_quantlist__44c5_s_p8_1,
  126226. NULL,
  126227. &_vq_auxt__44c5_s_p8_1,
  126228. NULL,
  126229. 0
  126230. };
  126231. static long _vq_quantlist__44c5_s_p9_0[] = {
  126232. 7,
  126233. 6,
  126234. 8,
  126235. 5,
  126236. 9,
  126237. 4,
  126238. 10,
  126239. 3,
  126240. 11,
  126241. 2,
  126242. 12,
  126243. 1,
  126244. 13,
  126245. 0,
  126246. 14,
  126247. };
  126248. static long _vq_lengthlist__44c5_s_p9_0[] = {
  126249. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  126250. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  126251. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126252. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126253. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126254. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126255. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126256. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126257. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126258. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126259. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126260. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126261. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  126262. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  126263. 12,
  126264. };
  126265. static float _vq_quantthresh__44c5_s_p9_0[] = {
  126266. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  126267. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  126268. };
  126269. static long _vq_quantmap__44c5_s_p9_0[] = {
  126270. 13, 11, 9, 7, 5, 3, 1, 0,
  126271. 2, 4, 6, 8, 10, 12, 14,
  126272. };
  126273. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  126274. _vq_quantthresh__44c5_s_p9_0,
  126275. _vq_quantmap__44c5_s_p9_0,
  126276. 15,
  126277. 15
  126278. };
  126279. static static_codebook _44c5_s_p9_0 = {
  126280. 2, 225,
  126281. _vq_lengthlist__44c5_s_p9_0,
  126282. 1, -512522752, 1628852224, 4, 0,
  126283. _vq_quantlist__44c5_s_p9_0,
  126284. NULL,
  126285. &_vq_auxt__44c5_s_p9_0,
  126286. NULL,
  126287. 0
  126288. };
  126289. static long _vq_quantlist__44c5_s_p9_1[] = {
  126290. 8,
  126291. 7,
  126292. 9,
  126293. 6,
  126294. 10,
  126295. 5,
  126296. 11,
  126297. 4,
  126298. 12,
  126299. 3,
  126300. 13,
  126301. 2,
  126302. 14,
  126303. 1,
  126304. 15,
  126305. 0,
  126306. 16,
  126307. };
  126308. static long _vq_lengthlist__44c5_s_p9_1[] = {
  126309. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  126310. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  126311. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  126312. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  126313. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  126314. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  126315. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  126316. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  126317. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  126318. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  126319. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  126320. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  126321. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  126322. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  126323. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  126324. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  126325. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  126326. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  126327. 15,
  126328. };
  126329. static float _vq_quantthresh__44c5_s_p9_1[] = {
  126330. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  126331. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  126332. };
  126333. static long _vq_quantmap__44c5_s_p9_1[] = {
  126334. 15, 13, 11, 9, 7, 5, 3, 1,
  126335. 0, 2, 4, 6, 8, 10, 12, 14,
  126336. 16,
  126337. };
  126338. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  126339. _vq_quantthresh__44c5_s_p9_1,
  126340. _vq_quantmap__44c5_s_p9_1,
  126341. 17,
  126342. 17
  126343. };
  126344. static static_codebook _44c5_s_p9_1 = {
  126345. 2, 289,
  126346. _vq_lengthlist__44c5_s_p9_1,
  126347. 1, -520814592, 1620377600, 5, 0,
  126348. _vq_quantlist__44c5_s_p9_1,
  126349. NULL,
  126350. &_vq_auxt__44c5_s_p9_1,
  126351. NULL,
  126352. 0
  126353. };
  126354. static long _vq_quantlist__44c5_s_p9_2[] = {
  126355. 10,
  126356. 9,
  126357. 11,
  126358. 8,
  126359. 12,
  126360. 7,
  126361. 13,
  126362. 6,
  126363. 14,
  126364. 5,
  126365. 15,
  126366. 4,
  126367. 16,
  126368. 3,
  126369. 17,
  126370. 2,
  126371. 18,
  126372. 1,
  126373. 19,
  126374. 0,
  126375. 20,
  126376. };
  126377. static long _vq_lengthlist__44c5_s_p9_2[] = {
  126378. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  126379. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  126380. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  126381. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  126382. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  126383. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  126384. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  126385. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  126386. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  126387. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126388. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  126389. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  126390. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  126391. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  126392. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  126393. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  126394. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  126395. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  126396. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  126397. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  126398. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126399. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  126400. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  126401. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  126402. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  126403. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  126404. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  126405. 10,10,10,10,10,10,10,10,10,
  126406. };
  126407. static float _vq_quantthresh__44c5_s_p9_2[] = {
  126408. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126409. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126410. 6.5, 7.5, 8.5, 9.5,
  126411. };
  126412. static long _vq_quantmap__44c5_s_p9_2[] = {
  126413. 19, 17, 15, 13, 11, 9, 7, 5,
  126414. 3, 1, 0, 2, 4, 6, 8, 10,
  126415. 12, 14, 16, 18, 20,
  126416. };
  126417. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  126418. _vq_quantthresh__44c5_s_p9_2,
  126419. _vq_quantmap__44c5_s_p9_2,
  126420. 21,
  126421. 21
  126422. };
  126423. static static_codebook _44c5_s_p9_2 = {
  126424. 2, 441,
  126425. _vq_lengthlist__44c5_s_p9_2,
  126426. 1, -529268736, 1611661312, 5, 0,
  126427. _vq_quantlist__44c5_s_p9_2,
  126428. NULL,
  126429. &_vq_auxt__44c5_s_p9_2,
  126430. NULL,
  126431. 0
  126432. };
  126433. static long _huff_lengthlist__44c5_s_short[] = {
  126434. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  126435. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  126436. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  126437. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  126438. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  126439. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  126440. 6, 8,11,16,
  126441. };
  126442. static static_codebook _huff_book__44c5_s_short = {
  126443. 2, 100,
  126444. _huff_lengthlist__44c5_s_short,
  126445. 0, 0, 0, 0, 0,
  126446. NULL,
  126447. NULL,
  126448. NULL,
  126449. NULL,
  126450. 0
  126451. };
  126452. static long _huff_lengthlist__44c6_s_long[] = {
  126453. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  126454. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  126455. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  126456. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  126457. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  126458. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  126459. 11,10,10,12,
  126460. };
  126461. static static_codebook _huff_book__44c6_s_long = {
  126462. 2, 100,
  126463. _huff_lengthlist__44c6_s_long,
  126464. 0, 0, 0, 0, 0,
  126465. NULL,
  126466. NULL,
  126467. NULL,
  126468. NULL,
  126469. 0
  126470. };
  126471. static long _vq_quantlist__44c6_s_p1_0[] = {
  126472. 1,
  126473. 0,
  126474. 2,
  126475. };
  126476. static long _vq_lengthlist__44c6_s_p1_0[] = {
  126477. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  126478. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  126479. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  126480. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  126481. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  126482. 8,
  126483. };
  126484. static float _vq_quantthresh__44c6_s_p1_0[] = {
  126485. -0.5, 0.5,
  126486. };
  126487. static long _vq_quantmap__44c6_s_p1_0[] = {
  126488. 1, 0, 2,
  126489. };
  126490. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  126491. _vq_quantthresh__44c6_s_p1_0,
  126492. _vq_quantmap__44c6_s_p1_0,
  126493. 3,
  126494. 3
  126495. };
  126496. static static_codebook _44c6_s_p1_0 = {
  126497. 4, 81,
  126498. _vq_lengthlist__44c6_s_p1_0,
  126499. 1, -535822336, 1611661312, 2, 0,
  126500. _vq_quantlist__44c6_s_p1_0,
  126501. NULL,
  126502. &_vq_auxt__44c6_s_p1_0,
  126503. NULL,
  126504. 0
  126505. };
  126506. static long _vq_quantlist__44c6_s_p2_0[] = {
  126507. 2,
  126508. 1,
  126509. 3,
  126510. 0,
  126511. 4,
  126512. };
  126513. static long _vq_lengthlist__44c6_s_p2_0[] = {
  126514. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  126515. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  126516. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  126517. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  126518. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  126519. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  126520. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  126521. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  126522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126523. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  126524. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  126525. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  126526. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  126527. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  126528. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  126529. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  126530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126531. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  126532. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  126533. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  126534. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  126535. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  126536. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  126537. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126539. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  126540. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  126541. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  126542. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  126543. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  126544. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  126545. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  126550. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  126551. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  126552. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  126553. 13,
  126554. };
  126555. static float _vq_quantthresh__44c6_s_p2_0[] = {
  126556. -1.5, -0.5, 0.5, 1.5,
  126557. };
  126558. static long _vq_quantmap__44c6_s_p2_0[] = {
  126559. 3, 1, 0, 2, 4,
  126560. };
  126561. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  126562. _vq_quantthresh__44c6_s_p2_0,
  126563. _vq_quantmap__44c6_s_p2_0,
  126564. 5,
  126565. 5
  126566. };
  126567. static static_codebook _44c6_s_p2_0 = {
  126568. 4, 625,
  126569. _vq_lengthlist__44c6_s_p2_0,
  126570. 1, -533725184, 1611661312, 3, 0,
  126571. _vq_quantlist__44c6_s_p2_0,
  126572. NULL,
  126573. &_vq_auxt__44c6_s_p2_0,
  126574. NULL,
  126575. 0
  126576. };
  126577. static long _vq_quantlist__44c6_s_p3_0[] = {
  126578. 4,
  126579. 3,
  126580. 5,
  126581. 2,
  126582. 6,
  126583. 1,
  126584. 7,
  126585. 0,
  126586. 8,
  126587. };
  126588. static long _vq_lengthlist__44c6_s_p3_0[] = {
  126589. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  126590. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  126591. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  126592. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  126593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126594. 0,
  126595. };
  126596. static float _vq_quantthresh__44c6_s_p3_0[] = {
  126597. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126598. };
  126599. static long _vq_quantmap__44c6_s_p3_0[] = {
  126600. 7, 5, 3, 1, 0, 2, 4, 6,
  126601. 8,
  126602. };
  126603. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  126604. _vq_quantthresh__44c6_s_p3_0,
  126605. _vq_quantmap__44c6_s_p3_0,
  126606. 9,
  126607. 9
  126608. };
  126609. static static_codebook _44c6_s_p3_0 = {
  126610. 2, 81,
  126611. _vq_lengthlist__44c6_s_p3_0,
  126612. 1, -531628032, 1611661312, 4, 0,
  126613. _vq_quantlist__44c6_s_p3_0,
  126614. NULL,
  126615. &_vq_auxt__44c6_s_p3_0,
  126616. NULL,
  126617. 0
  126618. };
  126619. static long _vq_quantlist__44c6_s_p4_0[] = {
  126620. 8,
  126621. 7,
  126622. 9,
  126623. 6,
  126624. 10,
  126625. 5,
  126626. 11,
  126627. 4,
  126628. 12,
  126629. 3,
  126630. 13,
  126631. 2,
  126632. 14,
  126633. 1,
  126634. 15,
  126635. 0,
  126636. 16,
  126637. };
  126638. static long _vq_lengthlist__44c6_s_p4_0[] = {
  126639. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  126640. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  126641. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  126642. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  126643. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  126644. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  126645. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  126646. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  126647. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  126648. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  126649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126657. 0,
  126658. };
  126659. static float _vq_quantthresh__44c6_s_p4_0[] = {
  126660. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126661. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126662. };
  126663. static long _vq_quantmap__44c6_s_p4_0[] = {
  126664. 15, 13, 11, 9, 7, 5, 3, 1,
  126665. 0, 2, 4, 6, 8, 10, 12, 14,
  126666. 16,
  126667. };
  126668. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  126669. _vq_quantthresh__44c6_s_p4_0,
  126670. _vq_quantmap__44c6_s_p4_0,
  126671. 17,
  126672. 17
  126673. };
  126674. static static_codebook _44c6_s_p4_0 = {
  126675. 2, 289,
  126676. _vq_lengthlist__44c6_s_p4_0,
  126677. 1, -529530880, 1611661312, 5, 0,
  126678. _vq_quantlist__44c6_s_p4_0,
  126679. NULL,
  126680. &_vq_auxt__44c6_s_p4_0,
  126681. NULL,
  126682. 0
  126683. };
  126684. static long _vq_quantlist__44c6_s_p5_0[] = {
  126685. 1,
  126686. 0,
  126687. 2,
  126688. };
  126689. static long _vq_lengthlist__44c6_s_p5_0[] = {
  126690. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  126691. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  126692. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  126693. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  126694. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  126695. 12,
  126696. };
  126697. static float _vq_quantthresh__44c6_s_p5_0[] = {
  126698. -5.5, 5.5,
  126699. };
  126700. static long _vq_quantmap__44c6_s_p5_0[] = {
  126701. 1, 0, 2,
  126702. };
  126703. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  126704. _vq_quantthresh__44c6_s_p5_0,
  126705. _vq_quantmap__44c6_s_p5_0,
  126706. 3,
  126707. 3
  126708. };
  126709. static static_codebook _44c6_s_p5_0 = {
  126710. 4, 81,
  126711. _vq_lengthlist__44c6_s_p5_0,
  126712. 1, -529137664, 1618345984, 2, 0,
  126713. _vq_quantlist__44c6_s_p5_0,
  126714. NULL,
  126715. &_vq_auxt__44c6_s_p5_0,
  126716. NULL,
  126717. 0
  126718. };
  126719. static long _vq_quantlist__44c6_s_p5_1[] = {
  126720. 5,
  126721. 4,
  126722. 6,
  126723. 3,
  126724. 7,
  126725. 2,
  126726. 8,
  126727. 1,
  126728. 9,
  126729. 0,
  126730. 10,
  126731. };
  126732. static long _vq_lengthlist__44c6_s_p5_1[] = {
  126733. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  126734. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  126735. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  126736. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  126737. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  126738. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  126739. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  126740. 11,10,10, 7, 7, 8, 8, 8, 8,
  126741. };
  126742. static float _vq_quantthresh__44c6_s_p5_1[] = {
  126743. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126744. 3.5, 4.5,
  126745. };
  126746. static long _vq_quantmap__44c6_s_p5_1[] = {
  126747. 9, 7, 5, 3, 1, 0, 2, 4,
  126748. 6, 8, 10,
  126749. };
  126750. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  126751. _vq_quantthresh__44c6_s_p5_1,
  126752. _vq_quantmap__44c6_s_p5_1,
  126753. 11,
  126754. 11
  126755. };
  126756. static static_codebook _44c6_s_p5_1 = {
  126757. 2, 121,
  126758. _vq_lengthlist__44c6_s_p5_1,
  126759. 1, -531365888, 1611661312, 4, 0,
  126760. _vq_quantlist__44c6_s_p5_1,
  126761. NULL,
  126762. &_vq_auxt__44c6_s_p5_1,
  126763. NULL,
  126764. 0
  126765. };
  126766. static long _vq_quantlist__44c6_s_p6_0[] = {
  126767. 6,
  126768. 5,
  126769. 7,
  126770. 4,
  126771. 8,
  126772. 3,
  126773. 9,
  126774. 2,
  126775. 10,
  126776. 1,
  126777. 11,
  126778. 0,
  126779. 12,
  126780. };
  126781. static long _vq_lengthlist__44c6_s_p6_0[] = {
  126782. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  126783. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  126784. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  126785. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  126786. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  126787. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  126788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126792. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126793. };
  126794. static float _vq_quantthresh__44c6_s_p6_0[] = {
  126795. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126796. 12.5, 17.5, 22.5, 27.5,
  126797. };
  126798. static long _vq_quantmap__44c6_s_p6_0[] = {
  126799. 11, 9, 7, 5, 3, 1, 0, 2,
  126800. 4, 6, 8, 10, 12,
  126801. };
  126802. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  126803. _vq_quantthresh__44c6_s_p6_0,
  126804. _vq_quantmap__44c6_s_p6_0,
  126805. 13,
  126806. 13
  126807. };
  126808. static static_codebook _44c6_s_p6_0 = {
  126809. 2, 169,
  126810. _vq_lengthlist__44c6_s_p6_0,
  126811. 1, -526516224, 1616117760, 4, 0,
  126812. _vq_quantlist__44c6_s_p6_0,
  126813. NULL,
  126814. &_vq_auxt__44c6_s_p6_0,
  126815. NULL,
  126816. 0
  126817. };
  126818. static long _vq_quantlist__44c6_s_p6_1[] = {
  126819. 2,
  126820. 1,
  126821. 3,
  126822. 0,
  126823. 4,
  126824. };
  126825. static long _vq_lengthlist__44c6_s_p6_1[] = {
  126826. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  126827. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126828. };
  126829. static float _vq_quantthresh__44c6_s_p6_1[] = {
  126830. -1.5, -0.5, 0.5, 1.5,
  126831. };
  126832. static long _vq_quantmap__44c6_s_p6_1[] = {
  126833. 3, 1, 0, 2, 4,
  126834. };
  126835. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  126836. _vq_quantthresh__44c6_s_p6_1,
  126837. _vq_quantmap__44c6_s_p6_1,
  126838. 5,
  126839. 5
  126840. };
  126841. static static_codebook _44c6_s_p6_1 = {
  126842. 2, 25,
  126843. _vq_lengthlist__44c6_s_p6_1,
  126844. 1, -533725184, 1611661312, 3, 0,
  126845. _vq_quantlist__44c6_s_p6_1,
  126846. NULL,
  126847. &_vq_auxt__44c6_s_p6_1,
  126848. NULL,
  126849. 0
  126850. };
  126851. static long _vq_quantlist__44c6_s_p7_0[] = {
  126852. 6,
  126853. 5,
  126854. 7,
  126855. 4,
  126856. 8,
  126857. 3,
  126858. 9,
  126859. 2,
  126860. 10,
  126861. 1,
  126862. 11,
  126863. 0,
  126864. 12,
  126865. };
  126866. static long _vq_lengthlist__44c6_s_p7_0[] = {
  126867. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  126868. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  126869. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  126870. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  126871. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  126872. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  126873. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  126874. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  126875. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  126876. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  126877. 20,13,13,13,13,13,13,14,14,
  126878. };
  126879. static float _vq_quantthresh__44c6_s_p7_0[] = {
  126880. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  126881. 27.5, 38.5, 49.5, 60.5,
  126882. };
  126883. static long _vq_quantmap__44c6_s_p7_0[] = {
  126884. 11, 9, 7, 5, 3, 1, 0, 2,
  126885. 4, 6, 8, 10, 12,
  126886. };
  126887. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  126888. _vq_quantthresh__44c6_s_p7_0,
  126889. _vq_quantmap__44c6_s_p7_0,
  126890. 13,
  126891. 13
  126892. };
  126893. static static_codebook _44c6_s_p7_0 = {
  126894. 2, 169,
  126895. _vq_lengthlist__44c6_s_p7_0,
  126896. 1, -523206656, 1618345984, 4, 0,
  126897. _vq_quantlist__44c6_s_p7_0,
  126898. NULL,
  126899. &_vq_auxt__44c6_s_p7_0,
  126900. NULL,
  126901. 0
  126902. };
  126903. static long _vq_quantlist__44c6_s_p7_1[] = {
  126904. 5,
  126905. 4,
  126906. 6,
  126907. 3,
  126908. 7,
  126909. 2,
  126910. 8,
  126911. 1,
  126912. 9,
  126913. 0,
  126914. 10,
  126915. };
  126916. static long _vq_lengthlist__44c6_s_p7_1[] = {
  126917. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  126918. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  126919. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  126920. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  126921. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  126922. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  126923. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  126924. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  126925. };
  126926. static float _vq_quantthresh__44c6_s_p7_1[] = {
  126927. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126928. 3.5, 4.5,
  126929. };
  126930. static long _vq_quantmap__44c6_s_p7_1[] = {
  126931. 9, 7, 5, 3, 1, 0, 2, 4,
  126932. 6, 8, 10,
  126933. };
  126934. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  126935. _vq_quantthresh__44c6_s_p7_1,
  126936. _vq_quantmap__44c6_s_p7_1,
  126937. 11,
  126938. 11
  126939. };
  126940. static static_codebook _44c6_s_p7_1 = {
  126941. 2, 121,
  126942. _vq_lengthlist__44c6_s_p7_1,
  126943. 1, -531365888, 1611661312, 4, 0,
  126944. _vq_quantlist__44c6_s_p7_1,
  126945. NULL,
  126946. &_vq_auxt__44c6_s_p7_1,
  126947. NULL,
  126948. 0
  126949. };
  126950. static long _vq_quantlist__44c6_s_p8_0[] = {
  126951. 7,
  126952. 6,
  126953. 8,
  126954. 5,
  126955. 9,
  126956. 4,
  126957. 10,
  126958. 3,
  126959. 11,
  126960. 2,
  126961. 12,
  126962. 1,
  126963. 13,
  126964. 0,
  126965. 14,
  126966. };
  126967. static long _vq_lengthlist__44c6_s_p8_0[] = {
  126968. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  126969. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  126970. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  126971. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  126972. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  126973. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  126974. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  126975. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  126976. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  126977. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  126978. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  126979. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  126980. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  126981. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  126982. 14,
  126983. };
  126984. static float _vq_quantthresh__44c6_s_p8_0[] = {
  126985. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126986. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126987. };
  126988. static long _vq_quantmap__44c6_s_p8_0[] = {
  126989. 13, 11, 9, 7, 5, 3, 1, 0,
  126990. 2, 4, 6, 8, 10, 12, 14,
  126991. };
  126992. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  126993. _vq_quantthresh__44c6_s_p8_0,
  126994. _vq_quantmap__44c6_s_p8_0,
  126995. 15,
  126996. 15
  126997. };
  126998. static static_codebook _44c6_s_p8_0 = {
  126999. 2, 225,
  127000. _vq_lengthlist__44c6_s_p8_0,
  127001. 1, -520986624, 1620377600, 4, 0,
  127002. _vq_quantlist__44c6_s_p8_0,
  127003. NULL,
  127004. &_vq_auxt__44c6_s_p8_0,
  127005. NULL,
  127006. 0
  127007. };
  127008. static long _vq_quantlist__44c6_s_p8_1[] = {
  127009. 10,
  127010. 9,
  127011. 11,
  127012. 8,
  127013. 12,
  127014. 7,
  127015. 13,
  127016. 6,
  127017. 14,
  127018. 5,
  127019. 15,
  127020. 4,
  127021. 16,
  127022. 3,
  127023. 17,
  127024. 2,
  127025. 18,
  127026. 1,
  127027. 19,
  127028. 0,
  127029. 20,
  127030. };
  127031. static long _vq_lengthlist__44c6_s_p8_1[] = {
  127032. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  127033. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  127034. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  127035. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  127036. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127037. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  127038. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  127039. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  127040. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127041. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127042. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  127043. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  127044. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  127045. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  127046. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  127047. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  127048. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  127049. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  127050. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  127051. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  127052. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  127053. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  127054. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  127055. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127056. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  127057. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  127058. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  127059. 10,10,10,10,10,10,10,10,10,
  127060. };
  127061. static float _vq_quantthresh__44c6_s_p8_1[] = {
  127062. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127063. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127064. 6.5, 7.5, 8.5, 9.5,
  127065. };
  127066. static long _vq_quantmap__44c6_s_p8_1[] = {
  127067. 19, 17, 15, 13, 11, 9, 7, 5,
  127068. 3, 1, 0, 2, 4, 6, 8, 10,
  127069. 12, 14, 16, 18, 20,
  127070. };
  127071. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  127072. _vq_quantthresh__44c6_s_p8_1,
  127073. _vq_quantmap__44c6_s_p8_1,
  127074. 21,
  127075. 21
  127076. };
  127077. static static_codebook _44c6_s_p8_1 = {
  127078. 2, 441,
  127079. _vq_lengthlist__44c6_s_p8_1,
  127080. 1, -529268736, 1611661312, 5, 0,
  127081. _vq_quantlist__44c6_s_p8_1,
  127082. NULL,
  127083. &_vq_auxt__44c6_s_p8_1,
  127084. NULL,
  127085. 0
  127086. };
  127087. static long _vq_quantlist__44c6_s_p9_0[] = {
  127088. 6,
  127089. 5,
  127090. 7,
  127091. 4,
  127092. 8,
  127093. 3,
  127094. 9,
  127095. 2,
  127096. 10,
  127097. 1,
  127098. 11,
  127099. 0,
  127100. 12,
  127101. };
  127102. static long _vq_lengthlist__44c6_s_p9_0[] = {
  127103. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  127104. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  127105. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127106. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  127107. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127108. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127109. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127110. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127111. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127112. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127113. 10,10,10,10,10,10,10,10,10,
  127114. };
  127115. static float _vq_quantthresh__44c6_s_p9_0[] = {
  127116. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  127117. 1592.5, 2229.5, 2866.5, 3503.5,
  127118. };
  127119. static long _vq_quantmap__44c6_s_p9_0[] = {
  127120. 11, 9, 7, 5, 3, 1, 0, 2,
  127121. 4, 6, 8, 10, 12,
  127122. };
  127123. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  127124. _vq_quantthresh__44c6_s_p9_0,
  127125. _vq_quantmap__44c6_s_p9_0,
  127126. 13,
  127127. 13
  127128. };
  127129. static static_codebook _44c6_s_p9_0 = {
  127130. 2, 169,
  127131. _vq_lengthlist__44c6_s_p9_0,
  127132. 1, -511845376, 1630791680, 4, 0,
  127133. _vq_quantlist__44c6_s_p9_0,
  127134. NULL,
  127135. &_vq_auxt__44c6_s_p9_0,
  127136. NULL,
  127137. 0
  127138. };
  127139. static long _vq_quantlist__44c6_s_p9_1[] = {
  127140. 6,
  127141. 5,
  127142. 7,
  127143. 4,
  127144. 8,
  127145. 3,
  127146. 9,
  127147. 2,
  127148. 10,
  127149. 1,
  127150. 11,
  127151. 0,
  127152. 12,
  127153. };
  127154. static long _vq_lengthlist__44c6_s_p9_1[] = {
  127155. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  127156. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  127157. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  127158. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  127159. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  127160. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  127161. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  127162. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  127163. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  127164. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  127165. 15,12,10,11,11,13,11,12,13,
  127166. };
  127167. static float _vq_quantthresh__44c6_s_p9_1[] = {
  127168. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  127169. 122.5, 171.5, 220.5, 269.5,
  127170. };
  127171. static long _vq_quantmap__44c6_s_p9_1[] = {
  127172. 11, 9, 7, 5, 3, 1, 0, 2,
  127173. 4, 6, 8, 10, 12,
  127174. };
  127175. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  127176. _vq_quantthresh__44c6_s_p9_1,
  127177. _vq_quantmap__44c6_s_p9_1,
  127178. 13,
  127179. 13
  127180. };
  127181. static static_codebook _44c6_s_p9_1 = {
  127182. 2, 169,
  127183. _vq_lengthlist__44c6_s_p9_1,
  127184. 1, -518889472, 1622704128, 4, 0,
  127185. _vq_quantlist__44c6_s_p9_1,
  127186. NULL,
  127187. &_vq_auxt__44c6_s_p9_1,
  127188. NULL,
  127189. 0
  127190. };
  127191. static long _vq_quantlist__44c6_s_p9_2[] = {
  127192. 24,
  127193. 23,
  127194. 25,
  127195. 22,
  127196. 26,
  127197. 21,
  127198. 27,
  127199. 20,
  127200. 28,
  127201. 19,
  127202. 29,
  127203. 18,
  127204. 30,
  127205. 17,
  127206. 31,
  127207. 16,
  127208. 32,
  127209. 15,
  127210. 33,
  127211. 14,
  127212. 34,
  127213. 13,
  127214. 35,
  127215. 12,
  127216. 36,
  127217. 11,
  127218. 37,
  127219. 10,
  127220. 38,
  127221. 9,
  127222. 39,
  127223. 8,
  127224. 40,
  127225. 7,
  127226. 41,
  127227. 6,
  127228. 42,
  127229. 5,
  127230. 43,
  127231. 4,
  127232. 44,
  127233. 3,
  127234. 45,
  127235. 2,
  127236. 46,
  127237. 1,
  127238. 47,
  127239. 0,
  127240. 48,
  127241. };
  127242. static long _vq_lengthlist__44c6_s_p9_2[] = {
  127243. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  127244. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  127245. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  127246. 7,
  127247. };
  127248. static float _vq_quantthresh__44c6_s_p9_2[] = {
  127249. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  127250. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  127251. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127252. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127253. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  127254. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  127255. };
  127256. static long _vq_quantmap__44c6_s_p9_2[] = {
  127257. 47, 45, 43, 41, 39, 37, 35, 33,
  127258. 31, 29, 27, 25, 23, 21, 19, 17,
  127259. 15, 13, 11, 9, 7, 5, 3, 1,
  127260. 0, 2, 4, 6, 8, 10, 12, 14,
  127261. 16, 18, 20, 22, 24, 26, 28, 30,
  127262. 32, 34, 36, 38, 40, 42, 44, 46,
  127263. 48,
  127264. };
  127265. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  127266. _vq_quantthresh__44c6_s_p9_2,
  127267. _vq_quantmap__44c6_s_p9_2,
  127268. 49,
  127269. 49
  127270. };
  127271. static static_codebook _44c6_s_p9_2 = {
  127272. 1, 49,
  127273. _vq_lengthlist__44c6_s_p9_2,
  127274. 1, -526909440, 1611661312, 6, 0,
  127275. _vq_quantlist__44c6_s_p9_2,
  127276. NULL,
  127277. &_vq_auxt__44c6_s_p9_2,
  127278. NULL,
  127279. 0
  127280. };
  127281. static long _huff_lengthlist__44c6_s_short[] = {
  127282. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  127283. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  127284. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  127285. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  127286. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  127287. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  127288. 9,10,17,18,
  127289. };
  127290. static static_codebook _huff_book__44c6_s_short = {
  127291. 2, 100,
  127292. _huff_lengthlist__44c6_s_short,
  127293. 0, 0, 0, 0, 0,
  127294. NULL,
  127295. NULL,
  127296. NULL,
  127297. NULL,
  127298. 0
  127299. };
  127300. static long _huff_lengthlist__44c7_s_long[] = {
  127301. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  127302. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  127303. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  127304. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  127305. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  127306. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  127307. 11,10,10,12,
  127308. };
  127309. static static_codebook _huff_book__44c7_s_long = {
  127310. 2, 100,
  127311. _huff_lengthlist__44c7_s_long,
  127312. 0, 0, 0, 0, 0,
  127313. NULL,
  127314. NULL,
  127315. NULL,
  127316. NULL,
  127317. 0
  127318. };
  127319. static long _vq_quantlist__44c7_s_p1_0[] = {
  127320. 1,
  127321. 0,
  127322. 2,
  127323. };
  127324. static long _vq_lengthlist__44c7_s_p1_0[] = {
  127325. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  127326. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  127327. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  127328. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  127329. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  127330. 8,
  127331. };
  127332. static float _vq_quantthresh__44c7_s_p1_0[] = {
  127333. -0.5, 0.5,
  127334. };
  127335. static long _vq_quantmap__44c7_s_p1_0[] = {
  127336. 1, 0, 2,
  127337. };
  127338. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  127339. _vq_quantthresh__44c7_s_p1_0,
  127340. _vq_quantmap__44c7_s_p1_0,
  127341. 3,
  127342. 3
  127343. };
  127344. static static_codebook _44c7_s_p1_0 = {
  127345. 4, 81,
  127346. _vq_lengthlist__44c7_s_p1_0,
  127347. 1, -535822336, 1611661312, 2, 0,
  127348. _vq_quantlist__44c7_s_p1_0,
  127349. NULL,
  127350. &_vq_auxt__44c7_s_p1_0,
  127351. NULL,
  127352. 0
  127353. };
  127354. static long _vq_quantlist__44c7_s_p2_0[] = {
  127355. 2,
  127356. 1,
  127357. 3,
  127358. 0,
  127359. 4,
  127360. };
  127361. static long _vq_lengthlist__44c7_s_p2_0[] = {
  127362. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  127363. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  127364. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  127365. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  127366. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  127367. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  127368. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  127369. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  127370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127371. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  127372. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  127373. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  127374. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  127375. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  127376. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  127377. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  127378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127379. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  127380. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  127381. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  127382. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  127383. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  127384. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  127385. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127387. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  127388. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  127389. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  127390. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  127391. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  127392. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  127393. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  127398. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  127399. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  127400. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  127401. 13,
  127402. };
  127403. static float _vq_quantthresh__44c7_s_p2_0[] = {
  127404. -1.5, -0.5, 0.5, 1.5,
  127405. };
  127406. static long _vq_quantmap__44c7_s_p2_0[] = {
  127407. 3, 1, 0, 2, 4,
  127408. };
  127409. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  127410. _vq_quantthresh__44c7_s_p2_0,
  127411. _vq_quantmap__44c7_s_p2_0,
  127412. 5,
  127413. 5
  127414. };
  127415. static static_codebook _44c7_s_p2_0 = {
  127416. 4, 625,
  127417. _vq_lengthlist__44c7_s_p2_0,
  127418. 1, -533725184, 1611661312, 3, 0,
  127419. _vq_quantlist__44c7_s_p2_0,
  127420. NULL,
  127421. &_vq_auxt__44c7_s_p2_0,
  127422. NULL,
  127423. 0
  127424. };
  127425. static long _vq_quantlist__44c7_s_p3_0[] = {
  127426. 4,
  127427. 3,
  127428. 5,
  127429. 2,
  127430. 6,
  127431. 1,
  127432. 7,
  127433. 0,
  127434. 8,
  127435. };
  127436. static long _vq_lengthlist__44c7_s_p3_0[] = {
  127437. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  127438. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  127439. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  127440. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  127441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127442. 0,
  127443. };
  127444. static float _vq_quantthresh__44c7_s_p3_0[] = {
  127445. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127446. };
  127447. static long _vq_quantmap__44c7_s_p3_0[] = {
  127448. 7, 5, 3, 1, 0, 2, 4, 6,
  127449. 8,
  127450. };
  127451. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  127452. _vq_quantthresh__44c7_s_p3_0,
  127453. _vq_quantmap__44c7_s_p3_0,
  127454. 9,
  127455. 9
  127456. };
  127457. static static_codebook _44c7_s_p3_0 = {
  127458. 2, 81,
  127459. _vq_lengthlist__44c7_s_p3_0,
  127460. 1, -531628032, 1611661312, 4, 0,
  127461. _vq_quantlist__44c7_s_p3_0,
  127462. NULL,
  127463. &_vq_auxt__44c7_s_p3_0,
  127464. NULL,
  127465. 0
  127466. };
  127467. static long _vq_quantlist__44c7_s_p4_0[] = {
  127468. 8,
  127469. 7,
  127470. 9,
  127471. 6,
  127472. 10,
  127473. 5,
  127474. 11,
  127475. 4,
  127476. 12,
  127477. 3,
  127478. 13,
  127479. 2,
  127480. 14,
  127481. 1,
  127482. 15,
  127483. 0,
  127484. 16,
  127485. };
  127486. static long _vq_lengthlist__44c7_s_p4_0[] = {
  127487. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  127488. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  127489. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  127490. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  127491. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  127492. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  127493. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  127494. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  127495. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  127496. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  127497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127505. 0,
  127506. };
  127507. static float _vq_quantthresh__44c7_s_p4_0[] = {
  127508. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127509. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127510. };
  127511. static long _vq_quantmap__44c7_s_p4_0[] = {
  127512. 15, 13, 11, 9, 7, 5, 3, 1,
  127513. 0, 2, 4, 6, 8, 10, 12, 14,
  127514. 16,
  127515. };
  127516. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  127517. _vq_quantthresh__44c7_s_p4_0,
  127518. _vq_quantmap__44c7_s_p4_0,
  127519. 17,
  127520. 17
  127521. };
  127522. static static_codebook _44c7_s_p4_0 = {
  127523. 2, 289,
  127524. _vq_lengthlist__44c7_s_p4_0,
  127525. 1, -529530880, 1611661312, 5, 0,
  127526. _vq_quantlist__44c7_s_p4_0,
  127527. NULL,
  127528. &_vq_auxt__44c7_s_p4_0,
  127529. NULL,
  127530. 0
  127531. };
  127532. static long _vq_quantlist__44c7_s_p5_0[] = {
  127533. 1,
  127534. 0,
  127535. 2,
  127536. };
  127537. static long _vq_lengthlist__44c7_s_p5_0[] = {
  127538. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  127539. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  127540. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  127541. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  127542. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  127543. 12,
  127544. };
  127545. static float _vq_quantthresh__44c7_s_p5_0[] = {
  127546. -5.5, 5.5,
  127547. };
  127548. static long _vq_quantmap__44c7_s_p5_0[] = {
  127549. 1, 0, 2,
  127550. };
  127551. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  127552. _vq_quantthresh__44c7_s_p5_0,
  127553. _vq_quantmap__44c7_s_p5_0,
  127554. 3,
  127555. 3
  127556. };
  127557. static static_codebook _44c7_s_p5_0 = {
  127558. 4, 81,
  127559. _vq_lengthlist__44c7_s_p5_0,
  127560. 1, -529137664, 1618345984, 2, 0,
  127561. _vq_quantlist__44c7_s_p5_0,
  127562. NULL,
  127563. &_vq_auxt__44c7_s_p5_0,
  127564. NULL,
  127565. 0
  127566. };
  127567. static long _vq_quantlist__44c7_s_p5_1[] = {
  127568. 5,
  127569. 4,
  127570. 6,
  127571. 3,
  127572. 7,
  127573. 2,
  127574. 8,
  127575. 1,
  127576. 9,
  127577. 0,
  127578. 10,
  127579. };
  127580. static long _vq_lengthlist__44c7_s_p5_1[] = {
  127581. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  127582. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  127583. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  127584. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  127585. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  127586. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  127587. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  127588. 11,11,11, 7, 7, 8, 8, 8, 8,
  127589. };
  127590. static float _vq_quantthresh__44c7_s_p5_1[] = {
  127591. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127592. 3.5, 4.5,
  127593. };
  127594. static long _vq_quantmap__44c7_s_p5_1[] = {
  127595. 9, 7, 5, 3, 1, 0, 2, 4,
  127596. 6, 8, 10,
  127597. };
  127598. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  127599. _vq_quantthresh__44c7_s_p5_1,
  127600. _vq_quantmap__44c7_s_p5_1,
  127601. 11,
  127602. 11
  127603. };
  127604. static static_codebook _44c7_s_p5_1 = {
  127605. 2, 121,
  127606. _vq_lengthlist__44c7_s_p5_1,
  127607. 1, -531365888, 1611661312, 4, 0,
  127608. _vq_quantlist__44c7_s_p5_1,
  127609. NULL,
  127610. &_vq_auxt__44c7_s_p5_1,
  127611. NULL,
  127612. 0
  127613. };
  127614. static long _vq_quantlist__44c7_s_p6_0[] = {
  127615. 6,
  127616. 5,
  127617. 7,
  127618. 4,
  127619. 8,
  127620. 3,
  127621. 9,
  127622. 2,
  127623. 10,
  127624. 1,
  127625. 11,
  127626. 0,
  127627. 12,
  127628. };
  127629. static long _vq_lengthlist__44c7_s_p6_0[] = {
  127630. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  127631. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127632. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  127633. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  127634. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  127635. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  127636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127640. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127641. };
  127642. static float _vq_quantthresh__44c7_s_p6_0[] = {
  127643. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127644. 12.5, 17.5, 22.5, 27.5,
  127645. };
  127646. static long _vq_quantmap__44c7_s_p6_0[] = {
  127647. 11, 9, 7, 5, 3, 1, 0, 2,
  127648. 4, 6, 8, 10, 12,
  127649. };
  127650. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  127651. _vq_quantthresh__44c7_s_p6_0,
  127652. _vq_quantmap__44c7_s_p6_0,
  127653. 13,
  127654. 13
  127655. };
  127656. static static_codebook _44c7_s_p6_0 = {
  127657. 2, 169,
  127658. _vq_lengthlist__44c7_s_p6_0,
  127659. 1, -526516224, 1616117760, 4, 0,
  127660. _vq_quantlist__44c7_s_p6_0,
  127661. NULL,
  127662. &_vq_auxt__44c7_s_p6_0,
  127663. NULL,
  127664. 0
  127665. };
  127666. static long _vq_quantlist__44c7_s_p6_1[] = {
  127667. 2,
  127668. 1,
  127669. 3,
  127670. 0,
  127671. 4,
  127672. };
  127673. static long _vq_lengthlist__44c7_s_p6_1[] = {
  127674. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  127675. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127676. };
  127677. static float _vq_quantthresh__44c7_s_p6_1[] = {
  127678. -1.5, -0.5, 0.5, 1.5,
  127679. };
  127680. static long _vq_quantmap__44c7_s_p6_1[] = {
  127681. 3, 1, 0, 2, 4,
  127682. };
  127683. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  127684. _vq_quantthresh__44c7_s_p6_1,
  127685. _vq_quantmap__44c7_s_p6_1,
  127686. 5,
  127687. 5
  127688. };
  127689. static static_codebook _44c7_s_p6_1 = {
  127690. 2, 25,
  127691. _vq_lengthlist__44c7_s_p6_1,
  127692. 1, -533725184, 1611661312, 3, 0,
  127693. _vq_quantlist__44c7_s_p6_1,
  127694. NULL,
  127695. &_vq_auxt__44c7_s_p6_1,
  127696. NULL,
  127697. 0
  127698. };
  127699. static long _vq_quantlist__44c7_s_p7_0[] = {
  127700. 6,
  127701. 5,
  127702. 7,
  127703. 4,
  127704. 8,
  127705. 3,
  127706. 9,
  127707. 2,
  127708. 10,
  127709. 1,
  127710. 11,
  127711. 0,
  127712. 12,
  127713. };
  127714. static long _vq_lengthlist__44c7_s_p7_0[] = {
  127715. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  127716. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  127717. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  127718. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  127719. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  127720. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  127721. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  127722. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  127723. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  127724. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  127725. 19,13,13,13,13,14,14,15,15,
  127726. };
  127727. static float _vq_quantthresh__44c7_s_p7_0[] = {
  127728. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  127729. 27.5, 38.5, 49.5, 60.5,
  127730. };
  127731. static long _vq_quantmap__44c7_s_p7_0[] = {
  127732. 11, 9, 7, 5, 3, 1, 0, 2,
  127733. 4, 6, 8, 10, 12,
  127734. };
  127735. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  127736. _vq_quantthresh__44c7_s_p7_0,
  127737. _vq_quantmap__44c7_s_p7_0,
  127738. 13,
  127739. 13
  127740. };
  127741. static static_codebook _44c7_s_p7_0 = {
  127742. 2, 169,
  127743. _vq_lengthlist__44c7_s_p7_0,
  127744. 1, -523206656, 1618345984, 4, 0,
  127745. _vq_quantlist__44c7_s_p7_0,
  127746. NULL,
  127747. &_vq_auxt__44c7_s_p7_0,
  127748. NULL,
  127749. 0
  127750. };
  127751. static long _vq_quantlist__44c7_s_p7_1[] = {
  127752. 5,
  127753. 4,
  127754. 6,
  127755. 3,
  127756. 7,
  127757. 2,
  127758. 8,
  127759. 1,
  127760. 9,
  127761. 0,
  127762. 10,
  127763. };
  127764. static long _vq_lengthlist__44c7_s_p7_1[] = {
  127765. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  127766. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  127767. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  127768. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  127769. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  127770. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  127771. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  127772. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  127773. };
  127774. static float _vq_quantthresh__44c7_s_p7_1[] = {
  127775. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127776. 3.5, 4.5,
  127777. };
  127778. static long _vq_quantmap__44c7_s_p7_1[] = {
  127779. 9, 7, 5, 3, 1, 0, 2, 4,
  127780. 6, 8, 10,
  127781. };
  127782. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  127783. _vq_quantthresh__44c7_s_p7_1,
  127784. _vq_quantmap__44c7_s_p7_1,
  127785. 11,
  127786. 11
  127787. };
  127788. static static_codebook _44c7_s_p7_1 = {
  127789. 2, 121,
  127790. _vq_lengthlist__44c7_s_p7_1,
  127791. 1, -531365888, 1611661312, 4, 0,
  127792. _vq_quantlist__44c7_s_p7_1,
  127793. NULL,
  127794. &_vq_auxt__44c7_s_p7_1,
  127795. NULL,
  127796. 0
  127797. };
  127798. static long _vq_quantlist__44c7_s_p8_0[] = {
  127799. 7,
  127800. 6,
  127801. 8,
  127802. 5,
  127803. 9,
  127804. 4,
  127805. 10,
  127806. 3,
  127807. 11,
  127808. 2,
  127809. 12,
  127810. 1,
  127811. 13,
  127812. 0,
  127813. 14,
  127814. };
  127815. static long _vq_lengthlist__44c7_s_p8_0[] = {
  127816. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  127817. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  127818. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  127819. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  127820. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  127821. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  127822. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  127823. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  127824. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  127825. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  127826. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  127827. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  127828. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  127829. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  127830. 14,
  127831. };
  127832. static float _vq_quantthresh__44c7_s_p8_0[] = {
  127833. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127834. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127835. };
  127836. static long _vq_quantmap__44c7_s_p8_0[] = {
  127837. 13, 11, 9, 7, 5, 3, 1, 0,
  127838. 2, 4, 6, 8, 10, 12, 14,
  127839. };
  127840. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  127841. _vq_quantthresh__44c7_s_p8_0,
  127842. _vq_quantmap__44c7_s_p8_0,
  127843. 15,
  127844. 15
  127845. };
  127846. static static_codebook _44c7_s_p8_0 = {
  127847. 2, 225,
  127848. _vq_lengthlist__44c7_s_p8_0,
  127849. 1, -520986624, 1620377600, 4, 0,
  127850. _vq_quantlist__44c7_s_p8_0,
  127851. NULL,
  127852. &_vq_auxt__44c7_s_p8_0,
  127853. NULL,
  127854. 0
  127855. };
  127856. static long _vq_quantlist__44c7_s_p8_1[] = {
  127857. 10,
  127858. 9,
  127859. 11,
  127860. 8,
  127861. 12,
  127862. 7,
  127863. 13,
  127864. 6,
  127865. 14,
  127866. 5,
  127867. 15,
  127868. 4,
  127869. 16,
  127870. 3,
  127871. 17,
  127872. 2,
  127873. 18,
  127874. 1,
  127875. 19,
  127876. 0,
  127877. 20,
  127878. };
  127879. static long _vq_lengthlist__44c7_s_p8_1[] = {
  127880. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  127881. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  127882. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  127883. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  127884. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127885. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  127886. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  127887. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  127888. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127889. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127890. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  127891. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  127892. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  127893. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  127894. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  127895. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  127896. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  127897. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  127898. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  127899. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  127900. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  127901. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  127902. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  127903. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  127904. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  127905. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  127906. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  127907. 10,10,10,10,10,10,10,10,10,
  127908. };
  127909. static float _vq_quantthresh__44c7_s_p8_1[] = {
  127910. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127911. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127912. 6.5, 7.5, 8.5, 9.5,
  127913. };
  127914. static long _vq_quantmap__44c7_s_p8_1[] = {
  127915. 19, 17, 15, 13, 11, 9, 7, 5,
  127916. 3, 1, 0, 2, 4, 6, 8, 10,
  127917. 12, 14, 16, 18, 20,
  127918. };
  127919. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  127920. _vq_quantthresh__44c7_s_p8_1,
  127921. _vq_quantmap__44c7_s_p8_1,
  127922. 21,
  127923. 21
  127924. };
  127925. static static_codebook _44c7_s_p8_1 = {
  127926. 2, 441,
  127927. _vq_lengthlist__44c7_s_p8_1,
  127928. 1, -529268736, 1611661312, 5, 0,
  127929. _vq_quantlist__44c7_s_p8_1,
  127930. NULL,
  127931. &_vq_auxt__44c7_s_p8_1,
  127932. NULL,
  127933. 0
  127934. };
  127935. static long _vq_quantlist__44c7_s_p9_0[] = {
  127936. 6,
  127937. 5,
  127938. 7,
  127939. 4,
  127940. 8,
  127941. 3,
  127942. 9,
  127943. 2,
  127944. 10,
  127945. 1,
  127946. 11,
  127947. 0,
  127948. 12,
  127949. };
  127950. static long _vq_lengthlist__44c7_s_p9_0[] = {
  127951. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  127952. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  127953. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127954. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127955. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127956. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127957. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127958. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127959. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127960. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127961. 11,11,11,11,11,11,11,11,11,
  127962. };
  127963. static float _vq_quantthresh__44c7_s_p9_0[] = {
  127964. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  127965. 1592.5, 2229.5, 2866.5, 3503.5,
  127966. };
  127967. static long _vq_quantmap__44c7_s_p9_0[] = {
  127968. 11, 9, 7, 5, 3, 1, 0, 2,
  127969. 4, 6, 8, 10, 12,
  127970. };
  127971. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  127972. _vq_quantthresh__44c7_s_p9_0,
  127973. _vq_quantmap__44c7_s_p9_0,
  127974. 13,
  127975. 13
  127976. };
  127977. static static_codebook _44c7_s_p9_0 = {
  127978. 2, 169,
  127979. _vq_lengthlist__44c7_s_p9_0,
  127980. 1, -511845376, 1630791680, 4, 0,
  127981. _vq_quantlist__44c7_s_p9_0,
  127982. NULL,
  127983. &_vq_auxt__44c7_s_p9_0,
  127984. NULL,
  127985. 0
  127986. };
  127987. static long _vq_quantlist__44c7_s_p9_1[] = {
  127988. 6,
  127989. 5,
  127990. 7,
  127991. 4,
  127992. 8,
  127993. 3,
  127994. 9,
  127995. 2,
  127996. 10,
  127997. 1,
  127998. 11,
  127999. 0,
  128000. 12,
  128001. };
  128002. static long _vq_lengthlist__44c7_s_p9_1[] = {
  128003. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  128004. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  128005. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  128006. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  128007. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  128008. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  128009. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  128010. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  128011. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  128012. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  128013. 15,11,11,10,10,12,12,12,12,
  128014. };
  128015. static float _vq_quantthresh__44c7_s_p9_1[] = {
  128016. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  128017. 122.5, 171.5, 220.5, 269.5,
  128018. };
  128019. static long _vq_quantmap__44c7_s_p9_1[] = {
  128020. 11, 9, 7, 5, 3, 1, 0, 2,
  128021. 4, 6, 8, 10, 12,
  128022. };
  128023. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  128024. _vq_quantthresh__44c7_s_p9_1,
  128025. _vq_quantmap__44c7_s_p9_1,
  128026. 13,
  128027. 13
  128028. };
  128029. static static_codebook _44c7_s_p9_1 = {
  128030. 2, 169,
  128031. _vq_lengthlist__44c7_s_p9_1,
  128032. 1, -518889472, 1622704128, 4, 0,
  128033. _vq_quantlist__44c7_s_p9_1,
  128034. NULL,
  128035. &_vq_auxt__44c7_s_p9_1,
  128036. NULL,
  128037. 0
  128038. };
  128039. static long _vq_quantlist__44c7_s_p9_2[] = {
  128040. 24,
  128041. 23,
  128042. 25,
  128043. 22,
  128044. 26,
  128045. 21,
  128046. 27,
  128047. 20,
  128048. 28,
  128049. 19,
  128050. 29,
  128051. 18,
  128052. 30,
  128053. 17,
  128054. 31,
  128055. 16,
  128056. 32,
  128057. 15,
  128058. 33,
  128059. 14,
  128060. 34,
  128061. 13,
  128062. 35,
  128063. 12,
  128064. 36,
  128065. 11,
  128066. 37,
  128067. 10,
  128068. 38,
  128069. 9,
  128070. 39,
  128071. 8,
  128072. 40,
  128073. 7,
  128074. 41,
  128075. 6,
  128076. 42,
  128077. 5,
  128078. 43,
  128079. 4,
  128080. 44,
  128081. 3,
  128082. 45,
  128083. 2,
  128084. 46,
  128085. 1,
  128086. 47,
  128087. 0,
  128088. 48,
  128089. };
  128090. static long _vq_lengthlist__44c7_s_p9_2[] = {
  128091. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  128092. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128093. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128094. 7,
  128095. };
  128096. static float _vq_quantthresh__44c7_s_p9_2[] = {
  128097. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  128098. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  128099. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128100. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128101. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  128102. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  128103. };
  128104. static long _vq_quantmap__44c7_s_p9_2[] = {
  128105. 47, 45, 43, 41, 39, 37, 35, 33,
  128106. 31, 29, 27, 25, 23, 21, 19, 17,
  128107. 15, 13, 11, 9, 7, 5, 3, 1,
  128108. 0, 2, 4, 6, 8, 10, 12, 14,
  128109. 16, 18, 20, 22, 24, 26, 28, 30,
  128110. 32, 34, 36, 38, 40, 42, 44, 46,
  128111. 48,
  128112. };
  128113. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  128114. _vq_quantthresh__44c7_s_p9_2,
  128115. _vq_quantmap__44c7_s_p9_2,
  128116. 49,
  128117. 49
  128118. };
  128119. static static_codebook _44c7_s_p9_2 = {
  128120. 1, 49,
  128121. _vq_lengthlist__44c7_s_p9_2,
  128122. 1, -526909440, 1611661312, 6, 0,
  128123. _vq_quantlist__44c7_s_p9_2,
  128124. NULL,
  128125. &_vq_auxt__44c7_s_p9_2,
  128126. NULL,
  128127. 0
  128128. };
  128129. static long _huff_lengthlist__44c7_s_short[] = {
  128130. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  128131. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  128132. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  128133. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  128134. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  128135. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  128136. 10, 9,11,14,
  128137. };
  128138. static static_codebook _huff_book__44c7_s_short = {
  128139. 2, 100,
  128140. _huff_lengthlist__44c7_s_short,
  128141. 0, 0, 0, 0, 0,
  128142. NULL,
  128143. NULL,
  128144. NULL,
  128145. NULL,
  128146. 0
  128147. };
  128148. static long _huff_lengthlist__44c8_s_long[] = {
  128149. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  128150. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  128151. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  128152. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  128153. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  128154. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  128155. 11, 9, 9,10,
  128156. };
  128157. static static_codebook _huff_book__44c8_s_long = {
  128158. 2, 100,
  128159. _huff_lengthlist__44c8_s_long,
  128160. 0, 0, 0, 0, 0,
  128161. NULL,
  128162. NULL,
  128163. NULL,
  128164. NULL,
  128165. 0
  128166. };
  128167. static long _vq_quantlist__44c8_s_p1_0[] = {
  128168. 1,
  128169. 0,
  128170. 2,
  128171. };
  128172. static long _vq_lengthlist__44c8_s_p1_0[] = {
  128173. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  128174. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128175. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  128176. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128177. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  128178. 8,
  128179. };
  128180. static float _vq_quantthresh__44c8_s_p1_0[] = {
  128181. -0.5, 0.5,
  128182. };
  128183. static long _vq_quantmap__44c8_s_p1_0[] = {
  128184. 1, 0, 2,
  128185. };
  128186. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  128187. _vq_quantthresh__44c8_s_p1_0,
  128188. _vq_quantmap__44c8_s_p1_0,
  128189. 3,
  128190. 3
  128191. };
  128192. static static_codebook _44c8_s_p1_0 = {
  128193. 4, 81,
  128194. _vq_lengthlist__44c8_s_p1_0,
  128195. 1, -535822336, 1611661312, 2, 0,
  128196. _vq_quantlist__44c8_s_p1_0,
  128197. NULL,
  128198. &_vq_auxt__44c8_s_p1_0,
  128199. NULL,
  128200. 0
  128201. };
  128202. static long _vq_quantlist__44c8_s_p2_0[] = {
  128203. 2,
  128204. 1,
  128205. 3,
  128206. 0,
  128207. 4,
  128208. };
  128209. static long _vq_lengthlist__44c8_s_p2_0[] = {
  128210. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  128211. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  128212. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  128213. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  128214. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  128215. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  128216. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  128217. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  128220. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  128221. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  128222. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  128223. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  128224. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  128225. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  128226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128227. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  128228. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  128229. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  128230. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  128231. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  128232. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  128233. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128235. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  128236. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  128237. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  128238. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  128239. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  128240. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  128241. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  128246. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  128247. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  128248. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  128249. 13,
  128250. };
  128251. static float _vq_quantthresh__44c8_s_p2_0[] = {
  128252. -1.5, -0.5, 0.5, 1.5,
  128253. };
  128254. static long _vq_quantmap__44c8_s_p2_0[] = {
  128255. 3, 1, 0, 2, 4,
  128256. };
  128257. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  128258. _vq_quantthresh__44c8_s_p2_0,
  128259. _vq_quantmap__44c8_s_p2_0,
  128260. 5,
  128261. 5
  128262. };
  128263. static static_codebook _44c8_s_p2_0 = {
  128264. 4, 625,
  128265. _vq_lengthlist__44c8_s_p2_0,
  128266. 1, -533725184, 1611661312, 3, 0,
  128267. _vq_quantlist__44c8_s_p2_0,
  128268. NULL,
  128269. &_vq_auxt__44c8_s_p2_0,
  128270. NULL,
  128271. 0
  128272. };
  128273. static long _vq_quantlist__44c8_s_p3_0[] = {
  128274. 4,
  128275. 3,
  128276. 5,
  128277. 2,
  128278. 6,
  128279. 1,
  128280. 7,
  128281. 0,
  128282. 8,
  128283. };
  128284. static long _vq_lengthlist__44c8_s_p3_0[] = {
  128285. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128286. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  128287. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  128288. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  128289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128290. 0,
  128291. };
  128292. static float _vq_quantthresh__44c8_s_p3_0[] = {
  128293. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128294. };
  128295. static long _vq_quantmap__44c8_s_p3_0[] = {
  128296. 7, 5, 3, 1, 0, 2, 4, 6,
  128297. 8,
  128298. };
  128299. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  128300. _vq_quantthresh__44c8_s_p3_0,
  128301. _vq_quantmap__44c8_s_p3_0,
  128302. 9,
  128303. 9
  128304. };
  128305. static static_codebook _44c8_s_p3_0 = {
  128306. 2, 81,
  128307. _vq_lengthlist__44c8_s_p3_0,
  128308. 1, -531628032, 1611661312, 4, 0,
  128309. _vq_quantlist__44c8_s_p3_0,
  128310. NULL,
  128311. &_vq_auxt__44c8_s_p3_0,
  128312. NULL,
  128313. 0
  128314. };
  128315. static long _vq_quantlist__44c8_s_p4_0[] = {
  128316. 8,
  128317. 7,
  128318. 9,
  128319. 6,
  128320. 10,
  128321. 5,
  128322. 11,
  128323. 4,
  128324. 12,
  128325. 3,
  128326. 13,
  128327. 2,
  128328. 14,
  128329. 1,
  128330. 15,
  128331. 0,
  128332. 16,
  128333. };
  128334. static long _vq_lengthlist__44c8_s_p4_0[] = {
  128335. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  128336. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  128337. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  128338. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  128339. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  128340. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  128341. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  128342. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  128343. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  128344. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  128345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128353. 0,
  128354. };
  128355. static float _vq_quantthresh__44c8_s_p4_0[] = {
  128356. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128357. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128358. };
  128359. static long _vq_quantmap__44c8_s_p4_0[] = {
  128360. 15, 13, 11, 9, 7, 5, 3, 1,
  128361. 0, 2, 4, 6, 8, 10, 12, 14,
  128362. 16,
  128363. };
  128364. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  128365. _vq_quantthresh__44c8_s_p4_0,
  128366. _vq_quantmap__44c8_s_p4_0,
  128367. 17,
  128368. 17
  128369. };
  128370. static static_codebook _44c8_s_p4_0 = {
  128371. 2, 289,
  128372. _vq_lengthlist__44c8_s_p4_0,
  128373. 1, -529530880, 1611661312, 5, 0,
  128374. _vq_quantlist__44c8_s_p4_0,
  128375. NULL,
  128376. &_vq_auxt__44c8_s_p4_0,
  128377. NULL,
  128378. 0
  128379. };
  128380. static long _vq_quantlist__44c8_s_p5_0[] = {
  128381. 1,
  128382. 0,
  128383. 2,
  128384. };
  128385. static long _vq_lengthlist__44c8_s_p5_0[] = {
  128386. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  128387. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  128388. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  128389. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  128390. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  128391. 12,
  128392. };
  128393. static float _vq_quantthresh__44c8_s_p5_0[] = {
  128394. -5.5, 5.5,
  128395. };
  128396. static long _vq_quantmap__44c8_s_p5_0[] = {
  128397. 1, 0, 2,
  128398. };
  128399. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  128400. _vq_quantthresh__44c8_s_p5_0,
  128401. _vq_quantmap__44c8_s_p5_0,
  128402. 3,
  128403. 3
  128404. };
  128405. static static_codebook _44c8_s_p5_0 = {
  128406. 4, 81,
  128407. _vq_lengthlist__44c8_s_p5_0,
  128408. 1, -529137664, 1618345984, 2, 0,
  128409. _vq_quantlist__44c8_s_p5_0,
  128410. NULL,
  128411. &_vq_auxt__44c8_s_p5_0,
  128412. NULL,
  128413. 0
  128414. };
  128415. static long _vq_quantlist__44c8_s_p5_1[] = {
  128416. 5,
  128417. 4,
  128418. 6,
  128419. 3,
  128420. 7,
  128421. 2,
  128422. 8,
  128423. 1,
  128424. 9,
  128425. 0,
  128426. 10,
  128427. };
  128428. static long _vq_lengthlist__44c8_s_p5_1[] = {
  128429. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  128430. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  128431. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  128432. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  128433. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  128434. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  128435. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  128436. 11,11,11, 7, 7, 7, 7, 8, 8,
  128437. };
  128438. static float _vq_quantthresh__44c8_s_p5_1[] = {
  128439. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128440. 3.5, 4.5,
  128441. };
  128442. static long _vq_quantmap__44c8_s_p5_1[] = {
  128443. 9, 7, 5, 3, 1, 0, 2, 4,
  128444. 6, 8, 10,
  128445. };
  128446. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  128447. _vq_quantthresh__44c8_s_p5_1,
  128448. _vq_quantmap__44c8_s_p5_1,
  128449. 11,
  128450. 11
  128451. };
  128452. static static_codebook _44c8_s_p5_1 = {
  128453. 2, 121,
  128454. _vq_lengthlist__44c8_s_p5_1,
  128455. 1, -531365888, 1611661312, 4, 0,
  128456. _vq_quantlist__44c8_s_p5_1,
  128457. NULL,
  128458. &_vq_auxt__44c8_s_p5_1,
  128459. NULL,
  128460. 0
  128461. };
  128462. static long _vq_quantlist__44c8_s_p6_0[] = {
  128463. 6,
  128464. 5,
  128465. 7,
  128466. 4,
  128467. 8,
  128468. 3,
  128469. 9,
  128470. 2,
  128471. 10,
  128472. 1,
  128473. 11,
  128474. 0,
  128475. 12,
  128476. };
  128477. static long _vq_lengthlist__44c8_s_p6_0[] = {
  128478. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  128479. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  128480. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  128481. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  128482. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  128483. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  128484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128488. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128489. };
  128490. static float _vq_quantthresh__44c8_s_p6_0[] = {
  128491. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128492. 12.5, 17.5, 22.5, 27.5,
  128493. };
  128494. static long _vq_quantmap__44c8_s_p6_0[] = {
  128495. 11, 9, 7, 5, 3, 1, 0, 2,
  128496. 4, 6, 8, 10, 12,
  128497. };
  128498. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  128499. _vq_quantthresh__44c8_s_p6_0,
  128500. _vq_quantmap__44c8_s_p6_0,
  128501. 13,
  128502. 13
  128503. };
  128504. static static_codebook _44c8_s_p6_0 = {
  128505. 2, 169,
  128506. _vq_lengthlist__44c8_s_p6_0,
  128507. 1, -526516224, 1616117760, 4, 0,
  128508. _vq_quantlist__44c8_s_p6_0,
  128509. NULL,
  128510. &_vq_auxt__44c8_s_p6_0,
  128511. NULL,
  128512. 0
  128513. };
  128514. static long _vq_quantlist__44c8_s_p6_1[] = {
  128515. 2,
  128516. 1,
  128517. 3,
  128518. 0,
  128519. 4,
  128520. };
  128521. static long _vq_lengthlist__44c8_s_p6_1[] = {
  128522. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  128523. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128524. };
  128525. static float _vq_quantthresh__44c8_s_p6_1[] = {
  128526. -1.5, -0.5, 0.5, 1.5,
  128527. };
  128528. static long _vq_quantmap__44c8_s_p6_1[] = {
  128529. 3, 1, 0, 2, 4,
  128530. };
  128531. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  128532. _vq_quantthresh__44c8_s_p6_1,
  128533. _vq_quantmap__44c8_s_p6_1,
  128534. 5,
  128535. 5
  128536. };
  128537. static static_codebook _44c8_s_p6_1 = {
  128538. 2, 25,
  128539. _vq_lengthlist__44c8_s_p6_1,
  128540. 1, -533725184, 1611661312, 3, 0,
  128541. _vq_quantlist__44c8_s_p6_1,
  128542. NULL,
  128543. &_vq_auxt__44c8_s_p6_1,
  128544. NULL,
  128545. 0
  128546. };
  128547. static long _vq_quantlist__44c8_s_p7_0[] = {
  128548. 6,
  128549. 5,
  128550. 7,
  128551. 4,
  128552. 8,
  128553. 3,
  128554. 9,
  128555. 2,
  128556. 10,
  128557. 1,
  128558. 11,
  128559. 0,
  128560. 12,
  128561. };
  128562. static long _vq_lengthlist__44c8_s_p7_0[] = {
  128563. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  128564. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  128565. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  128566. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  128567. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  128568. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  128569. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  128570. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  128571. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  128572. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  128573. 20,13,13,13,13,14,13,15,15,
  128574. };
  128575. static float _vq_quantthresh__44c8_s_p7_0[] = {
  128576. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  128577. 27.5, 38.5, 49.5, 60.5,
  128578. };
  128579. static long _vq_quantmap__44c8_s_p7_0[] = {
  128580. 11, 9, 7, 5, 3, 1, 0, 2,
  128581. 4, 6, 8, 10, 12,
  128582. };
  128583. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  128584. _vq_quantthresh__44c8_s_p7_0,
  128585. _vq_quantmap__44c8_s_p7_0,
  128586. 13,
  128587. 13
  128588. };
  128589. static static_codebook _44c8_s_p7_0 = {
  128590. 2, 169,
  128591. _vq_lengthlist__44c8_s_p7_0,
  128592. 1, -523206656, 1618345984, 4, 0,
  128593. _vq_quantlist__44c8_s_p7_0,
  128594. NULL,
  128595. &_vq_auxt__44c8_s_p7_0,
  128596. NULL,
  128597. 0
  128598. };
  128599. static long _vq_quantlist__44c8_s_p7_1[] = {
  128600. 5,
  128601. 4,
  128602. 6,
  128603. 3,
  128604. 7,
  128605. 2,
  128606. 8,
  128607. 1,
  128608. 9,
  128609. 0,
  128610. 10,
  128611. };
  128612. static long _vq_lengthlist__44c8_s_p7_1[] = {
  128613. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  128614. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  128615. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  128616. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  128617. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  128618. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  128619. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  128620. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  128621. };
  128622. static float _vq_quantthresh__44c8_s_p7_1[] = {
  128623. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128624. 3.5, 4.5,
  128625. };
  128626. static long _vq_quantmap__44c8_s_p7_1[] = {
  128627. 9, 7, 5, 3, 1, 0, 2, 4,
  128628. 6, 8, 10,
  128629. };
  128630. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  128631. _vq_quantthresh__44c8_s_p7_1,
  128632. _vq_quantmap__44c8_s_p7_1,
  128633. 11,
  128634. 11
  128635. };
  128636. static static_codebook _44c8_s_p7_1 = {
  128637. 2, 121,
  128638. _vq_lengthlist__44c8_s_p7_1,
  128639. 1, -531365888, 1611661312, 4, 0,
  128640. _vq_quantlist__44c8_s_p7_1,
  128641. NULL,
  128642. &_vq_auxt__44c8_s_p7_1,
  128643. NULL,
  128644. 0
  128645. };
  128646. static long _vq_quantlist__44c8_s_p8_0[] = {
  128647. 7,
  128648. 6,
  128649. 8,
  128650. 5,
  128651. 9,
  128652. 4,
  128653. 10,
  128654. 3,
  128655. 11,
  128656. 2,
  128657. 12,
  128658. 1,
  128659. 13,
  128660. 0,
  128661. 14,
  128662. };
  128663. static long _vq_lengthlist__44c8_s_p8_0[] = {
  128664. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  128665. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  128666. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  128667. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  128668. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  128669. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  128670. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  128671. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  128672. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  128673. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  128674. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  128675. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  128676. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  128677. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  128678. 15,
  128679. };
  128680. static float _vq_quantthresh__44c8_s_p8_0[] = {
  128681. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  128682. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  128683. };
  128684. static long _vq_quantmap__44c8_s_p8_0[] = {
  128685. 13, 11, 9, 7, 5, 3, 1, 0,
  128686. 2, 4, 6, 8, 10, 12, 14,
  128687. };
  128688. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  128689. _vq_quantthresh__44c8_s_p8_0,
  128690. _vq_quantmap__44c8_s_p8_0,
  128691. 15,
  128692. 15
  128693. };
  128694. static static_codebook _44c8_s_p8_0 = {
  128695. 2, 225,
  128696. _vq_lengthlist__44c8_s_p8_0,
  128697. 1, -520986624, 1620377600, 4, 0,
  128698. _vq_quantlist__44c8_s_p8_0,
  128699. NULL,
  128700. &_vq_auxt__44c8_s_p8_0,
  128701. NULL,
  128702. 0
  128703. };
  128704. static long _vq_quantlist__44c8_s_p8_1[] = {
  128705. 10,
  128706. 9,
  128707. 11,
  128708. 8,
  128709. 12,
  128710. 7,
  128711. 13,
  128712. 6,
  128713. 14,
  128714. 5,
  128715. 15,
  128716. 4,
  128717. 16,
  128718. 3,
  128719. 17,
  128720. 2,
  128721. 18,
  128722. 1,
  128723. 19,
  128724. 0,
  128725. 20,
  128726. };
  128727. static long _vq_lengthlist__44c8_s_p8_1[] = {
  128728. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  128729. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  128730. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  128731. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  128732. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128733. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  128734. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  128735. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  128736. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128737. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128738. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  128739. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  128740. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  128741. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128742. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  128743. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  128744. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  128745. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  128746. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  128747. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  128748. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  128749. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  128750. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  128751. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  128752. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  128753. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  128754. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  128755. 10, 9, 9,10,10, 9,10, 9, 9,
  128756. };
  128757. static float _vq_quantthresh__44c8_s_p8_1[] = {
  128758. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128759. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128760. 6.5, 7.5, 8.5, 9.5,
  128761. };
  128762. static long _vq_quantmap__44c8_s_p8_1[] = {
  128763. 19, 17, 15, 13, 11, 9, 7, 5,
  128764. 3, 1, 0, 2, 4, 6, 8, 10,
  128765. 12, 14, 16, 18, 20,
  128766. };
  128767. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  128768. _vq_quantthresh__44c8_s_p8_1,
  128769. _vq_quantmap__44c8_s_p8_1,
  128770. 21,
  128771. 21
  128772. };
  128773. static static_codebook _44c8_s_p8_1 = {
  128774. 2, 441,
  128775. _vq_lengthlist__44c8_s_p8_1,
  128776. 1, -529268736, 1611661312, 5, 0,
  128777. _vq_quantlist__44c8_s_p8_1,
  128778. NULL,
  128779. &_vq_auxt__44c8_s_p8_1,
  128780. NULL,
  128781. 0
  128782. };
  128783. static long _vq_quantlist__44c8_s_p9_0[] = {
  128784. 8,
  128785. 7,
  128786. 9,
  128787. 6,
  128788. 10,
  128789. 5,
  128790. 11,
  128791. 4,
  128792. 12,
  128793. 3,
  128794. 13,
  128795. 2,
  128796. 14,
  128797. 1,
  128798. 15,
  128799. 0,
  128800. 16,
  128801. };
  128802. static long _vq_lengthlist__44c8_s_p9_0[] = {
  128803. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128804. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  128805. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  128806. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128807. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128808. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128809. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128810. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128811. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128812. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128813. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128814. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128815. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128816. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128817. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128818. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128819. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128820. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128821. 10,
  128822. };
  128823. static float _vq_quantthresh__44c8_s_p9_0[] = {
  128824. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  128825. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  128826. };
  128827. static long _vq_quantmap__44c8_s_p9_0[] = {
  128828. 15, 13, 11, 9, 7, 5, 3, 1,
  128829. 0, 2, 4, 6, 8, 10, 12, 14,
  128830. 16,
  128831. };
  128832. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  128833. _vq_quantthresh__44c8_s_p9_0,
  128834. _vq_quantmap__44c8_s_p9_0,
  128835. 17,
  128836. 17
  128837. };
  128838. static static_codebook _44c8_s_p9_0 = {
  128839. 2, 289,
  128840. _vq_lengthlist__44c8_s_p9_0,
  128841. 1, -509798400, 1631393792, 5, 0,
  128842. _vq_quantlist__44c8_s_p9_0,
  128843. NULL,
  128844. &_vq_auxt__44c8_s_p9_0,
  128845. NULL,
  128846. 0
  128847. };
  128848. static long _vq_quantlist__44c8_s_p9_1[] = {
  128849. 9,
  128850. 8,
  128851. 10,
  128852. 7,
  128853. 11,
  128854. 6,
  128855. 12,
  128856. 5,
  128857. 13,
  128858. 4,
  128859. 14,
  128860. 3,
  128861. 15,
  128862. 2,
  128863. 16,
  128864. 1,
  128865. 17,
  128866. 0,
  128867. 18,
  128868. };
  128869. static long _vq_lengthlist__44c8_s_p9_1[] = {
  128870. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  128871. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  128872. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  128873. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  128874. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  128875. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  128876. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  128877. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  128878. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  128879. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  128880. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  128881. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  128882. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  128883. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  128884. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  128885. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  128886. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  128887. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  128888. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  128889. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  128890. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  128891. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  128892. 14,13,13,14,14,15,14,15,14,
  128893. };
  128894. static float _vq_quantthresh__44c8_s_p9_1[] = {
  128895. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  128896. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  128897. 367.5, 416.5,
  128898. };
  128899. static long _vq_quantmap__44c8_s_p9_1[] = {
  128900. 17, 15, 13, 11, 9, 7, 5, 3,
  128901. 1, 0, 2, 4, 6, 8, 10, 12,
  128902. 14, 16, 18,
  128903. };
  128904. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  128905. _vq_quantthresh__44c8_s_p9_1,
  128906. _vq_quantmap__44c8_s_p9_1,
  128907. 19,
  128908. 19
  128909. };
  128910. static static_codebook _44c8_s_p9_1 = {
  128911. 2, 361,
  128912. _vq_lengthlist__44c8_s_p9_1,
  128913. 1, -518287360, 1622704128, 5, 0,
  128914. _vq_quantlist__44c8_s_p9_1,
  128915. NULL,
  128916. &_vq_auxt__44c8_s_p9_1,
  128917. NULL,
  128918. 0
  128919. };
  128920. static long _vq_quantlist__44c8_s_p9_2[] = {
  128921. 24,
  128922. 23,
  128923. 25,
  128924. 22,
  128925. 26,
  128926. 21,
  128927. 27,
  128928. 20,
  128929. 28,
  128930. 19,
  128931. 29,
  128932. 18,
  128933. 30,
  128934. 17,
  128935. 31,
  128936. 16,
  128937. 32,
  128938. 15,
  128939. 33,
  128940. 14,
  128941. 34,
  128942. 13,
  128943. 35,
  128944. 12,
  128945. 36,
  128946. 11,
  128947. 37,
  128948. 10,
  128949. 38,
  128950. 9,
  128951. 39,
  128952. 8,
  128953. 40,
  128954. 7,
  128955. 41,
  128956. 6,
  128957. 42,
  128958. 5,
  128959. 43,
  128960. 4,
  128961. 44,
  128962. 3,
  128963. 45,
  128964. 2,
  128965. 46,
  128966. 1,
  128967. 47,
  128968. 0,
  128969. 48,
  128970. };
  128971. static long _vq_lengthlist__44c8_s_p9_2[] = {
  128972. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  128973. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128974. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128975. 7,
  128976. };
  128977. static float _vq_quantthresh__44c8_s_p9_2[] = {
  128978. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  128979. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  128980. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128981. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128982. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  128983. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  128984. };
  128985. static long _vq_quantmap__44c8_s_p9_2[] = {
  128986. 47, 45, 43, 41, 39, 37, 35, 33,
  128987. 31, 29, 27, 25, 23, 21, 19, 17,
  128988. 15, 13, 11, 9, 7, 5, 3, 1,
  128989. 0, 2, 4, 6, 8, 10, 12, 14,
  128990. 16, 18, 20, 22, 24, 26, 28, 30,
  128991. 32, 34, 36, 38, 40, 42, 44, 46,
  128992. 48,
  128993. };
  128994. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  128995. _vq_quantthresh__44c8_s_p9_2,
  128996. _vq_quantmap__44c8_s_p9_2,
  128997. 49,
  128998. 49
  128999. };
  129000. static static_codebook _44c8_s_p9_2 = {
  129001. 1, 49,
  129002. _vq_lengthlist__44c8_s_p9_2,
  129003. 1, -526909440, 1611661312, 6, 0,
  129004. _vq_quantlist__44c8_s_p9_2,
  129005. NULL,
  129006. &_vq_auxt__44c8_s_p9_2,
  129007. NULL,
  129008. 0
  129009. };
  129010. static long _huff_lengthlist__44c8_s_short[] = {
  129011. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  129012. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  129013. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  129014. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  129015. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  129016. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  129017. 10, 9,11,14,
  129018. };
  129019. static static_codebook _huff_book__44c8_s_short = {
  129020. 2, 100,
  129021. _huff_lengthlist__44c8_s_short,
  129022. 0, 0, 0, 0, 0,
  129023. NULL,
  129024. NULL,
  129025. NULL,
  129026. NULL,
  129027. 0
  129028. };
  129029. static long _huff_lengthlist__44c9_s_long[] = {
  129030. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  129031. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  129032. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  129033. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  129034. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  129035. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  129036. 10, 9, 8, 9,
  129037. };
  129038. static static_codebook _huff_book__44c9_s_long = {
  129039. 2, 100,
  129040. _huff_lengthlist__44c9_s_long,
  129041. 0, 0, 0, 0, 0,
  129042. NULL,
  129043. NULL,
  129044. NULL,
  129045. NULL,
  129046. 0
  129047. };
  129048. static long _vq_quantlist__44c9_s_p1_0[] = {
  129049. 1,
  129050. 0,
  129051. 2,
  129052. };
  129053. static long _vq_lengthlist__44c9_s_p1_0[] = {
  129054. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  129055. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  129056. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  129057. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  129058. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  129059. 7,
  129060. };
  129061. static float _vq_quantthresh__44c9_s_p1_0[] = {
  129062. -0.5, 0.5,
  129063. };
  129064. static long _vq_quantmap__44c9_s_p1_0[] = {
  129065. 1, 0, 2,
  129066. };
  129067. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  129068. _vq_quantthresh__44c9_s_p1_0,
  129069. _vq_quantmap__44c9_s_p1_0,
  129070. 3,
  129071. 3
  129072. };
  129073. static static_codebook _44c9_s_p1_0 = {
  129074. 4, 81,
  129075. _vq_lengthlist__44c9_s_p1_0,
  129076. 1, -535822336, 1611661312, 2, 0,
  129077. _vq_quantlist__44c9_s_p1_0,
  129078. NULL,
  129079. &_vq_auxt__44c9_s_p1_0,
  129080. NULL,
  129081. 0
  129082. };
  129083. static long _vq_quantlist__44c9_s_p2_0[] = {
  129084. 2,
  129085. 1,
  129086. 3,
  129087. 0,
  129088. 4,
  129089. };
  129090. static long _vq_lengthlist__44c9_s_p2_0[] = {
  129091. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  129092. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  129093. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  129094. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  129095. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  129096. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  129097. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  129098. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  129099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129100. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  129101. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  129102. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  129103. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  129104. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  129105. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  129106. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  129107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129108. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  129109. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  129110. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  129111. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  129112. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  129113. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  129114. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129116. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  129117. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  129118. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  129119. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  129120. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  129121. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  129122. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  129127. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  129128. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  129129. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  129130. 12,
  129131. };
  129132. static float _vq_quantthresh__44c9_s_p2_0[] = {
  129133. -1.5, -0.5, 0.5, 1.5,
  129134. };
  129135. static long _vq_quantmap__44c9_s_p2_0[] = {
  129136. 3, 1, 0, 2, 4,
  129137. };
  129138. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  129139. _vq_quantthresh__44c9_s_p2_0,
  129140. _vq_quantmap__44c9_s_p2_0,
  129141. 5,
  129142. 5
  129143. };
  129144. static static_codebook _44c9_s_p2_0 = {
  129145. 4, 625,
  129146. _vq_lengthlist__44c9_s_p2_0,
  129147. 1, -533725184, 1611661312, 3, 0,
  129148. _vq_quantlist__44c9_s_p2_0,
  129149. NULL,
  129150. &_vq_auxt__44c9_s_p2_0,
  129151. NULL,
  129152. 0
  129153. };
  129154. static long _vq_quantlist__44c9_s_p3_0[] = {
  129155. 4,
  129156. 3,
  129157. 5,
  129158. 2,
  129159. 6,
  129160. 1,
  129161. 7,
  129162. 0,
  129163. 8,
  129164. };
  129165. static long _vq_lengthlist__44c9_s_p3_0[] = {
  129166. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  129167. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  129168. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  129169. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  129170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129171. 0,
  129172. };
  129173. static float _vq_quantthresh__44c9_s_p3_0[] = {
  129174. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129175. };
  129176. static long _vq_quantmap__44c9_s_p3_0[] = {
  129177. 7, 5, 3, 1, 0, 2, 4, 6,
  129178. 8,
  129179. };
  129180. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  129181. _vq_quantthresh__44c9_s_p3_0,
  129182. _vq_quantmap__44c9_s_p3_0,
  129183. 9,
  129184. 9
  129185. };
  129186. static static_codebook _44c9_s_p3_0 = {
  129187. 2, 81,
  129188. _vq_lengthlist__44c9_s_p3_0,
  129189. 1, -531628032, 1611661312, 4, 0,
  129190. _vq_quantlist__44c9_s_p3_0,
  129191. NULL,
  129192. &_vq_auxt__44c9_s_p3_0,
  129193. NULL,
  129194. 0
  129195. };
  129196. static long _vq_quantlist__44c9_s_p4_0[] = {
  129197. 8,
  129198. 7,
  129199. 9,
  129200. 6,
  129201. 10,
  129202. 5,
  129203. 11,
  129204. 4,
  129205. 12,
  129206. 3,
  129207. 13,
  129208. 2,
  129209. 14,
  129210. 1,
  129211. 15,
  129212. 0,
  129213. 16,
  129214. };
  129215. static long _vq_lengthlist__44c9_s_p4_0[] = {
  129216. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  129217. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  129218. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  129219. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  129220. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  129221. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  129222. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  129223. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129224. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  129225. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  129226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129234. 0,
  129235. };
  129236. static float _vq_quantthresh__44c9_s_p4_0[] = {
  129237. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129238. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129239. };
  129240. static long _vq_quantmap__44c9_s_p4_0[] = {
  129241. 15, 13, 11, 9, 7, 5, 3, 1,
  129242. 0, 2, 4, 6, 8, 10, 12, 14,
  129243. 16,
  129244. };
  129245. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  129246. _vq_quantthresh__44c9_s_p4_0,
  129247. _vq_quantmap__44c9_s_p4_0,
  129248. 17,
  129249. 17
  129250. };
  129251. static static_codebook _44c9_s_p4_0 = {
  129252. 2, 289,
  129253. _vq_lengthlist__44c9_s_p4_0,
  129254. 1, -529530880, 1611661312, 5, 0,
  129255. _vq_quantlist__44c9_s_p4_0,
  129256. NULL,
  129257. &_vq_auxt__44c9_s_p4_0,
  129258. NULL,
  129259. 0
  129260. };
  129261. static long _vq_quantlist__44c9_s_p5_0[] = {
  129262. 1,
  129263. 0,
  129264. 2,
  129265. };
  129266. static long _vq_lengthlist__44c9_s_p5_0[] = {
  129267. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  129268. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  129269. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  129270. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  129271. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  129272. 12,
  129273. };
  129274. static float _vq_quantthresh__44c9_s_p5_0[] = {
  129275. -5.5, 5.5,
  129276. };
  129277. static long _vq_quantmap__44c9_s_p5_0[] = {
  129278. 1, 0, 2,
  129279. };
  129280. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  129281. _vq_quantthresh__44c9_s_p5_0,
  129282. _vq_quantmap__44c9_s_p5_0,
  129283. 3,
  129284. 3
  129285. };
  129286. static static_codebook _44c9_s_p5_0 = {
  129287. 4, 81,
  129288. _vq_lengthlist__44c9_s_p5_0,
  129289. 1, -529137664, 1618345984, 2, 0,
  129290. _vq_quantlist__44c9_s_p5_0,
  129291. NULL,
  129292. &_vq_auxt__44c9_s_p5_0,
  129293. NULL,
  129294. 0
  129295. };
  129296. static long _vq_quantlist__44c9_s_p5_1[] = {
  129297. 5,
  129298. 4,
  129299. 6,
  129300. 3,
  129301. 7,
  129302. 2,
  129303. 8,
  129304. 1,
  129305. 9,
  129306. 0,
  129307. 10,
  129308. };
  129309. static long _vq_lengthlist__44c9_s_p5_1[] = {
  129310. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  129311. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  129312. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  129313. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  129314. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  129315. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  129316. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  129317. 11,11,11, 7, 7, 7, 7, 7, 7,
  129318. };
  129319. static float _vq_quantthresh__44c9_s_p5_1[] = {
  129320. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129321. 3.5, 4.5,
  129322. };
  129323. static long _vq_quantmap__44c9_s_p5_1[] = {
  129324. 9, 7, 5, 3, 1, 0, 2, 4,
  129325. 6, 8, 10,
  129326. };
  129327. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  129328. _vq_quantthresh__44c9_s_p5_1,
  129329. _vq_quantmap__44c9_s_p5_1,
  129330. 11,
  129331. 11
  129332. };
  129333. static static_codebook _44c9_s_p5_1 = {
  129334. 2, 121,
  129335. _vq_lengthlist__44c9_s_p5_1,
  129336. 1, -531365888, 1611661312, 4, 0,
  129337. _vq_quantlist__44c9_s_p5_1,
  129338. NULL,
  129339. &_vq_auxt__44c9_s_p5_1,
  129340. NULL,
  129341. 0
  129342. };
  129343. static long _vq_quantlist__44c9_s_p6_0[] = {
  129344. 6,
  129345. 5,
  129346. 7,
  129347. 4,
  129348. 8,
  129349. 3,
  129350. 9,
  129351. 2,
  129352. 10,
  129353. 1,
  129354. 11,
  129355. 0,
  129356. 12,
  129357. };
  129358. static long _vq_lengthlist__44c9_s_p6_0[] = {
  129359. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  129360. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  129361. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  129362. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  129363. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  129364. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  129365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129370. };
  129371. static float _vq_quantthresh__44c9_s_p6_0[] = {
  129372. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129373. 12.5, 17.5, 22.5, 27.5,
  129374. };
  129375. static long _vq_quantmap__44c9_s_p6_0[] = {
  129376. 11, 9, 7, 5, 3, 1, 0, 2,
  129377. 4, 6, 8, 10, 12,
  129378. };
  129379. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  129380. _vq_quantthresh__44c9_s_p6_0,
  129381. _vq_quantmap__44c9_s_p6_0,
  129382. 13,
  129383. 13
  129384. };
  129385. static static_codebook _44c9_s_p6_0 = {
  129386. 2, 169,
  129387. _vq_lengthlist__44c9_s_p6_0,
  129388. 1, -526516224, 1616117760, 4, 0,
  129389. _vq_quantlist__44c9_s_p6_0,
  129390. NULL,
  129391. &_vq_auxt__44c9_s_p6_0,
  129392. NULL,
  129393. 0
  129394. };
  129395. static long _vq_quantlist__44c9_s_p6_1[] = {
  129396. 2,
  129397. 1,
  129398. 3,
  129399. 0,
  129400. 4,
  129401. };
  129402. static long _vq_lengthlist__44c9_s_p6_1[] = {
  129403. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  129404. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  129405. };
  129406. static float _vq_quantthresh__44c9_s_p6_1[] = {
  129407. -1.5, -0.5, 0.5, 1.5,
  129408. };
  129409. static long _vq_quantmap__44c9_s_p6_1[] = {
  129410. 3, 1, 0, 2, 4,
  129411. };
  129412. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  129413. _vq_quantthresh__44c9_s_p6_1,
  129414. _vq_quantmap__44c9_s_p6_1,
  129415. 5,
  129416. 5
  129417. };
  129418. static static_codebook _44c9_s_p6_1 = {
  129419. 2, 25,
  129420. _vq_lengthlist__44c9_s_p6_1,
  129421. 1, -533725184, 1611661312, 3, 0,
  129422. _vq_quantlist__44c9_s_p6_1,
  129423. NULL,
  129424. &_vq_auxt__44c9_s_p6_1,
  129425. NULL,
  129426. 0
  129427. };
  129428. static long _vq_quantlist__44c9_s_p7_0[] = {
  129429. 6,
  129430. 5,
  129431. 7,
  129432. 4,
  129433. 8,
  129434. 3,
  129435. 9,
  129436. 2,
  129437. 10,
  129438. 1,
  129439. 11,
  129440. 0,
  129441. 12,
  129442. };
  129443. static long _vq_lengthlist__44c9_s_p7_0[] = {
  129444. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  129445. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  129446. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  129447. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  129448. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  129449. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  129450. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  129451. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  129452. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  129453. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  129454. 19,12,12,12,12,13,13,14,14,
  129455. };
  129456. static float _vq_quantthresh__44c9_s_p7_0[] = {
  129457. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  129458. 27.5, 38.5, 49.5, 60.5,
  129459. };
  129460. static long _vq_quantmap__44c9_s_p7_0[] = {
  129461. 11, 9, 7, 5, 3, 1, 0, 2,
  129462. 4, 6, 8, 10, 12,
  129463. };
  129464. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  129465. _vq_quantthresh__44c9_s_p7_0,
  129466. _vq_quantmap__44c9_s_p7_0,
  129467. 13,
  129468. 13
  129469. };
  129470. static static_codebook _44c9_s_p7_0 = {
  129471. 2, 169,
  129472. _vq_lengthlist__44c9_s_p7_0,
  129473. 1, -523206656, 1618345984, 4, 0,
  129474. _vq_quantlist__44c9_s_p7_0,
  129475. NULL,
  129476. &_vq_auxt__44c9_s_p7_0,
  129477. NULL,
  129478. 0
  129479. };
  129480. static long _vq_quantlist__44c9_s_p7_1[] = {
  129481. 5,
  129482. 4,
  129483. 6,
  129484. 3,
  129485. 7,
  129486. 2,
  129487. 8,
  129488. 1,
  129489. 9,
  129490. 0,
  129491. 10,
  129492. };
  129493. static long _vq_lengthlist__44c9_s_p7_1[] = {
  129494. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  129495. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  129496. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  129497. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129498. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  129499. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  129500. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  129501. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129502. };
  129503. static float _vq_quantthresh__44c9_s_p7_1[] = {
  129504. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129505. 3.5, 4.5,
  129506. };
  129507. static long _vq_quantmap__44c9_s_p7_1[] = {
  129508. 9, 7, 5, 3, 1, 0, 2, 4,
  129509. 6, 8, 10,
  129510. };
  129511. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  129512. _vq_quantthresh__44c9_s_p7_1,
  129513. _vq_quantmap__44c9_s_p7_1,
  129514. 11,
  129515. 11
  129516. };
  129517. static static_codebook _44c9_s_p7_1 = {
  129518. 2, 121,
  129519. _vq_lengthlist__44c9_s_p7_1,
  129520. 1, -531365888, 1611661312, 4, 0,
  129521. _vq_quantlist__44c9_s_p7_1,
  129522. NULL,
  129523. &_vq_auxt__44c9_s_p7_1,
  129524. NULL,
  129525. 0
  129526. };
  129527. static long _vq_quantlist__44c9_s_p8_0[] = {
  129528. 7,
  129529. 6,
  129530. 8,
  129531. 5,
  129532. 9,
  129533. 4,
  129534. 10,
  129535. 3,
  129536. 11,
  129537. 2,
  129538. 12,
  129539. 1,
  129540. 13,
  129541. 0,
  129542. 14,
  129543. };
  129544. static long _vq_lengthlist__44c9_s_p8_0[] = {
  129545. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  129546. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  129547. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  129548. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  129549. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  129550. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  129551. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  129552. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  129553. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  129554. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  129555. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  129556. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  129557. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  129558. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  129559. 14,
  129560. };
  129561. static float _vq_quantthresh__44c9_s_p8_0[] = {
  129562. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  129563. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  129564. };
  129565. static long _vq_quantmap__44c9_s_p8_0[] = {
  129566. 13, 11, 9, 7, 5, 3, 1, 0,
  129567. 2, 4, 6, 8, 10, 12, 14,
  129568. };
  129569. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  129570. _vq_quantthresh__44c9_s_p8_0,
  129571. _vq_quantmap__44c9_s_p8_0,
  129572. 15,
  129573. 15
  129574. };
  129575. static static_codebook _44c9_s_p8_0 = {
  129576. 2, 225,
  129577. _vq_lengthlist__44c9_s_p8_0,
  129578. 1, -520986624, 1620377600, 4, 0,
  129579. _vq_quantlist__44c9_s_p8_0,
  129580. NULL,
  129581. &_vq_auxt__44c9_s_p8_0,
  129582. NULL,
  129583. 0
  129584. };
  129585. static long _vq_quantlist__44c9_s_p8_1[] = {
  129586. 10,
  129587. 9,
  129588. 11,
  129589. 8,
  129590. 12,
  129591. 7,
  129592. 13,
  129593. 6,
  129594. 14,
  129595. 5,
  129596. 15,
  129597. 4,
  129598. 16,
  129599. 3,
  129600. 17,
  129601. 2,
  129602. 18,
  129603. 1,
  129604. 19,
  129605. 0,
  129606. 20,
  129607. };
  129608. static long _vq_lengthlist__44c9_s_p8_1[] = {
  129609. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  129610. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  129611. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  129612. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  129613. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129614. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  129615. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  129616. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  129617. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129618. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129619. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  129620. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  129621. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129622. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129623. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  129624. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  129625. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  129626. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  129627. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  129628. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  129629. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  129630. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  129631. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  129632. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  129633. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  129634. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  129635. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  129636. 9, 9, 9,10, 9, 9, 9, 9, 9,
  129637. };
  129638. static float _vq_quantthresh__44c9_s_p8_1[] = {
  129639. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  129640. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  129641. 6.5, 7.5, 8.5, 9.5,
  129642. };
  129643. static long _vq_quantmap__44c9_s_p8_1[] = {
  129644. 19, 17, 15, 13, 11, 9, 7, 5,
  129645. 3, 1, 0, 2, 4, 6, 8, 10,
  129646. 12, 14, 16, 18, 20,
  129647. };
  129648. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  129649. _vq_quantthresh__44c9_s_p8_1,
  129650. _vq_quantmap__44c9_s_p8_1,
  129651. 21,
  129652. 21
  129653. };
  129654. static static_codebook _44c9_s_p8_1 = {
  129655. 2, 441,
  129656. _vq_lengthlist__44c9_s_p8_1,
  129657. 1, -529268736, 1611661312, 5, 0,
  129658. _vq_quantlist__44c9_s_p8_1,
  129659. NULL,
  129660. &_vq_auxt__44c9_s_p8_1,
  129661. NULL,
  129662. 0
  129663. };
  129664. static long _vq_quantlist__44c9_s_p9_0[] = {
  129665. 9,
  129666. 8,
  129667. 10,
  129668. 7,
  129669. 11,
  129670. 6,
  129671. 12,
  129672. 5,
  129673. 13,
  129674. 4,
  129675. 14,
  129676. 3,
  129677. 15,
  129678. 2,
  129679. 16,
  129680. 1,
  129681. 17,
  129682. 0,
  129683. 18,
  129684. };
  129685. static long _vq_lengthlist__44c9_s_p9_0[] = {
  129686. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129687. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  129688. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  129689. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  129690. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129691. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129692. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129693. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129694. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129695. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129696. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129697. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129698. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129699. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129700. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129701. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129702. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129703. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129704. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129705. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129706. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129707. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129708. 11,11,11,11,11,11,11,11,11,
  129709. };
  129710. static float _vq_quantthresh__44c9_s_p9_0[] = {
  129711. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  129712. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  129713. 6982.5, 7913.5,
  129714. };
  129715. static long _vq_quantmap__44c9_s_p9_0[] = {
  129716. 17, 15, 13, 11, 9, 7, 5, 3,
  129717. 1, 0, 2, 4, 6, 8, 10, 12,
  129718. 14, 16, 18,
  129719. };
  129720. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  129721. _vq_quantthresh__44c9_s_p9_0,
  129722. _vq_quantmap__44c9_s_p9_0,
  129723. 19,
  129724. 19
  129725. };
  129726. static static_codebook _44c9_s_p9_0 = {
  129727. 2, 361,
  129728. _vq_lengthlist__44c9_s_p9_0,
  129729. 1, -508535424, 1631393792, 5, 0,
  129730. _vq_quantlist__44c9_s_p9_0,
  129731. NULL,
  129732. &_vq_auxt__44c9_s_p9_0,
  129733. NULL,
  129734. 0
  129735. };
  129736. static long _vq_quantlist__44c9_s_p9_1[] = {
  129737. 9,
  129738. 8,
  129739. 10,
  129740. 7,
  129741. 11,
  129742. 6,
  129743. 12,
  129744. 5,
  129745. 13,
  129746. 4,
  129747. 14,
  129748. 3,
  129749. 15,
  129750. 2,
  129751. 16,
  129752. 1,
  129753. 17,
  129754. 0,
  129755. 18,
  129756. };
  129757. static long _vq_lengthlist__44c9_s_p9_1[] = {
  129758. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  129759. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  129760. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  129761. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  129762. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  129763. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  129764. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  129765. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  129766. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  129767. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  129768. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  129769. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  129770. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  129771. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  129772. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  129773. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  129774. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  129775. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  129776. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  129777. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  129778. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  129779. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  129780. 13,13,13,14,13,14,15,15,15,
  129781. };
  129782. static float _vq_quantthresh__44c9_s_p9_1[] = {
  129783. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  129784. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  129785. 367.5, 416.5,
  129786. };
  129787. static long _vq_quantmap__44c9_s_p9_1[] = {
  129788. 17, 15, 13, 11, 9, 7, 5, 3,
  129789. 1, 0, 2, 4, 6, 8, 10, 12,
  129790. 14, 16, 18,
  129791. };
  129792. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  129793. _vq_quantthresh__44c9_s_p9_1,
  129794. _vq_quantmap__44c9_s_p9_1,
  129795. 19,
  129796. 19
  129797. };
  129798. static static_codebook _44c9_s_p9_1 = {
  129799. 2, 361,
  129800. _vq_lengthlist__44c9_s_p9_1,
  129801. 1, -518287360, 1622704128, 5, 0,
  129802. _vq_quantlist__44c9_s_p9_1,
  129803. NULL,
  129804. &_vq_auxt__44c9_s_p9_1,
  129805. NULL,
  129806. 0
  129807. };
  129808. static long _vq_quantlist__44c9_s_p9_2[] = {
  129809. 24,
  129810. 23,
  129811. 25,
  129812. 22,
  129813. 26,
  129814. 21,
  129815. 27,
  129816. 20,
  129817. 28,
  129818. 19,
  129819. 29,
  129820. 18,
  129821. 30,
  129822. 17,
  129823. 31,
  129824. 16,
  129825. 32,
  129826. 15,
  129827. 33,
  129828. 14,
  129829. 34,
  129830. 13,
  129831. 35,
  129832. 12,
  129833. 36,
  129834. 11,
  129835. 37,
  129836. 10,
  129837. 38,
  129838. 9,
  129839. 39,
  129840. 8,
  129841. 40,
  129842. 7,
  129843. 41,
  129844. 6,
  129845. 42,
  129846. 5,
  129847. 43,
  129848. 4,
  129849. 44,
  129850. 3,
  129851. 45,
  129852. 2,
  129853. 46,
  129854. 1,
  129855. 47,
  129856. 0,
  129857. 48,
  129858. };
  129859. static long _vq_lengthlist__44c9_s_p9_2[] = {
  129860. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  129861. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  129862. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129863. 7,
  129864. };
  129865. static float _vq_quantthresh__44c9_s_p9_2[] = {
  129866. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  129867. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  129868. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129869. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129870. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  129871. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  129872. };
  129873. static long _vq_quantmap__44c9_s_p9_2[] = {
  129874. 47, 45, 43, 41, 39, 37, 35, 33,
  129875. 31, 29, 27, 25, 23, 21, 19, 17,
  129876. 15, 13, 11, 9, 7, 5, 3, 1,
  129877. 0, 2, 4, 6, 8, 10, 12, 14,
  129878. 16, 18, 20, 22, 24, 26, 28, 30,
  129879. 32, 34, 36, 38, 40, 42, 44, 46,
  129880. 48,
  129881. };
  129882. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  129883. _vq_quantthresh__44c9_s_p9_2,
  129884. _vq_quantmap__44c9_s_p9_2,
  129885. 49,
  129886. 49
  129887. };
  129888. static static_codebook _44c9_s_p9_2 = {
  129889. 1, 49,
  129890. _vq_lengthlist__44c9_s_p9_2,
  129891. 1, -526909440, 1611661312, 6, 0,
  129892. _vq_quantlist__44c9_s_p9_2,
  129893. NULL,
  129894. &_vq_auxt__44c9_s_p9_2,
  129895. NULL,
  129896. 0
  129897. };
  129898. static long _huff_lengthlist__44c9_s_short[] = {
  129899. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  129900. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  129901. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  129902. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  129903. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  129904. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  129905. 9, 8,10,13,
  129906. };
  129907. static static_codebook _huff_book__44c9_s_short = {
  129908. 2, 100,
  129909. _huff_lengthlist__44c9_s_short,
  129910. 0, 0, 0, 0, 0,
  129911. NULL,
  129912. NULL,
  129913. NULL,
  129914. NULL,
  129915. 0
  129916. };
  129917. static long _huff_lengthlist__44c0_s_long[] = {
  129918. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  129919. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  129920. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  129921. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  129922. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  129923. 12,
  129924. };
  129925. static static_codebook _huff_book__44c0_s_long = {
  129926. 2, 81,
  129927. _huff_lengthlist__44c0_s_long,
  129928. 0, 0, 0, 0, 0,
  129929. NULL,
  129930. NULL,
  129931. NULL,
  129932. NULL,
  129933. 0
  129934. };
  129935. static long _vq_quantlist__44c0_s_p1_0[] = {
  129936. 1,
  129937. 0,
  129938. 2,
  129939. };
  129940. static long _vq_lengthlist__44c0_s_p1_0[] = {
  129941. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129942. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  129947. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129949. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  129952. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129954. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  129987. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  129992. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  129997. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130033. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  130038. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  130043. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0,
  130352. };
  130353. static float _vq_quantthresh__44c0_s_p1_0[] = {
  130354. -0.5, 0.5,
  130355. };
  130356. static long _vq_quantmap__44c0_s_p1_0[] = {
  130357. 1, 0, 2,
  130358. };
  130359. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  130360. _vq_quantthresh__44c0_s_p1_0,
  130361. _vq_quantmap__44c0_s_p1_0,
  130362. 3,
  130363. 3
  130364. };
  130365. static static_codebook _44c0_s_p1_0 = {
  130366. 8, 6561,
  130367. _vq_lengthlist__44c0_s_p1_0,
  130368. 1, -535822336, 1611661312, 2, 0,
  130369. _vq_quantlist__44c0_s_p1_0,
  130370. NULL,
  130371. &_vq_auxt__44c0_s_p1_0,
  130372. NULL,
  130373. 0
  130374. };
  130375. static long _vq_quantlist__44c0_s_p2_0[] = {
  130376. 2,
  130377. 1,
  130378. 3,
  130379. 0,
  130380. 4,
  130381. };
  130382. static long _vq_lengthlist__44c0_s_p2_0[] = {
  130383. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  130385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130386. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  130388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130389. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0,
  130423. };
  130424. static float _vq_quantthresh__44c0_s_p2_0[] = {
  130425. -1.5, -0.5, 0.5, 1.5,
  130426. };
  130427. static long _vq_quantmap__44c0_s_p2_0[] = {
  130428. 3, 1, 0, 2, 4,
  130429. };
  130430. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  130431. _vq_quantthresh__44c0_s_p2_0,
  130432. _vq_quantmap__44c0_s_p2_0,
  130433. 5,
  130434. 5
  130435. };
  130436. static static_codebook _44c0_s_p2_0 = {
  130437. 4, 625,
  130438. _vq_lengthlist__44c0_s_p2_0,
  130439. 1, -533725184, 1611661312, 3, 0,
  130440. _vq_quantlist__44c0_s_p2_0,
  130441. NULL,
  130442. &_vq_auxt__44c0_s_p2_0,
  130443. NULL,
  130444. 0
  130445. };
  130446. static long _vq_quantlist__44c0_s_p3_0[] = {
  130447. 4,
  130448. 3,
  130449. 5,
  130450. 2,
  130451. 6,
  130452. 1,
  130453. 7,
  130454. 0,
  130455. 8,
  130456. };
  130457. static long _vq_lengthlist__44c0_s_p3_0[] = {
  130458. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  130459. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  130460. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  130461. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  130462. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130463. 0,
  130464. };
  130465. static float _vq_quantthresh__44c0_s_p3_0[] = {
  130466. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130467. };
  130468. static long _vq_quantmap__44c0_s_p3_0[] = {
  130469. 7, 5, 3, 1, 0, 2, 4, 6,
  130470. 8,
  130471. };
  130472. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  130473. _vq_quantthresh__44c0_s_p3_0,
  130474. _vq_quantmap__44c0_s_p3_0,
  130475. 9,
  130476. 9
  130477. };
  130478. static static_codebook _44c0_s_p3_0 = {
  130479. 2, 81,
  130480. _vq_lengthlist__44c0_s_p3_0,
  130481. 1, -531628032, 1611661312, 4, 0,
  130482. _vq_quantlist__44c0_s_p3_0,
  130483. NULL,
  130484. &_vq_auxt__44c0_s_p3_0,
  130485. NULL,
  130486. 0
  130487. };
  130488. static long _vq_quantlist__44c0_s_p4_0[] = {
  130489. 4,
  130490. 3,
  130491. 5,
  130492. 2,
  130493. 6,
  130494. 1,
  130495. 7,
  130496. 0,
  130497. 8,
  130498. };
  130499. static long _vq_lengthlist__44c0_s_p4_0[] = {
  130500. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  130501. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  130502. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  130503. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  130504. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  130505. 10,
  130506. };
  130507. static float _vq_quantthresh__44c0_s_p4_0[] = {
  130508. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130509. };
  130510. static long _vq_quantmap__44c0_s_p4_0[] = {
  130511. 7, 5, 3, 1, 0, 2, 4, 6,
  130512. 8,
  130513. };
  130514. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  130515. _vq_quantthresh__44c0_s_p4_0,
  130516. _vq_quantmap__44c0_s_p4_0,
  130517. 9,
  130518. 9
  130519. };
  130520. static static_codebook _44c0_s_p4_0 = {
  130521. 2, 81,
  130522. _vq_lengthlist__44c0_s_p4_0,
  130523. 1, -531628032, 1611661312, 4, 0,
  130524. _vq_quantlist__44c0_s_p4_0,
  130525. NULL,
  130526. &_vq_auxt__44c0_s_p4_0,
  130527. NULL,
  130528. 0
  130529. };
  130530. static long _vq_quantlist__44c0_s_p5_0[] = {
  130531. 8,
  130532. 7,
  130533. 9,
  130534. 6,
  130535. 10,
  130536. 5,
  130537. 11,
  130538. 4,
  130539. 12,
  130540. 3,
  130541. 13,
  130542. 2,
  130543. 14,
  130544. 1,
  130545. 15,
  130546. 0,
  130547. 16,
  130548. };
  130549. static long _vq_lengthlist__44c0_s_p5_0[] = {
  130550. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  130551. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  130552. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  130553. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130554. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130555. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  130556. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  130557. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130558. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130559. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130560. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  130561. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  130562. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  130563. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  130564. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  130565. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  130566. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  130567. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  130568. 14,
  130569. };
  130570. static float _vq_quantthresh__44c0_s_p5_0[] = {
  130571. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130572. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130573. };
  130574. static long _vq_quantmap__44c0_s_p5_0[] = {
  130575. 15, 13, 11, 9, 7, 5, 3, 1,
  130576. 0, 2, 4, 6, 8, 10, 12, 14,
  130577. 16,
  130578. };
  130579. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  130580. _vq_quantthresh__44c0_s_p5_0,
  130581. _vq_quantmap__44c0_s_p5_0,
  130582. 17,
  130583. 17
  130584. };
  130585. static static_codebook _44c0_s_p5_0 = {
  130586. 2, 289,
  130587. _vq_lengthlist__44c0_s_p5_0,
  130588. 1, -529530880, 1611661312, 5, 0,
  130589. _vq_quantlist__44c0_s_p5_0,
  130590. NULL,
  130591. &_vq_auxt__44c0_s_p5_0,
  130592. NULL,
  130593. 0
  130594. };
  130595. static long _vq_quantlist__44c0_s_p6_0[] = {
  130596. 1,
  130597. 0,
  130598. 2,
  130599. };
  130600. static long _vq_lengthlist__44c0_s_p6_0[] = {
  130601. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  130602. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130603. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  130604. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  130605. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  130606. 10,
  130607. };
  130608. static float _vq_quantthresh__44c0_s_p6_0[] = {
  130609. -5.5, 5.5,
  130610. };
  130611. static long _vq_quantmap__44c0_s_p6_0[] = {
  130612. 1, 0, 2,
  130613. };
  130614. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  130615. _vq_quantthresh__44c0_s_p6_0,
  130616. _vq_quantmap__44c0_s_p6_0,
  130617. 3,
  130618. 3
  130619. };
  130620. static static_codebook _44c0_s_p6_0 = {
  130621. 4, 81,
  130622. _vq_lengthlist__44c0_s_p6_0,
  130623. 1, -529137664, 1618345984, 2, 0,
  130624. _vq_quantlist__44c0_s_p6_0,
  130625. NULL,
  130626. &_vq_auxt__44c0_s_p6_0,
  130627. NULL,
  130628. 0
  130629. };
  130630. static long _vq_quantlist__44c0_s_p6_1[] = {
  130631. 5,
  130632. 4,
  130633. 6,
  130634. 3,
  130635. 7,
  130636. 2,
  130637. 8,
  130638. 1,
  130639. 9,
  130640. 0,
  130641. 10,
  130642. };
  130643. static long _vq_lengthlist__44c0_s_p6_1[] = {
  130644. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  130645. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  130646. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  130647. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130648. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130649. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130650. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  130651. 10,10,10, 8, 8, 8, 8, 8, 8,
  130652. };
  130653. static float _vq_quantthresh__44c0_s_p6_1[] = {
  130654. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130655. 3.5, 4.5,
  130656. };
  130657. static long _vq_quantmap__44c0_s_p6_1[] = {
  130658. 9, 7, 5, 3, 1, 0, 2, 4,
  130659. 6, 8, 10,
  130660. };
  130661. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  130662. _vq_quantthresh__44c0_s_p6_1,
  130663. _vq_quantmap__44c0_s_p6_1,
  130664. 11,
  130665. 11
  130666. };
  130667. static static_codebook _44c0_s_p6_1 = {
  130668. 2, 121,
  130669. _vq_lengthlist__44c0_s_p6_1,
  130670. 1, -531365888, 1611661312, 4, 0,
  130671. _vq_quantlist__44c0_s_p6_1,
  130672. NULL,
  130673. &_vq_auxt__44c0_s_p6_1,
  130674. NULL,
  130675. 0
  130676. };
  130677. static long _vq_quantlist__44c0_s_p7_0[] = {
  130678. 6,
  130679. 5,
  130680. 7,
  130681. 4,
  130682. 8,
  130683. 3,
  130684. 9,
  130685. 2,
  130686. 10,
  130687. 1,
  130688. 11,
  130689. 0,
  130690. 12,
  130691. };
  130692. static long _vq_lengthlist__44c0_s_p7_0[] = {
  130693. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  130694. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  130695. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130696. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130697. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  130698. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130699. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  130700. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  130701. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  130702. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  130703. 0,12,12,11,11,12,12,13,13,
  130704. };
  130705. static float _vq_quantthresh__44c0_s_p7_0[] = {
  130706. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130707. 12.5, 17.5, 22.5, 27.5,
  130708. };
  130709. static long _vq_quantmap__44c0_s_p7_0[] = {
  130710. 11, 9, 7, 5, 3, 1, 0, 2,
  130711. 4, 6, 8, 10, 12,
  130712. };
  130713. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  130714. _vq_quantthresh__44c0_s_p7_0,
  130715. _vq_quantmap__44c0_s_p7_0,
  130716. 13,
  130717. 13
  130718. };
  130719. static static_codebook _44c0_s_p7_0 = {
  130720. 2, 169,
  130721. _vq_lengthlist__44c0_s_p7_0,
  130722. 1, -526516224, 1616117760, 4, 0,
  130723. _vq_quantlist__44c0_s_p7_0,
  130724. NULL,
  130725. &_vq_auxt__44c0_s_p7_0,
  130726. NULL,
  130727. 0
  130728. };
  130729. static long _vq_quantlist__44c0_s_p7_1[] = {
  130730. 2,
  130731. 1,
  130732. 3,
  130733. 0,
  130734. 4,
  130735. };
  130736. static long _vq_lengthlist__44c0_s_p7_1[] = {
  130737. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  130738. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  130739. };
  130740. static float _vq_quantthresh__44c0_s_p7_1[] = {
  130741. -1.5, -0.5, 0.5, 1.5,
  130742. };
  130743. static long _vq_quantmap__44c0_s_p7_1[] = {
  130744. 3, 1, 0, 2, 4,
  130745. };
  130746. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  130747. _vq_quantthresh__44c0_s_p7_1,
  130748. _vq_quantmap__44c0_s_p7_1,
  130749. 5,
  130750. 5
  130751. };
  130752. static static_codebook _44c0_s_p7_1 = {
  130753. 2, 25,
  130754. _vq_lengthlist__44c0_s_p7_1,
  130755. 1, -533725184, 1611661312, 3, 0,
  130756. _vq_quantlist__44c0_s_p7_1,
  130757. NULL,
  130758. &_vq_auxt__44c0_s_p7_1,
  130759. NULL,
  130760. 0
  130761. };
  130762. static long _vq_quantlist__44c0_s_p8_0[] = {
  130763. 2,
  130764. 1,
  130765. 3,
  130766. 0,
  130767. 4,
  130768. };
  130769. static long _vq_lengthlist__44c0_s_p8_0[] = {
  130770. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  130771. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130772. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130773. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130774. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130775. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130776. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130777. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  130778. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130779. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130780. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130781. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130782. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  130783. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130784. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130785. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  130786. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130787. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130788. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130789. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130790. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130791. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130792. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130793. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130794. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130795. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130796. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130797. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130798. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130799. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130800. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130801. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130802. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130803. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130804. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130805. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130806. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130807. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130808. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130809. 11,
  130810. };
  130811. static float _vq_quantthresh__44c0_s_p8_0[] = {
  130812. -331.5, -110.5, 110.5, 331.5,
  130813. };
  130814. static long _vq_quantmap__44c0_s_p8_0[] = {
  130815. 3, 1, 0, 2, 4,
  130816. };
  130817. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  130818. _vq_quantthresh__44c0_s_p8_0,
  130819. _vq_quantmap__44c0_s_p8_0,
  130820. 5,
  130821. 5
  130822. };
  130823. static static_codebook _44c0_s_p8_0 = {
  130824. 4, 625,
  130825. _vq_lengthlist__44c0_s_p8_0,
  130826. 1, -518283264, 1627103232, 3, 0,
  130827. _vq_quantlist__44c0_s_p8_0,
  130828. NULL,
  130829. &_vq_auxt__44c0_s_p8_0,
  130830. NULL,
  130831. 0
  130832. };
  130833. static long _vq_quantlist__44c0_s_p8_1[] = {
  130834. 6,
  130835. 5,
  130836. 7,
  130837. 4,
  130838. 8,
  130839. 3,
  130840. 9,
  130841. 2,
  130842. 10,
  130843. 1,
  130844. 11,
  130845. 0,
  130846. 12,
  130847. };
  130848. static long _vq_lengthlist__44c0_s_p8_1[] = {
  130849. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  130850. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  130851. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  130852. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  130853. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  130854. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  130855. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  130856. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  130857. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  130858. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  130859. 16,13,13,12,12,14,14,15,13,
  130860. };
  130861. static float _vq_quantthresh__44c0_s_p8_1[] = {
  130862. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  130863. 42.5, 59.5, 76.5, 93.5,
  130864. };
  130865. static long _vq_quantmap__44c0_s_p8_1[] = {
  130866. 11, 9, 7, 5, 3, 1, 0, 2,
  130867. 4, 6, 8, 10, 12,
  130868. };
  130869. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  130870. _vq_quantthresh__44c0_s_p8_1,
  130871. _vq_quantmap__44c0_s_p8_1,
  130872. 13,
  130873. 13
  130874. };
  130875. static static_codebook _44c0_s_p8_1 = {
  130876. 2, 169,
  130877. _vq_lengthlist__44c0_s_p8_1,
  130878. 1, -522616832, 1620115456, 4, 0,
  130879. _vq_quantlist__44c0_s_p8_1,
  130880. NULL,
  130881. &_vq_auxt__44c0_s_p8_1,
  130882. NULL,
  130883. 0
  130884. };
  130885. static long _vq_quantlist__44c0_s_p8_2[] = {
  130886. 8,
  130887. 7,
  130888. 9,
  130889. 6,
  130890. 10,
  130891. 5,
  130892. 11,
  130893. 4,
  130894. 12,
  130895. 3,
  130896. 13,
  130897. 2,
  130898. 14,
  130899. 1,
  130900. 15,
  130901. 0,
  130902. 16,
  130903. };
  130904. static long _vq_lengthlist__44c0_s_p8_2[] = {
  130905. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130906. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  130907. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130908. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130909. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  130910. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  130911. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  130912. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  130913. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  130914. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  130915. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  130916. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  130917. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  130918. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130919. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  130920. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  130921. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  130922. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  130923. 10,
  130924. };
  130925. static float _vq_quantthresh__44c0_s_p8_2[] = {
  130926. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130927. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130928. };
  130929. static long _vq_quantmap__44c0_s_p8_2[] = {
  130930. 15, 13, 11, 9, 7, 5, 3, 1,
  130931. 0, 2, 4, 6, 8, 10, 12, 14,
  130932. 16,
  130933. };
  130934. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  130935. _vq_quantthresh__44c0_s_p8_2,
  130936. _vq_quantmap__44c0_s_p8_2,
  130937. 17,
  130938. 17
  130939. };
  130940. static static_codebook _44c0_s_p8_2 = {
  130941. 2, 289,
  130942. _vq_lengthlist__44c0_s_p8_2,
  130943. 1, -529530880, 1611661312, 5, 0,
  130944. _vq_quantlist__44c0_s_p8_2,
  130945. NULL,
  130946. &_vq_auxt__44c0_s_p8_2,
  130947. NULL,
  130948. 0
  130949. };
  130950. static long _huff_lengthlist__44c0_s_short[] = {
  130951. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  130952. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  130953. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  130954. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  130955. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  130956. 12,
  130957. };
  130958. static static_codebook _huff_book__44c0_s_short = {
  130959. 2, 81,
  130960. _huff_lengthlist__44c0_s_short,
  130961. 0, 0, 0, 0, 0,
  130962. NULL,
  130963. NULL,
  130964. NULL,
  130965. NULL,
  130966. 0
  130967. };
  130968. static long _huff_lengthlist__44c0_sm_long[] = {
  130969. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  130970. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  130971. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  130972. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  130973. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  130974. 13,
  130975. };
  130976. static static_codebook _huff_book__44c0_sm_long = {
  130977. 2, 81,
  130978. _huff_lengthlist__44c0_sm_long,
  130979. 0, 0, 0, 0, 0,
  130980. NULL,
  130981. NULL,
  130982. NULL,
  130983. NULL,
  130984. 0
  130985. };
  130986. static long _vq_quantlist__44c0_sm_p1_0[] = {
  130987. 1,
  130988. 0,
  130989. 2,
  130990. };
  130991. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  130992. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130993. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130998. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131000. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131003. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131005. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0,
  131038. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  131043. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  131048. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131084. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131089. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131094. 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131402. 0,
  131403. };
  131404. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  131405. -0.5, 0.5,
  131406. };
  131407. static long _vq_quantmap__44c0_sm_p1_0[] = {
  131408. 1, 0, 2,
  131409. };
  131410. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  131411. _vq_quantthresh__44c0_sm_p1_0,
  131412. _vq_quantmap__44c0_sm_p1_0,
  131413. 3,
  131414. 3
  131415. };
  131416. static static_codebook _44c0_sm_p1_0 = {
  131417. 8, 6561,
  131418. _vq_lengthlist__44c0_sm_p1_0,
  131419. 1, -535822336, 1611661312, 2, 0,
  131420. _vq_quantlist__44c0_sm_p1_0,
  131421. NULL,
  131422. &_vq_auxt__44c0_sm_p1_0,
  131423. NULL,
  131424. 0
  131425. };
  131426. static long _vq_quantlist__44c0_sm_p2_0[] = {
  131427. 2,
  131428. 1,
  131429. 3,
  131430. 0,
  131431. 4,
  131432. };
  131433. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  131434. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  131436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131437. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  131439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131440. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  131441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131473. 0,
  131474. };
  131475. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  131476. -1.5, -0.5, 0.5, 1.5,
  131477. };
  131478. static long _vq_quantmap__44c0_sm_p2_0[] = {
  131479. 3, 1, 0, 2, 4,
  131480. };
  131481. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  131482. _vq_quantthresh__44c0_sm_p2_0,
  131483. _vq_quantmap__44c0_sm_p2_0,
  131484. 5,
  131485. 5
  131486. };
  131487. static static_codebook _44c0_sm_p2_0 = {
  131488. 4, 625,
  131489. _vq_lengthlist__44c0_sm_p2_0,
  131490. 1, -533725184, 1611661312, 3, 0,
  131491. _vq_quantlist__44c0_sm_p2_0,
  131492. NULL,
  131493. &_vq_auxt__44c0_sm_p2_0,
  131494. NULL,
  131495. 0
  131496. };
  131497. static long _vq_quantlist__44c0_sm_p3_0[] = {
  131498. 4,
  131499. 3,
  131500. 5,
  131501. 2,
  131502. 6,
  131503. 1,
  131504. 7,
  131505. 0,
  131506. 8,
  131507. };
  131508. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  131509. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  131510. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  131511. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131512. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  131513. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131514. 0,
  131515. };
  131516. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  131517. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131518. };
  131519. static long _vq_quantmap__44c0_sm_p3_0[] = {
  131520. 7, 5, 3, 1, 0, 2, 4, 6,
  131521. 8,
  131522. };
  131523. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  131524. _vq_quantthresh__44c0_sm_p3_0,
  131525. _vq_quantmap__44c0_sm_p3_0,
  131526. 9,
  131527. 9
  131528. };
  131529. static static_codebook _44c0_sm_p3_0 = {
  131530. 2, 81,
  131531. _vq_lengthlist__44c0_sm_p3_0,
  131532. 1, -531628032, 1611661312, 4, 0,
  131533. _vq_quantlist__44c0_sm_p3_0,
  131534. NULL,
  131535. &_vq_auxt__44c0_sm_p3_0,
  131536. NULL,
  131537. 0
  131538. };
  131539. static long _vq_quantlist__44c0_sm_p4_0[] = {
  131540. 4,
  131541. 3,
  131542. 5,
  131543. 2,
  131544. 6,
  131545. 1,
  131546. 7,
  131547. 0,
  131548. 8,
  131549. };
  131550. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  131551. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  131552. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  131553. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  131554. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  131555. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  131556. 11,
  131557. };
  131558. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  131559. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131560. };
  131561. static long _vq_quantmap__44c0_sm_p4_0[] = {
  131562. 7, 5, 3, 1, 0, 2, 4, 6,
  131563. 8,
  131564. };
  131565. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  131566. _vq_quantthresh__44c0_sm_p4_0,
  131567. _vq_quantmap__44c0_sm_p4_0,
  131568. 9,
  131569. 9
  131570. };
  131571. static static_codebook _44c0_sm_p4_0 = {
  131572. 2, 81,
  131573. _vq_lengthlist__44c0_sm_p4_0,
  131574. 1, -531628032, 1611661312, 4, 0,
  131575. _vq_quantlist__44c0_sm_p4_0,
  131576. NULL,
  131577. &_vq_auxt__44c0_sm_p4_0,
  131578. NULL,
  131579. 0
  131580. };
  131581. static long _vq_quantlist__44c0_sm_p5_0[] = {
  131582. 8,
  131583. 7,
  131584. 9,
  131585. 6,
  131586. 10,
  131587. 5,
  131588. 11,
  131589. 4,
  131590. 12,
  131591. 3,
  131592. 13,
  131593. 2,
  131594. 14,
  131595. 1,
  131596. 15,
  131597. 0,
  131598. 16,
  131599. };
  131600. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  131601. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  131602. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  131603. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  131604. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  131605. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  131606. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  131607. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  131608. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  131609. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  131610. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  131611. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  131612. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  131613. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  131614. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  131615. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  131616. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  131617. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  131618. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  131619. 14,
  131620. };
  131621. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  131622. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131623. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131624. };
  131625. static long _vq_quantmap__44c0_sm_p5_0[] = {
  131626. 15, 13, 11, 9, 7, 5, 3, 1,
  131627. 0, 2, 4, 6, 8, 10, 12, 14,
  131628. 16,
  131629. };
  131630. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  131631. _vq_quantthresh__44c0_sm_p5_0,
  131632. _vq_quantmap__44c0_sm_p5_0,
  131633. 17,
  131634. 17
  131635. };
  131636. static static_codebook _44c0_sm_p5_0 = {
  131637. 2, 289,
  131638. _vq_lengthlist__44c0_sm_p5_0,
  131639. 1, -529530880, 1611661312, 5, 0,
  131640. _vq_quantlist__44c0_sm_p5_0,
  131641. NULL,
  131642. &_vq_auxt__44c0_sm_p5_0,
  131643. NULL,
  131644. 0
  131645. };
  131646. static long _vq_quantlist__44c0_sm_p6_0[] = {
  131647. 1,
  131648. 0,
  131649. 2,
  131650. };
  131651. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  131652. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131653. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  131654. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  131655. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  131656. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  131657. 11,
  131658. };
  131659. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  131660. -5.5, 5.5,
  131661. };
  131662. static long _vq_quantmap__44c0_sm_p6_0[] = {
  131663. 1, 0, 2,
  131664. };
  131665. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  131666. _vq_quantthresh__44c0_sm_p6_0,
  131667. _vq_quantmap__44c0_sm_p6_0,
  131668. 3,
  131669. 3
  131670. };
  131671. static static_codebook _44c0_sm_p6_0 = {
  131672. 4, 81,
  131673. _vq_lengthlist__44c0_sm_p6_0,
  131674. 1, -529137664, 1618345984, 2, 0,
  131675. _vq_quantlist__44c0_sm_p6_0,
  131676. NULL,
  131677. &_vq_auxt__44c0_sm_p6_0,
  131678. NULL,
  131679. 0
  131680. };
  131681. static long _vq_quantlist__44c0_sm_p6_1[] = {
  131682. 5,
  131683. 4,
  131684. 6,
  131685. 3,
  131686. 7,
  131687. 2,
  131688. 8,
  131689. 1,
  131690. 9,
  131691. 0,
  131692. 10,
  131693. };
  131694. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  131695. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  131696. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131697. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  131698. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  131699. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  131700. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  131701. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131702. 10,10,10, 8, 8, 8, 8, 8, 8,
  131703. };
  131704. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  131705. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131706. 3.5, 4.5,
  131707. };
  131708. static long _vq_quantmap__44c0_sm_p6_1[] = {
  131709. 9, 7, 5, 3, 1, 0, 2, 4,
  131710. 6, 8, 10,
  131711. };
  131712. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  131713. _vq_quantthresh__44c0_sm_p6_1,
  131714. _vq_quantmap__44c0_sm_p6_1,
  131715. 11,
  131716. 11
  131717. };
  131718. static static_codebook _44c0_sm_p6_1 = {
  131719. 2, 121,
  131720. _vq_lengthlist__44c0_sm_p6_1,
  131721. 1, -531365888, 1611661312, 4, 0,
  131722. _vq_quantlist__44c0_sm_p6_1,
  131723. NULL,
  131724. &_vq_auxt__44c0_sm_p6_1,
  131725. NULL,
  131726. 0
  131727. };
  131728. static long _vq_quantlist__44c0_sm_p7_0[] = {
  131729. 6,
  131730. 5,
  131731. 7,
  131732. 4,
  131733. 8,
  131734. 3,
  131735. 9,
  131736. 2,
  131737. 10,
  131738. 1,
  131739. 11,
  131740. 0,
  131741. 12,
  131742. };
  131743. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  131744. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  131745. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  131746. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131747. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131748. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  131749. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  131750. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  131751. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  131752. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  131753. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  131754. 0,12,12,11,11,13,12,14,14,
  131755. };
  131756. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  131757. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131758. 12.5, 17.5, 22.5, 27.5,
  131759. };
  131760. static long _vq_quantmap__44c0_sm_p7_0[] = {
  131761. 11, 9, 7, 5, 3, 1, 0, 2,
  131762. 4, 6, 8, 10, 12,
  131763. };
  131764. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  131765. _vq_quantthresh__44c0_sm_p7_0,
  131766. _vq_quantmap__44c0_sm_p7_0,
  131767. 13,
  131768. 13
  131769. };
  131770. static static_codebook _44c0_sm_p7_0 = {
  131771. 2, 169,
  131772. _vq_lengthlist__44c0_sm_p7_0,
  131773. 1, -526516224, 1616117760, 4, 0,
  131774. _vq_quantlist__44c0_sm_p7_0,
  131775. NULL,
  131776. &_vq_auxt__44c0_sm_p7_0,
  131777. NULL,
  131778. 0
  131779. };
  131780. static long _vq_quantlist__44c0_sm_p7_1[] = {
  131781. 2,
  131782. 1,
  131783. 3,
  131784. 0,
  131785. 4,
  131786. };
  131787. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  131788. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  131789. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  131790. };
  131791. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  131792. -1.5, -0.5, 0.5, 1.5,
  131793. };
  131794. static long _vq_quantmap__44c0_sm_p7_1[] = {
  131795. 3, 1, 0, 2, 4,
  131796. };
  131797. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  131798. _vq_quantthresh__44c0_sm_p7_1,
  131799. _vq_quantmap__44c0_sm_p7_1,
  131800. 5,
  131801. 5
  131802. };
  131803. static static_codebook _44c0_sm_p7_1 = {
  131804. 2, 25,
  131805. _vq_lengthlist__44c0_sm_p7_1,
  131806. 1, -533725184, 1611661312, 3, 0,
  131807. _vq_quantlist__44c0_sm_p7_1,
  131808. NULL,
  131809. &_vq_auxt__44c0_sm_p7_1,
  131810. NULL,
  131811. 0
  131812. };
  131813. static long _vq_quantlist__44c0_sm_p8_0[] = {
  131814. 4,
  131815. 3,
  131816. 5,
  131817. 2,
  131818. 6,
  131819. 1,
  131820. 7,
  131821. 0,
  131822. 8,
  131823. };
  131824. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  131825. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  131826. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  131827. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131828. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131829. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131830. 12,
  131831. };
  131832. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  131833. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  131834. };
  131835. static long _vq_quantmap__44c0_sm_p8_0[] = {
  131836. 7, 5, 3, 1, 0, 2, 4, 6,
  131837. 8,
  131838. };
  131839. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  131840. _vq_quantthresh__44c0_sm_p8_0,
  131841. _vq_quantmap__44c0_sm_p8_0,
  131842. 9,
  131843. 9
  131844. };
  131845. static static_codebook _44c0_sm_p8_0 = {
  131846. 2, 81,
  131847. _vq_lengthlist__44c0_sm_p8_0,
  131848. 1, -516186112, 1627103232, 4, 0,
  131849. _vq_quantlist__44c0_sm_p8_0,
  131850. NULL,
  131851. &_vq_auxt__44c0_sm_p8_0,
  131852. NULL,
  131853. 0
  131854. };
  131855. static long _vq_quantlist__44c0_sm_p8_1[] = {
  131856. 6,
  131857. 5,
  131858. 7,
  131859. 4,
  131860. 8,
  131861. 3,
  131862. 9,
  131863. 2,
  131864. 10,
  131865. 1,
  131866. 11,
  131867. 0,
  131868. 12,
  131869. };
  131870. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  131871. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  131872. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  131873. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  131874. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  131875. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  131876. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  131877. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  131878. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  131879. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  131880. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  131881. 20,13,13,12,12,16,13,15,13,
  131882. };
  131883. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  131884. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  131885. 42.5, 59.5, 76.5, 93.5,
  131886. };
  131887. static long _vq_quantmap__44c0_sm_p8_1[] = {
  131888. 11, 9, 7, 5, 3, 1, 0, 2,
  131889. 4, 6, 8, 10, 12,
  131890. };
  131891. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  131892. _vq_quantthresh__44c0_sm_p8_1,
  131893. _vq_quantmap__44c0_sm_p8_1,
  131894. 13,
  131895. 13
  131896. };
  131897. static static_codebook _44c0_sm_p8_1 = {
  131898. 2, 169,
  131899. _vq_lengthlist__44c0_sm_p8_1,
  131900. 1, -522616832, 1620115456, 4, 0,
  131901. _vq_quantlist__44c0_sm_p8_1,
  131902. NULL,
  131903. &_vq_auxt__44c0_sm_p8_1,
  131904. NULL,
  131905. 0
  131906. };
  131907. static long _vq_quantlist__44c0_sm_p8_2[] = {
  131908. 8,
  131909. 7,
  131910. 9,
  131911. 6,
  131912. 10,
  131913. 5,
  131914. 11,
  131915. 4,
  131916. 12,
  131917. 3,
  131918. 13,
  131919. 2,
  131920. 14,
  131921. 1,
  131922. 15,
  131923. 0,
  131924. 16,
  131925. };
  131926. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  131927. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131928. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  131929. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  131930. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  131931. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  131932. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  131933. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  131934. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  131935. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  131936. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  131937. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  131938. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  131939. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  131940. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  131941. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  131942. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131943. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  131944. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  131945. 9,
  131946. };
  131947. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  131948. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131949. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131950. };
  131951. static long _vq_quantmap__44c0_sm_p8_2[] = {
  131952. 15, 13, 11, 9, 7, 5, 3, 1,
  131953. 0, 2, 4, 6, 8, 10, 12, 14,
  131954. 16,
  131955. };
  131956. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  131957. _vq_quantthresh__44c0_sm_p8_2,
  131958. _vq_quantmap__44c0_sm_p8_2,
  131959. 17,
  131960. 17
  131961. };
  131962. static static_codebook _44c0_sm_p8_2 = {
  131963. 2, 289,
  131964. _vq_lengthlist__44c0_sm_p8_2,
  131965. 1, -529530880, 1611661312, 5, 0,
  131966. _vq_quantlist__44c0_sm_p8_2,
  131967. NULL,
  131968. &_vq_auxt__44c0_sm_p8_2,
  131969. NULL,
  131970. 0
  131971. };
  131972. static long _huff_lengthlist__44c0_sm_short[] = {
  131973. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  131974. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  131975. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  131976. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  131977. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  131978. 12,
  131979. };
  131980. static static_codebook _huff_book__44c0_sm_short = {
  131981. 2, 81,
  131982. _huff_lengthlist__44c0_sm_short,
  131983. 0, 0, 0, 0, 0,
  131984. NULL,
  131985. NULL,
  131986. NULL,
  131987. NULL,
  131988. 0
  131989. };
  131990. static long _huff_lengthlist__44c1_s_long[] = {
  131991. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  131992. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  131993. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  131994. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  131995. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  131996. 11,
  131997. };
  131998. static static_codebook _huff_book__44c1_s_long = {
  131999. 2, 81,
  132000. _huff_lengthlist__44c1_s_long,
  132001. 0, 0, 0, 0, 0,
  132002. NULL,
  132003. NULL,
  132004. NULL,
  132005. NULL,
  132006. 0
  132007. };
  132008. static long _vq_quantlist__44c1_s_p1_0[] = {
  132009. 1,
  132010. 0,
  132011. 2,
  132012. };
  132013. static long _vq_lengthlist__44c1_s_p1_0[] = {
  132014. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  132015. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  132020. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132022. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  132025. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132027. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0,
  132060. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  132065. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  132070. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  132106. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  132111. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  132116. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132424. 0,
  132425. };
  132426. static float _vq_quantthresh__44c1_s_p1_0[] = {
  132427. -0.5, 0.5,
  132428. };
  132429. static long _vq_quantmap__44c1_s_p1_0[] = {
  132430. 1, 0, 2,
  132431. };
  132432. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  132433. _vq_quantthresh__44c1_s_p1_0,
  132434. _vq_quantmap__44c1_s_p1_0,
  132435. 3,
  132436. 3
  132437. };
  132438. static static_codebook _44c1_s_p1_0 = {
  132439. 8, 6561,
  132440. _vq_lengthlist__44c1_s_p1_0,
  132441. 1, -535822336, 1611661312, 2, 0,
  132442. _vq_quantlist__44c1_s_p1_0,
  132443. NULL,
  132444. &_vq_auxt__44c1_s_p1_0,
  132445. NULL,
  132446. 0
  132447. };
  132448. static long _vq_quantlist__44c1_s_p2_0[] = {
  132449. 2,
  132450. 1,
  132451. 3,
  132452. 0,
  132453. 4,
  132454. };
  132455. static long _vq_lengthlist__44c1_s_p2_0[] = {
  132456. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  132458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132459. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  132461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132462. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  132463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132495. 0,
  132496. };
  132497. static float _vq_quantthresh__44c1_s_p2_0[] = {
  132498. -1.5, -0.5, 0.5, 1.5,
  132499. };
  132500. static long _vq_quantmap__44c1_s_p2_0[] = {
  132501. 3, 1, 0, 2, 4,
  132502. };
  132503. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  132504. _vq_quantthresh__44c1_s_p2_0,
  132505. _vq_quantmap__44c1_s_p2_0,
  132506. 5,
  132507. 5
  132508. };
  132509. static static_codebook _44c1_s_p2_0 = {
  132510. 4, 625,
  132511. _vq_lengthlist__44c1_s_p2_0,
  132512. 1, -533725184, 1611661312, 3, 0,
  132513. _vq_quantlist__44c1_s_p2_0,
  132514. NULL,
  132515. &_vq_auxt__44c1_s_p2_0,
  132516. NULL,
  132517. 0
  132518. };
  132519. static long _vq_quantlist__44c1_s_p3_0[] = {
  132520. 4,
  132521. 3,
  132522. 5,
  132523. 2,
  132524. 6,
  132525. 1,
  132526. 7,
  132527. 0,
  132528. 8,
  132529. };
  132530. static long _vq_lengthlist__44c1_s_p3_0[] = {
  132531. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  132532. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  132533. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  132534. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  132535. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132536. 0,
  132537. };
  132538. static float _vq_quantthresh__44c1_s_p3_0[] = {
  132539. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132540. };
  132541. static long _vq_quantmap__44c1_s_p3_0[] = {
  132542. 7, 5, 3, 1, 0, 2, 4, 6,
  132543. 8,
  132544. };
  132545. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  132546. _vq_quantthresh__44c1_s_p3_0,
  132547. _vq_quantmap__44c1_s_p3_0,
  132548. 9,
  132549. 9
  132550. };
  132551. static static_codebook _44c1_s_p3_0 = {
  132552. 2, 81,
  132553. _vq_lengthlist__44c1_s_p3_0,
  132554. 1, -531628032, 1611661312, 4, 0,
  132555. _vq_quantlist__44c1_s_p3_0,
  132556. NULL,
  132557. &_vq_auxt__44c1_s_p3_0,
  132558. NULL,
  132559. 0
  132560. };
  132561. static long _vq_quantlist__44c1_s_p4_0[] = {
  132562. 4,
  132563. 3,
  132564. 5,
  132565. 2,
  132566. 6,
  132567. 1,
  132568. 7,
  132569. 0,
  132570. 8,
  132571. };
  132572. static long _vq_lengthlist__44c1_s_p4_0[] = {
  132573. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  132574. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  132575. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  132576. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  132577. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  132578. 11,
  132579. };
  132580. static float _vq_quantthresh__44c1_s_p4_0[] = {
  132581. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132582. };
  132583. static long _vq_quantmap__44c1_s_p4_0[] = {
  132584. 7, 5, 3, 1, 0, 2, 4, 6,
  132585. 8,
  132586. };
  132587. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  132588. _vq_quantthresh__44c1_s_p4_0,
  132589. _vq_quantmap__44c1_s_p4_0,
  132590. 9,
  132591. 9
  132592. };
  132593. static static_codebook _44c1_s_p4_0 = {
  132594. 2, 81,
  132595. _vq_lengthlist__44c1_s_p4_0,
  132596. 1, -531628032, 1611661312, 4, 0,
  132597. _vq_quantlist__44c1_s_p4_0,
  132598. NULL,
  132599. &_vq_auxt__44c1_s_p4_0,
  132600. NULL,
  132601. 0
  132602. };
  132603. static long _vq_quantlist__44c1_s_p5_0[] = {
  132604. 8,
  132605. 7,
  132606. 9,
  132607. 6,
  132608. 10,
  132609. 5,
  132610. 11,
  132611. 4,
  132612. 12,
  132613. 3,
  132614. 13,
  132615. 2,
  132616. 14,
  132617. 1,
  132618. 15,
  132619. 0,
  132620. 16,
  132621. };
  132622. static long _vq_lengthlist__44c1_s_p5_0[] = {
  132623. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132624. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132625. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  132626. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132627. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132628. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  132629. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  132630. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  132631. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132632. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  132633. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  132634. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132635. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  132636. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  132637. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  132638. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  132639. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  132640. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  132641. 14,
  132642. };
  132643. static float _vq_quantthresh__44c1_s_p5_0[] = {
  132644. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132645. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132646. };
  132647. static long _vq_quantmap__44c1_s_p5_0[] = {
  132648. 15, 13, 11, 9, 7, 5, 3, 1,
  132649. 0, 2, 4, 6, 8, 10, 12, 14,
  132650. 16,
  132651. };
  132652. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  132653. _vq_quantthresh__44c1_s_p5_0,
  132654. _vq_quantmap__44c1_s_p5_0,
  132655. 17,
  132656. 17
  132657. };
  132658. static static_codebook _44c1_s_p5_0 = {
  132659. 2, 289,
  132660. _vq_lengthlist__44c1_s_p5_0,
  132661. 1, -529530880, 1611661312, 5, 0,
  132662. _vq_quantlist__44c1_s_p5_0,
  132663. NULL,
  132664. &_vq_auxt__44c1_s_p5_0,
  132665. NULL,
  132666. 0
  132667. };
  132668. static long _vq_quantlist__44c1_s_p6_0[] = {
  132669. 1,
  132670. 0,
  132671. 2,
  132672. };
  132673. static long _vq_lengthlist__44c1_s_p6_0[] = {
  132674. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132675. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  132676. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  132677. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  132678. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  132679. 11,
  132680. };
  132681. static float _vq_quantthresh__44c1_s_p6_0[] = {
  132682. -5.5, 5.5,
  132683. };
  132684. static long _vq_quantmap__44c1_s_p6_0[] = {
  132685. 1, 0, 2,
  132686. };
  132687. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  132688. _vq_quantthresh__44c1_s_p6_0,
  132689. _vq_quantmap__44c1_s_p6_0,
  132690. 3,
  132691. 3
  132692. };
  132693. static static_codebook _44c1_s_p6_0 = {
  132694. 4, 81,
  132695. _vq_lengthlist__44c1_s_p6_0,
  132696. 1, -529137664, 1618345984, 2, 0,
  132697. _vq_quantlist__44c1_s_p6_0,
  132698. NULL,
  132699. &_vq_auxt__44c1_s_p6_0,
  132700. NULL,
  132701. 0
  132702. };
  132703. static long _vq_quantlist__44c1_s_p6_1[] = {
  132704. 5,
  132705. 4,
  132706. 6,
  132707. 3,
  132708. 7,
  132709. 2,
  132710. 8,
  132711. 1,
  132712. 9,
  132713. 0,
  132714. 10,
  132715. };
  132716. static long _vq_lengthlist__44c1_s_p6_1[] = {
  132717. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  132718. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  132719. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  132720. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132721. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132722. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  132723. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132724. 10,10,10, 8, 8, 8, 8, 8, 8,
  132725. };
  132726. static float _vq_quantthresh__44c1_s_p6_1[] = {
  132727. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132728. 3.5, 4.5,
  132729. };
  132730. static long _vq_quantmap__44c1_s_p6_1[] = {
  132731. 9, 7, 5, 3, 1, 0, 2, 4,
  132732. 6, 8, 10,
  132733. };
  132734. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  132735. _vq_quantthresh__44c1_s_p6_1,
  132736. _vq_quantmap__44c1_s_p6_1,
  132737. 11,
  132738. 11
  132739. };
  132740. static static_codebook _44c1_s_p6_1 = {
  132741. 2, 121,
  132742. _vq_lengthlist__44c1_s_p6_1,
  132743. 1, -531365888, 1611661312, 4, 0,
  132744. _vq_quantlist__44c1_s_p6_1,
  132745. NULL,
  132746. &_vq_auxt__44c1_s_p6_1,
  132747. NULL,
  132748. 0
  132749. };
  132750. static long _vq_quantlist__44c1_s_p7_0[] = {
  132751. 6,
  132752. 5,
  132753. 7,
  132754. 4,
  132755. 8,
  132756. 3,
  132757. 9,
  132758. 2,
  132759. 10,
  132760. 1,
  132761. 11,
  132762. 0,
  132763. 12,
  132764. };
  132765. static long _vq_lengthlist__44c1_s_p7_0[] = {
  132766. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  132767. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  132768. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132769. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132770. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  132771. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132772. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  132773. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  132774. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  132775. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  132776. 0,12,11,11,11,13,10,14,13,
  132777. };
  132778. static float _vq_quantthresh__44c1_s_p7_0[] = {
  132779. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132780. 12.5, 17.5, 22.5, 27.5,
  132781. };
  132782. static long _vq_quantmap__44c1_s_p7_0[] = {
  132783. 11, 9, 7, 5, 3, 1, 0, 2,
  132784. 4, 6, 8, 10, 12,
  132785. };
  132786. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  132787. _vq_quantthresh__44c1_s_p7_0,
  132788. _vq_quantmap__44c1_s_p7_0,
  132789. 13,
  132790. 13
  132791. };
  132792. static static_codebook _44c1_s_p7_0 = {
  132793. 2, 169,
  132794. _vq_lengthlist__44c1_s_p7_0,
  132795. 1, -526516224, 1616117760, 4, 0,
  132796. _vq_quantlist__44c1_s_p7_0,
  132797. NULL,
  132798. &_vq_auxt__44c1_s_p7_0,
  132799. NULL,
  132800. 0
  132801. };
  132802. static long _vq_quantlist__44c1_s_p7_1[] = {
  132803. 2,
  132804. 1,
  132805. 3,
  132806. 0,
  132807. 4,
  132808. };
  132809. static long _vq_lengthlist__44c1_s_p7_1[] = {
  132810. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  132811. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  132812. };
  132813. static float _vq_quantthresh__44c1_s_p7_1[] = {
  132814. -1.5, -0.5, 0.5, 1.5,
  132815. };
  132816. static long _vq_quantmap__44c1_s_p7_1[] = {
  132817. 3, 1, 0, 2, 4,
  132818. };
  132819. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  132820. _vq_quantthresh__44c1_s_p7_1,
  132821. _vq_quantmap__44c1_s_p7_1,
  132822. 5,
  132823. 5
  132824. };
  132825. static static_codebook _44c1_s_p7_1 = {
  132826. 2, 25,
  132827. _vq_lengthlist__44c1_s_p7_1,
  132828. 1, -533725184, 1611661312, 3, 0,
  132829. _vq_quantlist__44c1_s_p7_1,
  132830. NULL,
  132831. &_vq_auxt__44c1_s_p7_1,
  132832. NULL,
  132833. 0
  132834. };
  132835. static long _vq_quantlist__44c1_s_p8_0[] = {
  132836. 6,
  132837. 5,
  132838. 7,
  132839. 4,
  132840. 8,
  132841. 3,
  132842. 9,
  132843. 2,
  132844. 10,
  132845. 1,
  132846. 11,
  132847. 0,
  132848. 12,
  132849. };
  132850. static long _vq_lengthlist__44c1_s_p8_0[] = {
  132851. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  132852. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  132853. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132854. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132855. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132856. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132857. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132858. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132859. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132860. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132861. 10,10,10,10,10,10,10,10,10,
  132862. };
  132863. static float _vq_quantthresh__44c1_s_p8_0[] = {
  132864. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  132865. 552.5, 773.5, 994.5, 1215.5,
  132866. };
  132867. static long _vq_quantmap__44c1_s_p8_0[] = {
  132868. 11, 9, 7, 5, 3, 1, 0, 2,
  132869. 4, 6, 8, 10, 12,
  132870. };
  132871. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  132872. _vq_quantthresh__44c1_s_p8_0,
  132873. _vq_quantmap__44c1_s_p8_0,
  132874. 13,
  132875. 13
  132876. };
  132877. static static_codebook _44c1_s_p8_0 = {
  132878. 2, 169,
  132879. _vq_lengthlist__44c1_s_p8_0,
  132880. 1, -514541568, 1627103232, 4, 0,
  132881. _vq_quantlist__44c1_s_p8_0,
  132882. NULL,
  132883. &_vq_auxt__44c1_s_p8_0,
  132884. NULL,
  132885. 0
  132886. };
  132887. static long _vq_quantlist__44c1_s_p8_1[] = {
  132888. 6,
  132889. 5,
  132890. 7,
  132891. 4,
  132892. 8,
  132893. 3,
  132894. 9,
  132895. 2,
  132896. 10,
  132897. 1,
  132898. 11,
  132899. 0,
  132900. 12,
  132901. };
  132902. static long _vq_lengthlist__44c1_s_p8_1[] = {
  132903. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  132904. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  132905. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  132906. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  132907. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  132908. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  132909. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  132910. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  132911. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  132912. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  132913. 16,13,12,12,11,14,12,15,13,
  132914. };
  132915. static float _vq_quantthresh__44c1_s_p8_1[] = {
  132916. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  132917. 42.5, 59.5, 76.5, 93.5,
  132918. };
  132919. static long _vq_quantmap__44c1_s_p8_1[] = {
  132920. 11, 9, 7, 5, 3, 1, 0, 2,
  132921. 4, 6, 8, 10, 12,
  132922. };
  132923. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  132924. _vq_quantthresh__44c1_s_p8_1,
  132925. _vq_quantmap__44c1_s_p8_1,
  132926. 13,
  132927. 13
  132928. };
  132929. static static_codebook _44c1_s_p8_1 = {
  132930. 2, 169,
  132931. _vq_lengthlist__44c1_s_p8_1,
  132932. 1, -522616832, 1620115456, 4, 0,
  132933. _vq_quantlist__44c1_s_p8_1,
  132934. NULL,
  132935. &_vq_auxt__44c1_s_p8_1,
  132936. NULL,
  132937. 0
  132938. };
  132939. static long _vq_quantlist__44c1_s_p8_2[] = {
  132940. 8,
  132941. 7,
  132942. 9,
  132943. 6,
  132944. 10,
  132945. 5,
  132946. 11,
  132947. 4,
  132948. 12,
  132949. 3,
  132950. 13,
  132951. 2,
  132952. 14,
  132953. 1,
  132954. 15,
  132955. 0,
  132956. 16,
  132957. };
  132958. static long _vq_lengthlist__44c1_s_p8_2[] = {
  132959. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132960. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  132961. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  132962. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  132963. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  132964. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  132965. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  132966. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  132967. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  132968. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  132969. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  132970. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  132971. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  132972. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  132973. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  132974. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  132975. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  132976. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  132977. 9,
  132978. };
  132979. static float _vq_quantthresh__44c1_s_p8_2[] = {
  132980. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132981. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132982. };
  132983. static long _vq_quantmap__44c1_s_p8_2[] = {
  132984. 15, 13, 11, 9, 7, 5, 3, 1,
  132985. 0, 2, 4, 6, 8, 10, 12, 14,
  132986. 16,
  132987. };
  132988. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  132989. _vq_quantthresh__44c1_s_p8_2,
  132990. _vq_quantmap__44c1_s_p8_2,
  132991. 17,
  132992. 17
  132993. };
  132994. static static_codebook _44c1_s_p8_2 = {
  132995. 2, 289,
  132996. _vq_lengthlist__44c1_s_p8_2,
  132997. 1, -529530880, 1611661312, 5, 0,
  132998. _vq_quantlist__44c1_s_p8_2,
  132999. NULL,
  133000. &_vq_auxt__44c1_s_p8_2,
  133001. NULL,
  133002. 0
  133003. };
  133004. static long _huff_lengthlist__44c1_s_short[] = {
  133005. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  133006. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  133007. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  133008. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  133009. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  133010. 11,
  133011. };
  133012. static static_codebook _huff_book__44c1_s_short = {
  133013. 2, 81,
  133014. _huff_lengthlist__44c1_s_short,
  133015. 0, 0, 0, 0, 0,
  133016. NULL,
  133017. NULL,
  133018. NULL,
  133019. NULL,
  133020. 0
  133021. };
  133022. static long _huff_lengthlist__44c1_sm_long[] = {
  133023. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  133024. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  133025. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  133026. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  133027. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  133028. 11,
  133029. };
  133030. static static_codebook _huff_book__44c1_sm_long = {
  133031. 2, 81,
  133032. _huff_lengthlist__44c1_sm_long,
  133033. 0, 0, 0, 0, 0,
  133034. NULL,
  133035. NULL,
  133036. NULL,
  133037. NULL,
  133038. 0
  133039. };
  133040. static long _vq_quantlist__44c1_sm_p1_0[] = {
  133041. 1,
  133042. 0,
  133043. 2,
  133044. };
  133045. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  133046. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  133047. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  133052. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133054. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  133057. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133059. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0,
  133092. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  133097. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  133102. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  133138. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  133143. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  133148. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133456. 0,
  133457. };
  133458. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  133459. -0.5, 0.5,
  133460. };
  133461. static long _vq_quantmap__44c1_sm_p1_0[] = {
  133462. 1, 0, 2,
  133463. };
  133464. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  133465. _vq_quantthresh__44c1_sm_p1_0,
  133466. _vq_quantmap__44c1_sm_p1_0,
  133467. 3,
  133468. 3
  133469. };
  133470. static static_codebook _44c1_sm_p1_0 = {
  133471. 8, 6561,
  133472. _vq_lengthlist__44c1_sm_p1_0,
  133473. 1, -535822336, 1611661312, 2, 0,
  133474. _vq_quantlist__44c1_sm_p1_0,
  133475. NULL,
  133476. &_vq_auxt__44c1_sm_p1_0,
  133477. NULL,
  133478. 0
  133479. };
  133480. static long _vq_quantlist__44c1_sm_p2_0[] = {
  133481. 2,
  133482. 1,
  133483. 3,
  133484. 0,
  133485. 4,
  133486. };
  133487. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  133488. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  133490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133491. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  133493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133494. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  133495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133527. 0,
  133528. };
  133529. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  133530. -1.5, -0.5, 0.5, 1.5,
  133531. };
  133532. static long _vq_quantmap__44c1_sm_p2_0[] = {
  133533. 3, 1, 0, 2, 4,
  133534. };
  133535. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  133536. _vq_quantthresh__44c1_sm_p2_0,
  133537. _vq_quantmap__44c1_sm_p2_0,
  133538. 5,
  133539. 5
  133540. };
  133541. static static_codebook _44c1_sm_p2_0 = {
  133542. 4, 625,
  133543. _vq_lengthlist__44c1_sm_p2_0,
  133544. 1, -533725184, 1611661312, 3, 0,
  133545. _vq_quantlist__44c1_sm_p2_0,
  133546. NULL,
  133547. &_vq_auxt__44c1_sm_p2_0,
  133548. NULL,
  133549. 0
  133550. };
  133551. static long _vq_quantlist__44c1_sm_p3_0[] = {
  133552. 4,
  133553. 3,
  133554. 5,
  133555. 2,
  133556. 6,
  133557. 1,
  133558. 7,
  133559. 0,
  133560. 8,
  133561. };
  133562. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  133563. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  133564. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  133565. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  133566. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  133567. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133568. 0,
  133569. };
  133570. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  133571. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133572. };
  133573. static long _vq_quantmap__44c1_sm_p3_0[] = {
  133574. 7, 5, 3, 1, 0, 2, 4, 6,
  133575. 8,
  133576. };
  133577. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  133578. _vq_quantthresh__44c1_sm_p3_0,
  133579. _vq_quantmap__44c1_sm_p3_0,
  133580. 9,
  133581. 9
  133582. };
  133583. static static_codebook _44c1_sm_p3_0 = {
  133584. 2, 81,
  133585. _vq_lengthlist__44c1_sm_p3_0,
  133586. 1, -531628032, 1611661312, 4, 0,
  133587. _vq_quantlist__44c1_sm_p3_0,
  133588. NULL,
  133589. &_vq_auxt__44c1_sm_p3_0,
  133590. NULL,
  133591. 0
  133592. };
  133593. static long _vq_quantlist__44c1_sm_p4_0[] = {
  133594. 4,
  133595. 3,
  133596. 5,
  133597. 2,
  133598. 6,
  133599. 1,
  133600. 7,
  133601. 0,
  133602. 8,
  133603. };
  133604. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  133605. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  133606. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  133607. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  133608. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  133609. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  133610. 11,
  133611. };
  133612. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  133613. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133614. };
  133615. static long _vq_quantmap__44c1_sm_p4_0[] = {
  133616. 7, 5, 3, 1, 0, 2, 4, 6,
  133617. 8,
  133618. };
  133619. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  133620. _vq_quantthresh__44c1_sm_p4_0,
  133621. _vq_quantmap__44c1_sm_p4_0,
  133622. 9,
  133623. 9
  133624. };
  133625. static static_codebook _44c1_sm_p4_0 = {
  133626. 2, 81,
  133627. _vq_lengthlist__44c1_sm_p4_0,
  133628. 1, -531628032, 1611661312, 4, 0,
  133629. _vq_quantlist__44c1_sm_p4_0,
  133630. NULL,
  133631. &_vq_auxt__44c1_sm_p4_0,
  133632. NULL,
  133633. 0
  133634. };
  133635. static long _vq_quantlist__44c1_sm_p5_0[] = {
  133636. 8,
  133637. 7,
  133638. 9,
  133639. 6,
  133640. 10,
  133641. 5,
  133642. 11,
  133643. 4,
  133644. 12,
  133645. 3,
  133646. 13,
  133647. 2,
  133648. 14,
  133649. 1,
  133650. 15,
  133651. 0,
  133652. 16,
  133653. };
  133654. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  133655. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133656. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  133657. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  133658. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  133659. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  133660. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  133661. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  133662. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  133663. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  133664. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  133665. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  133666. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  133667. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  133668. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  133669. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  133670. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  133671. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  133672. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  133673. 14,
  133674. };
  133675. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  133676. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133677. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133678. };
  133679. static long _vq_quantmap__44c1_sm_p5_0[] = {
  133680. 15, 13, 11, 9, 7, 5, 3, 1,
  133681. 0, 2, 4, 6, 8, 10, 12, 14,
  133682. 16,
  133683. };
  133684. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  133685. _vq_quantthresh__44c1_sm_p5_0,
  133686. _vq_quantmap__44c1_sm_p5_0,
  133687. 17,
  133688. 17
  133689. };
  133690. static static_codebook _44c1_sm_p5_0 = {
  133691. 2, 289,
  133692. _vq_lengthlist__44c1_sm_p5_0,
  133693. 1, -529530880, 1611661312, 5, 0,
  133694. _vq_quantlist__44c1_sm_p5_0,
  133695. NULL,
  133696. &_vq_auxt__44c1_sm_p5_0,
  133697. NULL,
  133698. 0
  133699. };
  133700. static long _vq_quantlist__44c1_sm_p6_0[] = {
  133701. 1,
  133702. 0,
  133703. 2,
  133704. };
  133705. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  133706. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  133707. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  133708. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  133709. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  133710. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  133711. 11,
  133712. };
  133713. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  133714. -5.5, 5.5,
  133715. };
  133716. static long _vq_quantmap__44c1_sm_p6_0[] = {
  133717. 1, 0, 2,
  133718. };
  133719. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  133720. _vq_quantthresh__44c1_sm_p6_0,
  133721. _vq_quantmap__44c1_sm_p6_0,
  133722. 3,
  133723. 3
  133724. };
  133725. static static_codebook _44c1_sm_p6_0 = {
  133726. 4, 81,
  133727. _vq_lengthlist__44c1_sm_p6_0,
  133728. 1, -529137664, 1618345984, 2, 0,
  133729. _vq_quantlist__44c1_sm_p6_0,
  133730. NULL,
  133731. &_vq_auxt__44c1_sm_p6_0,
  133732. NULL,
  133733. 0
  133734. };
  133735. static long _vq_quantlist__44c1_sm_p6_1[] = {
  133736. 5,
  133737. 4,
  133738. 6,
  133739. 3,
  133740. 7,
  133741. 2,
  133742. 8,
  133743. 1,
  133744. 9,
  133745. 0,
  133746. 10,
  133747. };
  133748. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  133749. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  133750. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133751. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  133752. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  133753. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  133754. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  133755. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  133756. 10,10,10, 8, 8, 8, 8, 8, 8,
  133757. };
  133758. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  133759. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133760. 3.5, 4.5,
  133761. };
  133762. static long _vq_quantmap__44c1_sm_p6_1[] = {
  133763. 9, 7, 5, 3, 1, 0, 2, 4,
  133764. 6, 8, 10,
  133765. };
  133766. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  133767. _vq_quantthresh__44c1_sm_p6_1,
  133768. _vq_quantmap__44c1_sm_p6_1,
  133769. 11,
  133770. 11
  133771. };
  133772. static static_codebook _44c1_sm_p6_1 = {
  133773. 2, 121,
  133774. _vq_lengthlist__44c1_sm_p6_1,
  133775. 1, -531365888, 1611661312, 4, 0,
  133776. _vq_quantlist__44c1_sm_p6_1,
  133777. NULL,
  133778. &_vq_auxt__44c1_sm_p6_1,
  133779. NULL,
  133780. 0
  133781. };
  133782. static long _vq_quantlist__44c1_sm_p7_0[] = {
  133783. 6,
  133784. 5,
  133785. 7,
  133786. 4,
  133787. 8,
  133788. 3,
  133789. 9,
  133790. 2,
  133791. 10,
  133792. 1,
  133793. 11,
  133794. 0,
  133795. 12,
  133796. };
  133797. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  133798. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  133799. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  133800. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  133801. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  133802. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  133803. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  133804. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  133805. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  133806. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  133807. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  133808. 0,12,12,11,11,13,12,14,13,
  133809. };
  133810. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  133811. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133812. 12.5, 17.5, 22.5, 27.5,
  133813. };
  133814. static long _vq_quantmap__44c1_sm_p7_0[] = {
  133815. 11, 9, 7, 5, 3, 1, 0, 2,
  133816. 4, 6, 8, 10, 12,
  133817. };
  133818. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  133819. _vq_quantthresh__44c1_sm_p7_0,
  133820. _vq_quantmap__44c1_sm_p7_0,
  133821. 13,
  133822. 13
  133823. };
  133824. static static_codebook _44c1_sm_p7_0 = {
  133825. 2, 169,
  133826. _vq_lengthlist__44c1_sm_p7_0,
  133827. 1, -526516224, 1616117760, 4, 0,
  133828. _vq_quantlist__44c1_sm_p7_0,
  133829. NULL,
  133830. &_vq_auxt__44c1_sm_p7_0,
  133831. NULL,
  133832. 0
  133833. };
  133834. static long _vq_quantlist__44c1_sm_p7_1[] = {
  133835. 2,
  133836. 1,
  133837. 3,
  133838. 0,
  133839. 4,
  133840. };
  133841. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  133842. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  133843. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133844. };
  133845. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  133846. -1.5, -0.5, 0.5, 1.5,
  133847. };
  133848. static long _vq_quantmap__44c1_sm_p7_1[] = {
  133849. 3, 1, 0, 2, 4,
  133850. };
  133851. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  133852. _vq_quantthresh__44c1_sm_p7_1,
  133853. _vq_quantmap__44c1_sm_p7_1,
  133854. 5,
  133855. 5
  133856. };
  133857. static static_codebook _44c1_sm_p7_1 = {
  133858. 2, 25,
  133859. _vq_lengthlist__44c1_sm_p7_1,
  133860. 1, -533725184, 1611661312, 3, 0,
  133861. _vq_quantlist__44c1_sm_p7_1,
  133862. NULL,
  133863. &_vq_auxt__44c1_sm_p7_1,
  133864. NULL,
  133865. 0
  133866. };
  133867. static long _vq_quantlist__44c1_sm_p8_0[] = {
  133868. 6,
  133869. 5,
  133870. 7,
  133871. 4,
  133872. 8,
  133873. 3,
  133874. 9,
  133875. 2,
  133876. 10,
  133877. 1,
  133878. 11,
  133879. 0,
  133880. 12,
  133881. };
  133882. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  133883. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  133884. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  133885. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133886. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133887. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133888. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133889. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133890. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133891. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133892. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133893. 13,13,13,13,13,13,13,13,13,
  133894. };
  133895. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  133896. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  133897. 552.5, 773.5, 994.5, 1215.5,
  133898. };
  133899. static long _vq_quantmap__44c1_sm_p8_0[] = {
  133900. 11, 9, 7, 5, 3, 1, 0, 2,
  133901. 4, 6, 8, 10, 12,
  133902. };
  133903. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  133904. _vq_quantthresh__44c1_sm_p8_0,
  133905. _vq_quantmap__44c1_sm_p8_0,
  133906. 13,
  133907. 13
  133908. };
  133909. static static_codebook _44c1_sm_p8_0 = {
  133910. 2, 169,
  133911. _vq_lengthlist__44c1_sm_p8_0,
  133912. 1, -514541568, 1627103232, 4, 0,
  133913. _vq_quantlist__44c1_sm_p8_0,
  133914. NULL,
  133915. &_vq_auxt__44c1_sm_p8_0,
  133916. NULL,
  133917. 0
  133918. };
  133919. static long _vq_quantlist__44c1_sm_p8_1[] = {
  133920. 6,
  133921. 5,
  133922. 7,
  133923. 4,
  133924. 8,
  133925. 3,
  133926. 9,
  133927. 2,
  133928. 10,
  133929. 1,
  133930. 11,
  133931. 0,
  133932. 12,
  133933. };
  133934. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  133935. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  133936. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  133937. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  133938. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  133939. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  133940. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  133941. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  133942. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  133943. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  133944. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  133945. 20,13,12,12,12,14,12,14,13,
  133946. };
  133947. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  133948. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  133949. 42.5, 59.5, 76.5, 93.5,
  133950. };
  133951. static long _vq_quantmap__44c1_sm_p8_1[] = {
  133952. 11, 9, 7, 5, 3, 1, 0, 2,
  133953. 4, 6, 8, 10, 12,
  133954. };
  133955. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  133956. _vq_quantthresh__44c1_sm_p8_1,
  133957. _vq_quantmap__44c1_sm_p8_1,
  133958. 13,
  133959. 13
  133960. };
  133961. static static_codebook _44c1_sm_p8_1 = {
  133962. 2, 169,
  133963. _vq_lengthlist__44c1_sm_p8_1,
  133964. 1, -522616832, 1620115456, 4, 0,
  133965. _vq_quantlist__44c1_sm_p8_1,
  133966. NULL,
  133967. &_vq_auxt__44c1_sm_p8_1,
  133968. NULL,
  133969. 0
  133970. };
  133971. static long _vq_quantlist__44c1_sm_p8_2[] = {
  133972. 8,
  133973. 7,
  133974. 9,
  133975. 6,
  133976. 10,
  133977. 5,
  133978. 11,
  133979. 4,
  133980. 12,
  133981. 3,
  133982. 13,
  133983. 2,
  133984. 14,
  133985. 1,
  133986. 15,
  133987. 0,
  133988. 16,
  133989. };
  133990. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  133991. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  133992. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  133993. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133994. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  133995. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  133996. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  133997. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  133998. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  133999. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  134000. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  134001. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  134002. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  134003. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  134004. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  134005. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  134006. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  134007. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  134008. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  134009. 9,
  134010. };
  134011. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  134012. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134013. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134014. };
  134015. static long _vq_quantmap__44c1_sm_p8_2[] = {
  134016. 15, 13, 11, 9, 7, 5, 3, 1,
  134017. 0, 2, 4, 6, 8, 10, 12, 14,
  134018. 16,
  134019. };
  134020. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  134021. _vq_quantthresh__44c1_sm_p8_2,
  134022. _vq_quantmap__44c1_sm_p8_2,
  134023. 17,
  134024. 17
  134025. };
  134026. static static_codebook _44c1_sm_p8_2 = {
  134027. 2, 289,
  134028. _vq_lengthlist__44c1_sm_p8_2,
  134029. 1, -529530880, 1611661312, 5, 0,
  134030. _vq_quantlist__44c1_sm_p8_2,
  134031. NULL,
  134032. &_vq_auxt__44c1_sm_p8_2,
  134033. NULL,
  134034. 0
  134035. };
  134036. static long _huff_lengthlist__44c1_sm_short[] = {
  134037. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  134038. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  134039. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  134040. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  134041. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  134042. 11,
  134043. };
  134044. static static_codebook _huff_book__44c1_sm_short = {
  134045. 2, 81,
  134046. _huff_lengthlist__44c1_sm_short,
  134047. 0, 0, 0, 0, 0,
  134048. NULL,
  134049. NULL,
  134050. NULL,
  134051. NULL,
  134052. 0
  134053. };
  134054. static long _huff_lengthlist__44cn1_s_long[] = {
  134055. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  134056. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  134057. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  134058. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  134059. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  134060. 20,
  134061. };
  134062. static static_codebook _huff_book__44cn1_s_long = {
  134063. 2, 81,
  134064. _huff_lengthlist__44cn1_s_long,
  134065. 0, 0, 0, 0, 0,
  134066. NULL,
  134067. NULL,
  134068. NULL,
  134069. NULL,
  134070. 0
  134071. };
  134072. static long _vq_quantlist__44cn1_s_p1_0[] = {
  134073. 1,
  134074. 0,
  134075. 2,
  134076. };
  134077. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  134078. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134079. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  134084. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134086. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  134089. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134091. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  134124. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 7,10,10, 0, 0, 0,
  134129. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 7,10,10, 0, 0,
  134134. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  134170. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  134175. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  134180. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134488. 0,
  134489. };
  134490. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  134491. -0.5, 0.5,
  134492. };
  134493. static long _vq_quantmap__44cn1_s_p1_0[] = {
  134494. 1, 0, 2,
  134495. };
  134496. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  134497. _vq_quantthresh__44cn1_s_p1_0,
  134498. _vq_quantmap__44cn1_s_p1_0,
  134499. 3,
  134500. 3
  134501. };
  134502. static static_codebook _44cn1_s_p1_0 = {
  134503. 8, 6561,
  134504. _vq_lengthlist__44cn1_s_p1_0,
  134505. 1, -535822336, 1611661312, 2, 0,
  134506. _vq_quantlist__44cn1_s_p1_0,
  134507. NULL,
  134508. &_vq_auxt__44cn1_s_p1_0,
  134509. NULL,
  134510. 0
  134511. };
  134512. static long _vq_quantlist__44cn1_s_p2_0[] = {
  134513. 2,
  134514. 1,
  134515. 3,
  134516. 0,
  134517. 4,
  134518. };
  134519. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  134520. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  134522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134523. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  134525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134526. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  134527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134559. 0,
  134560. };
  134561. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  134562. -1.5, -0.5, 0.5, 1.5,
  134563. };
  134564. static long _vq_quantmap__44cn1_s_p2_0[] = {
  134565. 3, 1, 0, 2, 4,
  134566. };
  134567. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  134568. _vq_quantthresh__44cn1_s_p2_0,
  134569. _vq_quantmap__44cn1_s_p2_0,
  134570. 5,
  134571. 5
  134572. };
  134573. static static_codebook _44cn1_s_p2_0 = {
  134574. 4, 625,
  134575. _vq_lengthlist__44cn1_s_p2_0,
  134576. 1, -533725184, 1611661312, 3, 0,
  134577. _vq_quantlist__44cn1_s_p2_0,
  134578. NULL,
  134579. &_vq_auxt__44cn1_s_p2_0,
  134580. NULL,
  134581. 0
  134582. };
  134583. static long _vq_quantlist__44cn1_s_p3_0[] = {
  134584. 4,
  134585. 3,
  134586. 5,
  134587. 2,
  134588. 6,
  134589. 1,
  134590. 7,
  134591. 0,
  134592. 8,
  134593. };
  134594. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  134595. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  134596. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  134597. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  134598. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  134599. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134600. 0,
  134601. };
  134602. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  134603. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134604. };
  134605. static long _vq_quantmap__44cn1_s_p3_0[] = {
  134606. 7, 5, 3, 1, 0, 2, 4, 6,
  134607. 8,
  134608. };
  134609. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  134610. _vq_quantthresh__44cn1_s_p3_0,
  134611. _vq_quantmap__44cn1_s_p3_0,
  134612. 9,
  134613. 9
  134614. };
  134615. static static_codebook _44cn1_s_p3_0 = {
  134616. 2, 81,
  134617. _vq_lengthlist__44cn1_s_p3_0,
  134618. 1, -531628032, 1611661312, 4, 0,
  134619. _vq_quantlist__44cn1_s_p3_0,
  134620. NULL,
  134621. &_vq_auxt__44cn1_s_p3_0,
  134622. NULL,
  134623. 0
  134624. };
  134625. static long _vq_quantlist__44cn1_s_p4_0[] = {
  134626. 4,
  134627. 3,
  134628. 5,
  134629. 2,
  134630. 6,
  134631. 1,
  134632. 7,
  134633. 0,
  134634. 8,
  134635. };
  134636. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  134637. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  134638. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  134639. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  134640. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  134641. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  134642. 11,
  134643. };
  134644. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  134645. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134646. };
  134647. static long _vq_quantmap__44cn1_s_p4_0[] = {
  134648. 7, 5, 3, 1, 0, 2, 4, 6,
  134649. 8,
  134650. };
  134651. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  134652. _vq_quantthresh__44cn1_s_p4_0,
  134653. _vq_quantmap__44cn1_s_p4_0,
  134654. 9,
  134655. 9
  134656. };
  134657. static static_codebook _44cn1_s_p4_0 = {
  134658. 2, 81,
  134659. _vq_lengthlist__44cn1_s_p4_0,
  134660. 1, -531628032, 1611661312, 4, 0,
  134661. _vq_quantlist__44cn1_s_p4_0,
  134662. NULL,
  134663. &_vq_auxt__44cn1_s_p4_0,
  134664. NULL,
  134665. 0
  134666. };
  134667. static long _vq_quantlist__44cn1_s_p5_0[] = {
  134668. 8,
  134669. 7,
  134670. 9,
  134671. 6,
  134672. 10,
  134673. 5,
  134674. 11,
  134675. 4,
  134676. 12,
  134677. 3,
  134678. 13,
  134679. 2,
  134680. 14,
  134681. 1,
  134682. 15,
  134683. 0,
  134684. 16,
  134685. };
  134686. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  134687. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  134688. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  134689. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  134690. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  134691. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  134692. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  134693. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  134694. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  134695. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  134696. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  134697. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  134698. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  134699. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  134700. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  134701. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  134702. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  134703. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  134704. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  134705. 14,
  134706. };
  134707. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  134708. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134709. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134710. };
  134711. static long _vq_quantmap__44cn1_s_p5_0[] = {
  134712. 15, 13, 11, 9, 7, 5, 3, 1,
  134713. 0, 2, 4, 6, 8, 10, 12, 14,
  134714. 16,
  134715. };
  134716. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  134717. _vq_quantthresh__44cn1_s_p5_0,
  134718. _vq_quantmap__44cn1_s_p5_0,
  134719. 17,
  134720. 17
  134721. };
  134722. static static_codebook _44cn1_s_p5_0 = {
  134723. 2, 289,
  134724. _vq_lengthlist__44cn1_s_p5_0,
  134725. 1, -529530880, 1611661312, 5, 0,
  134726. _vq_quantlist__44cn1_s_p5_0,
  134727. NULL,
  134728. &_vq_auxt__44cn1_s_p5_0,
  134729. NULL,
  134730. 0
  134731. };
  134732. static long _vq_quantlist__44cn1_s_p6_0[] = {
  134733. 1,
  134734. 0,
  134735. 2,
  134736. };
  134737. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  134738. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  134739. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  134740. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  134741. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  134742. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  134743. 10,
  134744. };
  134745. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  134746. -5.5, 5.5,
  134747. };
  134748. static long _vq_quantmap__44cn1_s_p6_0[] = {
  134749. 1, 0, 2,
  134750. };
  134751. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  134752. _vq_quantthresh__44cn1_s_p6_0,
  134753. _vq_quantmap__44cn1_s_p6_0,
  134754. 3,
  134755. 3
  134756. };
  134757. static static_codebook _44cn1_s_p6_0 = {
  134758. 4, 81,
  134759. _vq_lengthlist__44cn1_s_p6_0,
  134760. 1, -529137664, 1618345984, 2, 0,
  134761. _vq_quantlist__44cn1_s_p6_0,
  134762. NULL,
  134763. &_vq_auxt__44cn1_s_p6_0,
  134764. NULL,
  134765. 0
  134766. };
  134767. static long _vq_quantlist__44cn1_s_p6_1[] = {
  134768. 5,
  134769. 4,
  134770. 6,
  134771. 3,
  134772. 7,
  134773. 2,
  134774. 8,
  134775. 1,
  134776. 9,
  134777. 0,
  134778. 10,
  134779. };
  134780. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  134781. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  134782. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  134783. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  134784. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  134785. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  134786. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134787. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  134788. 10,10,10, 9, 9, 9, 9, 9, 9,
  134789. };
  134790. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  134791. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134792. 3.5, 4.5,
  134793. };
  134794. static long _vq_quantmap__44cn1_s_p6_1[] = {
  134795. 9, 7, 5, 3, 1, 0, 2, 4,
  134796. 6, 8, 10,
  134797. };
  134798. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  134799. _vq_quantthresh__44cn1_s_p6_1,
  134800. _vq_quantmap__44cn1_s_p6_1,
  134801. 11,
  134802. 11
  134803. };
  134804. static static_codebook _44cn1_s_p6_1 = {
  134805. 2, 121,
  134806. _vq_lengthlist__44cn1_s_p6_1,
  134807. 1, -531365888, 1611661312, 4, 0,
  134808. _vq_quantlist__44cn1_s_p6_1,
  134809. NULL,
  134810. &_vq_auxt__44cn1_s_p6_1,
  134811. NULL,
  134812. 0
  134813. };
  134814. static long _vq_quantlist__44cn1_s_p7_0[] = {
  134815. 6,
  134816. 5,
  134817. 7,
  134818. 4,
  134819. 8,
  134820. 3,
  134821. 9,
  134822. 2,
  134823. 10,
  134824. 1,
  134825. 11,
  134826. 0,
  134827. 12,
  134828. };
  134829. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  134830. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134831. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  134832. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  134833. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  134834. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  134835. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  134836. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  134837. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  134838. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  134839. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  134840. 0,13,13,12,12,13,13,13,14,
  134841. };
  134842. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  134843. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134844. 12.5, 17.5, 22.5, 27.5,
  134845. };
  134846. static long _vq_quantmap__44cn1_s_p7_0[] = {
  134847. 11, 9, 7, 5, 3, 1, 0, 2,
  134848. 4, 6, 8, 10, 12,
  134849. };
  134850. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  134851. _vq_quantthresh__44cn1_s_p7_0,
  134852. _vq_quantmap__44cn1_s_p7_0,
  134853. 13,
  134854. 13
  134855. };
  134856. static static_codebook _44cn1_s_p7_0 = {
  134857. 2, 169,
  134858. _vq_lengthlist__44cn1_s_p7_0,
  134859. 1, -526516224, 1616117760, 4, 0,
  134860. _vq_quantlist__44cn1_s_p7_0,
  134861. NULL,
  134862. &_vq_auxt__44cn1_s_p7_0,
  134863. NULL,
  134864. 0
  134865. };
  134866. static long _vq_quantlist__44cn1_s_p7_1[] = {
  134867. 2,
  134868. 1,
  134869. 3,
  134870. 0,
  134871. 4,
  134872. };
  134873. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  134874. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  134875. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  134876. };
  134877. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  134878. -1.5, -0.5, 0.5, 1.5,
  134879. };
  134880. static long _vq_quantmap__44cn1_s_p7_1[] = {
  134881. 3, 1, 0, 2, 4,
  134882. };
  134883. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  134884. _vq_quantthresh__44cn1_s_p7_1,
  134885. _vq_quantmap__44cn1_s_p7_1,
  134886. 5,
  134887. 5
  134888. };
  134889. static static_codebook _44cn1_s_p7_1 = {
  134890. 2, 25,
  134891. _vq_lengthlist__44cn1_s_p7_1,
  134892. 1, -533725184, 1611661312, 3, 0,
  134893. _vq_quantlist__44cn1_s_p7_1,
  134894. NULL,
  134895. &_vq_auxt__44cn1_s_p7_1,
  134896. NULL,
  134897. 0
  134898. };
  134899. static long _vq_quantlist__44cn1_s_p8_0[] = {
  134900. 2,
  134901. 1,
  134902. 3,
  134903. 0,
  134904. 4,
  134905. };
  134906. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  134907. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  134908. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  134909. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134910. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  134911. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134912. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134913. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134914. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  134915. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134916. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  134917. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  134918. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134919. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134920. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134921. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134922. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  134923. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134924. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134925. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134926. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134927. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134928. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134929. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134930. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134931. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134932. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134933. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134934. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134935. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134936. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134937. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134938. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134939. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134940. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  134941. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134942. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134943. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134944. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134945. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134946. 12,
  134947. };
  134948. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  134949. -331.5, -110.5, 110.5, 331.5,
  134950. };
  134951. static long _vq_quantmap__44cn1_s_p8_0[] = {
  134952. 3, 1, 0, 2, 4,
  134953. };
  134954. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  134955. _vq_quantthresh__44cn1_s_p8_0,
  134956. _vq_quantmap__44cn1_s_p8_0,
  134957. 5,
  134958. 5
  134959. };
  134960. static static_codebook _44cn1_s_p8_0 = {
  134961. 4, 625,
  134962. _vq_lengthlist__44cn1_s_p8_0,
  134963. 1, -518283264, 1627103232, 3, 0,
  134964. _vq_quantlist__44cn1_s_p8_0,
  134965. NULL,
  134966. &_vq_auxt__44cn1_s_p8_0,
  134967. NULL,
  134968. 0
  134969. };
  134970. static long _vq_quantlist__44cn1_s_p8_1[] = {
  134971. 6,
  134972. 5,
  134973. 7,
  134974. 4,
  134975. 8,
  134976. 3,
  134977. 9,
  134978. 2,
  134979. 10,
  134980. 1,
  134981. 11,
  134982. 0,
  134983. 12,
  134984. };
  134985. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  134986. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  134987. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  134988. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  134989. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  134990. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  134991. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  134992. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  134993. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  134994. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  134995. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  134996. 15,12,12,11,11,14,12,13,14,
  134997. };
  134998. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  134999. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135000. 42.5, 59.5, 76.5, 93.5,
  135001. };
  135002. static long _vq_quantmap__44cn1_s_p8_1[] = {
  135003. 11, 9, 7, 5, 3, 1, 0, 2,
  135004. 4, 6, 8, 10, 12,
  135005. };
  135006. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  135007. _vq_quantthresh__44cn1_s_p8_1,
  135008. _vq_quantmap__44cn1_s_p8_1,
  135009. 13,
  135010. 13
  135011. };
  135012. static static_codebook _44cn1_s_p8_1 = {
  135013. 2, 169,
  135014. _vq_lengthlist__44cn1_s_p8_1,
  135015. 1, -522616832, 1620115456, 4, 0,
  135016. _vq_quantlist__44cn1_s_p8_1,
  135017. NULL,
  135018. &_vq_auxt__44cn1_s_p8_1,
  135019. NULL,
  135020. 0
  135021. };
  135022. static long _vq_quantlist__44cn1_s_p8_2[] = {
  135023. 8,
  135024. 7,
  135025. 9,
  135026. 6,
  135027. 10,
  135028. 5,
  135029. 11,
  135030. 4,
  135031. 12,
  135032. 3,
  135033. 13,
  135034. 2,
  135035. 14,
  135036. 1,
  135037. 15,
  135038. 0,
  135039. 16,
  135040. };
  135041. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  135042. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  135043. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  135044. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  135045. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  135046. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  135047. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  135048. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  135049. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  135050. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  135051. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  135052. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  135053. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  135054. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  135055. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  135056. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  135057. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  135058. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135059. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  135060. 9,
  135061. };
  135062. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  135063. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135064. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135065. };
  135066. static long _vq_quantmap__44cn1_s_p8_2[] = {
  135067. 15, 13, 11, 9, 7, 5, 3, 1,
  135068. 0, 2, 4, 6, 8, 10, 12, 14,
  135069. 16,
  135070. };
  135071. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  135072. _vq_quantthresh__44cn1_s_p8_2,
  135073. _vq_quantmap__44cn1_s_p8_2,
  135074. 17,
  135075. 17
  135076. };
  135077. static static_codebook _44cn1_s_p8_2 = {
  135078. 2, 289,
  135079. _vq_lengthlist__44cn1_s_p8_2,
  135080. 1, -529530880, 1611661312, 5, 0,
  135081. _vq_quantlist__44cn1_s_p8_2,
  135082. NULL,
  135083. &_vq_auxt__44cn1_s_p8_2,
  135084. NULL,
  135085. 0
  135086. };
  135087. static long _huff_lengthlist__44cn1_s_short[] = {
  135088. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  135089. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  135090. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  135091. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  135092. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  135093. 10,
  135094. };
  135095. static static_codebook _huff_book__44cn1_s_short = {
  135096. 2, 81,
  135097. _huff_lengthlist__44cn1_s_short,
  135098. 0, 0, 0, 0, 0,
  135099. NULL,
  135100. NULL,
  135101. NULL,
  135102. NULL,
  135103. 0
  135104. };
  135105. static long _huff_lengthlist__44cn1_sm_long[] = {
  135106. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  135107. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  135108. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  135109. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  135110. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  135111. 17,
  135112. };
  135113. static static_codebook _huff_book__44cn1_sm_long = {
  135114. 2, 81,
  135115. _huff_lengthlist__44cn1_sm_long,
  135116. 0, 0, 0, 0, 0,
  135117. NULL,
  135118. NULL,
  135119. NULL,
  135120. NULL,
  135121. 0
  135122. };
  135123. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  135124. 1,
  135125. 0,
  135126. 2,
  135127. };
  135128. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  135129. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135130. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  135135. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135137. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  135140. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135142. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  135175. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  135180. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  135185. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  135221. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  135226. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  135231. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135539. 0,
  135540. };
  135541. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  135542. -0.5, 0.5,
  135543. };
  135544. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  135545. 1, 0, 2,
  135546. };
  135547. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  135548. _vq_quantthresh__44cn1_sm_p1_0,
  135549. _vq_quantmap__44cn1_sm_p1_0,
  135550. 3,
  135551. 3
  135552. };
  135553. static static_codebook _44cn1_sm_p1_0 = {
  135554. 8, 6561,
  135555. _vq_lengthlist__44cn1_sm_p1_0,
  135556. 1, -535822336, 1611661312, 2, 0,
  135557. _vq_quantlist__44cn1_sm_p1_0,
  135558. NULL,
  135559. &_vq_auxt__44cn1_sm_p1_0,
  135560. NULL,
  135561. 0
  135562. };
  135563. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  135564. 2,
  135565. 1,
  135566. 3,
  135567. 0,
  135568. 4,
  135569. };
  135570. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  135571. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  135573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135574. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135577. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135610. 0,
  135611. };
  135612. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  135613. -1.5, -0.5, 0.5, 1.5,
  135614. };
  135615. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  135616. 3, 1, 0, 2, 4,
  135617. };
  135618. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  135619. _vq_quantthresh__44cn1_sm_p2_0,
  135620. _vq_quantmap__44cn1_sm_p2_0,
  135621. 5,
  135622. 5
  135623. };
  135624. static static_codebook _44cn1_sm_p2_0 = {
  135625. 4, 625,
  135626. _vq_lengthlist__44cn1_sm_p2_0,
  135627. 1, -533725184, 1611661312, 3, 0,
  135628. _vq_quantlist__44cn1_sm_p2_0,
  135629. NULL,
  135630. &_vq_auxt__44cn1_sm_p2_0,
  135631. NULL,
  135632. 0
  135633. };
  135634. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  135635. 4,
  135636. 3,
  135637. 5,
  135638. 2,
  135639. 6,
  135640. 1,
  135641. 7,
  135642. 0,
  135643. 8,
  135644. };
  135645. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  135646. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  135647. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  135648. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  135649. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  135650. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135651. 0,
  135652. };
  135653. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  135654. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135655. };
  135656. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  135657. 7, 5, 3, 1, 0, 2, 4, 6,
  135658. 8,
  135659. };
  135660. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  135661. _vq_quantthresh__44cn1_sm_p3_0,
  135662. _vq_quantmap__44cn1_sm_p3_0,
  135663. 9,
  135664. 9
  135665. };
  135666. static static_codebook _44cn1_sm_p3_0 = {
  135667. 2, 81,
  135668. _vq_lengthlist__44cn1_sm_p3_0,
  135669. 1, -531628032, 1611661312, 4, 0,
  135670. _vq_quantlist__44cn1_sm_p3_0,
  135671. NULL,
  135672. &_vq_auxt__44cn1_sm_p3_0,
  135673. NULL,
  135674. 0
  135675. };
  135676. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  135677. 4,
  135678. 3,
  135679. 5,
  135680. 2,
  135681. 6,
  135682. 1,
  135683. 7,
  135684. 0,
  135685. 8,
  135686. };
  135687. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  135688. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  135689. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  135690. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  135691. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  135692. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  135693. 11,
  135694. };
  135695. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  135696. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135697. };
  135698. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  135699. 7, 5, 3, 1, 0, 2, 4, 6,
  135700. 8,
  135701. };
  135702. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  135703. _vq_quantthresh__44cn1_sm_p4_0,
  135704. _vq_quantmap__44cn1_sm_p4_0,
  135705. 9,
  135706. 9
  135707. };
  135708. static static_codebook _44cn1_sm_p4_0 = {
  135709. 2, 81,
  135710. _vq_lengthlist__44cn1_sm_p4_0,
  135711. 1, -531628032, 1611661312, 4, 0,
  135712. _vq_quantlist__44cn1_sm_p4_0,
  135713. NULL,
  135714. &_vq_auxt__44cn1_sm_p4_0,
  135715. NULL,
  135716. 0
  135717. };
  135718. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  135719. 8,
  135720. 7,
  135721. 9,
  135722. 6,
  135723. 10,
  135724. 5,
  135725. 11,
  135726. 4,
  135727. 12,
  135728. 3,
  135729. 13,
  135730. 2,
  135731. 14,
  135732. 1,
  135733. 15,
  135734. 0,
  135735. 16,
  135736. };
  135737. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  135738. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  135739. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  135740. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  135741. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135742. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  135743. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  135744. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  135745. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135746. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  135747. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  135748. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  135749. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  135750. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  135751. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  135752. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  135753. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  135754. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  135755. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  135756. 14,
  135757. };
  135758. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  135759. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135760. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135761. };
  135762. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  135763. 15, 13, 11, 9, 7, 5, 3, 1,
  135764. 0, 2, 4, 6, 8, 10, 12, 14,
  135765. 16,
  135766. };
  135767. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  135768. _vq_quantthresh__44cn1_sm_p5_0,
  135769. _vq_quantmap__44cn1_sm_p5_0,
  135770. 17,
  135771. 17
  135772. };
  135773. static static_codebook _44cn1_sm_p5_0 = {
  135774. 2, 289,
  135775. _vq_lengthlist__44cn1_sm_p5_0,
  135776. 1, -529530880, 1611661312, 5, 0,
  135777. _vq_quantlist__44cn1_sm_p5_0,
  135778. NULL,
  135779. &_vq_auxt__44cn1_sm_p5_0,
  135780. NULL,
  135781. 0
  135782. };
  135783. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  135784. 1,
  135785. 0,
  135786. 2,
  135787. };
  135788. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  135789. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  135790. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  135791. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  135792. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  135793. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  135794. 10,
  135795. };
  135796. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  135797. -5.5, 5.5,
  135798. };
  135799. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  135800. 1, 0, 2,
  135801. };
  135802. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  135803. _vq_quantthresh__44cn1_sm_p6_0,
  135804. _vq_quantmap__44cn1_sm_p6_0,
  135805. 3,
  135806. 3
  135807. };
  135808. static static_codebook _44cn1_sm_p6_0 = {
  135809. 4, 81,
  135810. _vq_lengthlist__44cn1_sm_p6_0,
  135811. 1, -529137664, 1618345984, 2, 0,
  135812. _vq_quantlist__44cn1_sm_p6_0,
  135813. NULL,
  135814. &_vq_auxt__44cn1_sm_p6_0,
  135815. NULL,
  135816. 0
  135817. };
  135818. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  135819. 5,
  135820. 4,
  135821. 6,
  135822. 3,
  135823. 7,
  135824. 2,
  135825. 8,
  135826. 1,
  135827. 9,
  135828. 0,
  135829. 10,
  135830. };
  135831. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  135832. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  135833. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  135834. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  135835. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  135836. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  135837. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  135838. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  135839. 10,10,10, 8, 9, 8, 8, 9, 8,
  135840. };
  135841. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  135842. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135843. 3.5, 4.5,
  135844. };
  135845. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  135846. 9, 7, 5, 3, 1, 0, 2, 4,
  135847. 6, 8, 10,
  135848. };
  135849. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  135850. _vq_quantthresh__44cn1_sm_p6_1,
  135851. _vq_quantmap__44cn1_sm_p6_1,
  135852. 11,
  135853. 11
  135854. };
  135855. static static_codebook _44cn1_sm_p6_1 = {
  135856. 2, 121,
  135857. _vq_lengthlist__44cn1_sm_p6_1,
  135858. 1, -531365888, 1611661312, 4, 0,
  135859. _vq_quantlist__44cn1_sm_p6_1,
  135860. NULL,
  135861. &_vq_auxt__44cn1_sm_p6_1,
  135862. NULL,
  135863. 0
  135864. };
  135865. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  135866. 6,
  135867. 5,
  135868. 7,
  135869. 4,
  135870. 8,
  135871. 3,
  135872. 9,
  135873. 2,
  135874. 10,
  135875. 1,
  135876. 11,
  135877. 0,
  135878. 12,
  135879. };
  135880. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  135881. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  135882. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  135883. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135884. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135885. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  135886. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  135887. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  135888. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  135889. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  135890. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  135891. 0,13,12,12,12,13,13,13,14,
  135892. };
  135893. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  135894. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135895. 12.5, 17.5, 22.5, 27.5,
  135896. };
  135897. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  135898. 11, 9, 7, 5, 3, 1, 0, 2,
  135899. 4, 6, 8, 10, 12,
  135900. };
  135901. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  135902. _vq_quantthresh__44cn1_sm_p7_0,
  135903. _vq_quantmap__44cn1_sm_p7_0,
  135904. 13,
  135905. 13
  135906. };
  135907. static static_codebook _44cn1_sm_p7_0 = {
  135908. 2, 169,
  135909. _vq_lengthlist__44cn1_sm_p7_0,
  135910. 1, -526516224, 1616117760, 4, 0,
  135911. _vq_quantlist__44cn1_sm_p7_0,
  135912. NULL,
  135913. &_vq_auxt__44cn1_sm_p7_0,
  135914. NULL,
  135915. 0
  135916. };
  135917. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  135918. 2,
  135919. 1,
  135920. 3,
  135921. 0,
  135922. 4,
  135923. };
  135924. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  135925. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  135926. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  135927. };
  135928. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  135929. -1.5, -0.5, 0.5, 1.5,
  135930. };
  135931. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  135932. 3, 1, 0, 2, 4,
  135933. };
  135934. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  135935. _vq_quantthresh__44cn1_sm_p7_1,
  135936. _vq_quantmap__44cn1_sm_p7_1,
  135937. 5,
  135938. 5
  135939. };
  135940. static static_codebook _44cn1_sm_p7_1 = {
  135941. 2, 25,
  135942. _vq_lengthlist__44cn1_sm_p7_1,
  135943. 1, -533725184, 1611661312, 3, 0,
  135944. _vq_quantlist__44cn1_sm_p7_1,
  135945. NULL,
  135946. &_vq_auxt__44cn1_sm_p7_1,
  135947. NULL,
  135948. 0
  135949. };
  135950. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  135951. 4,
  135952. 3,
  135953. 5,
  135954. 2,
  135955. 6,
  135956. 1,
  135957. 7,
  135958. 0,
  135959. 8,
  135960. };
  135961. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  135962. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  135963. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  135964. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  135965. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  135966. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  135967. 14,
  135968. };
  135969. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  135970. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  135971. };
  135972. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  135973. 7, 5, 3, 1, 0, 2, 4, 6,
  135974. 8,
  135975. };
  135976. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  135977. _vq_quantthresh__44cn1_sm_p8_0,
  135978. _vq_quantmap__44cn1_sm_p8_0,
  135979. 9,
  135980. 9
  135981. };
  135982. static static_codebook _44cn1_sm_p8_0 = {
  135983. 2, 81,
  135984. _vq_lengthlist__44cn1_sm_p8_0,
  135985. 1, -516186112, 1627103232, 4, 0,
  135986. _vq_quantlist__44cn1_sm_p8_0,
  135987. NULL,
  135988. &_vq_auxt__44cn1_sm_p8_0,
  135989. NULL,
  135990. 0
  135991. };
  135992. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  135993. 6,
  135994. 5,
  135995. 7,
  135996. 4,
  135997. 8,
  135998. 3,
  135999. 9,
  136000. 2,
  136001. 10,
  136002. 1,
  136003. 11,
  136004. 0,
  136005. 12,
  136006. };
  136007. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  136008. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  136009. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  136010. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  136011. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  136012. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  136013. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  136014. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  136015. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  136016. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  136017. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  136018. 17,12,12,11,10,13,11,13,13,
  136019. };
  136020. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  136021. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136022. 42.5, 59.5, 76.5, 93.5,
  136023. };
  136024. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  136025. 11, 9, 7, 5, 3, 1, 0, 2,
  136026. 4, 6, 8, 10, 12,
  136027. };
  136028. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  136029. _vq_quantthresh__44cn1_sm_p8_1,
  136030. _vq_quantmap__44cn1_sm_p8_1,
  136031. 13,
  136032. 13
  136033. };
  136034. static static_codebook _44cn1_sm_p8_1 = {
  136035. 2, 169,
  136036. _vq_lengthlist__44cn1_sm_p8_1,
  136037. 1, -522616832, 1620115456, 4, 0,
  136038. _vq_quantlist__44cn1_sm_p8_1,
  136039. NULL,
  136040. &_vq_auxt__44cn1_sm_p8_1,
  136041. NULL,
  136042. 0
  136043. };
  136044. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  136045. 8,
  136046. 7,
  136047. 9,
  136048. 6,
  136049. 10,
  136050. 5,
  136051. 11,
  136052. 4,
  136053. 12,
  136054. 3,
  136055. 13,
  136056. 2,
  136057. 14,
  136058. 1,
  136059. 15,
  136060. 0,
  136061. 16,
  136062. };
  136063. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  136064. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  136065. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  136066. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  136067. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136068. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  136069. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  136070. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  136071. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  136072. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  136073. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  136074. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  136075. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  136076. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  136077. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  136078. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  136079. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  136080. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  136081. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  136082. 9,
  136083. };
  136084. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  136085. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136086. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136087. };
  136088. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  136089. 15, 13, 11, 9, 7, 5, 3, 1,
  136090. 0, 2, 4, 6, 8, 10, 12, 14,
  136091. 16,
  136092. };
  136093. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  136094. _vq_quantthresh__44cn1_sm_p8_2,
  136095. _vq_quantmap__44cn1_sm_p8_2,
  136096. 17,
  136097. 17
  136098. };
  136099. static static_codebook _44cn1_sm_p8_2 = {
  136100. 2, 289,
  136101. _vq_lengthlist__44cn1_sm_p8_2,
  136102. 1, -529530880, 1611661312, 5, 0,
  136103. _vq_quantlist__44cn1_sm_p8_2,
  136104. NULL,
  136105. &_vq_auxt__44cn1_sm_p8_2,
  136106. NULL,
  136107. 0
  136108. };
  136109. static long _huff_lengthlist__44cn1_sm_short[] = {
  136110. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  136111. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  136112. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  136113. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  136114. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  136115. 9,
  136116. };
  136117. static static_codebook _huff_book__44cn1_sm_short = {
  136118. 2, 81,
  136119. _huff_lengthlist__44cn1_sm_short,
  136120. 0, 0, 0, 0, 0,
  136121. NULL,
  136122. NULL,
  136123. NULL,
  136124. NULL,
  136125. 0
  136126. };
  136127. /********* End of inlined file: res_books_stereo.h *********/
  136128. /***** residue backends *********************************************/
  136129. static vorbis_info_residue0 _residue_44_low={
  136130. 0,-1, -1, 9,-1,
  136131. /* 0 1 2 3 4 5 6 7 */
  136132. {0},
  136133. {-1},
  136134. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  136135. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  136136. };
  136137. static vorbis_info_residue0 _residue_44_mid={
  136138. 0,-1, -1, 10,-1,
  136139. /* 0 1 2 3 4 5 6 7 8 */
  136140. {0},
  136141. {-1},
  136142. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  136143. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  136144. };
  136145. static vorbis_info_residue0 _residue_44_high={
  136146. 0,-1, -1, 10,-1,
  136147. /* 0 1 2 3 4 5 6 7 8 */
  136148. {0},
  136149. {-1},
  136150. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  136151. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  136152. };
  136153. static static_bookblock _resbook_44s_n1={
  136154. {
  136155. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  136156. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  136157. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  136158. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  136159. }
  136160. };
  136161. static static_bookblock _resbook_44sm_n1={
  136162. {
  136163. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  136164. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  136165. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  136166. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  136167. }
  136168. };
  136169. static static_bookblock _resbook_44s_0={
  136170. {
  136171. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  136172. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  136173. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  136174. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  136175. }
  136176. };
  136177. static static_bookblock _resbook_44sm_0={
  136178. {
  136179. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  136180. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  136181. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  136182. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  136183. }
  136184. };
  136185. static static_bookblock _resbook_44s_1={
  136186. {
  136187. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  136188. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  136189. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  136190. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  136191. }
  136192. };
  136193. static static_bookblock _resbook_44sm_1={
  136194. {
  136195. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  136196. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  136197. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  136198. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  136199. }
  136200. };
  136201. static static_bookblock _resbook_44s_2={
  136202. {
  136203. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  136204. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  136205. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  136206. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  136207. }
  136208. };
  136209. static static_bookblock _resbook_44s_3={
  136210. {
  136211. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  136212. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  136213. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  136214. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  136215. }
  136216. };
  136217. static static_bookblock _resbook_44s_4={
  136218. {
  136219. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  136220. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  136221. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  136222. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  136223. }
  136224. };
  136225. static static_bookblock _resbook_44s_5={
  136226. {
  136227. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  136228. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  136229. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  136230. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  136231. }
  136232. };
  136233. static static_bookblock _resbook_44s_6={
  136234. {
  136235. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  136236. {0,0,&_44c6_s_p4_0},
  136237. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  136238. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  136239. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  136240. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  136241. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  136242. }
  136243. };
  136244. static static_bookblock _resbook_44s_7={
  136245. {
  136246. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  136247. {0,0,&_44c7_s_p4_0},
  136248. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  136249. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  136250. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  136251. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  136252. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  136253. }
  136254. };
  136255. static static_bookblock _resbook_44s_8={
  136256. {
  136257. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  136258. {0,0,&_44c8_s_p4_0},
  136259. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  136260. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  136261. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  136262. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  136263. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  136264. }
  136265. };
  136266. static static_bookblock _resbook_44s_9={
  136267. {
  136268. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  136269. {0,0,&_44c9_s_p4_0},
  136270. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  136271. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  136272. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  136273. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  136274. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  136275. }
  136276. };
  136277. static vorbis_residue_template _res_44s_n1[]={
  136278. {2,0, &_residue_44_low,
  136279. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  136280. &_resbook_44s_n1,&_resbook_44sm_n1},
  136281. {2,0, &_residue_44_low,
  136282. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  136283. &_resbook_44s_n1,&_resbook_44sm_n1}
  136284. };
  136285. static vorbis_residue_template _res_44s_0[]={
  136286. {2,0, &_residue_44_low,
  136287. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  136288. &_resbook_44s_0,&_resbook_44sm_0},
  136289. {2,0, &_residue_44_low,
  136290. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  136291. &_resbook_44s_0,&_resbook_44sm_0}
  136292. };
  136293. static vorbis_residue_template _res_44s_1[]={
  136294. {2,0, &_residue_44_low,
  136295. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  136296. &_resbook_44s_1,&_resbook_44sm_1},
  136297. {2,0, &_residue_44_low,
  136298. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  136299. &_resbook_44s_1,&_resbook_44sm_1}
  136300. };
  136301. static vorbis_residue_template _res_44s_2[]={
  136302. {2,0, &_residue_44_mid,
  136303. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  136304. &_resbook_44s_2,&_resbook_44s_2},
  136305. {2,0, &_residue_44_mid,
  136306. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  136307. &_resbook_44s_2,&_resbook_44s_2}
  136308. };
  136309. static vorbis_residue_template _res_44s_3[]={
  136310. {2,0, &_residue_44_mid,
  136311. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  136312. &_resbook_44s_3,&_resbook_44s_3},
  136313. {2,0, &_residue_44_mid,
  136314. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  136315. &_resbook_44s_3,&_resbook_44s_3}
  136316. };
  136317. static vorbis_residue_template _res_44s_4[]={
  136318. {2,0, &_residue_44_mid,
  136319. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  136320. &_resbook_44s_4,&_resbook_44s_4},
  136321. {2,0, &_residue_44_mid,
  136322. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  136323. &_resbook_44s_4,&_resbook_44s_4}
  136324. };
  136325. static vorbis_residue_template _res_44s_5[]={
  136326. {2,0, &_residue_44_mid,
  136327. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  136328. &_resbook_44s_5,&_resbook_44s_5},
  136329. {2,0, &_residue_44_mid,
  136330. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  136331. &_resbook_44s_5,&_resbook_44s_5}
  136332. };
  136333. static vorbis_residue_template _res_44s_6[]={
  136334. {2,0, &_residue_44_high,
  136335. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  136336. &_resbook_44s_6,&_resbook_44s_6},
  136337. {2,0, &_residue_44_high,
  136338. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  136339. &_resbook_44s_6,&_resbook_44s_6}
  136340. };
  136341. static vorbis_residue_template _res_44s_7[]={
  136342. {2,0, &_residue_44_high,
  136343. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  136344. &_resbook_44s_7,&_resbook_44s_7},
  136345. {2,0, &_residue_44_high,
  136346. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  136347. &_resbook_44s_7,&_resbook_44s_7}
  136348. };
  136349. static vorbis_residue_template _res_44s_8[]={
  136350. {2,0, &_residue_44_high,
  136351. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  136352. &_resbook_44s_8,&_resbook_44s_8},
  136353. {2,0, &_residue_44_high,
  136354. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  136355. &_resbook_44s_8,&_resbook_44s_8}
  136356. };
  136357. static vorbis_residue_template _res_44s_9[]={
  136358. {2,0, &_residue_44_high,
  136359. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  136360. &_resbook_44s_9,&_resbook_44s_9},
  136361. {2,0, &_residue_44_high,
  136362. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  136363. &_resbook_44s_9,&_resbook_44s_9}
  136364. };
  136365. static vorbis_mapping_template _mapres_template_44_stereo[]={
  136366. { _map_nominal, _res_44s_n1 }, /* -1 */
  136367. { _map_nominal, _res_44s_0 }, /* 0 */
  136368. { _map_nominal, _res_44s_1 }, /* 1 */
  136369. { _map_nominal, _res_44s_2 }, /* 2 */
  136370. { _map_nominal, _res_44s_3 }, /* 3 */
  136371. { _map_nominal, _res_44s_4 }, /* 4 */
  136372. { _map_nominal, _res_44s_5 }, /* 5 */
  136373. { _map_nominal, _res_44s_6 }, /* 6 */
  136374. { _map_nominal, _res_44s_7 }, /* 7 */
  136375. { _map_nominal, _res_44s_8 }, /* 8 */
  136376. { _map_nominal, _res_44s_9 }, /* 9 */
  136377. };
  136378. /********* End of inlined file: residue_44.h *********/
  136379. /********* Start of inlined file: psych_44.h *********/
  136380. /* preecho trigger settings *****************************************/
  136381. static vorbis_info_psy_global _psy_global_44[5]={
  136382. {8, /* lines per eighth octave */
  136383. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  136384. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  136385. -6.f,
  136386. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  136387. },
  136388. {8, /* lines per eighth octave */
  136389. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  136390. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  136391. -6.f,
  136392. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  136393. },
  136394. {8, /* lines per eighth octave */
  136395. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  136396. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  136397. -6.f,
  136398. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  136399. },
  136400. {8, /* lines per eighth octave */
  136401. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  136402. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  136403. -6.f,
  136404. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  136405. },
  136406. {8, /* lines per eighth octave */
  136407. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  136408. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  136409. -6.f,
  136410. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  136411. },
  136412. };
  136413. /* noise compander lookups * low, mid, high quality ****************/
  136414. static compandblock _psy_compand_44[6]={
  136415. /* sub-mode Z short */
  136416. {{
  136417. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  136418. 8, 9,10,11,12,13,14, 15, /* 15dB */
  136419. 16,17,18,19,20,21,22, 23, /* 23dB */
  136420. 24,25,26,27,28,29,30, 31, /* 31dB */
  136421. 32,33,34,35,36,37,38, 39, /* 39dB */
  136422. }},
  136423. /* mode_Z nominal short */
  136424. {{
  136425. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  136426. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  136427. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  136428. 15,16,17,17,17,18,18, 19, /* 31dB */
  136429. 19,19,20,21,22,23,24, 25, /* 39dB */
  136430. }},
  136431. /* mode A short */
  136432. {{
  136433. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  136434. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  136435. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  136436. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  136437. 11,12,13,14,15,16,17, 18, /* 39dB */
  136438. }},
  136439. /* sub-mode Z long */
  136440. {{
  136441. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  136442. 8, 9,10,11,12,13,14, 15, /* 15dB */
  136443. 16,17,18,19,20,21,22, 23, /* 23dB */
  136444. 24,25,26,27,28,29,30, 31, /* 31dB */
  136445. 32,33,34,35,36,37,38, 39, /* 39dB */
  136446. }},
  136447. /* mode_Z nominal long */
  136448. {{
  136449. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  136450. 8, 9,10,11,12,12,13, 13, /* 15dB */
  136451. 13,14,14,14,15,15,15, 15, /* 23dB */
  136452. 16,16,17,17,17,18,18, 19, /* 31dB */
  136453. 19,19,20,21,22,23,24, 25, /* 39dB */
  136454. }},
  136455. /* mode A long */
  136456. {{
  136457. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  136458. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  136459. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  136460. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  136461. 11,12,13,14,15,16,17, 18, /* 39dB */
  136462. }}
  136463. };
  136464. /* tonal masking curve level adjustments *************************/
  136465. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  136466. /* 63 125 250 500 1 2 4 8 16 */
  136467. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  136468. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  136469. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  136470. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  136471. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  136472. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  136473. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  136474. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  136475. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  136476. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  136477. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  136478. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  136479. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  136480. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  136481. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  136482. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  136483. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  136484. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  136485. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  136486. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  136487. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  136488. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  136489. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  136490. };
  136491. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  136492. /* 63 125 250 500 1 2 4 8 16 */
  136493. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  136494. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  136495. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  136496. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  136497. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  136498. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  136499. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  136500. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  136501. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  136502. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  136503. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  136504. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  136505. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  136506. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  136507. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  136508. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  136509. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  136510. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  136511. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  136512. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  136513. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  136514. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  136515. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  136516. };
  136517. /* noise bias (transition block) */
  136518. static noise3 _psy_noisebias_trans[12]={
  136519. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  136520. /* -1 */
  136521. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  136522. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  136523. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  136524. /* 0
  136525. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136526. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  136527. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  136528. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136529. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  136530. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  136531. /* 1
  136532. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136533. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  136534. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  136535. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136536. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  136537. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  136538. /* 2
  136539. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  136540. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  136541. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  136542. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  136543. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  136544. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  136545. /* 3
  136546. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  136547. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  136548. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  136549. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  136550. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  136551. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  136552. /* 4
  136553. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136554. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  136555. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  136556. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136557. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  136558. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  136559. /* 5
  136560. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136561. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  136562. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  136563. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136564. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  136565. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  136566. /* 6
  136567. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136568. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  136569. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  136570. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136571. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  136572. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  136573. /* 7
  136574. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136575. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  136576. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  136577. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  136578. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  136579. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  136580. /* 8
  136581. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  136582. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  136583. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  136584. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  136585. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  136586. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  136587. /* 9
  136588. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  136589. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  136590. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  136591. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  136592. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  136593. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  136594. /* 10 */
  136595. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  136596. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  136597. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  136598. };
  136599. /* noise bias (long block) */
  136600. static noise3 _psy_noisebias_long[12]={
  136601. /*63 125 250 500 1k 2k 4k 8k 16k*/
  136602. /* -1 */
  136603. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  136604. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  136605. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  136606. /* 0 */
  136607. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  136608. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  136609. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  136610. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  136611. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  136612. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  136613. /* 1 */
  136614. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136615. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  136616. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  136617. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  136618. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  136619. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  136620. /* 2 */
  136621. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  136622. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  136623. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  136624. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  136625. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  136626. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  136627. /* 3 */
  136628. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  136629. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  136630. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  136631. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  136632. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  136633. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  136634. /* 4 */
  136635. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136636. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  136637. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  136638. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136639. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  136640. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  136641. /* 5 */
  136642. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136643. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  136644. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  136645. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136646. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  136647. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  136648. /* 6 */
  136649. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136650. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  136651. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  136652. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136653. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  136654. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  136655. /* 7 */
  136656. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  136657. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  136658. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  136659. /* 8 */
  136660. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  136661. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  136662. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  136663. /* 9 */
  136664. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  136665. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  136666. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  136667. /* 10 */
  136668. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  136669. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  136670. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  136671. };
  136672. /* noise bias (impulse block) */
  136673. static noise3 _psy_noisebias_impulse[12]={
  136674. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  136675. /* -1 */
  136676. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  136677. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  136678. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  136679. /* 0 */
  136680. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  136681. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  136682. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  136683. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  136684. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  136685. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  136686. /* 1 */
  136687. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  136688. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  136689. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  136690. /* 2 */
  136691. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  136692. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  136693. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  136694. /* 3 */
  136695. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  136696. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  136697. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  136698. /* 4 */
  136699. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  136700. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  136701. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  136702. /* 5 */
  136703. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  136704. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  136705. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  136706. /* 6
  136707. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  136708. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  136709. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  136710. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  136711. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  136712. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  136713. /* 7 */
  136714. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  136715. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  136716. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  136717. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  136718. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  136719. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  136720. /* 8 */
  136721. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  136722. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  136723. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  136724. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  136725. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  136726. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  136727. /* 9 */
  136728. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  136729. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  136730. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  136731. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  136732. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  136733. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  136734. /* 10 */
  136735. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  136736. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  136737. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  136738. };
  136739. /* noise bias (padding block) */
  136740. static noise3 _psy_noisebias_padding[12]={
  136741. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  136742. /* -1 */
  136743. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  136744. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  136745. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  136746. /* 0 */
  136747. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  136748. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  136749. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  136750. /* 1 */
  136751. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  136752. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  136753. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  136754. /* 2 */
  136755. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  136756. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  136757. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  136758. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  136759. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  136760. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  136761. /* 3 */
  136762. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  136763. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  136764. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  136765. /* 4 */
  136766. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  136767. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  136768. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  136769. /* 5 */
  136770. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  136771. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  136772. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  136773. /* 6 */
  136774. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  136775. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  136776. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  136777. /* 7 */
  136778. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  136779. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  136780. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  136781. /* 8 */
  136782. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  136783. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  136784. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  136785. /* 9 */
  136786. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  136787. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  136788. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  136789. /* 10 */
  136790. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  136791. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  136792. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  136793. };
  136794. static noiseguard _psy_noiseguards_44[4]={
  136795. {3,3,15},
  136796. {3,3,15},
  136797. {10,10,100},
  136798. {10,10,100},
  136799. };
  136800. static int _psy_tone_suppress[12]={
  136801. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  136802. };
  136803. static int _psy_tone_0dB[12]={
  136804. 90,90,95,95,95,95,105,105,105,105,105,105,
  136805. };
  136806. static int _psy_noise_suppress[12]={
  136807. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  136808. };
  136809. static vorbis_info_psy _psy_info_template={
  136810. /* blockflag */
  136811. -1,
  136812. /* ath_adjatt, ath_maxatt */
  136813. -140.,-140.,
  136814. /* tonemask att boost/decay,suppr,curves */
  136815. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  136816. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  136817. 1, -0.f, .5f, .5f, 0,0,0,
  136818. /* noiseoffset*3, noisecompand, max_curve_dB */
  136819. {{-1},{-1},{-1}},{-1},105.f,
  136820. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  136821. 0,0,-1,-1,0.,
  136822. };
  136823. /* ath ****************/
  136824. static int _psy_ath_floater[12]={
  136825. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  136826. };
  136827. static int _psy_ath_abs[12]={
  136828. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  136829. };
  136830. /* stereo setup. These don't map directly to quality level, there's
  136831. an additional indirection as several of the below may be used in a
  136832. single bitmanaged stream
  136833. ****************/
  136834. /* various stereo possibilities */
  136835. /* stereo mode by base quality level */
  136836. static adj_stereo _psy_stereo_modes_44[12]={
  136837. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  136838. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  136839. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  136840. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  136841. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  136842. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  136843. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  136844. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  136845. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  136846. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136847. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  136848. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  136849. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136850. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  136851. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  136852. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  136853. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  136854. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136855. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136856. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  136857. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  136858. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  136859. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136860. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  136861. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  136862. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  136863. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136864. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136865. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  136866. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  136867. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  136868. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  136869. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136870. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  136871. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136872. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  136873. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  136874. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136875. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  136876. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136877. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  136878. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136879. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136880. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136881. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  136882. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  136883. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136884. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  136885. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136886. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136887. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136888. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  136889. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136890. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136891. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  136892. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136893. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  136894. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136895. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136896. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136897. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136898. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136899. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136900. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  136901. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136902. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  136903. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136904. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136905. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136906. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136907. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136908. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136909. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  136910. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136911. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  136912. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136913. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136914. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  136915. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136916. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  136917. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136918. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136919. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  136920. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136921. };
  136922. /* tone master attenuation by base quality mode and bitrate tweak */
  136923. static att3 _psy_tone_masteratt_44[12]={
  136924. {{ 35, 21, 9}, 0, 0}, /* -1 */
  136925. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  136926. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  136927. {{ 25, 12, 2}, 0, 0}, /* 1 */
  136928. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  136929. {{ 20, 9, -3}, 0, 0}, /* 2 */
  136930. {{ 20, 9, -4}, 0, 0}, /* 3 */
  136931. {{ 20, 9, -4}, 0, 0}, /* 4 */
  136932. {{ 20, 6, -6}, 0, 0}, /* 5 */
  136933. {{ 20, 3, -10}, 0, 0}, /* 6 */
  136934. {{ 18, 1, -14}, 0, 0}, /* 7 */
  136935. {{ 18, 0, -16}, 0, 0}, /* 8 */
  136936. {{ 18, -2, -16}, 0, 0}, /* 9 */
  136937. {{ 12, -2, -20}, 0, 0}, /* 10 */
  136938. };
  136939. /* lowpass by mode **************/
  136940. static double _psy_lowpass_44[12]={
  136941. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  136942. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  136943. };
  136944. /* noise normalization **********/
  136945. static int _noise_start_short_44[11]={
  136946. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  136947. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  136948. };
  136949. static int _noise_start_long_44[11]={
  136950. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  136951. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  136952. };
  136953. static int _noise_part_short_44[11]={
  136954. 8,8,8,8,8,8,8,8,8,8,8
  136955. };
  136956. static int _noise_part_long_44[11]={
  136957. 32,32,32,32,32,32,32,32,32,32,32
  136958. };
  136959. static double _noise_thresh_44[11]={
  136960. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  136961. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  136962. };
  136963. static double _noise_thresh_5only[2]={
  136964. .5,.5,
  136965. };
  136966. /********* End of inlined file: psych_44.h *********/
  136967. static double rate_mapping_44_stereo[12]={
  136968. 22500.,32000.,40000.,48000.,56000.,64000.,
  136969. 80000.,96000.,112000.,128000.,160000.,250001.
  136970. };
  136971. static double quality_mapping_44[12]={
  136972. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  136973. };
  136974. static int blocksize_short_44[11]={
  136975. 512,256,256,256,256,256,256,256,256,256,256
  136976. };
  136977. static int blocksize_long_44[11]={
  136978. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  136979. };
  136980. static double _psy_compand_short_mapping[12]={
  136981. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  136982. };
  136983. static double _psy_compand_long_mapping[12]={
  136984. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  136985. };
  136986. static double _global_mapping_44[12]={
  136987. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  136988. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  136989. };
  136990. static int _floor_short_mapping_44[11]={
  136991. 1,0,0,2,2,4,5,5,5,5,5
  136992. };
  136993. static int _floor_long_mapping_44[11]={
  136994. 8,7,7,7,7,7,7,7,7,7,7
  136995. };
  136996. ve_setup_data_template ve_setup_44_stereo={
  136997. 11,
  136998. rate_mapping_44_stereo,
  136999. quality_mapping_44,
  137000. 2,
  137001. 40000,
  137002. 50000,
  137003. blocksize_short_44,
  137004. blocksize_long_44,
  137005. _psy_tone_masteratt_44,
  137006. _psy_tone_0dB,
  137007. _psy_tone_suppress,
  137008. _vp_tonemask_adj_otherblock,
  137009. _vp_tonemask_adj_longblock,
  137010. _vp_tonemask_adj_otherblock,
  137011. _psy_noiseguards_44,
  137012. _psy_noisebias_impulse,
  137013. _psy_noisebias_padding,
  137014. _psy_noisebias_trans,
  137015. _psy_noisebias_long,
  137016. _psy_noise_suppress,
  137017. _psy_compand_44,
  137018. _psy_compand_short_mapping,
  137019. _psy_compand_long_mapping,
  137020. {_noise_start_short_44,_noise_start_long_44},
  137021. {_noise_part_short_44,_noise_part_long_44},
  137022. _noise_thresh_44,
  137023. _psy_ath_floater,
  137024. _psy_ath_abs,
  137025. _psy_lowpass_44,
  137026. _psy_global_44,
  137027. _global_mapping_44,
  137028. _psy_stereo_modes_44,
  137029. _floor_books,
  137030. _floor,
  137031. _floor_short_mapping_44,
  137032. _floor_long_mapping_44,
  137033. _mapres_template_44_stereo
  137034. };
  137035. /********* End of inlined file: setup_44.h *********/
  137036. /********* Start of inlined file: setup_44u.h *********/
  137037. /********* Start of inlined file: residue_44u.h *********/
  137038. /********* Start of inlined file: res_books_uncoupled.h *********/
  137039. static long _vq_quantlist__16u0__p1_0[] = {
  137040. 1,
  137041. 0,
  137042. 2,
  137043. };
  137044. static long _vq_lengthlist__16u0__p1_0[] = {
  137045. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  137046. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  137047. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  137048. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  137049. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  137050. 12,
  137051. };
  137052. static float _vq_quantthresh__16u0__p1_0[] = {
  137053. -0.5, 0.5,
  137054. };
  137055. static long _vq_quantmap__16u0__p1_0[] = {
  137056. 1, 0, 2,
  137057. };
  137058. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  137059. _vq_quantthresh__16u0__p1_0,
  137060. _vq_quantmap__16u0__p1_0,
  137061. 3,
  137062. 3
  137063. };
  137064. static static_codebook _16u0__p1_0 = {
  137065. 4, 81,
  137066. _vq_lengthlist__16u0__p1_0,
  137067. 1, -535822336, 1611661312, 2, 0,
  137068. _vq_quantlist__16u0__p1_0,
  137069. NULL,
  137070. &_vq_auxt__16u0__p1_0,
  137071. NULL,
  137072. 0
  137073. };
  137074. static long _vq_quantlist__16u0__p2_0[] = {
  137075. 1,
  137076. 0,
  137077. 2,
  137078. };
  137079. static long _vq_lengthlist__16u0__p2_0[] = {
  137080. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  137081. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  137082. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  137083. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  137084. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  137085. 8,
  137086. };
  137087. static float _vq_quantthresh__16u0__p2_0[] = {
  137088. -0.5, 0.5,
  137089. };
  137090. static long _vq_quantmap__16u0__p2_0[] = {
  137091. 1, 0, 2,
  137092. };
  137093. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  137094. _vq_quantthresh__16u0__p2_0,
  137095. _vq_quantmap__16u0__p2_0,
  137096. 3,
  137097. 3
  137098. };
  137099. static static_codebook _16u0__p2_0 = {
  137100. 4, 81,
  137101. _vq_lengthlist__16u0__p2_0,
  137102. 1, -535822336, 1611661312, 2, 0,
  137103. _vq_quantlist__16u0__p2_0,
  137104. NULL,
  137105. &_vq_auxt__16u0__p2_0,
  137106. NULL,
  137107. 0
  137108. };
  137109. static long _vq_quantlist__16u0__p3_0[] = {
  137110. 2,
  137111. 1,
  137112. 3,
  137113. 0,
  137114. 4,
  137115. };
  137116. static long _vq_lengthlist__16u0__p3_0[] = {
  137117. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  137118. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  137119. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  137120. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  137121. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  137122. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  137123. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  137124. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  137125. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  137126. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  137127. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  137128. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  137129. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  137130. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  137131. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  137132. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  137133. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  137134. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  137135. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  137136. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  137137. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  137138. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  137139. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  137140. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  137141. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  137142. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  137143. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  137144. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  137145. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  137146. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  137147. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  137148. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  137149. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  137150. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  137151. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  137152. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  137153. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  137154. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  137155. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  137156. 18,
  137157. };
  137158. static float _vq_quantthresh__16u0__p3_0[] = {
  137159. -1.5, -0.5, 0.5, 1.5,
  137160. };
  137161. static long _vq_quantmap__16u0__p3_0[] = {
  137162. 3, 1, 0, 2, 4,
  137163. };
  137164. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  137165. _vq_quantthresh__16u0__p3_0,
  137166. _vq_quantmap__16u0__p3_0,
  137167. 5,
  137168. 5
  137169. };
  137170. static static_codebook _16u0__p3_0 = {
  137171. 4, 625,
  137172. _vq_lengthlist__16u0__p3_0,
  137173. 1, -533725184, 1611661312, 3, 0,
  137174. _vq_quantlist__16u0__p3_0,
  137175. NULL,
  137176. &_vq_auxt__16u0__p3_0,
  137177. NULL,
  137178. 0
  137179. };
  137180. static long _vq_quantlist__16u0__p4_0[] = {
  137181. 2,
  137182. 1,
  137183. 3,
  137184. 0,
  137185. 4,
  137186. };
  137187. static long _vq_lengthlist__16u0__p4_0[] = {
  137188. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  137189. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  137190. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  137191. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  137192. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  137193. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  137194. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  137195. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  137196. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  137197. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  137198. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  137199. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  137200. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  137201. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  137202. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  137203. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  137204. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  137205. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  137206. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  137207. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  137208. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  137209. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  137210. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  137211. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  137212. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  137213. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  137214. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  137215. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  137216. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  137217. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  137218. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  137219. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  137220. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  137221. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  137222. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  137223. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  137224. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  137225. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  137226. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  137227. 11,
  137228. };
  137229. static float _vq_quantthresh__16u0__p4_0[] = {
  137230. -1.5, -0.5, 0.5, 1.5,
  137231. };
  137232. static long _vq_quantmap__16u0__p4_0[] = {
  137233. 3, 1, 0, 2, 4,
  137234. };
  137235. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  137236. _vq_quantthresh__16u0__p4_0,
  137237. _vq_quantmap__16u0__p4_0,
  137238. 5,
  137239. 5
  137240. };
  137241. static static_codebook _16u0__p4_0 = {
  137242. 4, 625,
  137243. _vq_lengthlist__16u0__p4_0,
  137244. 1, -533725184, 1611661312, 3, 0,
  137245. _vq_quantlist__16u0__p4_0,
  137246. NULL,
  137247. &_vq_auxt__16u0__p4_0,
  137248. NULL,
  137249. 0
  137250. };
  137251. static long _vq_quantlist__16u0__p5_0[] = {
  137252. 4,
  137253. 3,
  137254. 5,
  137255. 2,
  137256. 6,
  137257. 1,
  137258. 7,
  137259. 0,
  137260. 8,
  137261. };
  137262. static long _vq_lengthlist__16u0__p5_0[] = {
  137263. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  137264. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  137265. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  137266. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  137267. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  137268. 12,
  137269. };
  137270. static float _vq_quantthresh__16u0__p5_0[] = {
  137271. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137272. };
  137273. static long _vq_quantmap__16u0__p5_0[] = {
  137274. 7, 5, 3, 1, 0, 2, 4, 6,
  137275. 8,
  137276. };
  137277. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  137278. _vq_quantthresh__16u0__p5_0,
  137279. _vq_quantmap__16u0__p5_0,
  137280. 9,
  137281. 9
  137282. };
  137283. static static_codebook _16u0__p5_0 = {
  137284. 2, 81,
  137285. _vq_lengthlist__16u0__p5_0,
  137286. 1, -531628032, 1611661312, 4, 0,
  137287. _vq_quantlist__16u0__p5_0,
  137288. NULL,
  137289. &_vq_auxt__16u0__p5_0,
  137290. NULL,
  137291. 0
  137292. };
  137293. static long _vq_quantlist__16u0__p6_0[] = {
  137294. 6,
  137295. 5,
  137296. 7,
  137297. 4,
  137298. 8,
  137299. 3,
  137300. 9,
  137301. 2,
  137302. 10,
  137303. 1,
  137304. 11,
  137305. 0,
  137306. 12,
  137307. };
  137308. static long _vq_lengthlist__16u0__p6_0[] = {
  137309. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  137310. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  137311. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  137312. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  137313. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  137314. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  137315. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  137316. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  137317. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  137318. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  137319. 18, 0,19, 0, 0, 0, 0, 0, 0,
  137320. };
  137321. static float _vq_quantthresh__16u0__p6_0[] = {
  137322. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137323. 12.5, 17.5, 22.5, 27.5,
  137324. };
  137325. static long _vq_quantmap__16u0__p6_0[] = {
  137326. 11, 9, 7, 5, 3, 1, 0, 2,
  137327. 4, 6, 8, 10, 12,
  137328. };
  137329. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  137330. _vq_quantthresh__16u0__p6_0,
  137331. _vq_quantmap__16u0__p6_0,
  137332. 13,
  137333. 13
  137334. };
  137335. static static_codebook _16u0__p6_0 = {
  137336. 2, 169,
  137337. _vq_lengthlist__16u0__p6_0,
  137338. 1, -526516224, 1616117760, 4, 0,
  137339. _vq_quantlist__16u0__p6_0,
  137340. NULL,
  137341. &_vq_auxt__16u0__p6_0,
  137342. NULL,
  137343. 0
  137344. };
  137345. static long _vq_quantlist__16u0__p6_1[] = {
  137346. 2,
  137347. 1,
  137348. 3,
  137349. 0,
  137350. 4,
  137351. };
  137352. static long _vq_lengthlist__16u0__p6_1[] = {
  137353. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  137354. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  137355. };
  137356. static float _vq_quantthresh__16u0__p6_1[] = {
  137357. -1.5, -0.5, 0.5, 1.5,
  137358. };
  137359. static long _vq_quantmap__16u0__p6_1[] = {
  137360. 3, 1, 0, 2, 4,
  137361. };
  137362. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  137363. _vq_quantthresh__16u0__p6_1,
  137364. _vq_quantmap__16u0__p6_1,
  137365. 5,
  137366. 5
  137367. };
  137368. static static_codebook _16u0__p6_1 = {
  137369. 2, 25,
  137370. _vq_lengthlist__16u0__p6_1,
  137371. 1, -533725184, 1611661312, 3, 0,
  137372. _vq_quantlist__16u0__p6_1,
  137373. NULL,
  137374. &_vq_auxt__16u0__p6_1,
  137375. NULL,
  137376. 0
  137377. };
  137378. static long _vq_quantlist__16u0__p7_0[] = {
  137379. 1,
  137380. 0,
  137381. 2,
  137382. };
  137383. static long _vq_lengthlist__16u0__p7_0[] = {
  137384. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  137385. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  137386. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  137387. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  137388. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  137389. 7,
  137390. };
  137391. static float _vq_quantthresh__16u0__p7_0[] = {
  137392. -157.5, 157.5,
  137393. };
  137394. static long _vq_quantmap__16u0__p7_0[] = {
  137395. 1, 0, 2,
  137396. };
  137397. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  137398. _vq_quantthresh__16u0__p7_0,
  137399. _vq_quantmap__16u0__p7_0,
  137400. 3,
  137401. 3
  137402. };
  137403. static static_codebook _16u0__p7_0 = {
  137404. 4, 81,
  137405. _vq_lengthlist__16u0__p7_0,
  137406. 1, -518803456, 1628680192, 2, 0,
  137407. _vq_quantlist__16u0__p7_0,
  137408. NULL,
  137409. &_vq_auxt__16u0__p7_0,
  137410. NULL,
  137411. 0
  137412. };
  137413. static long _vq_quantlist__16u0__p7_1[] = {
  137414. 7,
  137415. 6,
  137416. 8,
  137417. 5,
  137418. 9,
  137419. 4,
  137420. 10,
  137421. 3,
  137422. 11,
  137423. 2,
  137424. 12,
  137425. 1,
  137426. 13,
  137427. 0,
  137428. 14,
  137429. };
  137430. static long _vq_lengthlist__16u0__p7_1[] = {
  137431. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  137432. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  137433. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  137434. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  137435. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  137436. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  137437. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137438. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137439. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137440. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137441. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137442. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137443. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137444. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137445. 10,
  137446. };
  137447. static float _vq_quantthresh__16u0__p7_1[] = {
  137448. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  137449. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  137450. };
  137451. static long _vq_quantmap__16u0__p7_1[] = {
  137452. 13, 11, 9, 7, 5, 3, 1, 0,
  137453. 2, 4, 6, 8, 10, 12, 14,
  137454. };
  137455. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  137456. _vq_quantthresh__16u0__p7_1,
  137457. _vq_quantmap__16u0__p7_1,
  137458. 15,
  137459. 15
  137460. };
  137461. static static_codebook _16u0__p7_1 = {
  137462. 2, 225,
  137463. _vq_lengthlist__16u0__p7_1,
  137464. 1, -520986624, 1620377600, 4, 0,
  137465. _vq_quantlist__16u0__p7_1,
  137466. NULL,
  137467. &_vq_auxt__16u0__p7_1,
  137468. NULL,
  137469. 0
  137470. };
  137471. static long _vq_quantlist__16u0__p7_2[] = {
  137472. 10,
  137473. 9,
  137474. 11,
  137475. 8,
  137476. 12,
  137477. 7,
  137478. 13,
  137479. 6,
  137480. 14,
  137481. 5,
  137482. 15,
  137483. 4,
  137484. 16,
  137485. 3,
  137486. 17,
  137487. 2,
  137488. 18,
  137489. 1,
  137490. 19,
  137491. 0,
  137492. 20,
  137493. };
  137494. static long _vq_lengthlist__16u0__p7_2[] = {
  137495. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  137496. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  137497. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  137498. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  137499. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  137500. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  137501. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  137502. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  137503. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  137504. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  137505. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  137506. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  137507. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  137508. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  137509. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  137510. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  137511. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  137512. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  137513. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  137514. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  137515. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  137516. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  137517. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  137518. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  137519. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  137520. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  137521. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  137522. 10,10,12,11,10,11,11,11,10,
  137523. };
  137524. static float _vq_quantthresh__16u0__p7_2[] = {
  137525. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  137526. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  137527. 6.5, 7.5, 8.5, 9.5,
  137528. };
  137529. static long _vq_quantmap__16u0__p7_2[] = {
  137530. 19, 17, 15, 13, 11, 9, 7, 5,
  137531. 3, 1, 0, 2, 4, 6, 8, 10,
  137532. 12, 14, 16, 18, 20,
  137533. };
  137534. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  137535. _vq_quantthresh__16u0__p7_2,
  137536. _vq_quantmap__16u0__p7_2,
  137537. 21,
  137538. 21
  137539. };
  137540. static static_codebook _16u0__p7_2 = {
  137541. 2, 441,
  137542. _vq_lengthlist__16u0__p7_2,
  137543. 1, -529268736, 1611661312, 5, 0,
  137544. _vq_quantlist__16u0__p7_2,
  137545. NULL,
  137546. &_vq_auxt__16u0__p7_2,
  137547. NULL,
  137548. 0
  137549. };
  137550. static long _huff_lengthlist__16u0__single[] = {
  137551. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  137552. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  137553. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  137554. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  137555. };
  137556. static static_codebook _huff_book__16u0__single = {
  137557. 2, 64,
  137558. _huff_lengthlist__16u0__single,
  137559. 0, 0, 0, 0, 0,
  137560. NULL,
  137561. NULL,
  137562. NULL,
  137563. NULL,
  137564. 0
  137565. };
  137566. static long _huff_lengthlist__16u1__long[] = {
  137567. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  137568. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  137569. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  137570. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  137571. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  137572. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  137573. 16,13,16,18,
  137574. };
  137575. static static_codebook _huff_book__16u1__long = {
  137576. 2, 100,
  137577. _huff_lengthlist__16u1__long,
  137578. 0, 0, 0, 0, 0,
  137579. NULL,
  137580. NULL,
  137581. NULL,
  137582. NULL,
  137583. 0
  137584. };
  137585. static long _vq_quantlist__16u1__p1_0[] = {
  137586. 1,
  137587. 0,
  137588. 2,
  137589. };
  137590. static long _vq_lengthlist__16u1__p1_0[] = {
  137591. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  137592. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  137593. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  137594. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  137595. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  137596. 11,
  137597. };
  137598. static float _vq_quantthresh__16u1__p1_0[] = {
  137599. -0.5, 0.5,
  137600. };
  137601. static long _vq_quantmap__16u1__p1_0[] = {
  137602. 1, 0, 2,
  137603. };
  137604. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  137605. _vq_quantthresh__16u1__p1_0,
  137606. _vq_quantmap__16u1__p1_0,
  137607. 3,
  137608. 3
  137609. };
  137610. static static_codebook _16u1__p1_0 = {
  137611. 4, 81,
  137612. _vq_lengthlist__16u1__p1_0,
  137613. 1, -535822336, 1611661312, 2, 0,
  137614. _vq_quantlist__16u1__p1_0,
  137615. NULL,
  137616. &_vq_auxt__16u1__p1_0,
  137617. NULL,
  137618. 0
  137619. };
  137620. static long _vq_quantlist__16u1__p2_0[] = {
  137621. 1,
  137622. 0,
  137623. 2,
  137624. };
  137625. static long _vq_lengthlist__16u1__p2_0[] = {
  137626. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  137627. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  137628. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  137629. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  137630. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  137631. 8,
  137632. };
  137633. static float _vq_quantthresh__16u1__p2_0[] = {
  137634. -0.5, 0.5,
  137635. };
  137636. static long _vq_quantmap__16u1__p2_0[] = {
  137637. 1, 0, 2,
  137638. };
  137639. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  137640. _vq_quantthresh__16u1__p2_0,
  137641. _vq_quantmap__16u1__p2_0,
  137642. 3,
  137643. 3
  137644. };
  137645. static static_codebook _16u1__p2_0 = {
  137646. 4, 81,
  137647. _vq_lengthlist__16u1__p2_0,
  137648. 1, -535822336, 1611661312, 2, 0,
  137649. _vq_quantlist__16u1__p2_0,
  137650. NULL,
  137651. &_vq_auxt__16u1__p2_0,
  137652. NULL,
  137653. 0
  137654. };
  137655. static long _vq_quantlist__16u1__p3_0[] = {
  137656. 2,
  137657. 1,
  137658. 3,
  137659. 0,
  137660. 4,
  137661. };
  137662. static long _vq_lengthlist__16u1__p3_0[] = {
  137663. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  137664. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  137665. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  137666. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  137667. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  137668. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  137669. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  137670. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  137671. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  137672. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  137673. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  137674. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  137675. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  137676. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  137677. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  137678. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  137679. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  137680. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  137681. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  137682. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  137683. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  137684. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  137685. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  137686. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  137687. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  137688. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  137689. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  137690. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  137691. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  137692. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  137693. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  137694. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  137695. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  137696. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  137697. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  137698. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  137699. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  137700. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  137701. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  137702. 16,
  137703. };
  137704. static float _vq_quantthresh__16u1__p3_0[] = {
  137705. -1.5, -0.5, 0.5, 1.5,
  137706. };
  137707. static long _vq_quantmap__16u1__p3_0[] = {
  137708. 3, 1, 0, 2, 4,
  137709. };
  137710. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  137711. _vq_quantthresh__16u1__p3_0,
  137712. _vq_quantmap__16u1__p3_0,
  137713. 5,
  137714. 5
  137715. };
  137716. static static_codebook _16u1__p3_0 = {
  137717. 4, 625,
  137718. _vq_lengthlist__16u1__p3_0,
  137719. 1, -533725184, 1611661312, 3, 0,
  137720. _vq_quantlist__16u1__p3_0,
  137721. NULL,
  137722. &_vq_auxt__16u1__p3_0,
  137723. NULL,
  137724. 0
  137725. };
  137726. static long _vq_quantlist__16u1__p4_0[] = {
  137727. 2,
  137728. 1,
  137729. 3,
  137730. 0,
  137731. 4,
  137732. };
  137733. static long _vq_lengthlist__16u1__p4_0[] = {
  137734. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  137735. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  137736. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  137737. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  137738. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  137739. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  137740. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  137741. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  137742. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  137743. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  137744. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  137745. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  137746. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  137747. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  137748. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  137749. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  137750. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  137751. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  137752. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  137753. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  137754. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  137755. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  137756. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  137757. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  137758. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  137759. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  137760. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  137761. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  137762. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  137763. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  137764. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  137765. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  137766. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  137767. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  137768. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  137769. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  137770. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  137771. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  137772. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  137773. 11,
  137774. };
  137775. static float _vq_quantthresh__16u1__p4_0[] = {
  137776. -1.5, -0.5, 0.5, 1.5,
  137777. };
  137778. static long _vq_quantmap__16u1__p4_0[] = {
  137779. 3, 1, 0, 2, 4,
  137780. };
  137781. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  137782. _vq_quantthresh__16u1__p4_0,
  137783. _vq_quantmap__16u1__p4_0,
  137784. 5,
  137785. 5
  137786. };
  137787. static static_codebook _16u1__p4_0 = {
  137788. 4, 625,
  137789. _vq_lengthlist__16u1__p4_0,
  137790. 1, -533725184, 1611661312, 3, 0,
  137791. _vq_quantlist__16u1__p4_0,
  137792. NULL,
  137793. &_vq_auxt__16u1__p4_0,
  137794. NULL,
  137795. 0
  137796. };
  137797. static long _vq_quantlist__16u1__p5_0[] = {
  137798. 4,
  137799. 3,
  137800. 5,
  137801. 2,
  137802. 6,
  137803. 1,
  137804. 7,
  137805. 0,
  137806. 8,
  137807. };
  137808. static long _vq_lengthlist__16u1__p5_0[] = {
  137809. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  137810. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  137811. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  137812. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  137813. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  137814. 13,
  137815. };
  137816. static float _vq_quantthresh__16u1__p5_0[] = {
  137817. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137818. };
  137819. static long _vq_quantmap__16u1__p5_0[] = {
  137820. 7, 5, 3, 1, 0, 2, 4, 6,
  137821. 8,
  137822. };
  137823. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  137824. _vq_quantthresh__16u1__p5_0,
  137825. _vq_quantmap__16u1__p5_0,
  137826. 9,
  137827. 9
  137828. };
  137829. static static_codebook _16u1__p5_0 = {
  137830. 2, 81,
  137831. _vq_lengthlist__16u1__p5_0,
  137832. 1, -531628032, 1611661312, 4, 0,
  137833. _vq_quantlist__16u1__p5_0,
  137834. NULL,
  137835. &_vq_auxt__16u1__p5_0,
  137836. NULL,
  137837. 0
  137838. };
  137839. static long _vq_quantlist__16u1__p6_0[] = {
  137840. 4,
  137841. 3,
  137842. 5,
  137843. 2,
  137844. 6,
  137845. 1,
  137846. 7,
  137847. 0,
  137848. 8,
  137849. };
  137850. static long _vq_lengthlist__16u1__p6_0[] = {
  137851. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  137852. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  137853. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  137854. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  137855. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  137856. 11,
  137857. };
  137858. static float _vq_quantthresh__16u1__p6_0[] = {
  137859. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137860. };
  137861. static long _vq_quantmap__16u1__p6_0[] = {
  137862. 7, 5, 3, 1, 0, 2, 4, 6,
  137863. 8,
  137864. };
  137865. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  137866. _vq_quantthresh__16u1__p6_0,
  137867. _vq_quantmap__16u1__p6_0,
  137868. 9,
  137869. 9
  137870. };
  137871. static static_codebook _16u1__p6_0 = {
  137872. 2, 81,
  137873. _vq_lengthlist__16u1__p6_0,
  137874. 1, -531628032, 1611661312, 4, 0,
  137875. _vq_quantlist__16u1__p6_0,
  137876. NULL,
  137877. &_vq_auxt__16u1__p6_0,
  137878. NULL,
  137879. 0
  137880. };
  137881. static long _vq_quantlist__16u1__p7_0[] = {
  137882. 1,
  137883. 0,
  137884. 2,
  137885. };
  137886. static long _vq_lengthlist__16u1__p7_0[] = {
  137887. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  137888. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  137889. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  137890. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  137891. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  137892. 13,
  137893. };
  137894. static float _vq_quantthresh__16u1__p7_0[] = {
  137895. -5.5, 5.5,
  137896. };
  137897. static long _vq_quantmap__16u1__p7_0[] = {
  137898. 1, 0, 2,
  137899. };
  137900. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  137901. _vq_quantthresh__16u1__p7_0,
  137902. _vq_quantmap__16u1__p7_0,
  137903. 3,
  137904. 3
  137905. };
  137906. static static_codebook _16u1__p7_0 = {
  137907. 4, 81,
  137908. _vq_lengthlist__16u1__p7_0,
  137909. 1, -529137664, 1618345984, 2, 0,
  137910. _vq_quantlist__16u1__p7_0,
  137911. NULL,
  137912. &_vq_auxt__16u1__p7_0,
  137913. NULL,
  137914. 0
  137915. };
  137916. static long _vq_quantlist__16u1__p7_1[] = {
  137917. 5,
  137918. 4,
  137919. 6,
  137920. 3,
  137921. 7,
  137922. 2,
  137923. 8,
  137924. 1,
  137925. 9,
  137926. 0,
  137927. 10,
  137928. };
  137929. static long _vq_lengthlist__16u1__p7_1[] = {
  137930. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  137931. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  137932. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  137933. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  137934. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  137935. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  137936. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  137937. 8, 9, 9,10,10,10,10,10,10,
  137938. };
  137939. static float _vq_quantthresh__16u1__p7_1[] = {
  137940. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137941. 3.5, 4.5,
  137942. };
  137943. static long _vq_quantmap__16u1__p7_1[] = {
  137944. 9, 7, 5, 3, 1, 0, 2, 4,
  137945. 6, 8, 10,
  137946. };
  137947. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  137948. _vq_quantthresh__16u1__p7_1,
  137949. _vq_quantmap__16u1__p7_1,
  137950. 11,
  137951. 11
  137952. };
  137953. static static_codebook _16u1__p7_1 = {
  137954. 2, 121,
  137955. _vq_lengthlist__16u1__p7_1,
  137956. 1, -531365888, 1611661312, 4, 0,
  137957. _vq_quantlist__16u1__p7_1,
  137958. NULL,
  137959. &_vq_auxt__16u1__p7_1,
  137960. NULL,
  137961. 0
  137962. };
  137963. static long _vq_quantlist__16u1__p8_0[] = {
  137964. 5,
  137965. 4,
  137966. 6,
  137967. 3,
  137968. 7,
  137969. 2,
  137970. 8,
  137971. 1,
  137972. 9,
  137973. 0,
  137974. 10,
  137975. };
  137976. static long _vq_lengthlist__16u1__p8_0[] = {
  137977. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  137978. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  137979. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  137980. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  137981. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  137982. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  137983. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  137984. 13,14,14,15,15,16,16,15,16,
  137985. };
  137986. static float _vq_quantthresh__16u1__p8_0[] = {
  137987. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  137988. 38.5, 49.5,
  137989. };
  137990. static long _vq_quantmap__16u1__p8_0[] = {
  137991. 9, 7, 5, 3, 1, 0, 2, 4,
  137992. 6, 8, 10,
  137993. };
  137994. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  137995. _vq_quantthresh__16u1__p8_0,
  137996. _vq_quantmap__16u1__p8_0,
  137997. 11,
  137998. 11
  137999. };
  138000. static static_codebook _16u1__p8_0 = {
  138001. 2, 121,
  138002. _vq_lengthlist__16u1__p8_0,
  138003. 1, -524582912, 1618345984, 4, 0,
  138004. _vq_quantlist__16u1__p8_0,
  138005. NULL,
  138006. &_vq_auxt__16u1__p8_0,
  138007. NULL,
  138008. 0
  138009. };
  138010. static long _vq_quantlist__16u1__p8_1[] = {
  138011. 5,
  138012. 4,
  138013. 6,
  138014. 3,
  138015. 7,
  138016. 2,
  138017. 8,
  138018. 1,
  138019. 9,
  138020. 0,
  138021. 10,
  138022. };
  138023. static long _vq_lengthlist__16u1__p8_1[] = {
  138024. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  138025. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  138026. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  138027. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  138028. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  138029. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  138030. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  138031. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  138032. };
  138033. static float _vq_quantthresh__16u1__p8_1[] = {
  138034. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138035. 3.5, 4.5,
  138036. };
  138037. static long _vq_quantmap__16u1__p8_1[] = {
  138038. 9, 7, 5, 3, 1, 0, 2, 4,
  138039. 6, 8, 10,
  138040. };
  138041. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  138042. _vq_quantthresh__16u1__p8_1,
  138043. _vq_quantmap__16u1__p8_1,
  138044. 11,
  138045. 11
  138046. };
  138047. static static_codebook _16u1__p8_1 = {
  138048. 2, 121,
  138049. _vq_lengthlist__16u1__p8_1,
  138050. 1, -531365888, 1611661312, 4, 0,
  138051. _vq_quantlist__16u1__p8_1,
  138052. NULL,
  138053. &_vq_auxt__16u1__p8_1,
  138054. NULL,
  138055. 0
  138056. };
  138057. static long _vq_quantlist__16u1__p9_0[] = {
  138058. 7,
  138059. 6,
  138060. 8,
  138061. 5,
  138062. 9,
  138063. 4,
  138064. 10,
  138065. 3,
  138066. 11,
  138067. 2,
  138068. 12,
  138069. 1,
  138070. 13,
  138071. 0,
  138072. 14,
  138073. };
  138074. static long _vq_lengthlist__16u1__p9_0[] = {
  138075. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138076. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138077. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138078. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138079. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138080. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138081. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138082. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138083. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138084. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138085. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138086. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138087. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138088. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138089. 8,
  138090. };
  138091. static float _vq_quantthresh__16u1__p9_0[] = {
  138092. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  138093. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  138094. };
  138095. static long _vq_quantmap__16u1__p9_0[] = {
  138096. 13, 11, 9, 7, 5, 3, 1, 0,
  138097. 2, 4, 6, 8, 10, 12, 14,
  138098. };
  138099. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  138100. _vq_quantthresh__16u1__p9_0,
  138101. _vq_quantmap__16u1__p9_0,
  138102. 15,
  138103. 15
  138104. };
  138105. static static_codebook _16u1__p9_0 = {
  138106. 2, 225,
  138107. _vq_lengthlist__16u1__p9_0,
  138108. 1, -514071552, 1627381760, 4, 0,
  138109. _vq_quantlist__16u1__p9_0,
  138110. NULL,
  138111. &_vq_auxt__16u1__p9_0,
  138112. NULL,
  138113. 0
  138114. };
  138115. static long _vq_quantlist__16u1__p9_1[] = {
  138116. 7,
  138117. 6,
  138118. 8,
  138119. 5,
  138120. 9,
  138121. 4,
  138122. 10,
  138123. 3,
  138124. 11,
  138125. 2,
  138126. 12,
  138127. 1,
  138128. 13,
  138129. 0,
  138130. 14,
  138131. };
  138132. static long _vq_lengthlist__16u1__p9_1[] = {
  138133. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  138134. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  138135. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  138136. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  138137. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  138138. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  138139. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  138140. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  138141. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  138142. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138143. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  138144. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138145. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138146. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  138147. 9,
  138148. };
  138149. static float _vq_quantthresh__16u1__p9_1[] = {
  138150. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  138151. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  138152. };
  138153. static long _vq_quantmap__16u1__p9_1[] = {
  138154. 13, 11, 9, 7, 5, 3, 1, 0,
  138155. 2, 4, 6, 8, 10, 12, 14,
  138156. };
  138157. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  138158. _vq_quantthresh__16u1__p9_1,
  138159. _vq_quantmap__16u1__p9_1,
  138160. 15,
  138161. 15
  138162. };
  138163. static static_codebook _16u1__p9_1 = {
  138164. 2, 225,
  138165. _vq_lengthlist__16u1__p9_1,
  138166. 1, -522338304, 1620115456, 4, 0,
  138167. _vq_quantlist__16u1__p9_1,
  138168. NULL,
  138169. &_vq_auxt__16u1__p9_1,
  138170. NULL,
  138171. 0
  138172. };
  138173. static long _vq_quantlist__16u1__p9_2[] = {
  138174. 8,
  138175. 7,
  138176. 9,
  138177. 6,
  138178. 10,
  138179. 5,
  138180. 11,
  138181. 4,
  138182. 12,
  138183. 3,
  138184. 13,
  138185. 2,
  138186. 14,
  138187. 1,
  138188. 15,
  138189. 0,
  138190. 16,
  138191. };
  138192. static long _vq_lengthlist__16u1__p9_2[] = {
  138193. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  138194. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  138195. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  138196. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  138197. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  138198. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  138199. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  138200. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  138201. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  138202. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  138203. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  138204. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  138205. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  138206. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  138207. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  138208. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  138209. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  138210. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  138211. 10,
  138212. };
  138213. static float _vq_quantthresh__16u1__p9_2[] = {
  138214. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138215. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138216. };
  138217. static long _vq_quantmap__16u1__p9_2[] = {
  138218. 15, 13, 11, 9, 7, 5, 3, 1,
  138219. 0, 2, 4, 6, 8, 10, 12, 14,
  138220. 16,
  138221. };
  138222. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  138223. _vq_quantthresh__16u1__p9_2,
  138224. _vq_quantmap__16u1__p9_2,
  138225. 17,
  138226. 17
  138227. };
  138228. static static_codebook _16u1__p9_2 = {
  138229. 2, 289,
  138230. _vq_lengthlist__16u1__p9_2,
  138231. 1, -529530880, 1611661312, 5, 0,
  138232. _vq_quantlist__16u1__p9_2,
  138233. NULL,
  138234. &_vq_auxt__16u1__p9_2,
  138235. NULL,
  138236. 0
  138237. };
  138238. static long _huff_lengthlist__16u1__short[] = {
  138239. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  138240. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  138241. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  138242. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  138243. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  138244. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  138245. 16,16,16,16,
  138246. };
  138247. static static_codebook _huff_book__16u1__short = {
  138248. 2, 100,
  138249. _huff_lengthlist__16u1__short,
  138250. 0, 0, 0, 0, 0,
  138251. NULL,
  138252. NULL,
  138253. NULL,
  138254. NULL,
  138255. 0
  138256. };
  138257. static long _huff_lengthlist__16u2__long[] = {
  138258. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  138259. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  138260. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  138261. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  138262. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  138263. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  138264. 13,14,18,18,
  138265. };
  138266. static static_codebook _huff_book__16u2__long = {
  138267. 2, 100,
  138268. _huff_lengthlist__16u2__long,
  138269. 0, 0, 0, 0, 0,
  138270. NULL,
  138271. NULL,
  138272. NULL,
  138273. NULL,
  138274. 0
  138275. };
  138276. static long _huff_lengthlist__16u2__short[] = {
  138277. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  138278. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  138279. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  138280. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  138281. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  138282. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  138283. 16,16,16,16,
  138284. };
  138285. static static_codebook _huff_book__16u2__short = {
  138286. 2, 100,
  138287. _huff_lengthlist__16u2__short,
  138288. 0, 0, 0, 0, 0,
  138289. NULL,
  138290. NULL,
  138291. NULL,
  138292. NULL,
  138293. 0
  138294. };
  138295. static long _vq_quantlist__16u2_p1_0[] = {
  138296. 1,
  138297. 0,
  138298. 2,
  138299. };
  138300. static long _vq_lengthlist__16u2_p1_0[] = {
  138301. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  138302. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  138303. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  138304. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  138305. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  138306. 10,
  138307. };
  138308. static float _vq_quantthresh__16u2_p1_0[] = {
  138309. -0.5, 0.5,
  138310. };
  138311. static long _vq_quantmap__16u2_p1_0[] = {
  138312. 1, 0, 2,
  138313. };
  138314. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  138315. _vq_quantthresh__16u2_p1_0,
  138316. _vq_quantmap__16u2_p1_0,
  138317. 3,
  138318. 3
  138319. };
  138320. static static_codebook _16u2_p1_0 = {
  138321. 4, 81,
  138322. _vq_lengthlist__16u2_p1_0,
  138323. 1, -535822336, 1611661312, 2, 0,
  138324. _vq_quantlist__16u2_p1_0,
  138325. NULL,
  138326. &_vq_auxt__16u2_p1_0,
  138327. NULL,
  138328. 0
  138329. };
  138330. static long _vq_quantlist__16u2_p2_0[] = {
  138331. 2,
  138332. 1,
  138333. 3,
  138334. 0,
  138335. 4,
  138336. };
  138337. static long _vq_lengthlist__16u2_p2_0[] = {
  138338. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  138339. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  138340. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  138341. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  138342. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  138343. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  138344. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  138345. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  138346. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  138347. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  138348. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  138349. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  138350. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  138351. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  138352. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  138353. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  138354. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  138355. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  138356. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  138357. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  138358. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  138359. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  138360. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  138361. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  138362. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  138363. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  138364. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  138365. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  138366. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  138367. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  138368. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  138369. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  138370. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  138371. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  138372. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  138373. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  138374. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  138375. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  138376. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  138377. 13,
  138378. };
  138379. static float _vq_quantthresh__16u2_p2_0[] = {
  138380. -1.5, -0.5, 0.5, 1.5,
  138381. };
  138382. static long _vq_quantmap__16u2_p2_0[] = {
  138383. 3, 1, 0, 2, 4,
  138384. };
  138385. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  138386. _vq_quantthresh__16u2_p2_0,
  138387. _vq_quantmap__16u2_p2_0,
  138388. 5,
  138389. 5
  138390. };
  138391. static static_codebook _16u2_p2_0 = {
  138392. 4, 625,
  138393. _vq_lengthlist__16u2_p2_0,
  138394. 1, -533725184, 1611661312, 3, 0,
  138395. _vq_quantlist__16u2_p2_0,
  138396. NULL,
  138397. &_vq_auxt__16u2_p2_0,
  138398. NULL,
  138399. 0
  138400. };
  138401. static long _vq_quantlist__16u2_p3_0[] = {
  138402. 4,
  138403. 3,
  138404. 5,
  138405. 2,
  138406. 6,
  138407. 1,
  138408. 7,
  138409. 0,
  138410. 8,
  138411. };
  138412. static long _vq_lengthlist__16u2_p3_0[] = {
  138413. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  138414. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  138415. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  138416. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  138417. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  138418. 11,
  138419. };
  138420. static float _vq_quantthresh__16u2_p3_0[] = {
  138421. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138422. };
  138423. static long _vq_quantmap__16u2_p3_0[] = {
  138424. 7, 5, 3, 1, 0, 2, 4, 6,
  138425. 8,
  138426. };
  138427. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  138428. _vq_quantthresh__16u2_p3_0,
  138429. _vq_quantmap__16u2_p3_0,
  138430. 9,
  138431. 9
  138432. };
  138433. static static_codebook _16u2_p3_0 = {
  138434. 2, 81,
  138435. _vq_lengthlist__16u2_p3_0,
  138436. 1, -531628032, 1611661312, 4, 0,
  138437. _vq_quantlist__16u2_p3_0,
  138438. NULL,
  138439. &_vq_auxt__16u2_p3_0,
  138440. NULL,
  138441. 0
  138442. };
  138443. static long _vq_quantlist__16u2_p4_0[] = {
  138444. 8,
  138445. 7,
  138446. 9,
  138447. 6,
  138448. 10,
  138449. 5,
  138450. 11,
  138451. 4,
  138452. 12,
  138453. 3,
  138454. 13,
  138455. 2,
  138456. 14,
  138457. 1,
  138458. 15,
  138459. 0,
  138460. 16,
  138461. };
  138462. static long _vq_lengthlist__16u2_p4_0[] = {
  138463. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  138464. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  138465. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  138466. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138467. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138468. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  138469. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  138470. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  138471. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  138472. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  138473. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  138474. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  138475. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  138476. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  138477. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  138478. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  138479. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  138480. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  138481. 14,
  138482. };
  138483. static float _vq_quantthresh__16u2_p4_0[] = {
  138484. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138485. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138486. };
  138487. static long _vq_quantmap__16u2_p4_0[] = {
  138488. 15, 13, 11, 9, 7, 5, 3, 1,
  138489. 0, 2, 4, 6, 8, 10, 12, 14,
  138490. 16,
  138491. };
  138492. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  138493. _vq_quantthresh__16u2_p4_0,
  138494. _vq_quantmap__16u2_p4_0,
  138495. 17,
  138496. 17
  138497. };
  138498. static static_codebook _16u2_p4_0 = {
  138499. 2, 289,
  138500. _vq_lengthlist__16u2_p4_0,
  138501. 1, -529530880, 1611661312, 5, 0,
  138502. _vq_quantlist__16u2_p4_0,
  138503. NULL,
  138504. &_vq_auxt__16u2_p4_0,
  138505. NULL,
  138506. 0
  138507. };
  138508. static long _vq_quantlist__16u2_p5_0[] = {
  138509. 1,
  138510. 0,
  138511. 2,
  138512. };
  138513. static long _vq_lengthlist__16u2_p5_0[] = {
  138514. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  138515. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  138516. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  138517. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  138518. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  138519. 10,
  138520. };
  138521. static float _vq_quantthresh__16u2_p5_0[] = {
  138522. -5.5, 5.5,
  138523. };
  138524. static long _vq_quantmap__16u2_p5_0[] = {
  138525. 1, 0, 2,
  138526. };
  138527. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  138528. _vq_quantthresh__16u2_p5_0,
  138529. _vq_quantmap__16u2_p5_0,
  138530. 3,
  138531. 3
  138532. };
  138533. static static_codebook _16u2_p5_0 = {
  138534. 4, 81,
  138535. _vq_lengthlist__16u2_p5_0,
  138536. 1, -529137664, 1618345984, 2, 0,
  138537. _vq_quantlist__16u2_p5_0,
  138538. NULL,
  138539. &_vq_auxt__16u2_p5_0,
  138540. NULL,
  138541. 0
  138542. };
  138543. static long _vq_quantlist__16u2_p5_1[] = {
  138544. 5,
  138545. 4,
  138546. 6,
  138547. 3,
  138548. 7,
  138549. 2,
  138550. 8,
  138551. 1,
  138552. 9,
  138553. 0,
  138554. 10,
  138555. };
  138556. static long _vq_lengthlist__16u2_p5_1[] = {
  138557. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  138558. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  138559. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  138560. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  138561. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  138562. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  138563. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  138564. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  138565. };
  138566. static float _vq_quantthresh__16u2_p5_1[] = {
  138567. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138568. 3.5, 4.5,
  138569. };
  138570. static long _vq_quantmap__16u2_p5_1[] = {
  138571. 9, 7, 5, 3, 1, 0, 2, 4,
  138572. 6, 8, 10,
  138573. };
  138574. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  138575. _vq_quantthresh__16u2_p5_1,
  138576. _vq_quantmap__16u2_p5_1,
  138577. 11,
  138578. 11
  138579. };
  138580. static static_codebook _16u2_p5_1 = {
  138581. 2, 121,
  138582. _vq_lengthlist__16u2_p5_1,
  138583. 1, -531365888, 1611661312, 4, 0,
  138584. _vq_quantlist__16u2_p5_1,
  138585. NULL,
  138586. &_vq_auxt__16u2_p5_1,
  138587. NULL,
  138588. 0
  138589. };
  138590. static long _vq_quantlist__16u2_p6_0[] = {
  138591. 6,
  138592. 5,
  138593. 7,
  138594. 4,
  138595. 8,
  138596. 3,
  138597. 9,
  138598. 2,
  138599. 10,
  138600. 1,
  138601. 11,
  138602. 0,
  138603. 12,
  138604. };
  138605. static long _vq_lengthlist__16u2_p6_0[] = {
  138606. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  138607. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  138608. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  138609. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  138610. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  138611. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  138612. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  138613. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  138614. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  138615. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  138616. 12,13,13,14,14,14,14,15,15,
  138617. };
  138618. static float _vq_quantthresh__16u2_p6_0[] = {
  138619. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138620. 12.5, 17.5, 22.5, 27.5,
  138621. };
  138622. static long _vq_quantmap__16u2_p6_0[] = {
  138623. 11, 9, 7, 5, 3, 1, 0, 2,
  138624. 4, 6, 8, 10, 12,
  138625. };
  138626. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  138627. _vq_quantthresh__16u2_p6_0,
  138628. _vq_quantmap__16u2_p6_0,
  138629. 13,
  138630. 13
  138631. };
  138632. static static_codebook _16u2_p6_0 = {
  138633. 2, 169,
  138634. _vq_lengthlist__16u2_p6_0,
  138635. 1, -526516224, 1616117760, 4, 0,
  138636. _vq_quantlist__16u2_p6_0,
  138637. NULL,
  138638. &_vq_auxt__16u2_p6_0,
  138639. NULL,
  138640. 0
  138641. };
  138642. static long _vq_quantlist__16u2_p6_1[] = {
  138643. 2,
  138644. 1,
  138645. 3,
  138646. 0,
  138647. 4,
  138648. };
  138649. static long _vq_lengthlist__16u2_p6_1[] = {
  138650. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  138651. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  138652. };
  138653. static float _vq_quantthresh__16u2_p6_1[] = {
  138654. -1.5, -0.5, 0.5, 1.5,
  138655. };
  138656. static long _vq_quantmap__16u2_p6_1[] = {
  138657. 3, 1, 0, 2, 4,
  138658. };
  138659. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  138660. _vq_quantthresh__16u2_p6_1,
  138661. _vq_quantmap__16u2_p6_1,
  138662. 5,
  138663. 5
  138664. };
  138665. static static_codebook _16u2_p6_1 = {
  138666. 2, 25,
  138667. _vq_lengthlist__16u2_p6_1,
  138668. 1, -533725184, 1611661312, 3, 0,
  138669. _vq_quantlist__16u2_p6_1,
  138670. NULL,
  138671. &_vq_auxt__16u2_p6_1,
  138672. NULL,
  138673. 0
  138674. };
  138675. static long _vq_quantlist__16u2_p7_0[] = {
  138676. 6,
  138677. 5,
  138678. 7,
  138679. 4,
  138680. 8,
  138681. 3,
  138682. 9,
  138683. 2,
  138684. 10,
  138685. 1,
  138686. 11,
  138687. 0,
  138688. 12,
  138689. };
  138690. static long _vq_lengthlist__16u2_p7_0[] = {
  138691. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  138692. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  138693. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  138694. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  138695. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  138696. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  138697. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  138698. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  138699. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  138700. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  138701. 12,13,13,13,14,14,14,15,14,
  138702. };
  138703. static float _vq_quantthresh__16u2_p7_0[] = {
  138704. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  138705. 27.5, 38.5, 49.5, 60.5,
  138706. };
  138707. static long _vq_quantmap__16u2_p7_0[] = {
  138708. 11, 9, 7, 5, 3, 1, 0, 2,
  138709. 4, 6, 8, 10, 12,
  138710. };
  138711. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  138712. _vq_quantthresh__16u2_p7_0,
  138713. _vq_quantmap__16u2_p7_0,
  138714. 13,
  138715. 13
  138716. };
  138717. static static_codebook _16u2_p7_0 = {
  138718. 2, 169,
  138719. _vq_lengthlist__16u2_p7_0,
  138720. 1, -523206656, 1618345984, 4, 0,
  138721. _vq_quantlist__16u2_p7_0,
  138722. NULL,
  138723. &_vq_auxt__16u2_p7_0,
  138724. NULL,
  138725. 0
  138726. };
  138727. static long _vq_quantlist__16u2_p7_1[] = {
  138728. 5,
  138729. 4,
  138730. 6,
  138731. 3,
  138732. 7,
  138733. 2,
  138734. 8,
  138735. 1,
  138736. 9,
  138737. 0,
  138738. 10,
  138739. };
  138740. static long _vq_lengthlist__16u2_p7_1[] = {
  138741. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  138742. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  138743. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  138744. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  138745. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  138746. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  138747. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  138748. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138749. };
  138750. static float _vq_quantthresh__16u2_p7_1[] = {
  138751. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138752. 3.5, 4.5,
  138753. };
  138754. static long _vq_quantmap__16u2_p7_1[] = {
  138755. 9, 7, 5, 3, 1, 0, 2, 4,
  138756. 6, 8, 10,
  138757. };
  138758. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  138759. _vq_quantthresh__16u2_p7_1,
  138760. _vq_quantmap__16u2_p7_1,
  138761. 11,
  138762. 11
  138763. };
  138764. static static_codebook _16u2_p7_1 = {
  138765. 2, 121,
  138766. _vq_lengthlist__16u2_p7_1,
  138767. 1, -531365888, 1611661312, 4, 0,
  138768. _vq_quantlist__16u2_p7_1,
  138769. NULL,
  138770. &_vq_auxt__16u2_p7_1,
  138771. NULL,
  138772. 0
  138773. };
  138774. static long _vq_quantlist__16u2_p8_0[] = {
  138775. 7,
  138776. 6,
  138777. 8,
  138778. 5,
  138779. 9,
  138780. 4,
  138781. 10,
  138782. 3,
  138783. 11,
  138784. 2,
  138785. 12,
  138786. 1,
  138787. 13,
  138788. 0,
  138789. 14,
  138790. };
  138791. static long _vq_lengthlist__16u2_p8_0[] = {
  138792. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  138793. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  138794. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  138795. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  138796. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  138797. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  138798. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  138799. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  138800. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  138801. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  138802. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  138803. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  138804. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  138805. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  138806. 14,
  138807. };
  138808. static float _vq_quantthresh__16u2_p8_0[] = {
  138809. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  138810. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  138811. };
  138812. static long _vq_quantmap__16u2_p8_0[] = {
  138813. 13, 11, 9, 7, 5, 3, 1, 0,
  138814. 2, 4, 6, 8, 10, 12, 14,
  138815. };
  138816. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  138817. _vq_quantthresh__16u2_p8_0,
  138818. _vq_quantmap__16u2_p8_0,
  138819. 15,
  138820. 15
  138821. };
  138822. static static_codebook _16u2_p8_0 = {
  138823. 2, 225,
  138824. _vq_lengthlist__16u2_p8_0,
  138825. 1, -520986624, 1620377600, 4, 0,
  138826. _vq_quantlist__16u2_p8_0,
  138827. NULL,
  138828. &_vq_auxt__16u2_p8_0,
  138829. NULL,
  138830. 0
  138831. };
  138832. static long _vq_quantlist__16u2_p8_1[] = {
  138833. 10,
  138834. 9,
  138835. 11,
  138836. 8,
  138837. 12,
  138838. 7,
  138839. 13,
  138840. 6,
  138841. 14,
  138842. 5,
  138843. 15,
  138844. 4,
  138845. 16,
  138846. 3,
  138847. 17,
  138848. 2,
  138849. 18,
  138850. 1,
  138851. 19,
  138852. 0,
  138853. 20,
  138854. };
  138855. static long _vq_lengthlist__16u2_p8_1[] = {
  138856. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  138857. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  138858. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  138859. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  138860. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  138861. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  138862. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  138863. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  138864. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  138865. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  138866. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  138867. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  138868. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  138869. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  138870. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  138871. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  138872. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  138873. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  138874. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  138875. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  138876. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  138877. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  138878. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  138879. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  138880. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  138881. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  138882. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  138883. 11,11,10,11,11,11,10,11,11,
  138884. };
  138885. static float _vq_quantthresh__16u2_p8_1[] = {
  138886. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  138887. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  138888. 6.5, 7.5, 8.5, 9.5,
  138889. };
  138890. static long _vq_quantmap__16u2_p8_1[] = {
  138891. 19, 17, 15, 13, 11, 9, 7, 5,
  138892. 3, 1, 0, 2, 4, 6, 8, 10,
  138893. 12, 14, 16, 18, 20,
  138894. };
  138895. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  138896. _vq_quantthresh__16u2_p8_1,
  138897. _vq_quantmap__16u2_p8_1,
  138898. 21,
  138899. 21
  138900. };
  138901. static static_codebook _16u2_p8_1 = {
  138902. 2, 441,
  138903. _vq_lengthlist__16u2_p8_1,
  138904. 1, -529268736, 1611661312, 5, 0,
  138905. _vq_quantlist__16u2_p8_1,
  138906. NULL,
  138907. &_vq_auxt__16u2_p8_1,
  138908. NULL,
  138909. 0
  138910. };
  138911. static long _vq_quantlist__16u2_p9_0[] = {
  138912. 5586,
  138913. 4655,
  138914. 6517,
  138915. 3724,
  138916. 7448,
  138917. 2793,
  138918. 8379,
  138919. 1862,
  138920. 9310,
  138921. 931,
  138922. 10241,
  138923. 0,
  138924. 11172,
  138925. 5521,
  138926. 5651,
  138927. };
  138928. static long _vq_lengthlist__16u2_p9_0[] = {
  138929. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  138930. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138931. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138932. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138933. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138934. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138935. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138936. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138937. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138938. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138939. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138940. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138941. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  138942. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  138943. 5,
  138944. };
  138945. static float _vq_quantthresh__16u2_p9_0[] = {
  138946. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  138947. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  138948. };
  138949. static long _vq_quantmap__16u2_p9_0[] = {
  138950. 11, 9, 7, 5, 3, 1, 13, 0,
  138951. 14, 2, 4, 6, 8, 10, 12,
  138952. };
  138953. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  138954. _vq_quantthresh__16u2_p9_0,
  138955. _vq_quantmap__16u2_p9_0,
  138956. 15,
  138957. 15
  138958. };
  138959. static static_codebook _16u2_p9_0 = {
  138960. 2, 225,
  138961. _vq_lengthlist__16u2_p9_0,
  138962. 1, -510275072, 1611661312, 14, 0,
  138963. _vq_quantlist__16u2_p9_0,
  138964. NULL,
  138965. &_vq_auxt__16u2_p9_0,
  138966. NULL,
  138967. 0
  138968. };
  138969. static long _vq_quantlist__16u2_p9_1[] = {
  138970. 392,
  138971. 343,
  138972. 441,
  138973. 294,
  138974. 490,
  138975. 245,
  138976. 539,
  138977. 196,
  138978. 588,
  138979. 147,
  138980. 637,
  138981. 98,
  138982. 686,
  138983. 49,
  138984. 735,
  138985. 0,
  138986. 784,
  138987. 388,
  138988. 396,
  138989. };
  138990. static long _vq_lengthlist__16u2_p9_1[] = {
  138991. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  138992. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  138993. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  138994. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  138995. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  138996. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  138997. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138998. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  138999. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  139000. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139001. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139002. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139003. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139004. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139005. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  139006. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139007. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139008. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139009. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139010. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139011. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  139012. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  139013. 11,11,11,11,11,11,11, 5, 4,
  139014. };
  139015. static float _vq_quantthresh__16u2_p9_1[] = {
  139016. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  139017. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  139018. 318.5, 367.5,
  139019. };
  139020. static long _vq_quantmap__16u2_p9_1[] = {
  139021. 15, 13, 11, 9, 7, 5, 3, 1,
  139022. 17, 0, 18, 2, 4, 6, 8, 10,
  139023. 12, 14, 16,
  139024. };
  139025. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  139026. _vq_quantthresh__16u2_p9_1,
  139027. _vq_quantmap__16u2_p9_1,
  139028. 19,
  139029. 19
  139030. };
  139031. static static_codebook _16u2_p9_1 = {
  139032. 2, 361,
  139033. _vq_lengthlist__16u2_p9_1,
  139034. 1, -518488064, 1611661312, 10, 0,
  139035. _vq_quantlist__16u2_p9_1,
  139036. NULL,
  139037. &_vq_auxt__16u2_p9_1,
  139038. NULL,
  139039. 0
  139040. };
  139041. static long _vq_quantlist__16u2_p9_2[] = {
  139042. 24,
  139043. 23,
  139044. 25,
  139045. 22,
  139046. 26,
  139047. 21,
  139048. 27,
  139049. 20,
  139050. 28,
  139051. 19,
  139052. 29,
  139053. 18,
  139054. 30,
  139055. 17,
  139056. 31,
  139057. 16,
  139058. 32,
  139059. 15,
  139060. 33,
  139061. 14,
  139062. 34,
  139063. 13,
  139064. 35,
  139065. 12,
  139066. 36,
  139067. 11,
  139068. 37,
  139069. 10,
  139070. 38,
  139071. 9,
  139072. 39,
  139073. 8,
  139074. 40,
  139075. 7,
  139076. 41,
  139077. 6,
  139078. 42,
  139079. 5,
  139080. 43,
  139081. 4,
  139082. 44,
  139083. 3,
  139084. 45,
  139085. 2,
  139086. 46,
  139087. 1,
  139088. 47,
  139089. 0,
  139090. 48,
  139091. };
  139092. static long _vq_lengthlist__16u2_p9_2[] = {
  139093. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  139094. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  139095. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  139096. 11,
  139097. };
  139098. static float _vq_quantthresh__16u2_p9_2[] = {
  139099. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  139100. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  139101. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139102. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139103. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  139104. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  139105. };
  139106. static long _vq_quantmap__16u2_p9_2[] = {
  139107. 47, 45, 43, 41, 39, 37, 35, 33,
  139108. 31, 29, 27, 25, 23, 21, 19, 17,
  139109. 15, 13, 11, 9, 7, 5, 3, 1,
  139110. 0, 2, 4, 6, 8, 10, 12, 14,
  139111. 16, 18, 20, 22, 24, 26, 28, 30,
  139112. 32, 34, 36, 38, 40, 42, 44, 46,
  139113. 48,
  139114. };
  139115. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  139116. _vq_quantthresh__16u2_p9_2,
  139117. _vq_quantmap__16u2_p9_2,
  139118. 49,
  139119. 49
  139120. };
  139121. static static_codebook _16u2_p9_2 = {
  139122. 1, 49,
  139123. _vq_lengthlist__16u2_p9_2,
  139124. 1, -526909440, 1611661312, 6, 0,
  139125. _vq_quantlist__16u2_p9_2,
  139126. NULL,
  139127. &_vq_auxt__16u2_p9_2,
  139128. NULL,
  139129. 0
  139130. };
  139131. static long _vq_quantlist__8u0__p1_0[] = {
  139132. 1,
  139133. 0,
  139134. 2,
  139135. };
  139136. static long _vq_lengthlist__8u0__p1_0[] = {
  139137. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  139138. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  139139. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  139140. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  139141. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  139142. 11,
  139143. };
  139144. static float _vq_quantthresh__8u0__p1_0[] = {
  139145. -0.5, 0.5,
  139146. };
  139147. static long _vq_quantmap__8u0__p1_0[] = {
  139148. 1, 0, 2,
  139149. };
  139150. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  139151. _vq_quantthresh__8u0__p1_0,
  139152. _vq_quantmap__8u0__p1_0,
  139153. 3,
  139154. 3
  139155. };
  139156. static static_codebook _8u0__p1_0 = {
  139157. 4, 81,
  139158. _vq_lengthlist__8u0__p1_0,
  139159. 1, -535822336, 1611661312, 2, 0,
  139160. _vq_quantlist__8u0__p1_0,
  139161. NULL,
  139162. &_vq_auxt__8u0__p1_0,
  139163. NULL,
  139164. 0
  139165. };
  139166. static long _vq_quantlist__8u0__p2_0[] = {
  139167. 1,
  139168. 0,
  139169. 2,
  139170. };
  139171. static long _vq_lengthlist__8u0__p2_0[] = {
  139172. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  139173. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  139174. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  139175. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  139176. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  139177. 8,
  139178. };
  139179. static float _vq_quantthresh__8u0__p2_0[] = {
  139180. -0.5, 0.5,
  139181. };
  139182. static long _vq_quantmap__8u0__p2_0[] = {
  139183. 1, 0, 2,
  139184. };
  139185. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  139186. _vq_quantthresh__8u0__p2_0,
  139187. _vq_quantmap__8u0__p2_0,
  139188. 3,
  139189. 3
  139190. };
  139191. static static_codebook _8u0__p2_0 = {
  139192. 4, 81,
  139193. _vq_lengthlist__8u0__p2_0,
  139194. 1, -535822336, 1611661312, 2, 0,
  139195. _vq_quantlist__8u0__p2_0,
  139196. NULL,
  139197. &_vq_auxt__8u0__p2_0,
  139198. NULL,
  139199. 0
  139200. };
  139201. static long _vq_quantlist__8u0__p3_0[] = {
  139202. 2,
  139203. 1,
  139204. 3,
  139205. 0,
  139206. 4,
  139207. };
  139208. static long _vq_lengthlist__8u0__p3_0[] = {
  139209. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  139210. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  139211. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  139212. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  139213. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  139214. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  139215. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  139216. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  139217. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  139218. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  139219. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  139220. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  139221. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  139222. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  139223. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  139224. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  139225. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  139226. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  139227. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  139228. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  139229. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  139230. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  139231. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  139232. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  139233. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  139234. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  139235. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  139236. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  139237. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  139238. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  139239. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  139240. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  139241. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  139242. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  139243. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  139244. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  139245. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  139246. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  139247. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  139248. 16,
  139249. };
  139250. static float _vq_quantthresh__8u0__p3_0[] = {
  139251. -1.5, -0.5, 0.5, 1.5,
  139252. };
  139253. static long _vq_quantmap__8u0__p3_0[] = {
  139254. 3, 1, 0, 2, 4,
  139255. };
  139256. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  139257. _vq_quantthresh__8u0__p3_0,
  139258. _vq_quantmap__8u0__p3_0,
  139259. 5,
  139260. 5
  139261. };
  139262. static static_codebook _8u0__p3_0 = {
  139263. 4, 625,
  139264. _vq_lengthlist__8u0__p3_0,
  139265. 1, -533725184, 1611661312, 3, 0,
  139266. _vq_quantlist__8u0__p3_0,
  139267. NULL,
  139268. &_vq_auxt__8u0__p3_0,
  139269. NULL,
  139270. 0
  139271. };
  139272. static long _vq_quantlist__8u0__p4_0[] = {
  139273. 2,
  139274. 1,
  139275. 3,
  139276. 0,
  139277. 4,
  139278. };
  139279. static long _vq_lengthlist__8u0__p4_0[] = {
  139280. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  139281. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  139282. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  139283. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  139284. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  139285. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  139286. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  139287. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  139288. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  139289. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  139290. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  139291. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  139292. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  139293. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  139294. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  139295. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  139296. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  139297. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  139298. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  139299. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  139300. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  139301. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  139302. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  139303. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  139304. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  139305. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  139306. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  139307. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  139308. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  139309. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  139310. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  139311. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  139312. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  139313. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  139314. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  139315. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  139316. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  139317. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  139318. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  139319. 12,
  139320. };
  139321. static float _vq_quantthresh__8u0__p4_0[] = {
  139322. -1.5, -0.5, 0.5, 1.5,
  139323. };
  139324. static long _vq_quantmap__8u0__p4_0[] = {
  139325. 3, 1, 0, 2, 4,
  139326. };
  139327. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  139328. _vq_quantthresh__8u0__p4_0,
  139329. _vq_quantmap__8u0__p4_0,
  139330. 5,
  139331. 5
  139332. };
  139333. static static_codebook _8u0__p4_0 = {
  139334. 4, 625,
  139335. _vq_lengthlist__8u0__p4_0,
  139336. 1, -533725184, 1611661312, 3, 0,
  139337. _vq_quantlist__8u0__p4_0,
  139338. NULL,
  139339. &_vq_auxt__8u0__p4_0,
  139340. NULL,
  139341. 0
  139342. };
  139343. static long _vq_quantlist__8u0__p5_0[] = {
  139344. 4,
  139345. 3,
  139346. 5,
  139347. 2,
  139348. 6,
  139349. 1,
  139350. 7,
  139351. 0,
  139352. 8,
  139353. };
  139354. static long _vq_lengthlist__8u0__p5_0[] = {
  139355. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  139356. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  139357. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  139358. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  139359. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  139360. 12,
  139361. };
  139362. static float _vq_quantthresh__8u0__p5_0[] = {
  139363. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139364. };
  139365. static long _vq_quantmap__8u0__p5_0[] = {
  139366. 7, 5, 3, 1, 0, 2, 4, 6,
  139367. 8,
  139368. };
  139369. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  139370. _vq_quantthresh__8u0__p5_0,
  139371. _vq_quantmap__8u0__p5_0,
  139372. 9,
  139373. 9
  139374. };
  139375. static static_codebook _8u0__p5_0 = {
  139376. 2, 81,
  139377. _vq_lengthlist__8u0__p5_0,
  139378. 1, -531628032, 1611661312, 4, 0,
  139379. _vq_quantlist__8u0__p5_0,
  139380. NULL,
  139381. &_vq_auxt__8u0__p5_0,
  139382. NULL,
  139383. 0
  139384. };
  139385. static long _vq_quantlist__8u0__p6_0[] = {
  139386. 6,
  139387. 5,
  139388. 7,
  139389. 4,
  139390. 8,
  139391. 3,
  139392. 9,
  139393. 2,
  139394. 10,
  139395. 1,
  139396. 11,
  139397. 0,
  139398. 12,
  139399. };
  139400. static long _vq_lengthlist__8u0__p6_0[] = {
  139401. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  139402. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  139403. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  139404. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  139405. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  139406. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  139407. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  139408. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  139409. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  139410. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  139411. 16, 0,15, 0,17, 0, 0, 0, 0,
  139412. };
  139413. static float _vq_quantthresh__8u0__p6_0[] = {
  139414. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139415. 12.5, 17.5, 22.5, 27.5,
  139416. };
  139417. static long _vq_quantmap__8u0__p6_0[] = {
  139418. 11, 9, 7, 5, 3, 1, 0, 2,
  139419. 4, 6, 8, 10, 12,
  139420. };
  139421. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  139422. _vq_quantthresh__8u0__p6_0,
  139423. _vq_quantmap__8u0__p6_0,
  139424. 13,
  139425. 13
  139426. };
  139427. static static_codebook _8u0__p6_0 = {
  139428. 2, 169,
  139429. _vq_lengthlist__8u0__p6_0,
  139430. 1, -526516224, 1616117760, 4, 0,
  139431. _vq_quantlist__8u0__p6_0,
  139432. NULL,
  139433. &_vq_auxt__8u0__p6_0,
  139434. NULL,
  139435. 0
  139436. };
  139437. static long _vq_quantlist__8u0__p6_1[] = {
  139438. 2,
  139439. 1,
  139440. 3,
  139441. 0,
  139442. 4,
  139443. };
  139444. static long _vq_lengthlist__8u0__p6_1[] = {
  139445. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  139446. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  139447. };
  139448. static float _vq_quantthresh__8u0__p6_1[] = {
  139449. -1.5, -0.5, 0.5, 1.5,
  139450. };
  139451. static long _vq_quantmap__8u0__p6_1[] = {
  139452. 3, 1, 0, 2, 4,
  139453. };
  139454. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  139455. _vq_quantthresh__8u0__p6_1,
  139456. _vq_quantmap__8u0__p6_1,
  139457. 5,
  139458. 5
  139459. };
  139460. static static_codebook _8u0__p6_1 = {
  139461. 2, 25,
  139462. _vq_lengthlist__8u0__p6_1,
  139463. 1, -533725184, 1611661312, 3, 0,
  139464. _vq_quantlist__8u0__p6_1,
  139465. NULL,
  139466. &_vq_auxt__8u0__p6_1,
  139467. NULL,
  139468. 0
  139469. };
  139470. static long _vq_quantlist__8u0__p7_0[] = {
  139471. 1,
  139472. 0,
  139473. 2,
  139474. };
  139475. static long _vq_lengthlist__8u0__p7_0[] = {
  139476. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139477. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139478. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139479. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139480. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  139481. 7,
  139482. };
  139483. static float _vq_quantthresh__8u0__p7_0[] = {
  139484. -157.5, 157.5,
  139485. };
  139486. static long _vq_quantmap__8u0__p7_0[] = {
  139487. 1, 0, 2,
  139488. };
  139489. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  139490. _vq_quantthresh__8u0__p7_0,
  139491. _vq_quantmap__8u0__p7_0,
  139492. 3,
  139493. 3
  139494. };
  139495. static static_codebook _8u0__p7_0 = {
  139496. 4, 81,
  139497. _vq_lengthlist__8u0__p7_0,
  139498. 1, -518803456, 1628680192, 2, 0,
  139499. _vq_quantlist__8u0__p7_0,
  139500. NULL,
  139501. &_vq_auxt__8u0__p7_0,
  139502. NULL,
  139503. 0
  139504. };
  139505. static long _vq_quantlist__8u0__p7_1[] = {
  139506. 7,
  139507. 6,
  139508. 8,
  139509. 5,
  139510. 9,
  139511. 4,
  139512. 10,
  139513. 3,
  139514. 11,
  139515. 2,
  139516. 12,
  139517. 1,
  139518. 13,
  139519. 0,
  139520. 14,
  139521. };
  139522. static long _vq_lengthlist__8u0__p7_1[] = {
  139523. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  139524. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  139525. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  139526. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  139527. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  139528. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  139529. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139530. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139531. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139532. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139533. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139534. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139535. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  139536. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139537. 10,
  139538. };
  139539. static float _vq_quantthresh__8u0__p7_1[] = {
  139540. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  139541. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  139542. };
  139543. static long _vq_quantmap__8u0__p7_1[] = {
  139544. 13, 11, 9, 7, 5, 3, 1, 0,
  139545. 2, 4, 6, 8, 10, 12, 14,
  139546. };
  139547. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  139548. _vq_quantthresh__8u0__p7_1,
  139549. _vq_quantmap__8u0__p7_1,
  139550. 15,
  139551. 15
  139552. };
  139553. static static_codebook _8u0__p7_1 = {
  139554. 2, 225,
  139555. _vq_lengthlist__8u0__p7_1,
  139556. 1, -520986624, 1620377600, 4, 0,
  139557. _vq_quantlist__8u0__p7_1,
  139558. NULL,
  139559. &_vq_auxt__8u0__p7_1,
  139560. NULL,
  139561. 0
  139562. };
  139563. static long _vq_quantlist__8u0__p7_2[] = {
  139564. 10,
  139565. 9,
  139566. 11,
  139567. 8,
  139568. 12,
  139569. 7,
  139570. 13,
  139571. 6,
  139572. 14,
  139573. 5,
  139574. 15,
  139575. 4,
  139576. 16,
  139577. 3,
  139578. 17,
  139579. 2,
  139580. 18,
  139581. 1,
  139582. 19,
  139583. 0,
  139584. 20,
  139585. };
  139586. static long _vq_lengthlist__8u0__p7_2[] = {
  139587. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  139588. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  139589. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  139590. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  139591. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  139592. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  139593. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  139594. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  139595. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  139596. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  139597. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  139598. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  139599. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  139600. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  139601. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  139602. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  139603. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  139604. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  139605. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  139606. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  139607. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  139608. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  139609. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  139610. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  139611. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  139612. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  139613. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  139614. 11,12,11,11,11,10,10,11,11,
  139615. };
  139616. static float _vq_quantthresh__8u0__p7_2[] = {
  139617. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  139618. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  139619. 6.5, 7.5, 8.5, 9.5,
  139620. };
  139621. static long _vq_quantmap__8u0__p7_2[] = {
  139622. 19, 17, 15, 13, 11, 9, 7, 5,
  139623. 3, 1, 0, 2, 4, 6, 8, 10,
  139624. 12, 14, 16, 18, 20,
  139625. };
  139626. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  139627. _vq_quantthresh__8u0__p7_2,
  139628. _vq_quantmap__8u0__p7_2,
  139629. 21,
  139630. 21
  139631. };
  139632. static static_codebook _8u0__p7_2 = {
  139633. 2, 441,
  139634. _vq_lengthlist__8u0__p7_2,
  139635. 1, -529268736, 1611661312, 5, 0,
  139636. _vq_quantlist__8u0__p7_2,
  139637. NULL,
  139638. &_vq_auxt__8u0__p7_2,
  139639. NULL,
  139640. 0
  139641. };
  139642. static long _huff_lengthlist__8u0__single[] = {
  139643. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  139644. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  139645. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  139646. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  139647. };
  139648. static static_codebook _huff_book__8u0__single = {
  139649. 2, 64,
  139650. _huff_lengthlist__8u0__single,
  139651. 0, 0, 0, 0, 0,
  139652. NULL,
  139653. NULL,
  139654. NULL,
  139655. NULL,
  139656. 0
  139657. };
  139658. static long _vq_quantlist__8u1__p1_0[] = {
  139659. 1,
  139660. 0,
  139661. 2,
  139662. };
  139663. static long _vq_lengthlist__8u1__p1_0[] = {
  139664. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  139665. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  139666. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  139667. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  139668. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  139669. 10,
  139670. };
  139671. static float _vq_quantthresh__8u1__p1_0[] = {
  139672. -0.5, 0.5,
  139673. };
  139674. static long _vq_quantmap__8u1__p1_0[] = {
  139675. 1, 0, 2,
  139676. };
  139677. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  139678. _vq_quantthresh__8u1__p1_0,
  139679. _vq_quantmap__8u1__p1_0,
  139680. 3,
  139681. 3
  139682. };
  139683. static static_codebook _8u1__p1_0 = {
  139684. 4, 81,
  139685. _vq_lengthlist__8u1__p1_0,
  139686. 1, -535822336, 1611661312, 2, 0,
  139687. _vq_quantlist__8u1__p1_0,
  139688. NULL,
  139689. &_vq_auxt__8u1__p1_0,
  139690. NULL,
  139691. 0
  139692. };
  139693. static long _vq_quantlist__8u1__p2_0[] = {
  139694. 1,
  139695. 0,
  139696. 2,
  139697. };
  139698. static long _vq_lengthlist__8u1__p2_0[] = {
  139699. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  139700. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  139701. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  139702. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  139703. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  139704. 7,
  139705. };
  139706. static float _vq_quantthresh__8u1__p2_0[] = {
  139707. -0.5, 0.5,
  139708. };
  139709. static long _vq_quantmap__8u1__p2_0[] = {
  139710. 1, 0, 2,
  139711. };
  139712. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  139713. _vq_quantthresh__8u1__p2_0,
  139714. _vq_quantmap__8u1__p2_0,
  139715. 3,
  139716. 3
  139717. };
  139718. static static_codebook _8u1__p2_0 = {
  139719. 4, 81,
  139720. _vq_lengthlist__8u1__p2_0,
  139721. 1, -535822336, 1611661312, 2, 0,
  139722. _vq_quantlist__8u1__p2_0,
  139723. NULL,
  139724. &_vq_auxt__8u1__p2_0,
  139725. NULL,
  139726. 0
  139727. };
  139728. static long _vq_quantlist__8u1__p3_0[] = {
  139729. 2,
  139730. 1,
  139731. 3,
  139732. 0,
  139733. 4,
  139734. };
  139735. static long _vq_lengthlist__8u1__p3_0[] = {
  139736. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  139737. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  139738. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  139739. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  139740. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  139741. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  139742. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  139743. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  139744. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  139745. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  139746. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  139747. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  139748. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  139749. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  139750. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  139751. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  139752. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  139753. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  139754. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  139755. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  139756. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  139757. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  139758. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  139759. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  139760. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  139761. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  139762. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  139763. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  139764. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  139765. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  139766. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  139767. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  139768. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  139769. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  139770. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  139771. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  139772. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  139773. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  139774. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  139775. 16,
  139776. };
  139777. static float _vq_quantthresh__8u1__p3_0[] = {
  139778. -1.5, -0.5, 0.5, 1.5,
  139779. };
  139780. static long _vq_quantmap__8u1__p3_0[] = {
  139781. 3, 1, 0, 2, 4,
  139782. };
  139783. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  139784. _vq_quantthresh__8u1__p3_0,
  139785. _vq_quantmap__8u1__p3_0,
  139786. 5,
  139787. 5
  139788. };
  139789. static static_codebook _8u1__p3_0 = {
  139790. 4, 625,
  139791. _vq_lengthlist__8u1__p3_0,
  139792. 1, -533725184, 1611661312, 3, 0,
  139793. _vq_quantlist__8u1__p3_0,
  139794. NULL,
  139795. &_vq_auxt__8u1__p3_0,
  139796. NULL,
  139797. 0
  139798. };
  139799. static long _vq_quantlist__8u1__p4_0[] = {
  139800. 2,
  139801. 1,
  139802. 3,
  139803. 0,
  139804. 4,
  139805. };
  139806. static long _vq_lengthlist__8u1__p4_0[] = {
  139807. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  139808. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  139809. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  139810. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  139811. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  139812. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  139813. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  139814. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  139815. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  139816. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  139817. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  139818. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  139819. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  139820. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  139821. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  139822. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  139823. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  139824. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  139825. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  139826. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  139827. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  139828. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  139829. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  139830. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  139831. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  139832. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  139833. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  139834. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  139835. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  139836. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  139837. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  139838. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  139839. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  139840. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  139841. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  139842. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  139843. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  139844. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  139845. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  139846. 10,
  139847. };
  139848. static float _vq_quantthresh__8u1__p4_0[] = {
  139849. -1.5, -0.5, 0.5, 1.5,
  139850. };
  139851. static long _vq_quantmap__8u1__p4_0[] = {
  139852. 3, 1, 0, 2, 4,
  139853. };
  139854. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  139855. _vq_quantthresh__8u1__p4_0,
  139856. _vq_quantmap__8u1__p4_0,
  139857. 5,
  139858. 5
  139859. };
  139860. static static_codebook _8u1__p4_0 = {
  139861. 4, 625,
  139862. _vq_lengthlist__8u1__p4_0,
  139863. 1, -533725184, 1611661312, 3, 0,
  139864. _vq_quantlist__8u1__p4_0,
  139865. NULL,
  139866. &_vq_auxt__8u1__p4_0,
  139867. NULL,
  139868. 0
  139869. };
  139870. static long _vq_quantlist__8u1__p5_0[] = {
  139871. 4,
  139872. 3,
  139873. 5,
  139874. 2,
  139875. 6,
  139876. 1,
  139877. 7,
  139878. 0,
  139879. 8,
  139880. };
  139881. static long _vq_lengthlist__8u1__p5_0[] = {
  139882. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  139883. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  139884. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  139885. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  139886. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  139887. 13,
  139888. };
  139889. static float _vq_quantthresh__8u1__p5_0[] = {
  139890. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139891. };
  139892. static long _vq_quantmap__8u1__p5_0[] = {
  139893. 7, 5, 3, 1, 0, 2, 4, 6,
  139894. 8,
  139895. };
  139896. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  139897. _vq_quantthresh__8u1__p5_0,
  139898. _vq_quantmap__8u1__p5_0,
  139899. 9,
  139900. 9
  139901. };
  139902. static static_codebook _8u1__p5_0 = {
  139903. 2, 81,
  139904. _vq_lengthlist__8u1__p5_0,
  139905. 1, -531628032, 1611661312, 4, 0,
  139906. _vq_quantlist__8u1__p5_0,
  139907. NULL,
  139908. &_vq_auxt__8u1__p5_0,
  139909. NULL,
  139910. 0
  139911. };
  139912. static long _vq_quantlist__8u1__p6_0[] = {
  139913. 4,
  139914. 3,
  139915. 5,
  139916. 2,
  139917. 6,
  139918. 1,
  139919. 7,
  139920. 0,
  139921. 8,
  139922. };
  139923. static long _vq_lengthlist__8u1__p6_0[] = {
  139924. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  139925. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  139926. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  139927. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  139928. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  139929. 10,
  139930. };
  139931. static float _vq_quantthresh__8u1__p6_0[] = {
  139932. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139933. };
  139934. static long _vq_quantmap__8u1__p6_0[] = {
  139935. 7, 5, 3, 1, 0, 2, 4, 6,
  139936. 8,
  139937. };
  139938. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  139939. _vq_quantthresh__8u1__p6_0,
  139940. _vq_quantmap__8u1__p6_0,
  139941. 9,
  139942. 9
  139943. };
  139944. static static_codebook _8u1__p6_0 = {
  139945. 2, 81,
  139946. _vq_lengthlist__8u1__p6_0,
  139947. 1, -531628032, 1611661312, 4, 0,
  139948. _vq_quantlist__8u1__p6_0,
  139949. NULL,
  139950. &_vq_auxt__8u1__p6_0,
  139951. NULL,
  139952. 0
  139953. };
  139954. static long _vq_quantlist__8u1__p7_0[] = {
  139955. 1,
  139956. 0,
  139957. 2,
  139958. };
  139959. static long _vq_lengthlist__8u1__p7_0[] = {
  139960. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  139961. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  139962. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  139963. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  139964. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  139965. 11,
  139966. };
  139967. static float _vq_quantthresh__8u1__p7_0[] = {
  139968. -5.5, 5.5,
  139969. };
  139970. static long _vq_quantmap__8u1__p7_0[] = {
  139971. 1, 0, 2,
  139972. };
  139973. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  139974. _vq_quantthresh__8u1__p7_0,
  139975. _vq_quantmap__8u1__p7_0,
  139976. 3,
  139977. 3
  139978. };
  139979. static static_codebook _8u1__p7_0 = {
  139980. 4, 81,
  139981. _vq_lengthlist__8u1__p7_0,
  139982. 1, -529137664, 1618345984, 2, 0,
  139983. _vq_quantlist__8u1__p7_0,
  139984. NULL,
  139985. &_vq_auxt__8u1__p7_0,
  139986. NULL,
  139987. 0
  139988. };
  139989. static long _vq_quantlist__8u1__p7_1[] = {
  139990. 5,
  139991. 4,
  139992. 6,
  139993. 3,
  139994. 7,
  139995. 2,
  139996. 8,
  139997. 1,
  139998. 9,
  139999. 0,
  140000. 10,
  140001. };
  140002. static long _vq_lengthlist__8u1__p7_1[] = {
  140003. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  140004. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  140005. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  140006. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  140007. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  140008. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  140009. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  140010. 9, 9, 9, 9, 9,10,10,10,10,
  140011. };
  140012. static float _vq_quantthresh__8u1__p7_1[] = {
  140013. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140014. 3.5, 4.5,
  140015. };
  140016. static long _vq_quantmap__8u1__p7_1[] = {
  140017. 9, 7, 5, 3, 1, 0, 2, 4,
  140018. 6, 8, 10,
  140019. };
  140020. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  140021. _vq_quantthresh__8u1__p7_1,
  140022. _vq_quantmap__8u1__p7_1,
  140023. 11,
  140024. 11
  140025. };
  140026. static static_codebook _8u1__p7_1 = {
  140027. 2, 121,
  140028. _vq_lengthlist__8u1__p7_1,
  140029. 1, -531365888, 1611661312, 4, 0,
  140030. _vq_quantlist__8u1__p7_1,
  140031. NULL,
  140032. &_vq_auxt__8u1__p7_1,
  140033. NULL,
  140034. 0
  140035. };
  140036. static long _vq_quantlist__8u1__p8_0[] = {
  140037. 5,
  140038. 4,
  140039. 6,
  140040. 3,
  140041. 7,
  140042. 2,
  140043. 8,
  140044. 1,
  140045. 9,
  140046. 0,
  140047. 10,
  140048. };
  140049. static long _vq_lengthlist__8u1__p8_0[] = {
  140050. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  140051. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  140052. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  140053. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  140054. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  140055. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  140056. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  140057. 12,13,13,14,14,15,15,15,15,
  140058. };
  140059. static float _vq_quantthresh__8u1__p8_0[] = {
  140060. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  140061. 38.5, 49.5,
  140062. };
  140063. static long _vq_quantmap__8u1__p8_0[] = {
  140064. 9, 7, 5, 3, 1, 0, 2, 4,
  140065. 6, 8, 10,
  140066. };
  140067. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  140068. _vq_quantthresh__8u1__p8_0,
  140069. _vq_quantmap__8u1__p8_0,
  140070. 11,
  140071. 11
  140072. };
  140073. static static_codebook _8u1__p8_0 = {
  140074. 2, 121,
  140075. _vq_lengthlist__8u1__p8_0,
  140076. 1, -524582912, 1618345984, 4, 0,
  140077. _vq_quantlist__8u1__p8_0,
  140078. NULL,
  140079. &_vq_auxt__8u1__p8_0,
  140080. NULL,
  140081. 0
  140082. };
  140083. static long _vq_quantlist__8u1__p8_1[] = {
  140084. 5,
  140085. 4,
  140086. 6,
  140087. 3,
  140088. 7,
  140089. 2,
  140090. 8,
  140091. 1,
  140092. 9,
  140093. 0,
  140094. 10,
  140095. };
  140096. static long _vq_lengthlist__8u1__p8_1[] = {
  140097. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  140098. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  140099. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  140100. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  140101. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140102. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  140103. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  140104. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  140105. };
  140106. static float _vq_quantthresh__8u1__p8_1[] = {
  140107. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140108. 3.5, 4.5,
  140109. };
  140110. static long _vq_quantmap__8u1__p8_1[] = {
  140111. 9, 7, 5, 3, 1, 0, 2, 4,
  140112. 6, 8, 10,
  140113. };
  140114. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  140115. _vq_quantthresh__8u1__p8_1,
  140116. _vq_quantmap__8u1__p8_1,
  140117. 11,
  140118. 11
  140119. };
  140120. static static_codebook _8u1__p8_1 = {
  140121. 2, 121,
  140122. _vq_lengthlist__8u1__p8_1,
  140123. 1, -531365888, 1611661312, 4, 0,
  140124. _vq_quantlist__8u1__p8_1,
  140125. NULL,
  140126. &_vq_auxt__8u1__p8_1,
  140127. NULL,
  140128. 0
  140129. };
  140130. static long _vq_quantlist__8u1__p9_0[] = {
  140131. 7,
  140132. 6,
  140133. 8,
  140134. 5,
  140135. 9,
  140136. 4,
  140137. 10,
  140138. 3,
  140139. 11,
  140140. 2,
  140141. 12,
  140142. 1,
  140143. 13,
  140144. 0,
  140145. 14,
  140146. };
  140147. static long _vq_lengthlist__8u1__p9_0[] = {
  140148. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  140149. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  140150. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140151. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140152. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140153. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140154. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140155. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140156. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140157. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140158. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140159. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140160. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  140161. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140162. 10,
  140163. };
  140164. static float _vq_quantthresh__8u1__p9_0[] = {
  140165. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  140166. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  140167. };
  140168. static long _vq_quantmap__8u1__p9_0[] = {
  140169. 13, 11, 9, 7, 5, 3, 1, 0,
  140170. 2, 4, 6, 8, 10, 12, 14,
  140171. };
  140172. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  140173. _vq_quantthresh__8u1__p9_0,
  140174. _vq_quantmap__8u1__p9_0,
  140175. 15,
  140176. 15
  140177. };
  140178. static static_codebook _8u1__p9_0 = {
  140179. 2, 225,
  140180. _vq_lengthlist__8u1__p9_0,
  140181. 1, -514071552, 1627381760, 4, 0,
  140182. _vq_quantlist__8u1__p9_0,
  140183. NULL,
  140184. &_vq_auxt__8u1__p9_0,
  140185. NULL,
  140186. 0
  140187. };
  140188. static long _vq_quantlist__8u1__p9_1[] = {
  140189. 7,
  140190. 6,
  140191. 8,
  140192. 5,
  140193. 9,
  140194. 4,
  140195. 10,
  140196. 3,
  140197. 11,
  140198. 2,
  140199. 12,
  140200. 1,
  140201. 13,
  140202. 0,
  140203. 14,
  140204. };
  140205. static long _vq_lengthlist__8u1__p9_1[] = {
  140206. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  140207. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  140208. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  140209. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  140210. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  140211. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  140212. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  140213. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  140214. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  140215. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  140216. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  140217. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  140218. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  140219. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  140220. 13,
  140221. };
  140222. static float _vq_quantthresh__8u1__p9_1[] = {
  140223. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  140224. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  140225. };
  140226. static long _vq_quantmap__8u1__p9_1[] = {
  140227. 13, 11, 9, 7, 5, 3, 1, 0,
  140228. 2, 4, 6, 8, 10, 12, 14,
  140229. };
  140230. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  140231. _vq_quantthresh__8u1__p9_1,
  140232. _vq_quantmap__8u1__p9_1,
  140233. 15,
  140234. 15
  140235. };
  140236. static static_codebook _8u1__p9_1 = {
  140237. 2, 225,
  140238. _vq_lengthlist__8u1__p9_1,
  140239. 1, -522338304, 1620115456, 4, 0,
  140240. _vq_quantlist__8u1__p9_1,
  140241. NULL,
  140242. &_vq_auxt__8u1__p9_1,
  140243. NULL,
  140244. 0
  140245. };
  140246. static long _vq_quantlist__8u1__p9_2[] = {
  140247. 8,
  140248. 7,
  140249. 9,
  140250. 6,
  140251. 10,
  140252. 5,
  140253. 11,
  140254. 4,
  140255. 12,
  140256. 3,
  140257. 13,
  140258. 2,
  140259. 14,
  140260. 1,
  140261. 15,
  140262. 0,
  140263. 16,
  140264. };
  140265. static long _vq_lengthlist__8u1__p9_2[] = {
  140266. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  140267. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  140268. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  140269. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  140270. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140271. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  140272. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140273. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  140274. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  140275. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  140276. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  140277. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  140278. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  140279. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  140280. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  140281. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  140282. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140283. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140284. 10,
  140285. };
  140286. static float _vq_quantthresh__8u1__p9_2[] = {
  140287. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140288. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140289. };
  140290. static long _vq_quantmap__8u1__p9_2[] = {
  140291. 15, 13, 11, 9, 7, 5, 3, 1,
  140292. 0, 2, 4, 6, 8, 10, 12, 14,
  140293. 16,
  140294. };
  140295. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  140296. _vq_quantthresh__8u1__p9_2,
  140297. _vq_quantmap__8u1__p9_2,
  140298. 17,
  140299. 17
  140300. };
  140301. static static_codebook _8u1__p9_2 = {
  140302. 2, 289,
  140303. _vq_lengthlist__8u1__p9_2,
  140304. 1, -529530880, 1611661312, 5, 0,
  140305. _vq_quantlist__8u1__p9_2,
  140306. NULL,
  140307. &_vq_auxt__8u1__p9_2,
  140308. NULL,
  140309. 0
  140310. };
  140311. static long _huff_lengthlist__8u1__single[] = {
  140312. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  140313. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  140314. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  140315. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  140316. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  140317. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  140318. 13, 8, 8,15,
  140319. };
  140320. static static_codebook _huff_book__8u1__single = {
  140321. 2, 100,
  140322. _huff_lengthlist__8u1__single,
  140323. 0, 0, 0, 0, 0,
  140324. NULL,
  140325. NULL,
  140326. NULL,
  140327. NULL,
  140328. 0
  140329. };
  140330. static long _huff_lengthlist__44u0__long[] = {
  140331. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  140332. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  140333. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  140334. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  140335. };
  140336. static static_codebook _huff_book__44u0__long = {
  140337. 2, 64,
  140338. _huff_lengthlist__44u0__long,
  140339. 0, 0, 0, 0, 0,
  140340. NULL,
  140341. NULL,
  140342. NULL,
  140343. NULL,
  140344. 0
  140345. };
  140346. static long _vq_quantlist__44u0__p1_0[] = {
  140347. 1,
  140348. 0,
  140349. 2,
  140350. };
  140351. static long _vq_lengthlist__44u0__p1_0[] = {
  140352. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  140353. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  140354. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  140355. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  140356. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  140357. 13,
  140358. };
  140359. static float _vq_quantthresh__44u0__p1_0[] = {
  140360. -0.5, 0.5,
  140361. };
  140362. static long _vq_quantmap__44u0__p1_0[] = {
  140363. 1, 0, 2,
  140364. };
  140365. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  140366. _vq_quantthresh__44u0__p1_0,
  140367. _vq_quantmap__44u0__p1_0,
  140368. 3,
  140369. 3
  140370. };
  140371. static static_codebook _44u0__p1_0 = {
  140372. 4, 81,
  140373. _vq_lengthlist__44u0__p1_0,
  140374. 1, -535822336, 1611661312, 2, 0,
  140375. _vq_quantlist__44u0__p1_0,
  140376. NULL,
  140377. &_vq_auxt__44u0__p1_0,
  140378. NULL,
  140379. 0
  140380. };
  140381. static long _vq_quantlist__44u0__p2_0[] = {
  140382. 1,
  140383. 0,
  140384. 2,
  140385. };
  140386. static long _vq_lengthlist__44u0__p2_0[] = {
  140387. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  140388. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  140389. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  140390. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  140391. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  140392. 9,
  140393. };
  140394. static float _vq_quantthresh__44u0__p2_0[] = {
  140395. -0.5, 0.5,
  140396. };
  140397. static long _vq_quantmap__44u0__p2_0[] = {
  140398. 1, 0, 2,
  140399. };
  140400. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  140401. _vq_quantthresh__44u0__p2_0,
  140402. _vq_quantmap__44u0__p2_0,
  140403. 3,
  140404. 3
  140405. };
  140406. static static_codebook _44u0__p2_0 = {
  140407. 4, 81,
  140408. _vq_lengthlist__44u0__p2_0,
  140409. 1, -535822336, 1611661312, 2, 0,
  140410. _vq_quantlist__44u0__p2_0,
  140411. NULL,
  140412. &_vq_auxt__44u0__p2_0,
  140413. NULL,
  140414. 0
  140415. };
  140416. static long _vq_quantlist__44u0__p3_0[] = {
  140417. 2,
  140418. 1,
  140419. 3,
  140420. 0,
  140421. 4,
  140422. };
  140423. static long _vq_lengthlist__44u0__p3_0[] = {
  140424. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  140425. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  140426. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  140427. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  140428. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  140429. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  140430. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  140431. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  140432. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  140433. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  140434. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  140435. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  140436. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  140437. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  140438. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  140439. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  140440. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  140441. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  140442. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  140443. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  140444. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  140445. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  140446. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  140447. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  140448. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  140449. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  140450. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  140451. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  140452. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  140453. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  140454. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  140455. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  140456. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  140457. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  140458. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  140459. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  140460. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  140461. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  140462. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  140463. 19,
  140464. };
  140465. static float _vq_quantthresh__44u0__p3_0[] = {
  140466. -1.5, -0.5, 0.5, 1.5,
  140467. };
  140468. static long _vq_quantmap__44u0__p3_0[] = {
  140469. 3, 1, 0, 2, 4,
  140470. };
  140471. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  140472. _vq_quantthresh__44u0__p3_0,
  140473. _vq_quantmap__44u0__p3_0,
  140474. 5,
  140475. 5
  140476. };
  140477. static static_codebook _44u0__p3_0 = {
  140478. 4, 625,
  140479. _vq_lengthlist__44u0__p3_0,
  140480. 1, -533725184, 1611661312, 3, 0,
  140481. _vq_quantlist__44u0__p3_0,
  140482. NULL,
  140483. &_vq_auxt__44u0__p3_0,
  140484. NULL,
  140485. 0
  140486. };
  140487. static long _vq_quantlist__44u0__p4_0[] = {
  140488. 2,
  140489. 1,
  140490. 3,
  140491. 0,
  140492. 4,
  140493. };
  140494. static long _vq_lengthlist__44u0__p4_0[] = {
  140495. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  140496. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  140497. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  140498. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  140499. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  140500. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  140501. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  140502. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  140503. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  140504. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  140505. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  140506. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  140507. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  140508. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  140509. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  140510. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  140511. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  140512. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  140513. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  140514. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  140515. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  140516. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  140517. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  140518. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  140519. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  140520. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  140521. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  140522. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  140523. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  140524. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  140525. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  140526. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  140527. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  140528. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  140529. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  140530. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  140531. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  140532. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  140533. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  140534. 12,
  140535. };
  140536. static float _vq_quantthresh__44u0__p4_0[] = {
  140537. -1.5, -0.5, 0.5, 1.5,
  140538. };
  140539. static long _vq_quantmap__44u0__p4_0[] = {
  140540. 3, 1, 0, 2, 4,
  140541. };
  140542. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  140543. _vq_quantthresh__44u0__p4_0,
  140544. _vq_quantmap__44u0__p4_0,
  140545. 5,
  140546. 5
  140547. };
  140548. static static_codebook _44u0__p4_0 = {
  140549. 4, 625,
  140550. _vq_lengthlist__44u0__p4_0,
  140551. 1, -533725184, 1611661312, 3, 0,
  140552. _vq_quantlist__44u0__p4_0,
  140553. NULL,
  140554. &_vq_auxt__44u0__p4_0,
  140555. NULL,
  140556. 0
  140557. };
  140558. static long _vq_quantlist__44u0__p5_0[] = {
  140559. 4,
  140560. 3,
  140561. 5,
  140562. 2,
  140563. 6,
  140564. 1,
  140565. 7,
  140566. 0,
  140567. 8,
  140568. };
  140569. static long _vq_lengthlist__44u0__p5_0[] = {
  140570. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  140571. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  140572. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  140573. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  140574. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  140575. 12,
  140576. };
  140577. static float _vq_quantthresh__44u0__p5_0[] = {
  140578. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140579. };
  140580. static long _vq_quantmap__44u0__p5_0[] = {
  140581. 7, 5, 3, 1, 0, 2, 4, 6,
  140582. 8,
  140583. };
  140584. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  140585. _vq_quantthresh__44u0__p5_0,
  140586. _vq_quantmap__44u0__p5_0,
  140587. 9,
  140588. 9
  140589. };
  140590. static static_codebook _44u0__p5_0 = {
  140591. 2, 81,
  140592. _vq_lengthlist__44u0__p5_0,
  140593. 1, -531628032, 1611661312, 4, 0,
  140594. _vq_quantlist__44u0__p5_0,
  140595. NULL,
  140596. &_vq_auxt__44u0__p5_0,
  140597. NULL,
  140598. 0
  140599. };
  140600. static long _vq_quantlist__44u0__p6_0[] = {
  140601. 6,
  140602. 5,
  140603. 7,
  140604. 4,
  140605. 8,
  140606. 3,
  140607. 9,
  140608. 2,
  140609. 10,
  140610. 1,
  140611. 11,
  140612. 0,
  140613. 12,
  140614. };
  140615. static long _vq_lengthlist__44u0__p6_0[] = {
  140616. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  140617. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  140618. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  140619. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  140620. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  140621. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  140622. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  140623. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  140624. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  140625. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  140626. 15,17,16,17,18,17,17,18, 0,
  140627. };
  140628. static float _vq_quantthresh__44u0__p6_0[] = {
  140629. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140630. 12.5, 17.5, 22.5, 27.5,
  140631. };
  140632. static long _vq_quantmap__44u0__p6_0[] = {
  140633. 11, 9, 7, 5, 3, 1, 0, 2,
  140634. 4, 6, 8, 10, 12,
  140635. };
  140636. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  140637. _vq_quantthresh__44u0__p6_0,
  140638. _vq_quantmap__44u0__p6_0,
  140639. 13,
  140640. 13
  140641. };
  140642. static static_codebook _44u0__p6_0 = {
  140643. 2, 169,
  140644. _vq_lengthlist__44u0__p6_0,
  140645. 1, -526516224, 1616117760, 4, 0,
  140646. _vq_quantlist__44u0__p6_0,
  140647. NULL,
  140648. &_vq_auxt__44u0__p6_0,
  140649. NULL,
  140650. 0
  140651. };
  140652. static long _vq_quantlist__44u0__p6_1[] = {
  140653. 2,
  140654. 1,
  140655. 3,
  140656. 0,
  140657. 4,
  140658. };
  140659. static long _vq_lengthlist__44u0__p6_1[] = {
  140660. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  140661. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  140662. };
  140663. static float _vq_quantthresh__44u0__p6_1[] = {
  140664. -1.5, -0.5, 0.5, 1.5,
  140665. };
  140666. static long _vq_quantmap__44u0__p6_1[] = {
  140667. 3, 1, 0, 2, 4,
  140668. };
  140669. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  140670. _vq_quantthresh__44u0__p6_1,
  140671. _vq_quantmap__44u0__p6_1,
  140672. 5,
  140673. 5
  140674. };
  140675. static static_codebook _44u0__p6_1 = {
  140676. 2, 25,
  140677. _vq_lengthlist__44u0__p6_1,
  140678. 1, -533725184, 1611661312, 3, 0,
  140679. _vq_quantlist__44u0__p6_1,
  140680. NULL,
  140681. &_vq_auxt__44u0__p6_1,
  140682. NULL,
  140683. 0
  140684. };
  140685. static long _vq_quantlist__44u0__p7_0[] = {
  140686. 2,
  140687. 1,
  140688. 3,
  140689. 0,
  140690. 4,
  140691. };
  140692. static long _vq_lengthlist__44u0__p7_0[] = {
  140693. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  140694. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140695. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140696. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140697. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140698. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140699. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140700. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  140701. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140702. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140703. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140704. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140705. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140706. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140707. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140708. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140710. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140711. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140712. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140713. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140714. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140715. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140716. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140717. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140718. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140719. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140720. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140721. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140722. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140723. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  140724. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140725. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140726. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140727. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140728. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140729. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140730. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140731. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140732. 10,
  140733. };
  140734. static float _vq_quantthresh__44u0__p7_0[] = {
  140735. -253.5, -84.5, 84.5, 253.5,
  140736. };
  140737. static long _vq_quantmap__44u0__p7_0[] = {
  140738. 3, 1, 0, 2, 4,
  140739. };
  140740. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  140741. _vq_quantthresh__44u0__p7_0,
  140742. _vq_quantmap__44u0__p7_0,
  140743. 5,
  140744. 5
  140745. };
  140746. static static_codebook _44u0__p7_0 = {
  140747. 4, 625,
  140748. _vq_lengthlist__44u0__p7_0,
  140749. 1, -518709248, 1626677248, 3, 0,
  140750. _vq_quantlist__44u0__p7_0,
  140751. NULL,
  140752. &_vq_auxt__44u0__p7_0,
  140753. NULL,
  140754. 0
  140755. };
  140756. static long _vq_quantlist__44u0__p7_1[] = {
  140757. 6,
  140758. 5,
  140759. 7,
  140760. 4,
  140761. 8,
  140762. 3,
  140763. 9,
  140764. 2,
  140765. 10,
  140766. 1,
  140767. 11,
  140768. 0,
  140769. 12,
  140770. };
  140771. static long _vq_lengthlist__44u0__p7_1[] = {
  140772. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  140773. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  140774. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  140775. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  140776. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  140777. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  140778. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  140779. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  140780. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  140781. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  140782. 15,15,15,15,15,15,15,15,15,
  140783. };
  140784. static float _vq_quantthresh__44u0__p7_1[] = {
  140785. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  140786. 32.5, 45.5, 58.5, 71.5,
  140787. };
  140788. static long _vq_quantmap__44u0__p7_1[] = {
  140789. 11, 9, 7, 5, 3, 1, 0, 2,
  140790. 4, 6, 8, 10, 12,
  140791. };
  140792. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  140793. _vq_quantthresh__44u0__p7_1,
  140794. _vq_quantmap__44u0__p7_1,
  140795. 13,
  140796. 13
  140797. };
  140798. static static_codebook _44u0__p7_1 = {
  140799. 2, 169,
  140800. _vq_lengthlist__44u0__p7_1,
  140801. 1, -523010048, 1618608128, 4, 0,
  140802. _vq_quantlist__44u0__p7_1,
  140803. NULL,
  140804. &_vq_auxt__44u0__p7_1,
  140805. NULL,
  140806. 0
  140807. };
  140808. static long _vq_quantlist__44u0__p7_2[] = {
  140809. 6,
  140810. 5,
  140811. 7,
  140812. 4,
  140813. 8,
  140814. 3,
  140815. 9,
  140816. 2,
  140817. 10,
  140818. 1,
  140819. 11,
  140820. 0,
  140821. 12,
  140822. };
  140823. static long _vq_lengthlist__44u0__p7_2[] = {
  140824. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  140825. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  140826. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  140827. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  140828. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  140829. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  140830. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  140831. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140832. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140833. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  140834. 9, 9, 9,10, 9, 9,10,10, 9,
  140835. };
  140836. static float _vq_quantthresh__44u0__p7_2[] = {
  140837. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  140838. 2.5, 3.5, 4.5, 5.5,
  140839. };
  140840. static long _vq_quantmap__44u0__p7_2[] = {
  140841. 11, 9, 7, 5, 3, 1, 0, 2,
  140842. 4, 6, 8, 10, 12,
  140843. };
  140844. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  140845. _vq_quantthresh__44u0__p7_2,
  140846. _vq_quantmap__44u0__p7_2,
  140847. 13,
  140848. 13
  140849. };
  140850. static static_codebook _44u0__p7_2 = {
  140851. 2, 169,
  140852. _vq_lengthlist__44u0__p7_2,
  140853. 1, -531103744, 1611661312, 4, 0,
  140854. _vq_quantlist__44u0__p7_2,
  140855. NULL,
  140856. &_vq_auxt__44u0__p7_2,
  140857. NULL,
  140858. 0
  140859. };
  140860. static long _huff_lengthlist__44u0__short[] = {
  140861. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  140862. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  140863. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  140864. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  140865. };
  140866. static static_codebook _huff_book__44u0__short = {
  140867. 2, 64,
  140868. _huff_lengthlist__44u0__short,
  140869. 0, 0, 0, 0, 0,
  140870. NULL,
  140871. NULL,
  140872. NULL,
  140873. NULL,
  140874. 0
  140875. };
  140876. static long _huff_lengthlist__44u1__long[] = {
  140877. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  140878. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  140879. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  140880. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  140881. };
  140882. static static_codebook _huff_book__44u1__long = {
  140883. 2, 64,
  140884. _huff_lengthlist__44u1__long,
  140885. 0, 0, 0, 0, 0,
  140886. NULL,
  140887. NULL,
  140888. NULL,
  140889. NULL,
  140890. 0
  140891. };
  140892. static long _vq_quantlist__44u1__p1_0[] = {
  140893. 1,
  140894. 0,
  140895. 2,
  140896. };
  140897. static long _vq_lengthlist__44u1__p1_0[] = {
  140898. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  140899. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  140900. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  140901. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  140902. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  140903. 13,
  140904. };
  140905. static float _vq_quantthresh__44u1__p1_0[] = {
  140906. -0.5, 0.5,
  140907. };
  140908. static long _vq_quantmap__44u1__p1_0[] = {
  140909. 1, 0, 2,
  140910. };
  140911. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  140912. _vq_quantthresh__44u1__p1_0,
  140913. _vq_quantmap__44u1__p1_0,
  140914. 3,
  140915. 3
  140916. };
  140917. static static_codebook _44u1__p1_0 = {
  140918. 4, 81,
  140919. _vq_lengthlist__44u1__p1_0,
  140920. 1, -535822336, 1611661312, 2, 0,
  140921. _vq_quantlist__44u1__p1_0,
  140922. NULL,
  140923. &_vq_auxt__44u1__p1_0,
  140924. NULL,
  140925. 0
  140926. };
  140927. static long _vq_quantlist__44u1__p2_0[] = {
  140928. 1,
  140929. 0,
  140930. 2,
  140931. };
  140932. static long _vq_lengthlist__44u1__p2_0[] = {
  140933. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  140934. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  140935. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  140936. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  140937. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  140938. 9,
  140939. };
  140940. static float _vq_quantthresh__44u1__p2_0[] = {
  140941. -0.5, 0.5,
  140942. };
  140943. static long _vq_quantmap__44u1__p2_0[] = {
  140944. 1, 0, 2,
  140945. };
  140946. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  140947. _vq_quantthresh__44u1__p2_0,
  140948. _vq_quantmap__44u1__p2_0,
  140949. 3,
  140950. 3
  140951. };
  140952. static static_codebook _44u1__p2_0 = {
  140953. 4, 81,
  140954. _vq_lengthlist__44u1__p2_0,
  140955. 1, -535822336, 1611661312, 2, 0,
  140956. _vq_quantlist__44u1__p2_0,
  140957. NULL,
  140958. &_vq_auxt__44u1__p2_0,
  140959. NULL,
  140960. 0
  140961. };
  140962. static long _vq_quantlist__44u1__p3_0[] = {
  140963. 2,
  140964. 1,
  140965. 3,
  140966. 0,
  140967. 4,
  140968. };
  140969. static long _vq_lengthlist__44u1__p3_0[] = {
  140970. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  140971. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  140972. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  140973. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  140974. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  140975. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  140976. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  140977. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  140978. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  140979. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  140980. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  140981. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  140982. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  140983. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  140984. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  140985. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  140986. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  140987. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  140988. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  140989. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  140990. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  140991. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  140992. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  140993. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  140994. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  140995. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  140996. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  140997. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  140998. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  140999. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  141000. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  141001. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  141002. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  141003. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  141004. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  141005. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  141006. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  141007. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  141008. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  141009. 19,
  141010. };
  141011. static float _vq_quantthresh__44u1__p3_0[] = {
  141012. -1.5, -0.5, 0.5, 1.5,
  141013. };
  141014. static long _vq_quantmap__44u1__p3_0[] = {
  141015. 3, 1, 0, 2, 4,
  141016. };
  141017. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  141018. _vq_quantthresh__44u1__p3_0,
  141019. _vq_quantmap__44u1__p3_0,
  141020. 5,
  141021. 5
  141022. };
  141023. static static_codebook _44u1__p3_0 = {
  141024. 4, 625,
  141025. _vq_lengthlist__44u1__p3_0,
  141026. 1, -533725184, 1611661312, 3, 0,
  141027. _vq_quantlist__44u1__p3_0,
  141028. NULL,
  141029. &_vq_auxt__44u1__p3_0,
  141030. NULL,
  141031. 0
  141032. };
  141033. static long _vq_quantlist__44u1__p4_0[] = {
  141034. 2,
  141035. 1,
  141036. 3,
  141037. 0,
  141038. 4,
  141039. };
  141040. static long _vq_lengthlist__44u1__p4_0[] = {
  141041. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  141042. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  141043. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  141044. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  141045. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  141046. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  141047. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  141048. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  141049. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  141050. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  141051. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  141052. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141053. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  141054. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  141055. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  141056. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  141057. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  141058. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  141059. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  141060. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  141061. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  141062. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  141063. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  141064. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  141065. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  141066. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  141067. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  141068. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  141069. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  141070. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  141071. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  141072. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  141073. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  141074. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  141075. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  141076. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  141077. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  141078. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  141079. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  141080. 12,
  141081. };
  141082. static float _vq_quantthresh__44u1__p4_0[] = {
  141083. -1.5, -0.5, 0.5, 1.5,
  141084. };
  141085. static long _vq_quantmap__44u1__p4_0[] = {
  141086. 3, 1, 0, 2, 4,
  141087. };
  141088. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  141089. _vq_quantthresh__44u1__p4_0,
  141090. _vq_quantmap__44u1__p4_0,
  141091. 5,
  141092. 5
  141093. };
  141094. static static_codebook _44u1__p4_0 = {
  141095. 4, 625,
  141096. _vq_lengthlist__44u1__p4_0,
  141097. 1, -533725184, 1611661312, 3, 0,
  141098. _vq_quantlist__44u1__p4_0,
  141099. NULL,
  141100. &_vq_auxt__44u1__p4_0,
  141101. NULL,
  141102. 0
  141103. };
  141104. static long _vq_quantlist__44u1__p5_0[] = {
  141105. 4,
  141106. 3,
  141107. 5,
  141108. 2,
  141109. 6,
  141110. 1,
  141111. 7,
  141112. 0,
  141113. 8,
  141114. };
  141115. static long _vq_lengthlist__44u1__p5_0[] = {
  141116. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  141117. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  141118. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  141119. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  141120. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  141121. 12,
  141122. };
  141123. static float _vq_quantthresh__44u1__p5_0[] = {
  141124. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141125. };
  141126. static long _vq_quantmap__44u1__p5_0[] = {
  141127. 7, 5, 3, 1, 0, 2, 4, 6,
  141128. 8,
  141129. };
  141130. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  141131. _vq_quantthresh__44u1__p5_0,
  141132. _vq_quantmap__44u1__p5_0,
  141133. 9,
  141134. 9
  141135. };
  141136. static static_codebook _44u1__p5_0 = {
  141137. 2, 81,
  141138. _vq_lengthlist__44u1__p5_0,
  141139. 1, -531628032, 1611661312, 4, 0,
  141140. _vq_quantlist__44u1__p5_0,
  141141. NULL,
  141142. &_vq_auxt__44u1__p5_0,
  141143. NULL,
  141144. 0
  141145. };
  141146. static long _vq_quantlist__44u1__p6_0[] = {
  141147. 6,
  141148. 5,
  141149. 7,
  141150. 4,
  141151. 8,
  141152. 3,
  141153. 9,
  141154. 2,
  141155. 10,
  141156. 1,
  141157. 11,
  141158. 0,
  141159. 12,
  141160. };
  141161. static long _vq_lengthlist__44u1__p6_0[] = {
  141162. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  141163. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  141164. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  141165. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  141166. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  141167. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  141168. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  141169. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  141170. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  141171. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  141172. 15,17,16,17,18,17,17,18, 0,
  141173. };
  141174. static float _vq_quantthresh__44u1__p6_0[] = {
  141175. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141176. 12.5, 17.5, 22.5, 27.5,
  141177. };
  141178. static long _vq_quantmap__44u1__p6_0[] = {
  141179. 11, 9, 7, 5, 3, 1, 0, 2,
  141180. 4, 6, 8, 10, 12,
  141181. };
  141182. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  141183. _vq_quantthresh__44u1__p6_0,
  141184. _vq_quantmap__44u1__p6_0,
  141185. 13,
  141186. 13
  141187. };
  141188. static static_codebook _44u1__p6_0 = {
  141189. 2, 169,
  141190. _vq_lengthlist__44u1__p6_0,
  141191. 1, -526516224, 1616117760, 4, 0,
  141192. _vq_quantlist__44u1__p6_0,
  141193. NULL,
  141194. &_vq_auxt__44u1__p6_0,
  141195. NULL,
  141196. 0
  141197. };
  141198. static long _vq_quantlist__44u1__p6_1[] = {
  141199. 2,
  141200. 1,
  141201. 3,
  141202. 0,
  141203. 4,
  141204. };
  141205. static long _vq_lengthlist__44u1__p6_1[] = {
  141206. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  141207. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  141208. };
  141209. static float _vq_quantthresh__44u1__p6_1[] = {
  141210. -1.5, -0.5, 0.5, 1.5,
  141211. };
  141212. static long _vq_quantmap__44u1__p6_1[] = {
  141213. 3, 1, 0, 2, 4,
  141214. };
  141215. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  141216. _vq_quantthresh__44u1__p6_1,
  141217. _vq_quantmap__44u1__p6_1,
  141218. 5,
  141219. 5
  141220. };
  141221. static static_codebook _44u1__p6_1 = {
  141222. 2, 25,
  141223. _vq_lengthlist__44u1__p6_1,
  141224. 1, -533725184, 1611661312, 3, 0,
  141225. _vq_quantlist__44u1__p6_1,
  141226. NULL,
  141227. &_vq_auxt__44u1__p6_1,
  141228. NULL,
  141229. 0
  141230. };
  141231. static long _vq_quantlist__44u1__p7_0[] = {
  141232. 3,
  141233. 2,
  141234. 4,
  141235. 1,
  141236. 5,
  141237. 0,
  141238. 6,
  141239. };
  141240. static long _vq_lengthlist__44u1__p7_0[] = {
  141241. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141242. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141243. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141244. 8,
  141245. };
  141246. static float _vq_quantthresh__44u1__p7_0[] = {
  141247. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  141248. };
  141249. static long _vq_quantmap__44u1__p7_0[] = {
  141250. 5, 3, 1, 0, 2, 4, 6,
  141251. };
  141252. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  141253. _vq_quantthresh__44u1__p7_0,
  141254. _vq_quantmap__44u1__p7_0,
  141255. 7,
  141256. 7
  141257. };
  141258. static static_codebook _44u1__p7_0 = {
  141259. 2, 49,
  141260. _vq_lengthlist__44u1__p7_0,
  141261. 1, -518017024, 1626677248, 3, 0,
  141262. _vq_quantlist__44u1__p7_0,
  141263. NULL,
  141264. &_vq_auxt__44u1__p7_0,
  141265. NULL,
  141266. 0
  141267. };
  141268. static long _vq_quantlist__44u1__p7_1[] = {
  141269. 6,
  141270. 5,
  141271. 7,
  141272. 4,
  141273. 8,
  141274. 3,
  141275. 9,
  141276. 2,
  141277. 10,
  141278. 1,
  141279. 11,
  141280. 0,
  141281. 12,
  141282. };
  141283. static long _vq_lengthlist__44u1__p7_1[] = {
  141284. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  141285. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  141286. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  141287. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  141288. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  141289. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  141290. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  141291. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  141292. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  141293. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  141294. 15,15,15,15,15,15,15,15,15,
  141295. };
  141296. static float _vq_quantthresh__44u1__p7_1[] = {
  141297. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  141298. 32.5, 45.5, 58.5, 71.5,
  141299. };
  141300. static long _vq_quantmap__44u1__p7_1[] = {
  141301. 11, 9, 7, 5, 3, 1, 0, 2,
  141302. 4, 6, 8, 10, 12,
  141303. };
  141304. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  141305. _vq_quantthresh__44u1__p7_1,
  141306. _vq_quantmap__44u1__p7_1,
  141307. 13,
  141308. 13
  141309. };
  141310. static static_codebook _44u1__p7_1 = {
  141311. 2, 169,
  141312. _vq_lengthlist__44u1__p7_1,
  141313. 1, -523010048, 1618608128, 4, 0,
  141314. _vq_quantlist__44u1__p7_1,
  141315. NULL,
  141316. &_vq_auxt__44u1__p7_1,
  141317. NULL,
  141318. 0
  141319. };
  141320. static long _vq_quantlist__44u1__p7_2[] = {
  141321. 6,
  141322. 5,
  141323. 7,
  141324. 4,
  141325. 8,
  141326. 3,
  141327. 9,
  141328. 2,
  141329. 10,
  141330. 1,
  141331. 11,
  141332. 0,
  141333. 12,
  141334. };
  141335. static long _vq_lengthlist__44u1__p7_2[] = {
  141336. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  141337. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  141338. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  141339. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  141340. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  141341. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  141342. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  141343. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141344. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141345. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  141346. 9, 9, 9,10, 9, 9,10,10, 9,
  141347. };
  141348. static float _vq_quantthresh__44u1__p7_2[] = {
  141349. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  141350. 2.5, 3.5, 4.5, 5.5,
  141351. };
  141352. static long _vq_quantmap__44u1__p7_2[] = {
  141353. 11, 9, 7, 5, 3, 1, 0, 2,
  141354. 4, 6, 8, 10, 12,
  141355. };
  141356. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  141357. _vq_quantthresh__44u1__p7_2,
  141358. _vq_quantmap__44u1__p7_2,
  141359. 13,
  141360. 13
  141361. };
  141362. static static_codebook _44u1__p7_2 = {
  141363. 2, 169,
  141364. _vq_lengthlist__44u1__p7_2,
  141365. 1, -531103744, 1611661312, 4, 0,
  141366. _vq_quantlist__44u1__p7_2,
  141367. NULL,
  141368. &_vq_auxt__44u1__p7_2,
  141369. NULL,
  141370. 0
  141371. };
  141372. static long _huff_lengthlist__44u1__short[] = {
  141373. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  141374. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  141375. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  141376. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  141377. };
  141378. static static_codebook _huff_book__44u1__short = {
  141379. 2, 64,
  141380. _huff_lengthlist__44u1__short,
  141381. 0, 0, 0, 0, 0,
  141382. NULL,
  141383. NULL,
  141384. NULL,
  141385. NULL,
  141386. 0
  141387. };
  141388. static long _huff_lengthlist__44u2__long[] = {
  141389. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  141390. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  141391. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  141392. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  141393. };
  141394. static static_codebook _huff_book__44u2__long = {
  141395. 2, 64,
  141396. _huff_lengthlist__44u2__long,
  141397. 0, 0, 0, 0, 0,
  141398. NULL,
  141399. NULL,
  141400. NULL,
  141401. NULL,
  141402. 0
  141403. };
  141404. static long _vq_quantlist__44u2__p1_0[] = {
  141405. 1,
  141406. 0,
  141407. 2,
  141408. };
  141409. static long _vq_lengthlist__44u2__p1_0[] = {
  141410. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  141411. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141412. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  141413. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  141414. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  141415. 13,
  141416. };
  141417. static float _vq_quantthresh__44u2__p1_0[] = {
  141418. -0.5, 0.5,
  141419. };
  141420. static long _vq_quantmap__44u2__p1_0[] = {
  141421. 1, 0, 2,
  141422. };
  141423. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  141424. _vq_quantthresh__44u2__p1_0,
  141425. _vq_quantmap__44u2__p1_0,
  141426. 3,
  141427. 3
  141428. };
  141429. static static_codebook _44u2__p1_0 = {
  141430. 4, 81,
  141431. _vq_lengthlist__44u2__p1_0,
  141432. 1, -535822336, 1611661312, 2, 0,
  141433. _vq_quantlist__44u2__p1_0,
  141434. NULL,
  141435. &_vq_auxt__44u2__p1_0,
  141436. NULL,
  141437. 0
  141438. };
  141439. static long _vq_quantlist__44u2__p2_0[] = {
  141440. 1,
  141441. 0,
  141442. 2,
  141443. };
  141444. static long _vq_lengthlist__44u2__p2_0[] = {
  141445. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  141446. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  141447. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141448. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  141449. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  141450. 9,
  141451. };
  141452. static float _vq_quantthresh__44u2__p2_0[] = {
  141453. -0.5, 0.5,
  141454. };
  141455. static long _vq_quantmap__44u2__p2_0[] = {
  141456. 1, 0, 2,
  141457. };
  141458. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  141459. _vq_quantthresh__44u2__p2_0,
  141460. _vq_quantmap__44u2__p2_0,
  141461. 3,
  141462. 3
  141463. };
  141464. static static_codebook _44u2__p2_0 = {
  141465. 4, 81,
  141466. _vq_lengthlist__44u2__p2_0,
  141467. 1, -535822336, 1611661312, 2, 0,
  141468. _vq_quantlist__44u2__p2_0,
  141469. NULL,
  141470. &_vq_auxt__44u2__p2_0,
  141471. NULL,
  141472. 0
  141473. };
  141474. static long _vq_quantlist__44u2__p3_0[] = {
  141475. 2,
  141476. 1,
  141477. 3,
  141478. 0,
  141479. 4,
  141480. };
  141481. static long _vq_lengthlist__44u2__p3_0[] = {
  141482. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  141483. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  141484. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  141485. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  141486. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  141487. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  141488. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  141489. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  141490. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  141491. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  141492. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  141493. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  141494. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  141495. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  141496. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  141497. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  141498. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  141499. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  141500. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  141501. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  141502. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  141503. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  141504. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  141505. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  141506. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  141507. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  141508. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  141509. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  141510. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  141511. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  141512. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  141513. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  141514. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  141515. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  141516. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  141517. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  141518. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  141519. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  141520. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  141521. 0,
  141522. };
  141523. static float _vq_quantthresh__44u2__p3_0[] = {
  141524. -1.5, -0.5, 0.5, 1.5,
  141525. };
  141526. static long _vq_quantmap__44u2__p3_0[] = {
  141527. 3, 1, 0, 2, 4,
  141528. };
  141529. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  141530. _vq_quantthresh__44u2__p3_0,
  141531. _vq_quantmap__44u2__p3_0,
  141532. 5,
  141533. 5
  141534. };
  141535. static static_codebook _44u2__p3_0 = {
  141536. 4, 625,
  141537. _vq_lengthlist__44u2__p3_0,
  141538. 1, -533725184, 1611661312, 3, 0,
  141539. _vq_quantlist__44u2__p3_0,
  141540. NULL,
  141541. &_vq_auxt__44u2__p3_0,
  141542. NULL,
  141543. 0
  141544. };
  141545. static long _vq_quantlist__44u2__p4_0[] = {
  141546. 2,
  141547. 1,
  141548. 3,
  141549. 0,
  141550. 4,
  141551. };
  141552. static long _vq_lengthlist__44u2__p4_0[] = {
  141553. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  141554. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  141555. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  141556. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  141557. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  141558. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  141559. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  141560. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  141561. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  141562. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  141563. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  141564. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141565. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  141566. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  141567. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  141568. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  141569. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  141570. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  141571. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  141572. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  141573. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  141574. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  141575. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  141576. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  141577. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  141578. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  141579. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  141580. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  141581. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  141582. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  141583. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  141584. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  141585. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  141586. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  141587. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  141588. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  141589. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  141590. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  141591. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  141592. 13,
  141593. };
  141594. static float _vq_quantthresh__44u2__p4_0[] = {
  141595. -1.5, -0.5, 0.5, 1.5,
  141596. };
  141597. static long _vq_quantmap__44u2__p4_0[] = {
  141598. 3, 1, 0, 2, 4,
  141599. };
  141600. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  141601. _vq_quantthresh__44u2__p4_0,
  141602. _vq_quantmap__44u2__p4_0,
  141603. 5,
  141604. 5
  141605. };
  141606. static static_codebook _44u2__p4_0 = {
  141607. 4, 625,
  141608. _vq_lengthlist__44u2__p4_0,
  141609. 1, -533725184, 1611661312, 3, 0,
  141610. _vq_quantlist__44u2__p4_0,
  141611. NULL,
  141612. &_vq_auxt__44u2__p4_0,
  141613. NULL,
  141614. 0
  141615. };
  141616. static long _vq_quantlist__44u2__p5_0[] = {
  141617. 4,
  141618. 3,
  141619. 5,
  141620. 2,
  141621. 6,
  141622. 1,
  141623. 7,
  141624. 0,
  141625. 8,
  141626. };
  141627. static long _vq_lengthlist__44u2__p5_0[] = {
  141628. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  141629. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  141630. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  141631. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  141632. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  141633. 13,
  141634. };
  141635. static float _vq_quantthresh__44u2__p5_0[] = {
  141636. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141637. };
  141638. static long _vq_quantmap__44u2__p5_0[] = {
  141639. 7, 5, 3, 1, 0, 2, 4, 6,
  141640. 8,
  141641. };
  141642. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  141643. _vq_quantthresh__44u2__p5_0,
  141644. _vq_quantmap__44u2__p5_0,
  141645. 9,
  141646. 9
  141647. };
  141648. static static_codebook _44u2__p5_0 = {
  141649. 2, 81,
  141650. _vq_lengthlist__44u2__p5_0,
  141651. 1, -531628032, 1611661312, 4, 0,
  141652. _vq_quantlist__44u2__p5_0,
  141653. NULL,
  141654. &_vq_auxt__44u2__p5_0,
  141655. NULL,
  141656. 0
  141657. };
  141658. static long _vq_quantlist__44u2__p6_0[] = {
  141659. 6,
  141660. 5,
  141661. 7,
  141662. 4,
  141663. 8,
  141664. 3,
  141665. 9,
  141666. 2,
  141667. 10,
  141668. 1,
  141669. 11,
  141670. 0,
  141671. 12,
  141672. };
  141673. static long _vq_lengthlist__44u2__p6_0[] = {
  141674. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  141675. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  141676. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  141677. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  141678. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  141679. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  141680. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  141681. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  141682. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  141683. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  141684. 15,17,17,16,18,17,18, 0, 0,
  141685. };
  141686. static float _vq_quantthresh__44u2__p6_0[] = {
  141687. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141688. 12.5, 17.5, 22.5, 27.5,
  141689. };
  141690. static long _vq_quantmap__44u2__p6_0[] = {
  141691. 11, 9, 7, 5, 3, 1, 0, 2,
  141692. 4, 6, 8, 10, 12,
  141693. };
  141694. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  141695. _vq_quantthresh__44u2__p6_0,
  141696. _vq_quantmap__44u2__p6_0,
  141697. 13,
  141698. 13
  141699. };
  141700. static static_codebook _44u2__p6_0 = {
  141701. 2, 169,
  141702. _vq_lengthlist__44u2__p6_0,
  141703. 1, -526516224, 1616117760, 4, 0,
  141704. _vq_quantlist__44u2__p6_0,
  141705. NULL,
  141706. &_vq_auxt__44u2__p6_0,
  141707. NULL,
  141708. 0
  141709. };
  141710. static long _vq_quantlist__44u2__p6_1[] = {
  141711. 2,
  141712. 1,
  141713. 3,
  141714. 0,
  141715. 4,
  141716. };
  141717. static long _vq_lengthlist__44u2__p6_1[] = {
  141718. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  141719. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  141720. };
  141721. static float _vq_quantthresh__44u2__p6_1[] = {
  141722. -1.5, -0.5, 0.5, 1.5,
  141723. };
  141724. static long _vq_quantmap__44u2__p6_1[] = {
  141725. 3, 1, 0, 2, 4,
  141726. };
  141727. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  141728. _vq_quantthresh__44u2__p6_1,
  141729. _vq_quantmap__44u2__p6_1,
  141730. 5,
  141731. 5
  141732. };
  141733. static static_codebook _44u2__p6_1 = {
  141734. 2, 25,
  141735. _vq_lengthlist__44u2__p6_1,
  141736. 1, -533725184, 1611661312, 3, 0,
  141737. _vq_quantlist__44u2__p6_1,
  141738. NULL,
  141739. &_vq_auxt__44u2__p6_1,
  141740. NULL,
  141741. 0
  141742. };
  141743. static long _vq_quantlist__44u2__p7_0[] = {
  141744. 4,
  141745. 3,
  141746. 5,
  141747. 2,
  141748. 6,
  141749. 1,
  141750. 7,
  141751. 0,
  141752. 8,
  141753. };
  141754. static long _vq_lengthlist__44u2__p7_0[] = {
  141755. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  141756. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  141757. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141758. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141759. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141760. 11,
  141761. };
  141762. static float _vq_quantthresh__44u2__p7_0[] = {
  141763. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  141764. };
  141765. static long _vq_quantmap__44u2__p7_0[] = {
  141766. 7, 5, 3, 1, 0, 2, 4, 6,
  141767. 8,
  141768. };
  141769. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  141770. _vq_quantthresh__44u2__p7_0,
  141771. _vq_quantmap__44u2__p7_0,
  141772. 9,
  141773. 9
  141774. };
  141775. static static_codebook _44u2__p7_0 = {
  141776. 2, 81,
  141777. _vq_lengthlist__44u2__p7_0,
  141778. 1, -516612096, 1626677248, 4, 0,
  141779. _vq_quantlist__44u2__p7_0,
  141780. NULL,
  141781. &_vq_auxt__44u2__p7_0,
  141782. NULL,
  141783. 0
  141784. };
  141785. static long _vq_quantlist__44u2__p7_1[] = {
  141786. 6,
  141787. 5,
  141788. 7,
  141789. 4,
  141790. 8,
  141791. 3,
  141792. 9,
  141793. 2,
  141794. 10,
  141795. 1,
  141796. 11,
  141797. 0,
  141798. 12,
  141799. };
  141800. static long _vq_lengthlist__44u2__p7_1[] = {
  141801. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  141802. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  141803. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  141804. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  141805. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  141806. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  141807. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  141808. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  141809. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  141810. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  141811. 14,14,14,17,15,17,17,17,17,
  141812. };
  141813. static float _vq_quantthresh__44u2__p7_1[] = {
  141814. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  141815. 32.5, 45.5, 58.5, 71.5,
  141816. };
  141817. static long _vq_quantmap__44u2__p7_1[] = {
  141818. 11, 9, 7, 5, 3, 1, 0, 2,
  141819. 4, 6, 8, 10, 12,
  141820. };
  141821. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  141822. _vq_quantthresh__44u2__p7_1,
  141823. _vq_quantmap__44u2__p7_1,
  141824. 13,
  141825. 13
  141826. };
  141827. static static_codebook _44u2__p7_1 = {
  141828. 2, 169,
  141829. _vq_lengthlist__44u2__p7_1,
  141830. 1, -523010048, 1618608128, 4, 0,
  141831. _vq_quantlist__44u2__p7_1,
  141832. NULL,
  141833. &_vq_auxt__44u2__p7_1,
  141834. NULL,
  141835. 0
  141836. };
  141837. static long _vq_quantlist__44u2__p7_2[] = {
  141838. 6,
  141839. 5,
  141840. 7,
  141841. 4,
  141842. 8,
  141843. 3,
  141844. 9,
  141845. 2,
  141846. 10,
  141847. 1,
  141848. 11,
  141849. 0,
  141850. 12,
  141851. };
  141852. static long _vq_lengthlist__44u2__p7_2[] = {
  141853. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  141854. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  141855. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  141856. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  141857. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  141858. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  141859. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  141860. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141861. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  141862. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  141863. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141864. };
  141865. static float _vq_quantthresh__44u2__p7_2[] = {
  141866. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  141867. 2.5, 3.5, 4.5, 5.5,
  141868. };
  141869. static long _vq_quantmap__44u2__p7_2[] = {
  141870. 11, 9, 7, 5, 3, 1, 0, 2,
  141871. 4, 6, 8, 10, 12,
  141872. };
  141873. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  141874. _vq_quantthresh__44u2__p7_2,
  141875. _vq_quantmap__44u2__p7_2,
  141876. 13,
  141877. 13
  141878. };
  141879. static static_codebook _44u2__p7_2 = {
  141880. 2, 169,
  141881. _vq_lengthlist__44u2__p7_2,
  141882. 1, -531103744, 1611661312, 4, 0,
  141883. _vq_quantlist__44u2__p7_2,
  141884. NULL,
  141885. &_vq_auxt__44u2__p7_2,
  141886. NULL,
  141887. 0
  141888. };
  141889. static long _huff_lengthlist__44u2__short[] = {
  141890. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  141891. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  141892. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  141893. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  141894. };
  141895. static static_codebook _huff_book__44u2__short = {
  141896. 2, 64,
  141897. _huff_lengthlist__44u2__short,
  141898. 0, 0, 0, 0, 0,
  141899. NULL,
  141900. NULL,
  141901. NULL,
  141902. NULL,
  141903. 0
  141904. };
  141905. static long _huff_lengthlist__44u3__long[] = {
  141906. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  141907. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  141908. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  141909. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  141910. };
  141911. static static_codebook _huff_book__44u3__long = {
  141912. 2, 64,
  141913. _huff_lengthlist__44u3__long,
  141914. 0, 0, 0, 0, 0,
  141915. NULL,
  141916. NULL,
  141917. NULL,
  141918. NULL,
  141919. 0
  141920. };
  141921. static long _vq_quantlist__44u3__p1_0[] = {
  141922. 1,
  141923. 0,
  141924. 2,
  141925. };
  141926. static long _vq_lengthlist__44u3__p1_0[] = {
  141927. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  141928. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141929. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  141930. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  141931. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  141932. 13,
  141933. };
  141934. static float _vq_quantthresh__44u3__p1_0[] = {
  141935. -0.5, 0.5,
  141936. };
  141937. static long _vq_quantmap__44u3__p1_0[] = {
  141938. 1, 0, 2,
  141939. };
  141940. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  141941. _vq_quantthresh__44u3__p1_0,
  141942. _vq_quantmap__44u3__p1_0,
  141943. 3,
  141944. 3
  141945. };
  141946. static static_codebook _44u3__p1_0 = {
  141947. 4, 81,
  141948. _vq_lengthlist__44u3__p1_0,
  141949. 1, -535822336, 1611661312, 2, 0,
  141950. _vq_quantlist__44u3__p1_0,
  141951. NULL,
  141952. &_vq_auxt__44u3__p1_0,
  141953. NULL,
  141954. 0
  141955. };
  141956. static long _vq_quantlist__44u3__p2_0[] = {
  141957. 1,
  141958. 0,
  141959. 2,
  141960. };
  141961. static long _vq_lengthlist__44u3__p2_0[] = {
  141962. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  141963. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  141964. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141965. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  141966. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  141967. 9,
  141968. };
  141969. static float _vq_quantthresh__44u3__p2_0[] = {
  141970. -0.5, 0.5,
  141971. };
  141972. static long _vq_quantmap__44u3__p2_0[] = {
  141973. 1, 0, 2,
  141974. };
  141975. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  141976. _vq_quantthresh__44u3__p2_0,
  141977. _vq_quantmap__44u3__p2_0,
  141978. 3,
  141979. 3
  141980. };
  141981. static static_codebook _44u3__p2_0 = {
  141982. 4, 81,
  141983. _vq_lengthlist__44u3__p2_0,
  141984. 1, -535822336, 1611661312, 2, 0,
  141985. _vq_quantlist__44u3__p2_0,
  141986. NULL,
  141987. &_vq_auxt__44u3__p2_0,
  141988. NULL,
  141989. 0
  141990. };
  141991. static long _vq_quantlist__44u3__p3_0[] = {
  141992. 2,
  141993. 1,
  141994. 3,
  141995. 0,
  141996. 4,
  141997. };
  141998. static long _vq_lengthlist__44u3__p3_0[] = {
  141999. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  142000. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  142001. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  142002. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  142003. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  142004. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  142005. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  142006. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  142007. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  142008. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  142009. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  142010. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  142011. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  142012. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  142013. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  142014. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  142015. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  142016. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  142017. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  142018. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  142019. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  142020. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  142021. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  142022. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  142023. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  142024. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  142025. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  142026. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  142027. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  142028. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  142029. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  142030. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  142031. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  142032. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  142033. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  142034. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  142035. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  142036. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  142037. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  142038. 0,
  142039. };
  142040. static float _vq_quantthresh__44u3__p3_0[] = {
  142041. -1.5, -0.5, 0.5, 1.5,
  142042. };
  142043. static long _vq_quantmap__44u3__p3_0[] = {
  142044. 3, 1, 0, 2, 4,
  142045. };
  142046. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  142047. _vq_quantthresh__44u3__p3_0,
  142048. _vq_quantmap__44u3__p3_0,
  142049. 5,
  142050. 5
  142051. };
  142052. static static_codebook _44u3__p3_0 = {
  142053. 4, 625,
  142054. _vq_lengthlist__44u3__p3_0,
  142055. 1, -533725184, 1611661312, 3, 0,
  142056. _vq_quantlist__44u3__p3_0,
  142057. NULL,
  142058. &_vq_auxt__44u3__p3_0,
  142059. NULL,
  142060. 0
  142061. };
  142062. static long _vq_quantlist__44u3__p4_0[] = {
  142063. 2,
  142064. 1,
  142065. 3,
  142066. 0,
  142067. 4,
  142068. };
  142069. static long _vq_lengthlist__44u3__p4_0[] = {
  142070. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  142071. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  142072. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  142073. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  142074. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  142075. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  142076. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  142077. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  142078. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  142079. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  142080. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  142081. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142082. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  142083. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  142084. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  142085. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  142086. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  142087. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  142088. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  142089. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  142090. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  142091. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  142092. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  142093. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  142094. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  142095. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  142096. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  142097. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  142098. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  142099. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  142100. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  142101. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  142102. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  142103. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  142104. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  142105. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  142106. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  142107. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  142108. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  142109. 13,
  142110. };
  142111. static float _vq_quantthresh__44u3__p4_0[] = {
  142112. -1.5, -0.5, 0.5, 1.5,
  142113. };
  142114. static long _vq_quantmap__44u3__p4_0[] = {
  142115. 3, 1, 0, 2, 4,
  142116. };
  142117. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  142118. _vq_quantthresh__44u3__p4_0,
  142119. _vq_quantmap__44u3__p4_0,
  142120. 5,
  142121. 5
  142122. };
  142123. static static_codebook _44u3__p4_0 = {
  142124. 4, 625,
  142125. _vq_lengthlist__44u3__p4_0,
  142126. 1, -533725184, 1611661312, 3, 0,
  142127. _vq_quantlist__44u3__p4_0,
  142128. NULL,
  142129. &_vq_auxt__44u3__p4_0,
  142130. NULL,
  142131. 0
  142132. };
  142133. static long _vq_quantlist__44u3__p5_0[] = {
  142134. 4,
  142135. 3,
  142136. 5,
  142137. 2,
  142138. 6,
  142139. 1,
  142140. 7,
  142141. 0,
  142142. 8,
  142143. };
  142144. static long _vq_lengthlist__44u3__p5_0[] = {
  142145. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  142146. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  142147. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  142148. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142149. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  142150. 12,
  142151. };
  142152. static float _vq_quantthresh__44u3__p5_0[] = {
  142153. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142154. };
  142155. static long _vq_quantmap__44u3__p5_0[] = {
  142156. 7, 5, 3, 1, 0, 2, 4, 6,
  142157. 8,
  142158. };
  142159. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  142160. _vq_quantthresh__44u3__p5_0,
  142161. _vq_quantmap__44u3__p5_0,
  142162. 9,
  142163. 9
  142164. };
  142165. static static_codebook _44u3__p5_0 = {
  142166. 2, 81,
  142167. _vq_lengthlist__44u3__p5_0,
  142168. 1, -531628032, 1611661312, 4, 0,
  142169. _vq_quantlist__44u3__p5_0,
  142170. NULL,
  142171. &_vq_auxt__44u3__p5_0,
  142172. NULL,
  142173. 0
  142174. };
  142175. static long _vq_quantlist__44u3__p6_0[] = {
  142176. 6,
  142177. 5,
  142178. 7,
  142179. 4,
  142180. 8,
  142181. 3,
  142182. 9,
  142183. 2,
  142184. 10,
  142185. 1,
  142186. 11,
  142187. 0,
  142188. 12,
  142189. };
  142190. static long _vq_lengthlist__44u3__p6_0[] = {
  142191. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  142192. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  142193. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142194. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  142195. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  142196. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  142197. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  142198. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  142199. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  142200. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  142201. 15,16,16,16,17,18,16,20,18,
  142202. };
  142203. static float _vq_quantthresh__44u3__p6_0[] = {
  142204. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142205. 12.5, 17.5, 22.5, 27.5,
  142206. };
  142207. static long _vq_quantmap__44u3__p6_0[] = {
  142208. 11, 9, 7, 5, 3, 1, 0, 2,
  142209. 4, 6, 8, 10, 12,
  142210. };
  142211. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  142212. _vq_quantthresh__44u3__p6_0,
  142213. _vq_quantmap__44u3__p6_0,
  142214. 13,
  142215. 13
  142216. };
  142217. static static_codebook _44u3__p6_0 = {
  142218. 2, 169,
  142219. _vq_lengthlist__44u3__p6_0,
  142220. 1, -526516224, 1616117760, 4, 0,
  142221. _vq_quantlist__44u3__p6_0,
  142222. NULL,
  142223. &_vq_auxt__44u3__p6_0,
  142224. NULL,
  142225. 0
  142226. };
  142227. static long _vq_quantlist__44u3__p6_1[] = {
  142228. 2,
  142229. 1,
  142230. 3,
  142231. 0,
  142232. 4,
  142233. };
  142234. static long _vq_lengthlist__44u3__p6_1[] = {
  142235. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  142236. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  142237. };
  142238. static float _vq_quantthresh__44u3__p6_1[] = {
  142239. -1.5, -0.5, 0.5, 1.5,
  142240. };
  142241. static long _vq_quantmap__44u3__p6_1[] = {
  142242. 3, 1, 0, 2, 4,
  142243. };
  142244. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  142245. _vq_quantthresh__44u3__p6_1,
  142246. _vq_quantmap__44u3__p6_1,
  142247. 5,
  142248. 5
  142249. };
  142250. static static_codebook _44u3__p6_1 = {
  142251. 2, 25,
  142252. _vq_lengthlist__44u3__p6_1,
  142253. 1, -533725184, 1611661312, 3, 0,
  142254. _vq_quantlist__44u3__p6_1,
  142255. NULL,
  142256. &_vq_auxt__44u3__p6_1,
  142257. NULL,
  142258. 0
  142259. };
  142260. static long _vq_quantlist__44u3__p7_0[] = {
  142261. 4,
  142262. 3,
  142263. 5,
  142264. 2,
  142265. 6,
  142266. 1,
  142267. 7,
  142268. 0,
  142269. 8,
  142270. };
  142271. static long _vq_lengthlist__44u3__p7_0[] = {
  142272. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  142273. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  142274. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142275. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142276. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142277. 9,
  142278. };
  142279. static float _vq_quantthresh__44u3__p7_0[] = {
  142280. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  142281. };
  142282. static long _vq_quantmap__44u3__p7_0[] = {
  142283. 7, 5, 3, 1, 0, 2, 4, 6,
  142284. 8,
  142285. };
  142286. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  142287. _vq_quantthresh__44u3__p7_0,
  142288. _vq_quantmap__44u3__p7_0,
  142289. 9,
  142290. 9
  142291. };
  142292. static static_codebook _44u3__p7_0 = {
  142293. 2, 81,
  142294. _vq_lengthlist__44u3__p7_0,
  142295. 1, -515907584, 1627381760, 4, 0,
  142296. _vq_quantlist__44u3__p7_0,
  142297. NULL,
  142298. &_vq_auxt__44u3__p7_0,
  142299. NULL,
  142300. 0
  142301. };
  142302. static long _vq_quantlist__44u3__p7_1[] = {
  142303. 7,
  142304. 6,
  142305. 8,
  142306. 5,
  142307. 9,
  142308. 4,
  142309. 10,
  142310. 3,
  142311. 11,
  142312. 2,
  142313. 12,
  142314. 1,
  142315. 13,
  142316. 0,
  142317. 14,
  142318. };
  142319. static long _vq_lengthlist__44u3__p7_1[] = {
  142320. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  142321. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  142322. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  142323. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  142324. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  142325. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  142326. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  142327. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  142328. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  142329. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  142330. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  142331. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  142332. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  142333. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  142334. 17,
  142335. };
  142336. static float _vq_quantthresh__44u3__p7_1[] = {
  142337. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  142338. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  142339. };
  142340. static long _vq_quantmap__44u3__p7_1[] = {
  142341. 13, 11, 9, 7, 5, 3, 1, 0,
  142342. 2, 4, 6, 8, 10, 12, 14,
  142343. };
  142344. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  142345. _vq_quantthresh__44u3__p7_1,
  142346. _vq_quantmap__44u3__p7_1,
  142347. 15,
  142348. 15
  142349. };
  142350. static static_codebook _44u3__p7_1 = {
  142351. 2, 225,
  142352. _vq_lengthlist__44u3__p7_1,
  142353. 1, -522338304, 1620115456, 4, 0,
  142354. _vq_quantlist__44u3__p7_1,
  142355. NULL,
  142356. &_vq_auxt__44u3__p7_1,
  142357. NULL,
  142358. 0
  142359. };
  142360. static long _vq_quantlist__44u3__p7_2[] = {
  142361. 8,
  142362. 7,
  142363. 9,
  142364. 6,
  142365. 10,
  142366. 5,
  142367. 11,
  142368. 4,
  142369. 12,
  142370. 3,
  142371. 13,
  142372. 2,
  142373. 14,
  142374. 1,
  142375. 15,
  142376. 0,
  142377. 16,
  142378. };
  142379. static long _vq_lengthlist__44u3__p7_2[] = {
  142380. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142381. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142382. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  142383. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142384. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  142385. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142386. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  142387. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142388. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  142389. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  142390. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  142391. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  142392. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  142393. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  142394. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  142395. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  142396. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142397. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  142398. 11,
  142399. };
  142400. static float _vq_quantthresh__44u3__p7_2[] = {
  142401. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142402. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142403. };
  142404. static long _vq_quantmap__44u3__p7_2[] = {
  142405. 15, 13, 11, 9, 7, 5, 3, 1,
  142406. 0, 2, 4, 6, 8, 10, 12, 14,
  142407. 16,
  142408. };
  142409. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  142410. _vq_quantthresh__44u3__p7_2,
  142411. _vq_quantmap__44u3__p7_2,
  142412. 17,
  142413. 17
  142414. };
  142415. static static_codebook _44u3__p7_2 = {
  142416. 2, 289,
  142417. _vq_lengthlist__44u3__p7_2,
  142418. 1, -529530880, 1611661312, 5, 0,
  142419. _vq_quantlist__44u3__p7_2,
  142420. NULL,
  142421. &_vq_auxt__44u3__p7_2,
  142422. NULL,
  142423. 0
  142424. };
  142425. static long _huff_lengthlist__44u3__short[] = {
  142426. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  142427. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  142428. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  142429. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  142430. };
  142431. static static_codebook _huff_book__44u3__short = {
  142432. 2, 64,
  142433. _huff_lengthlist__44u3__short,
  142434. 0, 0, 0, 0, 0,
  142435. NULL,
  142436. NULL,
  142437. NULL,
  142438. NULL,
  142439. 0
  142440. };
  142441. static long _huff_lengthlist__44u4__long[] = {
  142442. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  142443. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  142444. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  142445. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  142446. };
  142447. static static_codebook _huff_book__44u4__long = {
  142448. 2, 64,
  142449. _huff_lengthlist__44u4__long,
  142450. 0, 0, 0, 0, 0,
  142451. NULL,
  142452. NULL,
  142453. NULL,
  142454. NULL,
  142455. 0
  142456. };
  142457. static long _vq_quantlist__44u4__p1_0[] = {
  142458. 1,
  142459. 0,
  142460. 2,
  142461. };
  142462. static long _vq_lengthlist__44u4__p1_0[] = {
  142463. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  142464. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  142465. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  142466. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  142467. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  142468. 13,
  142469. };
  142470. static float _vq_quantthresh__44u4__p1_0[] = {
  142471. -0.5, 0.5,
  142472. };
  142473. static long _vq_quantmap__44u4__p1_0[] = {
  142474. 1, 0, 2,
  142475. };
  142476. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  142477. _vq_quantthresh__44u4__p1_0,
  142478. _vq_quantmap__44u4__p1_0,
  142479. 3,
  142480. 3
  142481. };
  142482. static static_codebook _44u4__p1_0 = {
  142483. 4, 81,
  142484. _vq_lengthlist__44u4__p1_0,
  142485. 1, -535822336, 1611661312, 2, 0,
  142486. _vq_quantlist__44u4__p1_0,
  142487. NULL,
  142488. &_vq_auxt__44u4__p1_0,
  142489. NULL,
  142490. 0
  142491. };
  142492. static long _vq_quantlist__44u4__p2_0[] = {
  142493. 1,
  142494. 0,
  142495. 2,
  142496. };
  142497. static long _vq_lengthlist__44u4__p2_0[] = {
  142498. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  142499. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  142500. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  142501. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  142502. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  142503. 9,
  142504. };
  142505. static float _vq_quantthresh__44u4__p2_0[] = {
  142506. -0.5, 0.5,
  142507. };
  142508. static long _vq_quantmap__44u4__p2_0[] = {
  142509. 1, 0, 2,
  142510. };
  142511. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  142512. _vq_quantthresh__44u4__p2_0,
  142513. _vq_quantmap__44u4__p2_0,
  142514. 3,
  142515. 3
  142516. };
  142517. static static_codebook _44u4__p2_0 = {
  142518. 4, 81,
  142519. _vq_lengthlist__44u4__p2_0,
  142520. 1, -535822336, 1611661312, 2, 0,
  142521. _vq_quantlist__44u4__p2_0,
  142522. NULL,
  142523. &_vq_auxt__44u4__p2_0,
  142524. NULL,
  142525. 0
  142526. };
  142527. static long _vq_quantlist__44u4__p3_0[] = {
  142528. 2,
  142529. 1,
  142530. 3,
  142531. 0,
  142532. 4,
  142533. };
  142534. static long _vq_lengthlist__44u4__p3_0[] = {
  142535. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  142536. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  142537. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  142538. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  142539. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  142540. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  142541. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  142542. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  142543. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  142544. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  142545. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  142546. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  142547. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  142548. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  142549. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  142550. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  142551. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  142552. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  142553. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  142554. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  142555. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  142556. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  142557. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  142558. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  142559. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  142560. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  142561. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  142562. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  142563. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  142564. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  142565. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  142566. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  142567. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  142568. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  142569. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  142570. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  142571. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  142572. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  142573. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  142574. 0,
  142575. };
  142576. static float _vq_quantthresh__44u4__p3_0[] = {
  142577. -1.5, -0.5, 0.5, 1.5,
  142578. };
  142579. static long _vq_quantmap__44u4__p3_0[] = {
  142580. 3, 1, 0, 2, 4,
  142581. };
  142582. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  142583. _vq_quantthresh__44u4__p3_0,
  142584. _vq_quantmap__44u4__p3_0,
  142585. 5,
  142586. 5
  142587. };
  142588. static static_codebook _44u4__p3_0 = {
  142589. 4, 625,
  142590. _vq_lengthlist__44u4__p3_0,
  142591. 1, -533725184, 1611661312, 3, 0,
  142592. _vq_quantlist__44u4__p3_0,
  142593. NULL,
  142594. &_vq_auxt__44u4__p3_0,
  142595. NULL,
  142596. 0
  142597. };
  142598. static long _vq_quantlist__44u4__p4_0[] = {
  142599. 2,
  142600. 1,
  142601. 3,
  142602. 0,
  142603. 4,
  142604. };
  142605. static long _vq_lengthlist__44u4__p4_0[] = {
  142606. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  142607. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  142608. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  142609. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  142610. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  142611. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  142612. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  142613. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  142614. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  142615. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  142616. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  142617. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142618. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  142619. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  142620. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  142621. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  142622. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  142623. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  142624. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  142625. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  142626. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  142627. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  142628. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  142629. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  142630. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  142631. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  142632. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  142633. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  142634. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  142635. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  142636. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  142637. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  142638. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  142639. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  142640. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  142641. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  142642. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  142643. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  142644. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  142645. 13,
  142646. };
  142647. static float _vq_quantthresh__44u4__p4_0[] = {
  142648. -1.5, -0.5, 0.5, 1.5,
  142649. };
  142650. static long _vq_quantmap__44u4__p4_0[] = {
  142651. 3, 1, 0, 2, 4,
  142652. };
  142653. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  142654. _vq_quantthresh__44u4__p4_0,
  142655. _vq_quantmap__44u4__p4_0,
  142656. 5,
  142657. 5
  142658. };
  142659. static static_codebook _44u4__p4_0 = {
  142660. 4, 625,
  142661. _vq_lengthlist__44u4__p4_0,
  142662. 1, -533725184, 1611661312, 3, 0,
  142663. _vq_quantlist__44u4__p4_0,
  142664. NULL,
  142665. &_vq_auxt__44u4__p4_0,
  142666. NULL,
  142667. 0
  142668. };
  142669. static long _vq_quantlist__44u4__p5_0[] = {
  142670. 4,
  142671. 3,
  142672. 5,
  142673. 2,
  142674. 6,
  142675. 1,
  142676. 7,
  142677. 0,
  142678. 8,
  142679. };
  142680. static long _vq_lengthlist__44u4__p5_0[] = {
  142681. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  142682. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  142683. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  142684. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142685. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  142686. 12,
  142687. };
  142688. static float _vq_quantthresh__44u4__p5_0[] = {
  142689. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142690. };
  142691. static long _vq_quantmap__44u4__p5_0[] = {
  142692. 7, 5, 3, 1, 0, 2, 4, 6,
  142693. 8,
  142694. };
  142695. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  142696. _vq_quantthresh__44u4__p5_0,
  142697. _vq_quantmap__44u4__p5_0,
  142698. 9,
  142699. 9
  142700. };
  142701. static static_codebook _44u4__p5_0 = {
  142702. 2, 81,
  142703. _vq_lengthlist__44u4__p5_0,
  142704. 1, -531628032, 1611661312, 4, 0,
  142705. _vq_quantlist__44u4__p5_0,
  142706. NULL,
  142707. &_vq_auxt__44u4__p5_0,
  142708. NULL,
  142709. 0
  142710. };
  142711. static long _vq_quantlist__44u4__p6_0[] = {
  142712. 6,
  142713. 5,
  142714. 7,
  142715. 4,
  142716. 8,
  142717. 3,
  142718. 9,
  142719. 2,
  142720. 10,
  142721. 1,
  142722. 11,
  142723. 0,
  142724. 12,
  142725. };
  142726. static long _vq_lengthlist__44u4__p6_0[] = {
  142727. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  142728. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  142729. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142730. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  142731. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  142732. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  142733. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  142734. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  142735. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  142736. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  142737. 16,16,16,17,17,18,17,20,21,
  142738. };
  142739. static float _vq_quantthresh__44u4__p6_0[] = {
  142740. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142741. 12.5, 17.5, 22.5, 27.5,
  142742. };
  142743. static long _vq_quantmap__44u4__p6_0[] = {
  142744. 11, 9, 7, 5, 3, 1, 0, 2,
  142745. 4, 6, 8, 10, 12,
  142746. };
  142747. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  142748. _vq_quantthresh__44u4__p6_0,
  142749. _vq_quantmap__44u4__p6_0,
  142750. 13,
  142751. 13
  142752. };
  142753. static static_codebook _44u4__p6_0 = {
  142754. 2, 169,
  142755. _vq_lengthlist__44u4__p6_0,
  142756. 1, -526516224, 1616117760, 4, 0,
  142757. _vq_quantlist__44u4__p6_0,
  142758. NULL,
  142759. &_vq_auxt__44u4__p6_0,
  142760. NULL,
  142761. 0
  142762. };
  142763. static long _vq_quantlist__44u4__p6_1[] = {
  142764. 2,
  142765. 1,
  142766. 3,
  142767. 0,
  142768. 4,
  142769. };
  142770. static long _vq_lengthlist__44u4__p6_1[] = {
  142771. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  142772. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  142773. };
  142774. static float _vq_quantthresh__44u4__p6_1[] = {
  142775. -1.5, -0.5, 0.5, 1.5,
  142776. };
  142777. static long _vq_quantmap__44u4__p6_1[] = {
  142778. 3, 1, 0, 2, 4,
  142779. };
  142780. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  142781. _vq_quantthresh__44u4__p6_1,
  142782. _vq_quantmap__44u4__p6_1,
  142783. 5,
  142784. 5
  142785. };
  142786. static static_codebook _44u4__p6_1 = {
  142787. 2, 25,
  142788. _vq_lengthlist__44u4__p6_1,
  142789. 1, -533725184, 1611661312, 3, 0,
  142790. _vq_quantlist__44u4__p6_1,
  142791. NULL,
  142792. &_vq_auxt__44u4__p6_1,
  142793. NULL,
  142794. 0
  142795. };
  142796. static long _vq_quantlist__44u4__p7_0[] = {
  142797. 6,
  142798. 5,
  142799. 7,
  142800. 4,
  142801. 8,
  142802. 3,
  142803. 9,
  142804. 2,
  142805. 10,
  142806. 1,
  142807. 11,
  142808. 0,
  142809. 12,
  142810. };
  142811. static long _vq_lengthlist__44u4__p7_0[] = {
  142812. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  142813. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  142814. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142815. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142816. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142817. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142818. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142819. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142820. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142821. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142822. 11,11,11,11,11,11,11,11,11,
  142823. };
  142824. static float _vq_quantthresh__44u4__p7_0[] = {
  142825. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  142826. 637.5, 892.5, 1147.5, 1402.5,
  142827. };
  142828. static long _vq_quantmap__44u4__p7_0[] = {
  142829. 11, 9, 7, 5, 3, 1, 0, 2,
  142830. 4, 6, 8, 10, 12,
  142831. };
  142832. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  142833. _vq_quantthresh__44u4__p7_0,
  142834. _vq_quantmap__44u4__p7_0,
  142835. 13,
  142836. 13
  142837. };
  142838. static static_codebook _44u4__p7_0 = {
  142839. 2, 169,
  142840. _vq_lengthlist__44u4__p7_0,
  142841. 1, -514332672, 1627381760, 4, 0,
  142842. _vq_quantlist__44u4__p7_0,
  142843. NULL,
  142844. &_vq_auxt__44u4__p7_0,
  142845. NULL,
  142846. 0
  142847. };
  142848. static long _vq_quantlist__44u4__p7_1[] = {
  142849. 7,
  142850. 6,
  142851. 8,
  142852. 5,
  142853. 9,
  142854. 4,
  142855. 10,
  142856. 3,
  142857. 11,
  142858. 2,
  142859. 12,
  142860. 1,
  142861. 13,
  142862. 0,
  142863. 14,
  142864. };
  142865. static long _vq_lengthlist__44u4__p7_1[] = {
  142866. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  142867. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  142868. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  142869. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  142870. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  142871. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  142872. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  142873. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  142874. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  142875. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  142876. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  142877. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  142878. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  142879. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  142880. 16,
  142881. };
  142882. static float _vq_quantthresh__44u4__p7_1[] = {
  142883. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  142884. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  142885. };
  142886. static long _vq_quantmap__44u4__p7_1[] = {
  142887. 13, 11, 9, 7, 5, 3, 1, 0,
  142888. 2, 4, 6, 8, 10, 12, 14,
  142889. };
  142890. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  142891. _vq_quantthresh__44u4__p7_1,
  142892. _vq_quantmap__44u4__p7_1,
  142893. 15,
  142894. 15
  142895. };
  142896. static static_codebook _44u4__p7_1 = {
  142897. 2, 225,
  142898. _vq_lengthlist__44u4__p7_1,
  142899. 1, -522338304, 1620115456, 4, 0,
  142900. _vq_quantlist__44u4__p7_1,
  142901. NULL,
  142902. &_vq_auxt__44u4__p7_1,
  142903. NULL,
  142904. 0
  142905. };
  142906. static long _vq_quantlist__44u4__p7_2[] = {
  142907. 8,
  142908. 7,
  142909. 9,
  142910. 6,
  142911. 10,
  142912. 5,
  142913. 11,
  142914. 4,
  142915. 12,
  142916. 3,
  142917. 13,
  142918. 2,
  142919. 14,
  142920. 1,
  142921. 15,
  142922. 0,
  142923. 16,
  142924. };
  142925. static long _vq_lengthlist__44u4__p7_2[] = {
  142926. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142927. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142928. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142929. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142930. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  142931. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142932. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142933. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  142934. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  142935. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  142936. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  142937. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  142938. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  142939. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  142940. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  142941. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  142942. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142943. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  142944. 10,
  142945. };
  142946. static float _vq_quantthresh__44u4__p7_2[] = {
  142947. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142948. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142949. };
  142950. static long _vq_quantmap__44u4__p7_2[] = {
  142951. 15, 13, 11, 9, 7, 5, 3, 1,
  142952. 0, 2, 4, 6, 8, 10, 12, 14,
  142953. 16,
  142954. };
  142955. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  142956. _vq_quantthresh__44u4__p7_2,
  142957. _vq_quantmap__44u4__p7_2,
  142958. 17,
  142959. 17
  142960. };
  142961. static static_codebook _44u4__p7_2 = {
  142962. 2, 289,
  142963. _vq_lengthlist__44u4__p7_2,
  142964. 1, -529530880, 1611661312, 5, 0,
  142965. _vq_quantlist__44u4__p7_2,
  142966. NULL,
  142967. &_vq_auxt__44u4__p7_2,
  142968. NULL,
  142969. 0
  142970. };
  142971. static long _huff_lengthlist__44u4__short[] = {
  142972. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  142973. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  142974. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  142975. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  142976. };
  142977. static static_codebook _huff_book__44u4__short = {
  142978. 2, 64,
  142979. _huff_lengthlist__44u4__short,
  142980. 0, 0, 0, 0, 0,
  142981. NULL,
  142982. NULL,
  142983. NULL,
  142984. NULL,
  142985. 0
  142986. };
  142987. static long _huff_lengthlist__44u5__long[] = {
  142988. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  142989. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  142990. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  142991. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  142992. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  142993. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  142994. 14, 8, 7, 8,
  142995. };
  142996. static static_codebook _huff_book__44u5__long = {
  142997. 2, 100,
  142998. _huff_lengthlist__44u5__long,
  142999. 0, 0, 0, 0, 0,
  143000. NULL,
  143001. NULL,
  143002. NULL,
  143003. NULL,
  143004. 0
  143005. };
  143006. static long _vq_quantlist__44u5__p1_0[] = {
  143007. 1,
  143008. 0,
  143009. 2,
  143010. };
  143011. static long _vq_lengthlist__44u5__p1_0[] = {
  143012. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  143013. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  143014. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  143015. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  143016. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  143017. 12,
  143018. };
  143019. static float _vq_quantthresh__44u5__p1_0[] = {
  143020. -0.5, 0.5,
  143021. };
  143022. static long _vq_quantmap__44u5__p1_0[] = {
  143023. 1, 0, 2,
  143024. };
  143025. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  143026. _vq_quantthresh__44u5__p1_0,
  143027. _vq_quantmap__44u5__p1_0,
  143028. 3,
  143029. 3
  143030. };
  143031. static static_codebook _44u5__p1_0 = {
  143032. 4, 81,
  143033. _vq_lengthlist__44u5__p1_0,
  143034. 1, -535822336, 1611661312, 2, 0,
  143035. _vq_quantlist__44u5__p1_0,
  143036. NULL,
  143037. &_vq_auxt__44u5__p1_0,
  143038. NULL,
  143039. 0
  143040. };
  143041. static long _vq_quantlist__44u5__p2_0[] = {
  143042. 1,
  143043. 0,
  143044. 2,
  143045. };
  143046. static long _vq_lengthlist__44u5__p2_0[] = {
  143047. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  143048. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  143049. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  143050. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  143051. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  143052. 9,
  143053. };
  143054. static float _vq_quantthresh__44u5__p2_0[] = {
  143055. -0.5, 0.5,
  143056. };
  143057. static long _vq_quantmap__44u5__p2_0[] = {
  143058. 1, 0, 2,
  143059. };
  143060. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  143061. _vq_quantthresh__44u5__p2_0,
  143062. _vq_quantmap__44u5__p2_0,
  143063. 3,
  143064. 3
  143065. };
  143066. static static_codebook _44u5__p2_0 = {
  143067. 4, 81,
  143068. _vq_lengthlist__44u5__p2_0,
  143069. 1, -535822336, 1611661312, 2, 0,
  143070. _vq_quantlist__44u5__p2_0,
  143071. NULL,
  143072. &_vq_auxt__44u5__p2_0,
  143073. NULL,
  143074. 0
  143075. };
  143076. static long _vq_quantlist__44u5__p3_0[] = {
  143077. 2,
  143078. 1,
  143079. 3,
  143080. 0,
  143081. 4,
  143082. };
  143083. static long _vq_lengthlist__44u5__p3_0[] = {
  143084. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  143085. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  143086. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  143087. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  143088. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  143089. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  143090. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  143091. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  143092. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  143093. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  143094. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  143095. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  143096. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  143097. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  143098. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  143099. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  143100. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  143101. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  143102. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  143103. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  143104. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  143105. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  143106. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  143107. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  143108. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  143109. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  143110. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  143111. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  143112. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  143113. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  143114. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  143115. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  143116. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  143117. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  143118. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  143119. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  143120. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  143121. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  143122. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  143123. 0,
  143124. };
  143125. static float _vq_quantthresh__44u5__p3_0[] = {
  143126. -1.5, -0.5, 0.5, 1.5,
  143127. };
  143128. static long _vq_quantmap__44u5__p3_0[] = {
  143129. 3, 1, 0, 2, 4,
  143130. };
  143131. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  143132. _vq_quantthresh__44u5__p3_0,
  143133. _vq_quantmap__44u5__p3_0,
  143134. 5,
  143135. 5
  143136. };
  143137. static static_codebook _44u5__p3_0 = {
  143138. 4, 625,
  143139. _vq_lengthlist__44u5__p3_0,
  143140. 1, -533725184, 1611661312, 3, 0,
  143141. _vq_quantlist__44u5__p3_0,
  143142. NULL,
  143143. &_vq_auxt__44u5__p3_0,
  143144. NULL,
  143145. 0
  143146. };
  143147. static long _vq_quantlist__44u5__p4_0[] = {
  143148. 2,
  143149. 1,
  143150. 3,
  143151. 0,
  143152. 4,
  143153. };
  143154. static long _vq_lengthlist__44u5__p4_0[] = {
  143155. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  143156. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  143157. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  143158. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  143159. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  143160. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  143161. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  143162. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  143163. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  143164. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  143165. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  143166. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143167. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  143168. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  143169. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  143170. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  143171. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  143172. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143173. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  143174. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  143175. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  143176. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  143177. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  143178. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  143179. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  143180. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  143181. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  143182. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  143183. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  143184. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  143185. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  143186. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  143187. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  143188. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  143189. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  143190. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  143191. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  143192. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  143193. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  143194. 12,
  143195. };
  143196. static float _vq_quantthresh__44u5__p4_0[] = {
  143197. -1.5, -0.5, 0.5, 1.5,
  143198. };
  143199. static long _vq_quantmap__44u5__p4_0[] = {
  143200. 3, 1, 0, 2, 4,
  143201. };
  143202. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  143203. _vq_quantthresh__44u5__p4_0,
  143204. _vq_quantmap__44u5__p4_0,
  143205. 5,
  143206. 5
  143207. };
  143208. static static_codebook _44u5__p4_0 = {
  143209. 4, 625,
  143210. _vq_lengthlist__44u5__p4_0,
  143211. 1, -533725184, 1611661312, 3, 0,
  143212. _vq_quantlist__44u5__p4_0,
  143213. NULL,
  143214. &_vq_auxt__44u5__p4_0,
  143215. NULL,
  143216. 0
  143217. };
  143218. static long _vq_quantlist__44u5__p5_0[] = {
  143219. 4,
  143220. 3,
  143221. 5,
  143222. 2,
  143223. 6,
  143224. 1,
  143225. 7,
  143226. 0,
  143227. 8,
  143228. };
  143229. static long _vq_lengthlist__44u5__p5_0[] = {
  143230. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  143231. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  143232. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  143233. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  143234. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  143235. 14,
  143236. };
  143237. static float _vq_quantthresh__44u5__p5_0[] = {
  143238. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143239. };
  143240. static long _vq_quantmap__44u5__p5_0[] = {
  143241. 7, 5, 3, 1, 0, 2, 4, 6,
  143242. 8,
  143243. };
  143244. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  143245. _vq_quantthresh__44u5__p5_0,
  143246. _vq_quantmap__44u5__p5_0,
  143247. 9,
  143248. 9
  143249. };
  143250. static static_codebook _44u5__p5_0 = {
  143251. 2, 81,
  143252. _vq_lengthlist__44u5__p5_0,
  143253. 1, -531628032, 1611661312, 4, 0,
  143254. _vq_quantlist__44u5__p5_0,
  143255. NULL,
  143256. &_vq_auxt__44u5__p5_0,
  143257. NULL,
  143258. 0
  143259. };
  143260. static long _vq_quantlist__44u5__p6_0[] = {
  143261. 4,
  143262. 3,
  143263. 5,
  143264. 2,
  143265. 6,
  143266. 1,
  143267. 7,
  143268. 0,
  143269. 8,
  143270. };
  143271. static long _vq_lengthlist__44u5__p6_0[] = {
  143272. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  143273. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  143274. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  143275. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  143276. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  143277. 11,
  143278. };
  143279. static float _vq_quantthresh__44u5__p6_0[] = {
  143280. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143281. };
  143282. static long _vq_quantmap__44u5__p6_0[] = {
  143283. 7, 5, 3, 1, 0, 2, 4, 6,
  143284. 8,
  143285. };
  143286. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  143287. _vq_quantthresh__44u5__p6_0,
  143288. _vq_quantmap__44u5__p6_0,
  143289. 9,
  143290. 9
  143291. };
  143292. static static_codebook _44u5__p6_0 = {
  143293. 2, 81,
  143294. _vq_lengthlist__44u5__p6_0,
  143295. 1, -531628032, 1611661312, 4, 0,
  143296. _vq_quantlist__44u5__p6_0,
  143297. NULL,
  143298. &_vq_auxt__44u5__p6_0,
  143299. NULL,
  143300. 0
  143301. };
  143302. static long _vq_quantlist__44u5__p7_0[] = {
  143303. 1,
  143304. 0,
  143305. 2,
  143306. };
  143307. static long _vq_lengthlist__44u5__p7_0[] = {
  143308. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  143309. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  143310. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  143311. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  143312. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  143313. 12,
  143314. };
  143315. static float _vq_quantthresh__44u5__p7_0[] = {
  143316. -5.5, 5.5,
  143317. };
  143318. static long _vq_quantmap__44u5__p7_0[] = {
  143319. 1, 0, 2,
  143320. };
  143321. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  143322. _vq_quantthresh__44u5__p7_0,
  143323. _vq_quantmap__44u5__p7_0,
  143324. 3,
  143325. 3
  143326. };
  143327. static static_codebook _44u5__p7_0 = {
  143328. 4, 81,
  143329. _vq_lengthlist__44u5__p7_0,
  143330. 1, -529137664, 1618345984, 2, 0,
  143331. _vq_quantlist__44u5__p7_0,
  143332. NULL,
  143333. &_vq_auxt__44u5__p7_0,
  143334. NULL,
  143335. 0
  143336. };
  143337. static long _vq_quantlist__44u5__p7_1[] = {
  143338. 5,
  143339. 4,
  143340. 6,
  143341. 3,
  143342. 7,
  143343. 2,
  143344. 8,
  143345. 1,
  143346. 9,
  143347. 0,
  143348. 10,
  143349. };
  143350. static long _vq_lengthlist__44u5__p7_1[] = {
  143351. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  143352. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  143353. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143354. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  143355. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  143356. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  143357. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  143358. 9, 9, 9, 9, 9,10,10,10,10,
  143359. };
  143360. static float _vq_quantthresh__44u5__p7_1[] = {
  143361. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143362. 3.5, 4.5,
  143363. };
  143364. static long _vq_quantmap__44u5__p7_1[] = {
  143365. 9, 7, 5, 3, 1, 0, 2, 4,
  143366. 6, 8, 10,
  143367. };
  143368. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  143369. _vq_quantthresh__44u5__p7_1,
  143370. _vq_quantmap__44u5__p7_1,
  143371. 11,
  143372. 11
  143373. };
  143374. static static_codebook _44u5__p7_1 = {
  143375. 2, 121,
  143376. _vq_lengthlist__44u5__p7_1,
  143377. 1, -531365888, 1611661312, 4, 0,
  143378. _vq_quantlist__44u5__p7_1,
  143379. NULL,
  143380. &_vq_auxt__44u5__p7_1,
  143381. NULL,
  143382. 0
  143383. };
  143384. static long _vq_quantlist__44u5__p8_0[] = {
  143385. 5,
  143386. 4,
  143387. 6,
  143388. 3,
  143389. 7,
  143390. 2,
  143391. 8,
  143392. 1,
  143393. 9,
  143394. 0,
  143395. 10,
  143396. };
  143397. static long _vq_lengthlist__44u5__p8_0[] = {
  143398. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  143399. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  143400. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  143401. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  143402. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  143403. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  143404. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  143405. 12,13,13,14,14,14,14,15,15,
  143406. };
  143407. static float _vq_quantthresh__44u5__p8_0[] = {
  143408. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143409. 38.5, 49.5,
  143410. };
  143411. static long _vq_quantmap__44u5__p8_0[] = {
  143412. 9, 7, 5, 3, 1, 0, 2, 4,
  143413. 6, 8, 10,
  143414. };
  143415. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  143416. _vq_quantthresh__44u5__p8_0,
  143417. _vq_quantmap__44u5__p8_0,
  143418. 11,
  143419. 11
  143420. };
  143421. static static_codebook _44u5__p8_0 = {
  143422. 2, 121,
  143423. _vq_lengthlist__44u5__p8_0,
  143424. 1, -524582912, 1618345984, 4, 0,
  143425. _vq_quantlist__44u5__p8_0,
  143426. NULL,
  143427. &_vq_auxt__44u5__p8_0,
  143428. NULL,
  143429. 0
  143430. };
  143431. static long _vq_quantlist__44u5__p8_1[] = {
  143432. 5,
  143433. 4,
  143434. 6,
  143435. 3,
  143436. 7,
  143437. 2,
  143438. 8,
  143439. 1,
  143440. 9,
  143441. 0,
  143442. 10,
  143443. };
  143444. static long _vq_lengthlist__44u5__p8_1[] = {
  143445. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  143446. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  143447. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  143448. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  143449. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  143450. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  143451. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143452. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143453. };
  143454. static float _vq_quantthresh__44u5__p8_1[] = {
  143455. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143456. 3.5, 4.5,
  143457. };
  143458. static long _vq_quantmap__44u5__p8_1[] = {
  143459. 9, 7, 5, 3, 1, 0, 2, 4,
  143460. 6, 8, 10,
  143461. };
  143462. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  143463. _vq_quantthresh__44u5__p8_1,
  143464. _vq_quantmap__44u5__p8_1,
  143465. 11,
  143466. 11
  143467. };
  143468. static static_codebook _44u5__p8_1 = {
  143469. 2, 121,
  143470. _vq_lengthlist__44u5__p8_1,
  143471. 1, -531365888, 1611661312, 4, 0,
  143472. _vq_quantlist__44u5__p8_1,
  143473. NULL,
  143474. &_vq_auxt__44u5__p8_1,
  143475. NULL,
  143476. 0
  143477. };
  143478. static long _vq_quantlist__44u5__p9_0[] = {
  143479. 6,
  143480. 5,
  143481. 7,
  143482. 4,
  143483. 8,
  143484. 3,
  143485. 9,
  143486. 2,
  143487. 10,
  143488. 1,
  143489. 11,
  143490. 0,
  143491. 12,
  143492. };
  143493. static long _vq_lengthlist__44u5__p9_0[] = {
  143494. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  143495. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  143496. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  143497. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  143498. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  143499. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  143500. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  143501. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  143502. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  143503. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143504. 12,12,12,12,12,12,12,12,12,
  143505. };
  143506. static float _vq_quantthresh__44u5__p9_0[] = {
  143507. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  143508. 637.5, 892.5, 1147.5, 1402.5,
  143509. };
  143510. static long _vq_quantmap__44u5__p9_0[] = {
  143511. 11, 9, 7, 5, 3, 1, 0, 2,
  143512. 4, 6, 8, 10, 12,
  143513. };
  143514. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  143515. _vq_quantthresh__44u5__p9_0,
  143516. _vq_quantmap__44u5__p9_0,
  143517. 13,
  143518. 13
  143519. };
  143520. static static_codebook _44u5__p9_0 = {
  143521. 2, 169,
  143522. _vq_lengthlist__44u5__p9_0,
  143523. 1, -514332672, 1627381760, 4, 0,
  143524. _vq_quantlist__44u5__p9_0,
  143525. NULL,
  143526. &_vq_auxt__44u5__p9_0,
  143527. NULL,
  143528. 0
  143529. };
  143530. static long _vq_quantlist__44u5__p9_1[] = {
  143531. 7,
  143532. 6,
  143533. 8,
  143534. 5,
  143535. 9,
  143536. 4,
  143537. 10,
  143538. 3,
  143539. 11,
  143540. 2,
  143541. 12,
  143542. 1,
  143543. 13,
  143544. 0,
  143545. 14,
  143546. };
  143547. static long _vq_lengthlist__44u5__p9_1[] = {
  143548. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  143549. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  143550. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  143551. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  143552. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  143553. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  143554. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  143555. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  143556. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  143557. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  143558. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  143559. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  143560. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  143561. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  143562. 14,
  143563. };
  143564. static float _vq_quantthresh__44u5__p9_1[] = {
  143565. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143566. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143567. };
  143568. static long _vq_quantmap__44u5__p9_1[] = {
  143569. 13, 11, 9, 7, 5, 3, 1, 0,
  143570. 2, 4, 6, 8, 10, 12, 14,
  143571. };
  143572. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  143573. _vq_quantthresh__44u5__p9_1,
  143574. _vq_quantmap__44u5__p9_1,
  143575. 15,
  143576. 15
  143577. };
  143578. static static_codebook _44u5__p9_1 = {
  143579. 2, 225,
  143580. _vq_lengthlist__44u5__p9_1,
  143581. 1, -522338304, 1620115456, 4, 0,
  143582. _vq_quantlist__44u5__p9_1,
  143583. NULL,
  143584. &_vq_auxt__44u5__p9_1,
  143585. NULL,
  143586. 0
  143587. };
  143588. static long _vq_quantlist__44u5__p9_2[] = {
  143589. 8,
  143590. 7,
  143591. 9,
  143592. 6,
  143593. 10,
  143594. 5,
  143595. 11,
  143596. 4,
  143597. 12,
  143598. 3,
  143599. 13,
  143600. 2,
  143601. 14,
  143602. 1,
  143603. 15,
  143604. 0,
  143605. 16,
  143606. };
  143607. static long _vq_lengthlist__44u5__p9_2[] = {
  143608. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143609. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  143610. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  143611. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  143612. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  143613. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  143614. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  143615. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143616. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  143617. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  143618. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  143619. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  143620. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  143621. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  143622. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  143623. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  143624. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143625. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  143626. 10,
  143627. };
  143628. static float _vq_quantthresh__44u5__p9_2[] = {
  143629. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143630. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143631. };
  143632. static long _vq_quantmap__44u5__p9_2[] = {
  143633. 15, 13, 11, 9, 7, 5, 3, 1,
  143634. 0, 2, 4, 6, 8, 10, 12, 14,
  143635. 16,
  143636. };
  143637. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  143638. _vq_quantthresh__44u5__p9_2,
  143639. _vq_quantmap__44u5__p9_2,
  143640. 17,
  143641. 17
  143642. };
  143643. static static_codebook _44u5__p9_2 = {
  143644. 2, 289,
  143645. _vq_lengthlist__44u5__p9_2,
  143646. 1, -529530880, 1611661312, 5, 0,
  143647. _vq_quantlist__44u5__p9_2,
  143648. NULL,
  143649. &_vq_auxt__44u5__p9_2,
  143650. NULL,
  143651. 0
  143652. };
  143653. static long _huff_lengthlist__44u5__short[] = {
  143654. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  143655. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  143656. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  143657. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  143658. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  143659. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  143660. 6, 8,15,17,
  143661. };
  143662. static static_codebook _huff_book__44u5__short = {
  143663. 2, 100,
  143664. _huff_lengthlist__44u5__short,
  143665. 0, 0, 0, 0, 0,
  143666. NULL,
  143667. NULL,
  143668. NULL,
  143669. NULL,
  143670. 0
  143671. };
  143672. static long _huff_lengthlist__44u6__long[] = {
  143673. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  143674. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  143675. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  143676. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  143677. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  143678. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  143679. 13, 8, 7, 7,
  143680. };
  143681. static static_codebook _huff_book__44u6__long = {
  143682. 2, 100,
  143683. _huff_lengthlist__44u6__long,
  143684. 0, 0, 0, 0, 0,
  143685. NULL,
  143686. NULL,
  143687. NULL,
  143688. NULL,
  143689. 0
  143690. };
  143691. static long _vq_quantlist__44u6__p1_0[] = {
  143692. 1,
  143693. 0,
  143694. 2,
  143695. };
  143696. static long _vq_lengthlist__44u6__p1_0[] = {
  143697. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  143698. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  143699. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  143700. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  143701. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  143702. 12,
  143703. };
  143704. static float _vq_quantthresh__44u6__p1_0[] = {
  143705. -0.5, 0.5,
  143706. };
  143707. static long _vq_quantmap__44u6__p1_0[] = {
  143708. 1, 0, 2,
  143709. };
  143710. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  143711. _vq_quantthresh__44u6__p1_0,
  143712. _vq_quantmap__44u6__p1_0,
  143713. 3,
  143714. 3
  143715. };
  143716. static static_codebook _44u6__p1_0 = {
  143717. 4, 81,
  143718. _vq_lengthlist__44u6__p1_0,
  143719. 1, -535822336, 1611661312, 2, 0,
  143720. _vq_quantlist__44u6__p1_0,
  143721. NULL,
  143722. &_vq_auxt__44u6__p1_0,
  143723. NULL,
  143724. 0
  143725. };
  143726. static long _vq_quantlist__44u6__p2_0[] = {
  143727. 1,
  143728. 0,
  143729. 2,
  143730. };
  143731. static long _vq_lengthlist__44u6__p2_0[] = {
  143732. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  143733. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  143734. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  143735. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  143736. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  143737. 9,
  143738. };
  143739. static float _vq_quantthresh__44u6__p2_0[] = {
  143740. -0.5, 0.5,
  143741. };
  143742. static long _vq_quantmap__44u6__p2_0[] = {
  143743. 1, 0, 2,
  143744. };
  143745. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  143746. _vq_quantthresh__44u6__p2_0,
  143747. _vq_quantmap__44u6__p2_0,
  143748. 3,
  143749. 3
  143750. };
  143751. static static_codebook _44u6__p2_0 = {
  143752. 4, 81,
  143753. _vq_lengthlist__44u6__p2_0,
  143754. 1, -535822336, 1611661312, 2, 0,
  143755. _vq_quantlist__44u6__p2_0,
  143756. NULL,
  143757. &_vq_auxt__44u6__p2_0,
  143758. NULL,
  143759. 0
  143760. };
  143761. static long _vq_quantlist__44u6__p3_0[] = {
  143762. 2,
  143763. 1,
  143764. 3,
  143765. 0,
  143766. 4,
  143767. };
  143768. static long _vq_lengthlist__44u6__p3_0[] = {
  143769. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  143770. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  143771. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  143772. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  143773. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  143774. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  143775. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  143776. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  143777. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  143778. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  143779. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  143780. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  143781. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  143782. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  143783. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  143784. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  143785. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  143786. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  143787. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  143788. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  143789. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  143790. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  143791. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  143792. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  143793. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  143794. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  143795. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  143796. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  143797. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  143798. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  143799. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  143800. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  143801. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  143802. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  143803. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  143804. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  143805. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  143806. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  143807. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  143808. 19,
  143809. };
  143810. static float _vq_quantthresh__44u6__p3_0[] = {
  143811. -1.5, -0.5, 0.5, 1.5,
  143812. };
  143813. static long _vq_quantmap__44u6__p3_0[] = {
  143814. 3, 1, 0, 2, 4,
  143815. };
  143816. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  143817. _vq_quantthresh__44u6__p3_0,
  143818. _vq_quantmap__44u6__p3_0,
  143819. 5,
  143820. 5
  143821. };
  143822. static static_codebook _44u6__p3_0 = {
  143823. 4, 625,
  143824. _vq_lengthlist__44u6__p3_0,
  143825. 1, -533725184, 1611661312, 3, 0,
  143826. _vq_quantlist__44u6__p3_0,
  143827. NULL,
  143828. &_vq_auxt__44u6__p3_0,
  143829. NULL,
  143830. 0
  143831. };
  143832. static long _vq_quantlist__44u6__p4_0[] = {
  143833. 2,
  143834. 1,
  143835. 3,
  143836. 0,
  143837. 4,
  143838. };
  143839. static long _vq_lengthlist__44u6__p4_0[] = {
  143840. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  143841. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  143842. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  143843. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  143844. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  143845. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  143846. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  143847. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  143848. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  143849. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  143850. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  143851. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  143852. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  143853. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  143854. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  143855. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  143856. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  143857. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143858. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  143859. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  143860. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  143861. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  143862. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  143863. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  143864. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  143865. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  143866. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  143867. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  143868. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  143869. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  143870. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  143871. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  143872. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  143873. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  143874. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  143875. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  143876. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  143877. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  143878. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  143879. 13,
  143880. };
  143881. static float _vq_quantthresh__44u6__p4_0[] = {
  143882. -1.5, -0.5, 0.5, 1.5,
  143883. };
  143884. static long _vq_quantmap__44u6__p4_0[] = {
  143885. 3, 1, 0, 2, 4,
  143886. };
  143887. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  143888. _vq_quantthresh__44u6__p4_0,
  143889. _vq_quantmap__44u6__p4_0,
  143890. 5,
  143891. 5
  143892. };
  143893. static static_codebook _44u6__p4_0 = {
  143894. 4, 625,
  143895. _vq_lengthlist__44u6__p4_0,
  143896. 1, -533725184, 1611661312, 3, 0,
  143897. _vq_quantlist__44u6__p4_0,
  143898. NULL,
  143899. &_vq_auxt__44u6__p4_0,
  143900. NULL,
  143901. 0
  143902. };
  143903. static long _vq_quantlist__44u6__p5_0[] = {
  143904. 4,
  143905. 3,
  143906. 5,
  143907. 2,
  143908. 6,
  143909. 1,
  143910. 7,
  143911. 0,
  143912. 8,
  143913. };
  143914. static long _vq_lengthlist__44u6__p5_0[] = {
  143915. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  143916. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  143917. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  143918. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  143919. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  143920. 14,
  143921. };
  143922. static float _vq_quantthresh__44u6__p5_0[] = {
  143923. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143924. };
  143925. static long _vq_quantmap__44u6__p5_0[] = {
  143926. 7, 5, 3, 1, 0, 2, 4, 6,
  143927. 8,
  143928. };
  143929. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  143930. _vq_quantthresh__44u6__p5_0,
  143931. _vq_quantmap__44u6__p5_0,
  143932. 9,
  143933. 9
  143934. };
  143935. static static_codebook _44u6__p5_0 = {
  143936. 2, 81,
  143937. _vq_lengthlist__44u6__p5_0,
  143938. 1, -531628032, 1611661312, 4, 0,
  143939. _vq_quantlist__44u6__p5_0,
  143940. NULL,
  143941. &_vq_auxt__44u6__p5_0,
  143942. NULL,
  143943. 0
  143944. };
  143945. static long _vq_quantlist__44u6__p6_0[] = {
  143946. 4,
  143947. 3,
  143948. 5,
  143949. 2,
  143950. 6,
  143951. 1,
  143952. 7,
  143953. 0,
  143954. 8,
  143955. };
  143956. static long _vq_lengthlist__44u6__p6_0[] = {
  143957. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  143958. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  143959. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  143960. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  143961. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  143962. 12,
  143963. };
  143964. static float _vq_quantthresh__44u6__p6_0[] = {
  143965. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143966. };
  143967. static long _vq_quantmap__44u6__p6_0[] = {
  143968. 7, 5, 3, 1, 0, 2, 4, 6,
  143969. 8,
  143970. };
  143971. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  143972. _vq_quantthresh__44u6__p6_0,
  143973. _vq_quantmap__44u6__p6_0,
  143974. 9,
  143975. 9
  143976. };
  143977. static static_codebook _44u6__p6_0 = {
  143978. 2, 81,
  143979. _vq_lengthlist__44u6__p6_0,
  143980. 1, -531628032, 1611661312, 4, 0,
  143981. _vq_quantlist__44u6__p6_0,
  143982. NULL,
  143983. &_vq_auxt__44u6__p6_0,
  143984. NULL,
  143985. 0
  143986. };
  143987. static long _vq_quantlist__44u6__p7_0[] = {
  143988. 1,
  143989. 0,
  143990. 2,
  143991. };
  143992. static long _vq_lengthlist__44u6__p7_0[] = {
  143993. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  143994. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  143995. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  143996. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  143997. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  143998. 10,
  143999. };
  144000. static float _vq_quantthresh__44u6__p7_0[] = {
  144001. -5.5, 5.5,
  144002. };
  144003. static long _vq_quantmap__44u6__p7_0[] = {
  144004. 1, 0, 2,
  144005. };
  144006. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  144007. _vq_quantthresh__44u6__p7_0,
  144008. _vq_quantmap__44u6__p7_0,
  144009. 3,
  144010. 3
  144011. };
  144012. static static_codebook _44u6__p7_0 = {
  144013. 4, 81,
  144014. _vq_lengthlist__44u6__p7_0,
  144015. 1, -529137664, 1618345984, 2, 0,
  144016. _vq_quantlist__44u6__p7_0,
  144017. NULL,
  144018. &_vq_auxt__44u6__p7_0,
  144019. NULL,
  144020. 0
  144021. };
  144022. static long _vq_quantlist__44u6__p7_1[] = {
  144023. 5,
  144024. 4,
  144025. 6,
  144026. 3,
  144027. 7,
  144028. 2,
  144029. 8,
  144030. 1,
  144031. 9,
  144032. 0,
  144033. 10,
  144034. };
  144035. static long _vq_lengthlist__44u6__p7_1[] = {
  144036. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  144037. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  144038. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144039. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  144040. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144041. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144042. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144043. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144044. };
  144045. static float _vq_quantthresh__44u6__p7_1[] = {
  144046. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144047. 3.5, 4.5,
  144048. };
  144049. static long _vq_quantmap__44u6__p7_1[] = {
  144050. 9, 7, 5, 3, 1, 0, 2, 4,
  144051. 6, 8, 10,
  144052. };
  144053. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  144054. _vq_quantthresh__44u6__p7_1,
  144055. _vq_quantmap__44u6__p7_1,
  144056. 11,
  144057. 11
  144058. };
  144059. static static_codebook _44u6__p7_1 = {
  144060. 2, 121,
  144061. _vq_lengthlist__44u6__p7_1,
  144062. 1, -531365888, 1611661312, 4, 0,
  144063. _vq_quantlist__44u6__p7_1,
  144064. NULL,
  144065. &_vq_auxt__44u6__p7_1,
  144066. NULL,
  144067. 0
  144068. };
  144069. static long _vq_quantlist__44u6__p8_0[] = {
  144070. 5,
  144071. 4,
  144072. 6,
  144073. 3,
  144074. 7,
  144075. 2,
  144076. 8,
  144077. 1,
  144078. 9,
  144079. 0,
  144080. 10,
  144081. };
  144082. static long _vq_lengthlist__44u6__p8_0[] = {
  144083. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  144084. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  144085. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  144086. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  144087. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  144088. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  144089. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  144090. 12,13,13,14,14,14,15,15,15,
  144091. };
  144092. static float _vq_quantthresh__44u6__p8_0[] = {
  144093. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144094. 38.5, 49.5,
  144095. };
  144096. static long _vq_quantmap__44u6__p8_0[] = {
  144097. 9, 7, 5, 3, 1, 0, 2, 4,
  144098. 6, 8, 10,
  144099. };
  144100. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  144101. _vq_quantthresh__44u6__p8_0,
  144102. _vq_quantmap__44u6__p8_0,
  144103. 11,
  144104. 11
  144105. };
  144106. static static_codebook _44u6__p8_0 = {
  144107. 2, 121,
  144108. _vq_lengthlist__44u6__p8_0,
  144109. 1, -524582912, 1618345984, 4, 0,
  144110. _vq_quantlist__44u6__p8_0,
  144111. NULL,
  144112. &_vq_auxt__44u6__p8_0,
  144113. NULL,
  144114. 0
  144115. };
  144116. static long _vq_quantlist__44u6__p8_1[] = {
  144117. 5,
  144118. 4,
  144119. 6,
  144120. 3,
  144121. 7,
  144122. 2,
  144123. 8,
  144124. 1,
  144125. 9,
  144126. 0,
  144127. 10,
  144128. };
  144129. static long _vq_lengthlist__44u6__p8_1[] = {
  144130. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  144131. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  144132. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  144133. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  144134. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144135. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  144136. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144137. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144138. };
  144139. static float _vq_quantthresh__44u6__p8_1[] = {
  144140. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144141. 3.5, 4.5,
  144142. };
  144143. static long _vq_quantmap__44u6__p8_1[] = {
  144144. 9, 7, 5, 3, 1, 0, 2, 4,
  144145. 6, 8, 10,
  144146. };
  144147. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  144148. _vq_quantthresh__44u6__p8_1,
  144149. _vq_quantmap__44u6__p8_1,
  144150. 11,
  144151. 11
  144152. };
  144153. static static_codebook _44u6__p8_1 = {
  144154. 2, 121,
  144155. _vq_lengthlist__44u6__p8_1,
  144156. 1, -531365888, 1611661312, 4, 0,
  144157. _vq_quantlist__44u6__p8_1,
  144158. NULL,
  144159. &_vq_auxt__44u6__p8_1,
  144160. NULL,
  144161. 0
  144162. };
  144163. static long _vq_quantlist__44u6__p9_0[] = {
  144164. 7,
  144165. 6,
  144166. 8,
  144167. 5,
  144168. 9,
  144169. 4,
  144170. 10,
  144171. 3,
  144172. 11,
  144173. 2,
  144174. 12,
  144175. 1,
  144176. 13,
  144177. 0,
  144178. 14,
  144179. };
  144180. static long _vq_lengthlist__44u6__p9_0[] = {
  144181. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  144182. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  144183. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  144184. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  144185. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144186. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144187. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144188. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144189. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144190. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144191. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144192. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144193. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144194. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  144195. 14,
  144196. };
  144197. static float _vq_quantthresh__44u6__p9_0[] = {
  144198. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144199. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144200. };
  144201. static long _vq_quantmap__44u6__p9_0[] = {
  144202. 13, 11, 9, 7, 5, 3, 1, 0,
  144203. 2, 4, 6, 8, 10, 12, 14,
  144204. };
  144205. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  144206. _vq_quantthresh__44u6__p9_0,
  144207. _vq_quantmap__44u6__p9_0,
  144208. 15,
  144209. 15
  144210. };
  144211. static static_codebook _44u6__p9_0 = {
  144212. 2, 225,
  144213. _vq_lengthlist__44u6__p9_0,
  144214. 1, -514071552, 1627381760, 4, 0,
  144215. _vq_quantlist__44u6__p9_0,
  144216. NULL,
  144217. &_vq_auxt__44u6__p9_0,
  144218. NULL,
  144219. 0
  144220. };
  144221. static long _vq_quantlist__44u6__p9_1[] = {
  144222. 7,
  144223. 6,
  144224. 8,
  144225. 5,
  144226. 9,
  144227. 4,
  144228. 10,
  144229. 3,
  144230. 11,
  144231. 2,
  144232. 12,
  144233. 1,
  144234. 13,
  144235. 0,
  144236. 14,
  144237. };
  144238. static long _vq_lengthlist__44u6__p9_1[] = {
  144239. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  144240. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  144241. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  144242. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  144243. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  144244. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  144245. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  144246. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  144247. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  144248. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  144249. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  144250. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  144251. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  144252. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  144253. 13,
  144254. };
  144255. static float _vq_quantthresh__44u6__p9_1[] = {
  144256. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144257. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144258. };
  144259. static long _vq_quantmap__44u6__p9_1[] = {
  144260. 13, 11, 9, 7, 5, 3, 1, 0,
  144261. 2, 4, 6, 8, 10, 12, 14,
  144262. };
  144263. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  144264. _vq_quantthresh__44u6__p9_1,
  144265. _vq_quantmap__44u6__p9_1,
  144266. 15,
  144267. 15
  144268. };
  144269. static static_codebook _44u6__p9_1 = {
  144270. 2, 225,
  144271. _vq_lengthlist__44u6__p9_1,
  144272. 1, -522338304, 1620115456, 4, 0,
  144273. _vq_quantlist__44u6__p9_1,
  144274. NULL,
  144275. &_vq_auxt__44u6__p9_1,
  144276. NULL,
  144277. 0
  144278. };
  144279. static long _vq_quantlist__44u6__p9_2[] = {
  144280. 8,
  144281. 7,
  144282. 9,
  144283. 6,
  144284. 10,
  144285. 5,
  144286. 11,
  144287. 4,
  144288. 12,
  144289. 3,
  144290. 13,
  144291. 2,
  144292. 14,
  144293. 1,
  144294. 15,
  144295. 0,
  144296. 16,
  144297. };
  144298. static long _vq_lengthlist__44u6__p9_2[] = {
  144299. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  144300. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  144301. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  144302. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144303. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144304. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144305. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144306. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144307. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  144308. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  144309. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  144310. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144311. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  144312. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  144313. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  144314. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  144315. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  144316. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  144317. 10,
  144318. };
  144319. static float _vq_quantthresh__44u6__p9_2[] = {
  144320. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144321. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144322. };
  144323. static long _vq_quantmap__44u6__p9_2[] = {
  144324. 15, 13, 11, 9, 7, 5, 3, 1,
  144325. 0, 2, 4, 6, 8, 10, 12, 14,
  144326. 16,
  144327. };
  144328. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  144329. _vq_quantthresh__44u6__p9_2,
  144330. _vq_quantmap__44u6__p9_2,
  144331. 17,
  144332. 17
  144333. };
  144334. static static_codebook _44u6__p9_2 = {
  144335. 2, 289,
  144336. _vq_lengthlist__44u6__p9_2,
  144337. 1, -529530880, 1611661312, 5, 0,
  144338. _vq_quantlist__44u6__p9_2,
  144339. NULL,
  144340. &_vq_auxt__44u6__p9_2,
  144341. NULL,
  144342. 0
  144343. };
  144344. static long _huff_lengthlist__44u6__short[] = {
  144345. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  144346. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  144347. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  144348. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  144349. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  144350. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  144351. 7, 6, 9,16,
  144352. };
  144353. static static_codebook _huff_book__44u6__short = {
  144354. 2, 100,
  144355. _huff_lengthlist__44u6__short,
  144356. 0, 0, 0, 0, 0,
  144357. NULL,
  144358. NULL,
  144359. NULL,
  144360. NULL,
  144361. 0
  144362. };
  144363. static long _huff_lengthlist__44u7__long[] = {
  144364. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  144365. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  144366. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  144367. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  144368. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  144369. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  144370. 12, 8, 6, 7,
  144371. };
  144372. static static_codebook _huff_book__44u7__long = {
  144373. 2, 100,
  144374. _huff_lengthlist__44u7__long,
  144375. 0, 0, 0, 0, 0,
  144376. NULL,
  144377. NULL,
  144378. NULL,
  144379. NULL,
  144380. 0
  144381. };
  144382. static long _vq_quantlist__44u7__p1_0[] = {
  144383. 1,
  144384. 0,
  144385. 2,
  144386. };
  144387. static long _vq_lengthlist__44u7__p1_0[] = {
  144388. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144389. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  144390. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  144391. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  144392. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  144393. 12,
  144394. };
  144395. static float _vq_quantthresh__44u7__p1_0[] = {
  144396. -0.5, 0.5,
  144397. };
  144398. static long _vq_quantmap__44u7__p1_0[] = {
  144399. 1, 0, 2,
  144400. };
  144401. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  144402. _vq_quantthresh__44u7__p1_0,
  144403. _vq_quantmap__44u7__p1_0,
  144404. 3,
  144405. 3
  144406. };
  144407. static static_codebook _44u7__p1_0 = {
  144408. 4, 81,
  144409. _vq_lengthlist__44u7__p1_0,
  144410. 1, -535822336, 1611661312, 2, 0,
  144411. _vq_quantlist__44u7__p1_0,
  144412. NULL,
  144413. &_vq_auxt__44u7__p1_0,
  144414. NULL,
  144415. 0
  144416. };
  144417. static long _vq_quantlist__44u7__p2_0[] = {
  144418. 1,
  144419. 0,
  144420. 2,
  144421. };
  144422. static long _vq_lengthlist__44u7__p2_0[] = {
  144423. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  144424. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  144425. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  144426. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  144427. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  144428. 9,
  144429. };
  144430. static float _vq_quantthresh__44u7__p2_0[] = {
  144431. -0.5, 0.5,
  144432. };
  144433. static long _vq_quantmap__44u7__p2_0[] = {
  144434. 1, 0, 2,
  144435. };
  144436. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  144437. _vq_quantthresh__44u7__p2_0,
  144438. _vq_quantmap__44u7__p2_0,
  144439. 3,
  144440. 3
  144441. };
  144442. static static_codebook _44u7__p2_0 = {
  144443. 4, 81,
  144444. _vq_lengthlist__44u7__p2_0,
  144445. 1, -535822336, 1611661312, 2, 0,
  144446. _vq_quantlist__44u7__p2_0,
  144447. NULL,
  144448. &_vq_auxt__44u7__p2_0,
  144449. NULL,
  144450. 0
  144451. };
  144452. static long _vq_quantlist__44u7__p3_0[] = {
  144453. 2,
  144454. 1,
  144455. 3,
  144456. 0,
  144457. 4,
  144458. };
  144459. static long _vq_lengthlist__44u7__p3_0[] = {
  144460. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  144461. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  144462. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  144463. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  144464. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  144465. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  144466. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  144467. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  144468. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  144469. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  144470. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  144471. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  144472. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  144473. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  144474. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  144475. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  144476. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  144477. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  144478. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  144479. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  144480. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  144481. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  144482. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  144483. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  144484. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  144485. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  144486. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  144487. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  144488. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  144489. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  144490. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  144491. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  144492. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  144493. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  144494. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  144495. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  144496. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  144497. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  144498. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  144499. 0,
  144500. };
  144501. static float _vq_quantthresh__44u7__p3_0[] = {
  144502. -1.5, -0.5, 0.5, 1.5,
  144503. };
  144504. static long _vq_quantmap__44u7__p3_0[] = {
  144505. 3, 1, 0, 2, 4,
  144506. };
  144507. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  144508. _vq_quantthresh__44u7__p3_0,
  144509. _vq_quantmap__44u7__p3_0,
  144510. 5,
  144511. 5
  144512. };
  144513. static static_codebook _44u7__p3_0 = {
  144514. 4, 625,
  144515. _vq_lengthlist__44u7__p3_0,
  144516. 1, -533725184, 1611661312, 3, 0,
  144517. _vq_quantlist__44u7__p3_0,
  144518. NULL,
  144519. &_vq_auxt__44u7__p3_0,
  144520. NULL,
  144521. 0
  144522. };
  144523. static long _vq_quantlist__44u7__p4_0[] = {
  144524. 2,
  144525. 1,
  144526. 3,
  144527. 0,
  144528. 4,
  144529. };
  144530. static long _vq_lengthlist__44u7__p4_0[] = {
  144531. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  144532. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  144533. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  144534. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  144535. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  144536. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  144537. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  144538. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  144539. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  144540. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  144541. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  144542. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  144543. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  144544. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  144545. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  144546. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  144547. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  144548. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  144549. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  144550. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  144551. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  144552. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  144553. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  144554. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  144555. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  144556. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  144557. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  144558. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  144559. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  144560. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  144561. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  144562. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  144563. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  144564. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  144565. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  144566. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  144567. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  144568. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  144569. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  144570. 14,
  144571. };
  144572. static float _vq_quantthresh__44u7__p4_0[] = {
  144573. -1.5, -0.5, 0.5, 1.5,
  144574. };
  144575. static long _vq_quantmap__44u7__p4_0[] = {
  144576. 3, 1, 0, 2, 4,
  144577. };
  144578. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  144579. _vq_quantthresh__44u7__p4_0,
  144580. _vq_quantmap__44u7__p4_0,
  144581. 5,
  144582. 5
  144583. };
  144584. static static_codebook _44u7__p4_0 = {
  144585. 4, 625,
  144586. _vq_lengthlist__44u7__p4_0,
  144587. 1, -533725184, 1611661312, 3, 0,
  144588. _vq_quantlist__44u7__p4_0,
  144589. NULL,
  144590. &_vq_auxt__44u7__p4_0,
  144591. NULL,
  144592. 0
  144593. };
  144594. static long _vq_quantlist__44u7__p5_0[] = {
  144595. 4,
  144596. 3,
  144597. 5,
  144598. 2,
  144599. 6,
  144600. 1,
  144601. 7,
  144602. 0,
  144603. 8,
  144604. };
  144605. static long _vq_lengthlist__44u7__p5_0[] = {
  144606. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  144607. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  144608. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  144609. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  144610. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  144611. 14,
  144612. };
  144613. static float _vq_quantthresh__44u7__p5_0[] = {
  144614. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144615. };
  144616. static long _vq_quantmap__44u7__p5_0[] = {
  144617. 7, 5, 3, 1, 0, 2, 4, 6,
  144618. 8,
  144619. };
  144620. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  144621. _vq_quantthresh__44u7__p5_0,
  144622. _vq_quantmap__44u7__p5_0,
  144623. 9,
  144624. 9
  144625. };
  144626. static static_codebook _44u7__p5_0 = {
  144627. 2, 81,
  144628. _vq_lengthlist__44u7__p5_0,
  144629. 1, -531628032, 1611661312, 4, 0,
  144630. _vq_quantlist__44u7__p5_0,
  144631. NULL,
  144632. &_vq_auxt__44u7__p5_0,
  144633. NULL,
  144634. 0
  144635. };
  144636. static long _vq_quantlist__44u7__p6_0[] = {
  144637. 4,
  144638. 3,
  144639. 5,
  144640. 2,
  144641. 6,
  144642. 1,
  144643. 7,
  144644. 0,
  144645. 8,
  144646. };
  144647. static long _vq_lengthlist__44u7__p6_0[] = {
  144648. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  144649. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  144650. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  144651. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  144652. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  144653. 12,
  144654. };
  144655. static float _vq_quantthresh__44u7__p6_0[] = {
  144656. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144657. };
  144658. static long _vq_quantmap__44u7__p6_0[] = {
  144659. 7, 5, 3, 1, 0, 2, 4, 6,
  144660. 8,
  144661. };
  144662. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  144663. _vq_quantthresh__44u7__p6_0,
  144664. _vq_quantmap__44u7__p6_0,
  144665. 9,
  144666. 9
  144667. };
  144668. static static_codebook _44u7__p6_0 = {
  144669. 2, 81,
  144670. _vq_lengthlist__44u7__p6_0,
  144671. 1, -531628032, 1611661312, 4, 0,
  144672. _vq_quantlist__44u7__p6_0,
  144673. NULL,
  144674. &_vq_auxt__44u7__p6_0,
  144675. NULL,
  144676. 0
  144677. };
  144678. static long _vq_quantlist__44u7__p7_0[] = {
  144679. 1,
  144680. 0,
  144681. 2,
  144682. };
  144683. static long _vq_lengthlist__44u7__p7_0[] = {
  144684. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  144685. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  144686. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  144687. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  144688. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  144689. 10,
  144690. };
  144691. static float _vq_quantthresh__44u7__p7_0[] = {
  144692. -5.5, 5.5,
  144693. };
  144694. static long _vq_quantmap__44u7__p7_0[] = {
  144695. 1, 0, 2,
  144696. };
  144697. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  144698. _vq_quantthresh__44u7__p7_0,
  144699. _vq_quantmap__44u7__p7_0,
  144700. 3,
  144701. 3
  144702. };
  144703. static static_codebook _44u7__p7_0 = {
  144704. 4, 81,
  144705. _vq_lengthlist__44u7__p7_0,
  144706. 1, -529137664, 1618345984, 2, 0,
  144707. _vq_quantlist__44u7__p7_0,
  144708. NULL,
  144709. &_vq_auxt__44u7__p7_0,
  144710. NULL,
  144711. 0
  144712. };
  144713. static long _vq_quantlist__44u7__p7_1[] = {
  144714. 5,
  144715. 4,
  144716. 6,
  144717. 3,
  144718. 7,
  144719. 2,
  144720. 8,
  144721. 1,
  144722. 9,
  144723. 0,
  144724. 10,
  144725. };
  144726. static long _vq_lengthlist__44u7__p7_1[] = {
  144727. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  144728. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  144729. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  144730. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  144731. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  144732. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  144733. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  144734. 8, 9, 9, 9, 9, 9,10,10,10,
  144735. };
  144736. static float _vq_quantthresh__44u7__p7_1[] = {
  144737. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144738. 3.5, 4.5,
  144739. };
  144740. static long _vq_quantmap__44u7__p7_1[] = {
  144741. 9, 7, 5, 3, 1, 0, 2, 4,
  144742. 6, 8, 10,
  144743. };
  144744. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  144745. _vq_quantthresh__44u7__p7_1,
  144746. _vq_quantmap__44u7__p7_1,
  144747. 11,
  144748. 11
  144749. };
  144750. static static_codebook _44u7__p7_1 = {
  144751. 2, 121,
  144752. _vq_lengthlist__44u7__p7_1,
  144753. 1, -531365888, 1611661312, 4, 0,
  144754. _vq_quantlist__44u7__p7_1,
  144755. NULL,
  144756. &_vq_auxt__44u7__p7_1,
  144757. NULL,
  144758. 0
  144759. };
  144760. static long _vq_quantlist__44u7__p8_0[] = {
  144761. 5,
  144762. 4,
  144763. 6,
  144764. 3,
  144765. 7,
  144766. 2,
  144767. 8,
  144768. 1,
  144769. 9,
  144770. 0,
  144771. 10,
  144772. };
  144773. static long _vq_lengthlist__44u7__p8_0[] = {
  144774. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  144775. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  144776. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  144777. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  144778. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  144779. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  144780. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  144781. 12,13,13,14,14,15,15,15,16,
  144782. };
  144783. static float _vq_quantthresh__44u7__p8_0[] = {
  144784. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144785. 38.5, 49.5,
  144786. };
  144787. static long _vq_quantmap__44u7__p8_0[] = {
  144788. 9, 7, 5, 3, 1, 0, 2, 4,
  144789. 6, 8, 10,
  144790. };
  144791. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  144792. _vq_quantthresh__44u7__p8_0,
  144793. _vq_quantmap__44u7__p8_0,
  144794. 11,
  144795. 11
  144796. };
  144797. static static_codebook _44u7__p8_0 = {
  144798. 2, 121,
  144799. _vq_lengthlist__44u7__p8_0,
  144800. 1, -524582912, 1618345984, 4, 0,
  144801. _vq_quantlist__44u7__p8_0,
  144802. NULL,
  144803. &_vq_auxt__44u7__p8_0,
  144804. NULL,
  144805. 0
  144806. };
  144807. static long _vq_quantlist__44u7__p8_1[] = {
  144808. 5,
  144809. 4,
  144810. 6,
  144811. 3,
  144812. 7,
  144813. 2,
  144814. 8,
  144815. 1,
  144816. 9,
  144817. 0,
  144818. 10,
  144819. };
  144820. static long _vq_lengthlist__44u7__p8_1[] = {
  144821. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144822. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  144823. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  144824. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  144825. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  144826. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  144827. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  144828. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  144829. };
  144830. static float _vq_quantthresh__44u7__p8_1[] = {
  144831. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144832. 3.5, 4.5,
  144833. };
  144834. static long _vq_quantmap__44u7__p8_1[] = {
  144835. 9, 7, 5, 3, 1, 0, 2, 4,
  144836. 6, 8, 10,
  144837. };
  144838. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  144839. _vq_quantthresh__44u7__p8_1,
  144840. _vq_quantmap__44u7__p8_1,
  144841. 11,
  144842. 11
  144843. };
  144844. static static_codebook _44u7__p8_1 = {
  144845. 2, 121,
  144846. _vq_lengthlist__44u7__p8_1,
  144847. 1, -531365888, 1611661312, 4, 0,
  144848. _vq_quantlist__44u7__p8_1,
  144849. NULL,
  144850. &_vq_auxt__44u7__p8_1,
  144851. NULL,
  144852. 0
  144853. };
  144854. static long _vq_quantlist__44u7__p9_0[] = {
  144855. 5,
  144856. 4,
  144857. 6,
  144858. 3,
  144859. 7,
  144860. 2,
  144861. 8,
  144862. 1,
  144863. 9,
  144864. 0,
  144865. 10,
  144866. };
  144867. static long _vq_lengthlist__44u7__p9_0[] = {
  144868. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  144869. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  144870. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144871. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144872. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144873. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144874. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  144875. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144876. };
  144877. static float _vq_quantthresh__44u7__p9_0[] = {
  144878. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  144879. 2229.5, 2866.5,
  144880. };
  144881. static long _vq_quantmap__44u7__p9_0[] = {
  144882. 9, 7, 5, 3, 1, 0, 2, 4,
  144883. 6, 8, 10,
  144884. };
  144885. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  144886. _vq_quantthresh__44u7__p9_0,
  144887. _vq_quantmap__44u7__p9_0,
  144888. 11,
  144889. 11
  144890. };
  144891. static static_codebook _44u7__p9_0 = {
  144892. 2, 121,
  144893. _vq_lengthlist__44u7__p9_0,
  144894. 1, -512171520, 1630791680, 4, 0,
  144895. _vq_quantlist__44u7__p9_0,
  144896. NULL,
  144897. &_vq_auxt__44u7__p9_0,
  144898. NULL,
  144899. 0
  144900. };
  144901. static long _vq_quantlist__44u7__p9_1[] = {
  144902. 6,
  144903. 5,
  144904. 7,
  144905. 4,
  144906. 8,
  144907. 3,
  144908. 9,
  144909. 2,
  144910. 10,
  144911. 1,
  144912. 11,
  144913. 0,
  144914. 12,
  144915. };
  144916. static long _vq_lengthlist__44u7__p9_1[] = {
  144917. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  144918. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  144919. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  144920. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  144921. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  144922. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  144923. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  144924. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  144925. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  144926. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  144927. 15,15,15,15,17,17,16,17,16,
  144928. };
  144929. static float _vq_quantthresh__44u7__p9_1[] = {
  144930. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  144931. 122.5, 171.5, 220.5, 269.5,
  144932. };
  144933. static long _vq_quantmap__44u7__p9_1[] = {
  144934. 11, 9, 7, 5, 3, 1, 0, 2,
  144935. 4, 6, 8, 10, 12,
  144936. };
  144937. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  144938. _vq_quantthresh__44u7__p9_1,
  144939. _vq_quantmap__44u7__p9_1,
  144940. 13,
  144941. 13
  144942. };
  144943. static static_codebook _44u7__p9_1 = {
  144944. 2, 169,
  144945. _vq_lengthlist__44u7__p9_1,
  144946. 1, -518889472, 1622704128, 4, 0,
  144947. _vq_quantlist__44u7__p9_1,
  144948. NULL,
  144949. &_vq_auxt__44u7__p9_1,
  144950. NULL,
  144951. 0
  144952. };
  144953. static long _vq_quantlist__44u7__p9_2[] = {
  144954. 24,
  144955. 23,
  144956. 25,
  144957. 22,
  144958. 26,
  144959. 21,
  144960. 27,
  144961. 20,
  144962. 28,
  144963. 19,
  144964. 29,
  144965. 18,
  144966. 30,
  144967. 17,
  144968. 31,
  144969. 16,
  144970. 32,
  144971. 15,
  144972. 33,
  144973. 14,
  144974. 34,
  144975. 13,
  144976. 35,
  144977. 12,
  144978. 36,
  144979. 11,
  144980. 37,
  144981. 10,
  144982. 38,
  144983. 9,
  144984. 39,
  144985. 8,
  144986. 40,
  144987. 7,
  144988. 41,
  144989. 6,
  144990. 42,
  144991. 5,
  144992. 43,
  144993. 4,
  144994. 44,
  144995. 3,
  144996. 45,
  144997. 2,
  144998. 46,
  144999. 1,
  145000. 47,
  145001. 0,
  145002. 48,
  145003. };
  145004. static long _vq_lengthlist__44u7__p9_2[] = {
  145005. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  145006. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145007. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  145008. 8,
  145009. };
  145010. static float _vq_quantthresh__44u7__p9_2[] = {
  145011. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145012. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145013. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145014. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145015. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145016. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145017. };
  145018. static long _vq_quantmap__44u7__p9_2[] = {
  145019. 47, 45, 43, 41, 39, 37, 35, 33,
  145020. 31, 29, 27, 25, 23, 21, 19, 17,
  145021. 15, 13, 11, 9, 7, 5, 3, 1,
  145022. 0, 2, 4, 6, 8, 10, 12, 14,
  145023. 16, 18, 20, 22, 24, 26, 28, 30,
  145024. 32, 34, 36, 38, 40, 42, 44, 46,
  145025. 48,
  145026. };
  145027. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  145028. _vq_quantthresh__44u7__p9_2,
  145029. _vq_quantmap__44u7__p9_2,
  145030. 49,
  145031. 49
  145032. };
  145033. static static_codebook _44u7__p9_2 = {
  145034. 1, 49,
  145035. _vq_lengthlist__44u7__p9_2,
  145036. 1, -526909440, 1611661312, 6, 0,
  145037. _vq_quantlist__44u7__p9_2,
  145038. NULL,
  145039. &_vq_auxt__44u7__p9_2,
  145040. NULL,
  145041. 0
  145042. };
  145043. static long _huff_lengthlist__44u7__short[] = {
  145044. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  145045. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  145046. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  145047. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  145048. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  145049. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  145050. 6, 8, 5, 9,
  145051. };
  145052. static static_codebook _huff_book__44u7__short = {
  145053. 2, 100,
  145054. _huff_lengthlist__44u7__short,
  145055. 0, 0, 0, 0, 0,
  145056. NULL,
  145057. NULL,
  145058. NULL,
  145059. NULL,
  145060. 0
  145061. };
  145062. static long _huff_lengthlist__44u8__long[] = {
  145063. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  145064. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  145065. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  145066. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  145067. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  145068. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  145069. 10, 8, 8, 9,
  145070. };
  145071. static static_codebook _huff_book__44u8__long = {
  145072. 2, 100,
  145073. _huff_lengthlist__44u8__long,
  145074. 0, 0, 0, 0, 0,
  145075. NULL,
  145076. NULL,
  145077. NULL,
  145078. NULL,
  145079. 0
  145080. };
  145081. static long _huff_lengthlist__44u8__short[] = {
  145082. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  145083. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  145084. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  145085. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  145086. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  145087. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  145088. 10,10,15,17,
  145089. };
  145090. static static_codebook _huff_book__44u8__short = {
  145091. 2, 100,
  145092. _huff_lengthlist__44u8__short,
  145093. 0, 0, 0, 0, 0,
  145094. NULL,
  145095. NULL,
  145096. NULL,
  145097. NULL,
  145098. 0
  145099. };
  145100. static long _vq_quantlist__44u8_p1_0[] = {
  145101. 1,
  145102. 0,
  145103. 2,
  145104. };
  145105. static long _vq_lengthlist__44u8_p1_0[] = {
  145106. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  145107. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  145108. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  145109. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  145110. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  145111. 10,
  145112. };
  145113. static float _vq_quantthresh__44u8_p1_0[] = {
  145114. -0.5, 0.5,
  145115. };
  145116. static long _vq_quantmap__44u8_p1_0[] = {
  145117. 1, 0, 2,
  145118. };
  145119. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  145120. _vq_quantthresh__44u8_p1_0,
  145121. _vq_quantmap__44u8_p1_0,
  145122. 3,
  145123. 3
  145124. };
  145125. static static_codebook _44u8_p1_0 = {
  145126. 4, 81,
  145127. _vq_lengthlist__44u8_p1_0,
  145128. 1, -535822336, 1611661312, 2, 0,
  145129. _vq_quantlist__44u8_p1_0,
  145130. NULL,
  145131. &_vq_auxt__44u8_p1_0,
  145132. NULL,
  145133. 0
  145134. };
  145135. static long _vq_quantlist__44u8_p2_0[] = {
  145136. 2,
  145137. 1,
  145138. 3,
  145139. 0,
  145140. 4,
  145141. };
  145142. static long _vq_lengthlist__44u8_p2_0[] = {
  145143. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  145144. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  145145. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  145146. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  145147. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  145148. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  145149. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145150. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  145151. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  145152. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  145153. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  145154. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145155. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  145156. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  145157. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  145158. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  145159. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  145160. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  145161. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  145162. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  145163. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  145164. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  145165. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  145166. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  145167. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  145168. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  145169. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  145170. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  145171. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  145172. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  145173. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  145174. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145175. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  145176. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  145177. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  145178. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  145179. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  145180. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  145181. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  145182. 14,
  145183. };
  145184. static float _vq_quantthresh__44u8_p2_0[] = {
  145185. -1.5, -0.5, 0.5, 1.5,
  145186. };
  145187. static long _vq_quantmap__44u8_p2_0[] = {
  145188. 3, 1, 0, 2, 4,
  145189. };
  145190. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  145191. _vq_quantthresh__44u8_p2_0,
  145192. _vq_quantmap__44u8_p2_0,
  145193. 5,
  145194. 5
  145195. };
  145196. static static_codebook _44u8_p2_0 = {
  145197. 4, 625,
  145198. _vq_lengthlist__44u8_p2_0,
  145199. 1, -533725184, 1611661312, 3, 0,
  145200. _vq_quantlist__44u8_p2_0,
  145201. NULL,
  145202. &_vq_auxt__44u8_p2_0,
  145203. NULL,
  145204. 0
  145205. };
  145206. static long _vq_quantlist__44u8_p3_0[] = {
  145207. 4,
  145208. 3,
  145209. 5,
  145210. 2,
  145211. 6,
  145212. 1,
  145213. 7,
  145214. 0,
  145215. 8,
  145216. };
  145217. static long _vq_lengthlist__44u8_p3_0[] = {
  145218. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  145219. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  145220. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  145221. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  145222. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  145223. 12,
  145224. };
  145225. static float _vq_quantthresh__44u8_p3_0[] = {
  145226. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145227. };
  145228. static long _vq_quantmap__44u8_p3_0[] = {
  145229. 7, 5, 3, 1, 0, 2, 4, 6,
  145230. 8,
  145231. };
  145232. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  145233. _vq_quantthresh__44u8_p3_0,
  145234. _vq_quantmap__44u8_p3_0,
  145235. 9,
  145236. 9
  145237. };
  145238. static static_codebook _44u8_p3_0 = {
  145239. 2, 81,
  145240. _vq_lengthlist__44u8_p3_0,
  145241. 1, -531628032, 1611661312, 4, 0,
  145242. _vq_quantlist__44u8_p3_0,
  145243. NULL,
  145244. &_vq_auxt__44u8_p3_0,
  145245. NULL,
  145246. 0
  145247. };
  145248. static long _vq_quantlist__44u8_p4_0[] = {
  145249. 8,
  145250. 7,
  145251. 9,
  145252. 6,
  145253. 10,
  145254. 5,
  145255. 11,
  145256. 4,
  145257. 12,
  145258. 3,
  145259. 13,
  145260. 2,
  145261. 14,
  145262. 1,
  145263. 15,
  145264. 0,
  145265. 16,
  145266. };
  145267. static long _vq_lengthlist__44u8_p4_0[] = {
  145268. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  145269. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  145270. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  145271. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  145272. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  145273. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  145274. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  145275. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  145276. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  145277. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  145278. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  145279. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  145280. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  145281. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  145282. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  145283. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  145284. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  145285. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  145286. 14,
  145287. };
  145288. static float _vq_quantthresh__44u8_p4_0[] = {
  145289. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145290. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145291. };
  145292. static long _vq_quantmap__44u8_p4_0[] = {
  145293. 15, 13, 11, 9, 7, 5, 3, 1,
  145294. 0, 2, 4, 6, 8, 10, 12, 14,
  145295. 16,
  145296. };
  145297. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  145298. _vq_quantthresh__44u8_p4_0,
  145299. _vq_quantmap__44u8_p4_0,
  145300. 17,
  145301. 17
  145302. };
  145303. static static_codebook _44u8_p4_0 = {
  145304. 2, 289,
  145305. _vq_lengthlist__44u8_p4_0,
  145306. 1, -529530880, 1611661312, 5, 0,
  145307. _vq_quantlist__44u8_p4_0,
  145308. NULL,
  145309. &_vq_auxt__44u8_p4_0,
  145310. NULL,
  145311. 0
  145312. };
  145313. static long _vq_quantlist__44u8_p5_0[] = {
  145314. 1,
  145315. 0,
  145316. 2,
  145317. };
  145318. static long _vq_lengthlist__44u8_p5_0[] = {
  145319. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  145320. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  145321. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  145322. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145323. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  145324. 10,
  145325. };
  145326. static float _vq_quantthresh__44u8_p5_0[] = {
  145327. -5.5, 5.5,
  145328. };
  145329. static long _vq_quantmap__44u8_p5_0[] = {
  145330. 1, 0, 2,
  145331. };
  145332. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  145333. _vq_quantthresh__44u8_p5_0,
  145334. _vq_quantmap__44u8_p5_0,
  145335. 3,
  145336. 3
  145337. };
  145338. static static_codebook _44u8_p5_0 = {
  145339. 4, 81,
  145340. _vq_lengthlist__44u8_p5_0,
  145341. 1, -529137664, 1618345984, 2, 0,
  145342. _vq_quantlist__44u8_p5_0,
  145343. NULL,
  145344. &_vq_auxt__44u8_p5_0,
  145345. NULL,
  145346. 0
  145347. };
  145348. static long _vq_quantlist__44u8_p5_1[] = {
  145349. 5,
  145350. 4,
  145351. 6,
  145352. 3,
  145353. 7,
  145354. 2,
  145355. 8,
  145356. 1,
  145357. 9,
  145358. 0,
  145359. 10,
  145360. };
  145361. static long _vq_lengthlist__44u8_p5_1[] = {
  145362. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  145363. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  145364. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  145365. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  145366. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  145367. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  145368. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  145369. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  145370. };
  145371. static float _vq_quantthresh__44u8_p5_1[] = {
  145372. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145373. 3.5, 4.5,
  145374. };
  145375. static long _vq_quantmap__44u8_p5_1[] = {
  145376. 9, 7, 5, 3, 1, 0, 2, 4,
  145377. 6, 8, 10,
  145378. };
  145379. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  145380. _vq_quantthresh__44u8_p5_1,
  145381. _vq_quantmap__44u8_p5_1,
  145382. 11,
  145383. 11
  145384. };
  145385. static static_codebook _44u8_p5_1 = {
  145386. 2, 121,
  145387. _vq_lengthlist__44u8_p5_1,
  145388. 1, -531365888, 1611661312, 4, 0,
  145389. _vq_quantlist__44u8_p5_1,
  145390. NULL,
  145391. &_vq_auxt__44u8_p5_1,
  145392. NULL,
  145393. 0
  145394. };
  145395. static long _vq_quantlist__44u8_p6_0[] = {
  145396. 6,
  145397. 5,
  145398. 7,
  145399. 4,
  145400. 8,
  145401. 3,
  145402. 9,
  145403. 2,
  145404. 10,
  145405. 1,
  145406. 11,
  145407. 0,
  145408. 12,
  145409. };
  145410. static long _vq_lengthlist__44u8_p6_0[] = {
  145411. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  145412. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  145413. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  145414. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  145415. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  145416. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  145417. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  145418. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  145419. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  145420. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  145421. 11,11,11,11,11,12,11,12,12,
  145422. };
  145423. static float _vq_quantthresh__44u8_p6_0[] = {
  145424. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145425. 12.5, 17.5, 22.5, 27.5,
  145426. };
  145427. static long _vq_quantmap__44u8_p6_0[] = {
  145428. 11, 9, 7, 5, 3, 1, 0, 2,
  145429. 4, 6, 8, 10, 12,
  145430. };
  145431. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  145432. _vq_quantthresh__44u8_p6_0,
  145433. _vq_quantmap__44u8_p6_0,
  145434. 13,
  145435. 13
  145436. };
  145437. static static_codebook _44u8_p6_0 = {
  145438. 2, 169,
  145439. _vq_lengthlist__44u8_p6_0,
  145440. 1, -526516224, 1616117760, 4, 0,
  145441. _vq_quantlist__44u8_p6_0,
  145442. NULL,
  145443. &_vq_auxt__44u8_p6_0,
  145444. NULL,
  145445. 0
  145446. };
  145447. static long _vq_quantlist__44u8_p6_1[] = {
  145448. 2,
  145449. 1,
  145450. 3,
  145451. 0,
  145452. 4,
  145453. };
  145454. static long _vq_lengthlist__44u8_p6_1[] = {
  145455. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  145456. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  145457. };
  145458. static float _vq_quantthresh__44u8_p6_1[] = {
  145459. -1.5, -0.5, 0.5, 1.5,
  145460. };
  145461. static long _vq_quantmap__44u8_p6_1[] = {
  145462. 3, 1, 0, 2, 4,
  145463. };
  145464. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  145465. _vq_quantthresh__44u8_p6_1,
  145466. _vq_quantmap__44u8_p6_1,
  145467. 5,
  145468. 5
  145469. };
  145470. static static_codebook _44u8_p6_1 = {
  145471. 2, 25,
  145472. _vq_lengthlist__44u8_p6_1,
  145473. 1, -533725184, 1611661312, 3, 0,
  145474. _vq_quantlist__44u8_p6_1,
  145475. NULL,
  145476. &_vq_auxt__44u8_p6_1,
  145477. NULL,
  145478. 0
  145479. };
  145480. static long _vq_quantlist__44u8_p7_0[] = {
  145481. 6,
  145482. 5,
  145483. 7,
  145484. 4,
  145485. 8,
  145486. 3,
  145487. 9,
  145488. 2,
  145489. 10,
  145490. 1,
  145491. 11,
  145492. 0,
  145493. 12,
  145494. };
  145495. static long _vq_lengthlist__44u8_p7_0[] = {
  145496. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  145497. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  145498. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  145499. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  145500. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  145501. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  145502. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  145503. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  145504. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  145505. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  145506. 13,13,14,14,14,15,15,15,16,
  145507. };
  145508. static float _vq_quantthresh__44u8_p7_0[] = {
  145509. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  145510. 27.5, 38.5, 49.5, 60.5,
  145511. };
  145512. static long _vq_quantmap__44u8_p7_0[] = {
  145513. 11, 9, 7, 5, 3, 1, 0, 2,
  145514. 4, 6, 8, 10, 12,
  145515. };
  145516. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  145517. _vq_quantthresh__44u8_p7_0,
  145518. _vq_quantmap__44u8_p7_0,
  145519. 13,
  145520. 13
  145521. };
  145522. static static_codebook _44u8_p7_0 = {
  145523. 2, 169,
  145524. _vq_lengthlist__44u8_p7_0,
  145525. 1, -523206656, 1618345984, 4, 0,
  145526. _vq_quantlist__44u8_p7_0,
  145527. NULL,
  145528. &_vq_auxt__44u8_p7_0,
  145529. NULL,
  145530. 0
  145531. };
  145532. static long _vq_quantlist__44u8_p7_1[] = {
  145533. 5,
  145534. 4,
  145535. 6,
  145536. 3,
  145537. 7,
  145538. 2,
  145539. 8,
  145540. 1,
  145541. 9,
  145542. 0,
  145543. 10,
  145544. };
  145545. static long _vq_lengthlist__44u8_p7_1[] = {
  145546. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  145547. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  145548. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  145549. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  145550. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  145551. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  145552. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  145553. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  145554. };
  145555. static float _vq_quantthresh__44u8_p7_1[] = {
  145556. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145557. 3.5, 4.5,
  145558. };
  145559. static long _vq_quantmap__44u8_p7_1[] = {
  145560. 9, 7, 5, 3, 1, 0, 2, 4,
  145561. 6, 8, 10,
  145562. };
  145563. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  145564. _vq_quantthresh__44u8_p7_1,
  145565. _vq_quantmap__44u8_p7_1,
  145566. 11,
  145567. 11
  145568. };
  145569. static static_codebook _44u8_p7_1 = {
  145570. 2, 121,
  145571. _vq_lengthlist__44u8_p7_1,
  145572. 1, -531365888, 1611661312, 4, 0,
  145573. _vq_quantlist__44u8_p7_1,
  145574. NULL,
  145575. &_vq_auxt__44u8_p7_1,
  145576. NULL,
  145577. 0
  145578. };
  145579. static long _vq_quantlist__44u8_p8_0[] = {
  145580. 7,
  145581. 6,
  145582. 8,
  145583. 5,
  145584. 9,
  145585. 4,
  145586. 10,
  145587. 3,
  145588. 11,
  145589. 2,
  145590. 12,
  145591. 1,
  145592. 13,
  145593. 0,
  145594. 14,
  145595. };
  145596. static long _vq_lengthlist__44u8_p8_0[] = {
  145597. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  145598. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  145599. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  145600. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  145601. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  145602. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  145603. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  145604. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  145605. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  145606. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  145607. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  145608. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  145609. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  145610. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  145611. 17,
  145612. };
  145613. static float _vq_quantthresh__44u8_p8_0[] = {
  145614. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145615. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145616. };
  145617. static long _vq_quantmap__44u8_p8_0[] = {
  145618. 13, 11, 9, 7, 5, 3, 1, 0,
  145619. 2, 4, 6, 8, 10, 12, 14,
  145620. };
  145621. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  145622. _vq_quantthresh__44u8_p8_0,
  145623. _vq_quantmap__44u8_p8_0,
  145624. 15,
  145625. 15
  145626. };
  145627. static static_codebook _44u8_p8_0 = {
  145628. 2, 225,
  145629. _vq_lengthlist__44u8_p8_0,
  145630. 1, -520986624, 1620377600, 4, 0,
  145631. _vq_quantlist__44u8_p8_0,
  145632. NULL,
  145633. &_vq_auxt__44u8_p8_0,
  145634. NULL,
  145635. 0
  145636. };
  145637. static long _vq_quantlist__44u8_p8_1[] = {
  145638. 10,
  145639. 9,
  145640. 11,
  145641. 8,
  145642. 12,
  145643. 7,
  145644. 13,
  145645. 6,
  145646. 14,
  145647. 5,
  145648. 15,
  145649. 4,
  145650. 16,
  145651. 3,
  145652. 17,
  145653. 2,
  145654. 18,
  145655. 1,
  145656. 19,
  145657. 0,
  145658. 20,
  145659. };
  145660. static long _vq_lengthlist__44u8_p8_1[] = {
  145661. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145662. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  145663. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  145664. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  145665. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145666. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145667. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  145668. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  145669. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  145670. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  145671. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  145672. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  145673. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  145674. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  145675. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  145676. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145677. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  145678. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  145679. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  145680. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  145681. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145682. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  145683. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  145684. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145685. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145686. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  145687. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  145688. 10,10,10,10,10,10,10,10,10,
  145689. };
  145690. static float _vq_quantthresh__44u8_p8_1[] = {
  145691. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145692. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145693. 6.5, 7.5, 8.5, 9.5,
  145694. };
  145695. static long _vq_quantmap__44u8_p8_1[] = {
  145696. 19, 17, 15, 13, 11, 9, 7, 5,
  145697. 3, 1, 0, 2, 4, 6, 8, 10,
  145698. 12, 14, 16, 18, 20,
  145699. };
  145700. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  145701. _vq_quantthresh__44u8_p8_1,
  145702. _vq_quantmap__44u8_p8_1,
  145703. 21,
  145704. 21
  145705. };
  145706. static static_codebook _44u8_p8_1 = {
  145707. 2, 441,
  145708. _vq_lengthlist__44u8_p8_1,
  145709. 1, -529268736, 1611661312, 5, 0,
  145710. _vq_quantlist__44u8_p8_1,
  145711. NULL,
  145712. &_vq_auxt__44u8_p8_1,
  145713. NULL,
  145714. 0
  145715. };
  145716. static long _vq_quantlist__44u8_p9_0[] = {
  145717. 4,
  145718. 3,
  145719. 5,
  145720. 2,
  145721. 6,
  145722. 1,
  145723. 7,
  145724. 0,
  145725. 8,
  145726. };
  145727. static long _vq_lengthlist__44u8_p9_0[] = {
  145728. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  145729. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145730. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145731. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145732. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  145733. 8,
  145734. };
  145735. static float _vq_quantthresh__44u8_p9_0[] = {
  145736. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  145737. };
  145738. static long _vq_quantmap__44u8_p9_0[] = {
  145739. 7, 5, 3, 1, 0, 2, 4, 6,
  145740. 8,
  145741. };
  145742. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  145743. _vq_quantthresh__44u8_p9_0,
  145744. _vq_quantmap__44u8_p9_0,
  145745. 9,
  145746. 9
  145747. };
  145748. static static_codebook _44u8_p9_0 = {
  145749. 2, 81,
  145750. _vq_lengthlist__44u8_p9_0,
  145751. 1, -511895552, 1631393792, 4, 0,
  145752. _vq_quantlist__44u8_p9_0,
  145753. NULL,
  145754. &_vq_auxt__44u8_p9_0,
  145755. NULL,
  145756. 0
  145757. };
  145758. static long _vq_quantlist__44u8_p9_1[] = {
  145759. 9,
  145760. 8,
  145761. 10,
  145762. 7,
  145763. 11,
  145764. 6,
  145765. 12,
  145766. 5,
  145767. 13,
  145768. 4,
  145769. 14,
  145770. 3,
  145771. 15,
  145772. 2,
  145773. 16,
  145774. 1,
  145775. 17,
  145776. 0,
  145777. 18,
  145778. };
  145779. static long _vq_lengthlist__44u8_p9_1[] = {
  145780. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  145781. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  145782. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  145783. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  145784. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  145785. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  145786. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  145787. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  145788. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  145789. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  145790. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  145791. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  145792. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  145793. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  145794. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  145795. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  145796. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  145797. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  145798. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  145799. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  145800. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  145801. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  145802. 16,15,16,16,16,16,16,16,16,
  145803. };
  145804. static float _vq_quantthresh__44u8_p9_1[] = {
  145805. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  145806. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  145807. 367.5, 416.5,
  145808. };
  145809. static long _vq_quantmap__44u8_p9_1[] = {
  145810. 17, 15, 13, 11, 9, 7, 5, 3,
  145811. 1, 0, 2, 4, 6, 8, 10, 12,
  145812. 14, 16, 18,
  145813. };
  145814. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  145815. _vq_quantthresh__44u8_p9_1,
  145816. _vq_quantmap__44u8_p9_1,
  145817. 19,
  145818. 19
  145819. };
  145820. static static_codebook _44u8_p9_1 = {
  145821. 2, 361,
  145822. _vq_lengthlist__44u8_p9_1,
  145823. 1, -518287360, 1622704128, 5, 0,
  145824. _vq_quantlist__44u8_p9_1,
  145825. NULL,
  145826. &_vq_auxt__44u8_p9_1,
  145827. NULL,
  145828. 0
  145829. };
  145830. static long _vq_quantlist__44u8_p9_2[] = {
  145831. 24,
  145832. 23,
  145833. 25,
  145834. 22,
  145835. 26,
  145836. 21,
  145837. 27,
  145838. 20,
  145839. 28,
  145840. 19,
  145841. 29,
  145842. 18,
  145843. 30,
  145844. 17,
  145845. 31,
  145846. 16,
  145847. 32,
  145848. 15,
  145849. 33,
  145850. 14,
  145851. 34,
  145852. 13,
  145853. 35,
  145854. 12,
  145855. 36,
  145856. 11,
  145857. 37,
  145858. 10,
  145859. 38,
  145860. 9,
  145861. 39,
  145862. 8,
  145863. 40,
  145864. 7,
  145865. 41,
  145866. 6,
  145867. 42,
  145868. 5,
  145869. 43,
  145870. 4,
  145871. 44,
  145872. 3,
  145873. 45,
  145874. 2,
  145875. 46,
  145876. 1,
  145877. 47,
  145878. 0,
  145879. 48,
  145880. };
  145881. static long _vq_lengthlist__44u8_p9_2[] = {
  145882. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  145883. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145884. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145885. 7,
  145886. };
  145887. static float _vq_quantthresh__44u8_p9_2[] = {
  145888. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145889. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145890. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145891. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145892. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145893. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145894. };
  145895. static long _vq_quantmap__44u8_p9_2[] = {
  145896. 47, 45, 43, 41, 39, 37, 35, 33,
  145897. 31, 29, 27, 25, 23, 21, 19, 17,
  145898. 15, 13, 11, 9, 7, 5, 3, 1,
  145899. 0, 2, 4, 6, 8, 10, 12, 14,
  145900. 16, 18, 20, 22, 24, 26, 28, 30,
  145901. 32, 34, 36, 38, 40, 42, 44, 46,
  145902. 48,
  145903. };
  145904. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  145905. _vq_quantthresh__44u8_p9_2,
  145906. _vq_quantmap__44u8_p9_2,
  145907. 49,
  145908. 49
  145909. };
  145910. static static_codebook _44u8_p9_2 = {
  145911. 1, 49,
  145912. _vq_lengthlist__44u8_p9_2,
  145913. 1, -526909440, 1611661312, 6, 0,
  145914. _vq_quantlist__44u8_p9_2,
  145915. NULL,
  145916. &_vq_auxt__44u8_p9_2,
  145917. NULL,
  145918. 0
  145919. };
  145920. static long _huff_lengthlist__44u9__long[] = {
  145921. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  145922. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  145923. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  145924. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  145925. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  145926. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  145927. 10, 8, 8, 9,
  145928. };
  145929. static static_codebook _huff_book__44u9__long = {
  145930. 2, 100,
  145931. _huff_lengthlist__44u9__long,
  145932. 0, 0, 0, 0, 0,
  145933. NULL,
  145934. NULL,
  145935. NULL,
  145936. NULL,
  145937. 0
  145938. };
  145939. static long _huff_lengthlist__44u9__short[] = {
  145940. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  145941. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  145942. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  145943. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  145944. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  145945. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  145946. 9, 9,12,15,
  145947. };
  145948. static static_codebook _huff_book__44u9__short = {
  145949. 2, 100,
  145950. _huff_lengthlist__44u9__short,
  145951. 0, 0, 0, 0, 0,
  145952. NULL,
  145953. NULL,
  145954. NULL,
  145955. NULL,
  145956. 0
  145957. };
  145958. static long _vq_quantlist__44u9_p1_0[] = {
  145959. 1,
  145960. 0,
  145961. 2,
  145962. };
  145963. static long _vq_lengthlist__44u9_p1_0[] = {
  145964. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  145965. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  145966. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  145967. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  145968. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  145969. 10,
  145970. };
  145971. static float _vq_quantthresh__44u9_p1_0[] = {
  145972. -0.5, 0.5,
  145973. };
  145974. static long _vq_quantmap__44u9_p1_0[] = {
  145975. 1, 0, 2,
  145976. };
  145977. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  145978. _vq_quantthresh__44u9_p1_0,
  145979. _vq_quantmap__44u9_p1_0,
  145980. 3,
  145981. 3
  145982. };
  145983. static static_codebook _44u9_p1_0 = {
  145984. 4, 81,
  145985. _vq_lengthlist__44u9_p1_0,
  145986. 1, -535822336, 1611661312, 2, 0,
  145987. _vq_quantlist__44u9_p1_0,
  145988. NULL,
  145989. &_vq_auxt__44u9_p1_0,
  145990. NULL,
  145991. 0
  145992. };
  145993. static long _vq_quantlist__44u9_p2_0[] = {
  145994. 2,
  145995. 1,
  145996. 3,
  145997. 0,
  145998. 4,
  145999. };
  146000. static long _vq_lengthlist__44u9_p2_0[] = {
  146001. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  146002. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  146003. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  146004. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  146005. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  146006. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  146007. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  146008. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  146009. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  146010. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  146011. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  146012. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  146013. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  146014. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  146015. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  146016. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  146017. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  146018. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  146019. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  146020. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  146021. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  146022. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  146023. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  146024. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  146025. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  146026. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  146027. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  146028. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  146029. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  146030. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  146031. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  146032. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  146033. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  146034. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  146035. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  146036. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  146037. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  146038. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  146039. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  146040. 14,
  146041. };
  146042. static float _vq_quantthresh__44u9_p2_0[] = {
  146043. -1.5, -0.5, 0.5, 1.5,
  146044. };
  146045. static long _vq_quantmap__44u9_p2_0[] = {
  146046. 3, 1, 0, 2, 4,
  146047. };
  146048. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  146049. _vq_quantthresh__44u9_p2_0,
  146050. _vq_quantmap__44u9_p2_0,
  146051. 5,
  146052. 5
  146053. };
  146054. static static_codebook _44u9_p2_0 = {
  146055. 4, 625,
  146056. _vq_lengthlist__44u9_p2_0,
  146057. 1, -533725184, 1611661312, 3, 0,
  146058. _vq_quantlist__44u9_p2_0,
  146059. NULL,
  146060. &_vq_auxt__44u9_p2_0,
  146061. NULL,
  146062. 0
  146063. };
  146064. static long _vq_quantlist__44u9_p3_0[] = {
  146065. 4,
  146066. 3,
  146067. 5,
  146068. 2,
  146069. 6,
  146070. 1,
  146071. 7,
  146072. 0,
  146073. 8,
  146074. };
  146075. static long _vq_lengthlist__44u9_p3_0[] = {
  146076. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  146077. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  146078. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  146079. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  146080. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  146081. 11,
  146082. };
  146083. static float _vq_quantthresh__44u9_p3_0[] = {
  146084. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146085. };
  146086. static long _vq_quantmap__44u9_p3_0[] = {
  146087. 7, 5, 3, 1, 0, 2, 4, 6,
  146088. 8,
  146089. };
  146090. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  146091. _vq_quantthresh__44u9_p3_0,
  146092. _vq_quantmap__44u9_p3_0,
  146093. 9,
  146094. 9
  146095. };
  146096. static static_codebook _44u9_p3_0 = {
  146097. 2, 81,
  146098. _vq_lengthlist__44u9_p3_0,
  146099. 1, -531628032, 1611661312, 4, 0,
  146100. _vq_quantlist__44u9_p3_0,
  146101. NULL,
  146102. &_vq_auxt__44u9_p3_0,
  146103. NULL,
  146104. 0
  146105. };
  146106. static long _vq_quantlist__44u9_p4_0[] = {
  146107. 8,
  146108. 7,
  146109. 9,
  146110. 6,
  146111. 10,
  146112. 5,
  146113. 11,
  146114. 4,
  146115. 12,
  146116. 3,
  146117. 13,
  146118. 2,
  146119. 14,
  146120. 1,
  146121. 15,
  146122. 0,
  146123. 16,
  146124. };
  146125. static long _vq_lengthlist__44u9_p4_0[] = {
  146126. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  146127. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  146128. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  146129. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  146130. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  146131. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  146132. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  146133. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  146134. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  146135. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  146136. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  146137. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  146138. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  146139. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  146140. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  146141. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  146142. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  146143. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  146144. 14,
  146145. };
  146146. static float _vq_quantthresh__44u9_p4_0[] = {
  146147. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146148. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146149. };
  146150. static long _vq_quantmap__44u9_p4_0[] = {
  146151. 15, 13, 11, 9, 7, 5, 3, 1,
  146152. 0, 2, 4, 6, 8, 10, 12, 14,
  146153. 16,
  146154. };
  146155. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  146156. _vq_quantthresh__44u9_p4_0,
  146157. _vq_quantmap__44u9_p4_0,
  146158. 17,
  146159. 17
  146160. };
  146161. static static_codebook _44u9_p4_0 = {
  146162. 2, 289,
  146163. _vq_lengthlist__44u9_p4_0,
  146164. 1, -529530880, 1611661312, 5, 0,
  146165. _vq_quantlist__44u9_p4_0,
  146166. NULL,
  146167. &_vq_auxt__44u9_p4_0,
  146168. NULL,
  146169. 0
  146170. };
  146171. static long _vq_quantlist__44u9_p5_0[] = {
  146172. 1,
  146173. 0,
  146174. 2,
  146175. };
  146176. static long _vq_lengthlist__44u9_p5_0[] = {
  146177. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  146178. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  146179. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  146180. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  146181. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  146182. 10,
  146183. };
  146184. static float _vq_quantthresh__44u9_p5_0[] = {
  146185. -5.5, 5.5,
  146186. };
  146187. static long _vq_quantmap__44u9_p5_0[] = {
  146188. 1, 0, 2,
  146189. };
  146190. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  146191. _vq_quantthresh__44u9_p5_0,
  146192. _vq_quantmap__44u9_p5_0,
  146193. 3,
  146194. 3
  146195. };
  146196. static static_codebook _44u9_p5_0 = {
  146197. 4, 81,
  146198. _vq_lengthlist__44u9_p5_0,
  146199. 1, -529137664, 1618345984, 2, 0,
  146200. _vq_quantlist__44u9_p5_0,
  146201. NULL,
  146202. &_vq_auxt__44u9_p5_0,
  146203. NULL,
  146204. 0
  146205. };
  146206. static long _vq_quantlist__44u9_p5_1[] = {
  146207. 5,
  146208. 4,
  146209. 6,
  146210. 3,
  146211. 7,
  146212. 2,
  146213. 8,
  146214. 1,
  146215. 9,
  146216. 0,
  146217. 10,
  146218. };
  146219. static long _vq_lengthlist__44u9_p5_1[] = {
  146220. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  146221. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  146222. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  146223. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  146224. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  146225. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  146226. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  146227. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146228. };
  146229. static float _vq_quantthresh__44u9_p5_1[] = {
  146230. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146231. 3.5, 4.5,
  146232. };
  146233. static long _vq_quantmap__44u9_p5_1[] = {
  146234. 9, 7, 5, 3, 1, 0, 2, 4,
  146235. 6, 8, 10,
  146236. };
  146237. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  146238. _vq_quantthresh__44u9_p5_1,
  146239. _vq_quantmap__44u9_p5_1,
  146240. 11,
  146241. 11
  146242. };
  146243. static static_codebook _44u9_p5_1 = {
  146244. 2, 121,
  146245. _vq_lengthlist__44u9_p5_1,
  146246. 1, -531365888, 1611661312, 4, 0,
  146247. _vq_quantlist__44u9_p5_1,
  146248. NULL,
  146249. &_vq_auxt__44u9_p5_1,
  146250. NULL,
  146251. 0
  146252. };
  146253. static long _vq_quantlist__44u9_p6_0[] = {
  146254. 6,
  146255. 5,
  146256. 7,
  146257. 4,
  146258. 8,
  146259. 3,
  146260. 9,
  146261. 2,
  146262. 10,
  146263. 1,
  146264. 11,
  146265. 0,
  146266. 12,
  146267. };
  146268. static long _vq_lengthlist__44u9_p6_0[] = {
  146269. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  146270. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  146271. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  146272. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  146273. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  146274. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  146275. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  146276. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  146277. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  146278. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  146279. 10,11,11,11,11,12,11,12,12,
  146280. };
  146281. static float _vq_quantthresh__44u9_p6_0[] = {
  146282. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146283. 12.5, 17.5, 22.5, 27.5,
  146284. };
  146285. static long _vq_quantmap__44u9_p6_0[] = {
  146286. 11, 9, 7, 5, 3, 1, 0, 2,
  146287. 4, 6, 8, 10, 12,
  146288. };
  146289. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  146290. _vq_quantthresh__44u9_p6_0,
  146291. _vq_quantmap__44u9_p6_0,
  146292. 13,
  146293. 13
  146294. };
  146295. static static_codebook _44u9_p6_0 = {
  146296. 2, 169,
  146297. _vq_lengthlist__44u9_p6_0,
  146298. 1, -526516224, 1616117760, 4, 0,
  146299. _vq_quantlist__44u9_p6_0,
  146300. NULL,
  146301. &_vq_auxt__44u9_p6_0,
  146302. NULL,
  146303. 0
  146304. };
  146305. static long _vq_quantlist__44u9_p6_1[] = {
  146306. 2,
  146307. 1,
  146308. 3,
  146309. 0,
  146310. 4,
  146311. };
  146312. static long _vq_lengthlist__44u9_p6_1[] = {
  146313. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  146314. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  146315. };
  146316. static float _vq_quantthresh__44u9_p6_1[] = {
  146317. -1.5, -0.5, 0.5, 1.5,
  146318. };
  146319. static long _vq_quantmap__44u9_p6_1[] = {
  146320. 3, 1, 0, 2, 4,
  146321. };
  146322. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  146323. _vq_quantthresh__44u9_p6_1,
  146324. _vq_quantmap__44u9_p6_1,
  146325. 5,
  146326. 5
  146327. };
  146328. static static_codebook _44u9_p6_1 = {
  146329. 2, 25,
  146330. _vq_lengthlist__44u9_p6_1,
  146331. 1, -533725184, 1611661312, 3, 0,
  146332. _vq_quantlist__44u9_p6_1,
  146333. NULL,
  146334. &_vq_auxt__44u9_p6_1,
  146335. NULL,
  146336. 0
  146337. };
  146338. static long _vq_quantlist__44u9_p7_0[] = {
  146339. 6,
  146340. 5,
  146341. 7,
  146342. 4,
  146343. 8,
  146344. 3,
  146345. 9,
  146346. 2,
  146347. 10,
  146348. 1,
  146349. 11,
  146350. 0,
  146351. 12,
  146352. };
  146353. static long _vq_lengthlist__44u9_p7_0[] = {
  146354. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  146355. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  146356. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  146357. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  146358. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  146359. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  146360. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  146361. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  146362. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  146363. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  146364. 12,13,13,14,14,14,15,15,15,
  146365. };
  146366. static float _vq_quantthresh__44u9_p7_0[] = {
  146367. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  146368. 27.5, 38.5, 49.5, 60.5,
  146369. };
  146370. static long _vq_quantmap__44u9_p7_0[] = {
  146371. 11, 9, 7, 5, 3, 1, 0, 2,
  146372. 4, 6, 8, 10, 12,
  146373. };
  146374. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  146375. _vq_quantthresh__44u9_p7_0,
  146376. _vq_quantmap__44u9_p7_0,
  146377. 13,
  146378. 13
  146379. };
  146380. static static_codebook _44u9_p7_0 = {
  146381. 2, 169,
  146382. _vq_lengthlist__44u9_p7_0,
  146383. 1, -523206656, 1618345984, 4, 0,
  146384. _vq_quantlist__44u9_p7_0,
  146385. NULL,
  146386. &_vq_auxt__44u9_p7_0,
  146387. NULL,
  146388. 0
  146389. };
  146390. static long _vq_quantlist__44u9_p7_1[] = {
  146391. 5,
  146392. 4,
  146393. 6,
  146394. 3,
  146395. 7,
  146396. 2,
  146397. 8,
  146398. 1,
  146399. 9,
  146400. 0,
  146401. 10,
  146402. };
  146403. static long _vq_lengthlist__44u9_p7_1[] = {
  146404. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  146405. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  146406. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  146407. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146408. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146409. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146410. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  146411. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  146412. };
  146413. static float _vq_quantthresh__44u9_p7_1[] = {
  146414. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146415. 3.5, 4.5,
  146416. };
  146417. static long _vq_quantmap__44u9_p7_1[] = {
  146418. 9, 7, 5, 3, 1, 0, 2, 4,
  146419. 6, 8, 10,
  146420. };
  146421. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  146422. _vq_quantthresh__44u9_p7_1,
  146423. _vq_quantmap__44u9_p7_1,
  146424. 11,
  146425. 11
  146426. };
  146427. static static_codebook _44u9_p7_1 = {
  146428. 2, 121,
  146429. _vq_lengthlist__44u9_p7_1,
  146430. 1, -531365888, 1611661312, 4, 0,
  146431. _vq_quantlist__44u9_p7_1,
  146432. NULL,
  146433. &_vq_auxt__44u9_p7_1,
  146434. NULL,
  146435. 0
  146436. };
  146437. static long _vq_quantlist__44u9_p8_0[] = {
  146438. 7,
  146439. 6,
  146440. 8,
  146441. 5,
  146442. 9,
  146443. 4,
  146444. 10,
  146445. 3,
  146446. 11,
  146447. 2,
  146448. 12,
  146449. 1,
  146450. 13,
  146451. 0,
  146452. 14,
  146453. };
  146454. static long _vq_lengthlist__44u9_p8_0[] = {
  146455. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  146456. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  146457. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  146458. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  146459. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  146460. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  146461. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  146462. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  146463. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  146464. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  146465. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  146466. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  146467. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  146468. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  146469. 15,
  146470. };
  146471. static float _vq_quantthresh__44u9_p8_0[] = {
  146472. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  146473. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  146474. };
  146475. static long _vq_quantmap__44u9_p8_0[] = {
  146476. 13, 11, 9, 7, 5, 3, 1, 0,
  146477. 2, 4, 6, 8, 10, 12, 14,
  146478. };
  146479. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  146480. _vq_quantthresh__44u9_p8_0,
  146481. _vq_quantmap__44u9_p8_0,
  146482. 15,
  146483. 15
  146484. };
  146485. static static_codebook _44u9_p8_0 = {
  146486. 2, 225,
  146487. _vq_lengthlist__44u9_p8_0,
  146488. 1, -520986624, 1620377600, 4, 0,
  146489. _vq_quantlist__44u9_p8_0,
  146490. NULL,
  146491. &_vq_auxt__44u9_p8_0,
  146492. NULL,
  146493. 0
  146494. };
  146495. static long _vq_quantlist__44u9_p8_1[] = {
  146496. 10,
  146497. 9,
  146498. 11,
  146499. 8,
  146500. 12,
  146501. 7,
  146502. 13,
  146503. 6,
  146504. 14,
  146505. 5,
  146506. 15,
  146507. 4,
  146508. 16,
  146509. 3,
  146510. 17,
  146511. 2,
  146512. 18,
  146513. 1,
  146514. 19,
  146515. 0,
  146516. 20,
  146517. };
  146518. static long _vq_lengthlist__44u9_p8_1[] = {
  146519. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146520. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  146521. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  146522. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  146523. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146524. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  146525. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  146526. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  146527. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146528. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146529. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  146530. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  146531. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  146532. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  146533. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146534. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146535. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  146536. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  146537. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  146538. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  146539. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146540. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  146541. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  146542. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  146543. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146544. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  146545. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  146546. 10,10,10,10,10,10,10,10,10,
  146547. };
  146548. static float _vq_quantthresh__44u9_p8_1[] = {
  146549. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  146550. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  146551. 6.5, 7.5, 8.5, 9.5,
  146552. };
  146553. static long _vq_quantmap__44u9_p8_1[] = {
  146554. 19, 17, 15, 13, 11, 9, 7, 5,
  146555. 3, 1, 0, 2, 4, 6, 8, 10,
  146556. 12, 14, 16, 18, 20,
  146557. };
  146558. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  146559. _vq_quantthresh__44u9_p8_1,
  146560. _vq_quantmap__44u9_p8_1,
  146561. 21,
  146562. 21
  146563. };
  146564. static static_codebook _44u9_p8_1 = {
  146565. 2, 441,
  146566. _vq_lengthlist__44u9_p8_1,
  146567. 1, -529268736, 1611661312, 5, 0,
  146568. _vq_quantlist__44u9_p8_1,
  146569. NULL,
  146570. &_vq_auxt__44u9_p8_1,
  146571. NULL,
  146572. 0
  146573. };
  146574. static long _vq_quantlist__44u9_p9_0[] = {
  146575. 7,
  146576. 6,
  146577. 8,
  146578. 5,
  146579. 9,
  146580. 4,
  146581. 10,
  146582. 3,
  146583. 11,
  146584. 2,
  146585. 12,
  146586. 1,
  146587. 13,
  146588. 0,
  146589. 14,
  146590. };
  146591. static long _vq_lengthlist__44u9_p9_0[] = {
  146592. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  146593. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  146594. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146595. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146596. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146597. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146598. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146599. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146600. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146601. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146602. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146603. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146604. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146605. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146606. 10,
  146607. };
  146608. static float _vq_quantthresh__44u9_p9_0[] = {
  146609. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  146610. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  146611. };
  146612. static long _vq_quantmap__44u9_p9_0[] = {
  146613. 13, 11, 9, 7, 5, 3, 1, 0,
  146614. 2, 4, 6, 8, 10, 12, 14,
  146615. };
  146616. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  146617. _vq_quantthresh__44u9_p9_0,
  146618. _vq_quantmap__44u9_p9_0,
  146619. 15,
  146620. 15
  146621. };
  146622. static static_codebook _44u9_p9_0 = {
  146623. 2, 225,
  146624. _vq_lengthlist__44u9_p9_0,
  146625. 1, -510036736, 1631393792, 4, 0,
  146626. _vq_quantlist__44u9_p9_0,
  146627. NULL,
  146628. &_vq_auxt__44u9_p9_0,
  146629. NULL,
  146630. 0
  146631. };
  146632. static long _vq_quantlist__44u9_p9_1[] = {
  146633. 9,
  146634. 8,
  146635. 10,
  146636. 7,
  146637. 11,
  146638. 6,
  146639. 12,
  146640. 5,
  146641. 13,
  146642. 4,
  146643. 14,
  146644. 3,
  146645. 15,
  146646. 2,
  146647. 16,
  146648. 1,
  146649. 17,
  146650. 0,
  146651. 18,
  146652. };
  146653. static long _vq_lengthlist__44u9_p9_1[] = {
  146654. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  146655. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  146656. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  146657. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  146658. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  146659. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  146660. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  146661. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  146662. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  146663. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  146664. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  146665. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  146666. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  146667. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  146668. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  146669. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  146670. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  146671. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  146672. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  146673. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  146674. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  146675. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  146676. 17,17,15,17,15,17,16,16,17,
  146677. };
  146678. static float _vq_quantthresh__44u9_p9_1[] = {
  146679. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  146680. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  146681. 367.5, 416.5,
  146682. };
  146683. static long _vq_quantmap__44u9_p9_1[] = {
  146684. 17, 15, 13, 11, 9, 7, 5, 3,
  146685. 1, 0, 2, 4, 6, 8, 10, 12,
  146686. 14, 16, 18,
  146687. };
  146688. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  146689. _vq_quantthresh__44u9_p9_1,
  146690. _vq_quantmap__44u9_p9_1,
  146691. 19,
  146692. 19
  146693. };
  146694. static static_codebook _44u9_p9_1 = {
  146695. 2, 361,
  146696. _vq_lengthlist__44u9_p9_1,
  146697. 1, -518287360, 1622704128, 5, 0,
  146698. _vq_quantlist__44u9_p9_1,
  146699. NULL,
  146700. &_vq_auxt__44u9_p9_1,
  146701. NULL,
  146702. 0
  146703. };
  146704. static long _vq_quantlist__44u9_p9_2[] = {
  146705. 24,
  146706. 23,
  146707. 25,
  146708. 22,
  146709. 26,
  146710. 21,
  146711. 27,
  146712. 20,
  146713. 28,
  146714. 19,
  146715. 29,
  146716. 18,
  146717. 30,
  146718. 17,
  146719. 31,
  146720. 16,
  146721. 32,
  146722. 15,
  146723. 33,
  146724. 14,
  146725. 34,
  146726. 13,
  146727. 35,
  146728. 12,
  146729. 36,
  146730. 11,
  146731. 37,
  146732. 10,
  146733. 38,
  146734. 9,
  146735. 39,
  146736. 8,
  146737. 40,
  146738. 7,
  146739. 41,
  146740. 6,
  146741. 42,
  146742. 5,
  146743. 43,
  146744. 4,
  146745. 44,
  146746. 3,
  146747. 45,
  146748. 2,
  146749. 46,
  146750. 1,
  146751. 47,
  146752. 0,
  146753. 48,
  146754. };
  146755. static long _vq_lengthlist__44u9_p9_2[] = {
  146756. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  146757. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146758. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146759. 7,
  146760. };
  146761. static float _vq_quantthresh__44u9_p9_2[] = {
  146762. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  146763. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  146764. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146765. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146766. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  146767. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  146768. };
  146769. static long _vq_quantmap__44u9_p9_2[] = {
  146770. 47, 45, 43, 41, 39, 37, 35, 33,
  146771. 31, 29, 27, 25, 23, 21, 19, 17,
  146772. 15, 13, 11, 9, 7, 5, 3, 1,
  146773. 0, 2, 4, 6, 8, 10, 12, 14,
  146774. 16, 18, 20, 22, 24, 26, 28, 30,
  146775. 32, 34, 36, 38, 40, 42, 44, 46,
  146776. 48,
  146777. };
  146778. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  146779. _vq_quantthresh__44u9_p9_2,
  146780. _vq_quantmap__44u9_p9_2,
  146781. 49,
  146782. 49
  146783. };
  146784. static static_codebook _44u9_p9_2 = {
  146785. 1, 49,
  146786. _vq_lengthlist__44u9_p9_2,
  146787. 1, -526909440, 1611661312, 6, 0,
  146788. _vq_quantlist__44u9_p9_2,
  146789. NULL,
  146790. &_vq_auxt__44u9_p9_2,
  146791. NULL,
  146792. 0
  146793. };
  146794. static long _huff_lengthlist__44un1__long[] = {
  146795. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  146796. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  146797. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  146798. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  146799. };
  146800. static static_codebook _huff_book__44un1__long = {
  146801. 2, 64,
  146802. _huff_lengthlist__44un1__long,
  146803. 0, 0, 0, 0, 0,
  146804. NULL,
  146805. NULL,
  146806. NULL,
  146807. NULL,
  146808. 0
  146809. };
  146810. static long _vq_quantlist__44un1__p1_0[] = {
  146811. 1,
  146812. 0,
  146813. 2,
  146814. };
  146815. static long _vq_lengthlist__44un1__p1_0[] = {
  146816. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  146817. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  146818. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  146819. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  146820. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  146821. 12,
  146822. };
  146823. static float _vq_quantthresh__44un1__p1_0[] = {
  146824. -0.5, 0.5,
  146825. };
  146826. static long _vq_quantmap__44un1__p1_0[] = {
  146827. 1, 0, 2,
  146828. };
  146829. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  146830. _vq_quantthresh__44un1__p1_0,
  146831. _vq_quantmap__44un1__p1_0,
  146832. 3,
  146833. 3
  146834. };
  146835. static static_codebook _44un1__p1_0 = {
  146836. 4, 81,
  146837. _vq_lengthlist__44un1__p1_0,
  146838. 1, -535822336, 1611661312, 2, 0,
  146839. _vq_quantlist__44un1__p1_0,
  146840. NULL,
  146841. &_vq_auxt__44un1__p1_0,
  146842. NULL,
  146843. 0
  146844. };
  146845. static long _vq_quantlist__44un1__p2_0[] = {
  146846. 1,
  146847. 0,
  146848. 2,
  146849. };
  146850. static long _vq_lengthlist__44un1__p2_0[] = {
  146851. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146852. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  146853. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  146854. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  146855. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  146856. 8,
  146857. };
  146858. static float _vq_quantthresh__44un1__p2_0[] = {
  146859. -0.5, 0.5,
  146860. };
  146861. static long _vq_quantmap__44un1__p2_0[] = {
  146862. 1, 0, 2,
  146863. };
  146864. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  146865. _vq_quantthresh__44un1__p2_0,
  146866. _vq_quantmap__44un1__p2_0,
  146867. 3,
  146868. 3
  146869. };
  146870. static static_codebook _44un1__p2_0 = {
  146871. 4, 81,
  146872. _vq_lengthlist__44un1__p2_0,
  146873. 1, -535822336, 1611661312, 2, 0,
  146874. _vq_quantlist__44un1__p2_0,
  146875. NULL,
  146876. &_vq_auxt__44un1__p2_0,
  146877. NULL,
  146878. 0
  146879. };
  146880. static long _vq_quantlist__44un1__p3_0[] = {
  146881. 2,
  146882. 1,
  146883. 3,
  146884. 0,
  146885. 4,
  146886. };
  146887. static long _vq_lengthlist__44un1__p3_0[] = {
  146888. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146889. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  146890. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  146891. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  146892. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  146893. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  146894. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  146895. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  146896. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  146897. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  146898. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  146899. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  146900. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  146901. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  146902. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  146903. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  146904. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  146905. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  146906. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  146907. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  146908. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  146909. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  146910. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  146911. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  146912. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  146913. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  146914. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  146915. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  146916. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  146917. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  146918. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  146919. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  146920. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  146921. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  146922. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  146923. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  146924. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  146925. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  146926. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  146927. 17,
  146928. };
  146929. static float _vq_quantthresh__44un1__p3_0[] = {
  146930. -1.5, -0.5, 0.5, 1.5,
  146931. };
  146932. static long _vq_quantmap__44un1__p3_0[] = {
  146933. 3, 1, 0, 2, 4,
  146934. };
  146935. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  146936. _vq_quantthresh__44un1__p3_0,
  146937. _vq_quantmap__44un1__p3_0,
  146938. 5,
  146939. 5
  146940. };
  146941. static static_codebook _44un1__p3_0 = {
  146942. 4, 625,
  146943. _vq_lengthlist__44un1__p3_0,
  146944. 1, -533725184, 1611661312, 3, 0,
  146945. _vq_quantlist__44un1__p3_0,
  146946. NULL,
  146947. &_vq_auxt__44un1__p3_0,
  146948. NULL,
  146949. 0
  146950. };
  146951. static long _vq_quantlist__44un1__p4_0[] = {
  146952. 2,
  146953. 1,
  146954. 3,
  146955. 0,
  146956. 4,
  146957. };
  146958. static long _vq_lengthlist__44un1__p4_0[] = {
  146959. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  146960. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  146961. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  146962. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  146963. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  146964. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  146965. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  146966. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  146967. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  146968. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  146969. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  146970. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  146971. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  146972. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  146973. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  146974. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  146975. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  146976. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  146977. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  146978. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  146979. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  146980. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  146981. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  146982. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  146983. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  146984. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  146985. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  146986. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  146987. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  146988. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  146989. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  146990. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  146991. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  146992. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  146993. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  146994. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  146995. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  146996. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  146997. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  146998. 12,
  146999. };
  147000. static float _vq_quantthresh__44un1__p4_0[] = {
  147001. -1.5, -0.5, 0.5, 1.5,
  147002. };
  147003. static long _vq_quantmap__44un1__p4_0[] = {
  147004. 3, 1, 0, 2, 4,
  147005. };
  147006. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  147007. _vq_quantthresh__44un1__p4_0,
  147008. _vq_quantmap__44un1__p4_0,
  147009. 5,
  147010. 5
  147011. };
  147012. static static_codebook _44un1__p4_0 = {
  147013. 4, 625,
  147014. _vq_lengthlist__44un1__p4_0,
  147015. 1, -533725184, 1611661312, 3, 0,
  147016. _vq_quantlist__44un1__p4_0,
  147017. NULL,
  147018. &_vq_auxt__44un1__p4_0,
  147019. NULL,
  147020. 0
  147021. };
  147022. static long _vq_quantlist__44un1__p5_0[] = {
  147023. 4,
  147024. 3,
  147025. 5,
  147026. 2,
  147027. 6,
  147028. 1,
  147029. 7,
  147030. 0,
  147031. 8,
  147032. };
  147033. static long _vq_lengthlist__44un1__p5_0[] = {
  147034. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  147035. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  147036. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  147037. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  147038. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  147039. 12,
  147040. };
  147041. static float _vq_quantthresh__44un1__p5_0[] = {
  147042. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147043. };
  147044. static long _vq_quantmap__44un1__p5_0[] = {
  147045. 7, 5, 3, 1, 0, 2, 4, 6,
  147046. 8,
  147047. };
  147048. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  147049. _vq_quantthresh__44un1__p5_0,
  147050. _vq_quantmap__44un1__p5_0,
  147051. 9,
  147052. 9
  147053. };
  147054. static static_codebook _44un1__p5_0 = {
  147055. 2, 81,
  147056. _vq_lengthlist__44un1__p5_0,
  147057. 1, -531628032, 1611661312, 4, 0,
  147058. _vq_quantlist__44un1__p5_0,
  147059. NULL,
  147060. &_vq_auxt__44un1__p5_0,
  147061. NULL,
  147062. 0
  147063. };
  147064. static long _vq_quantlist__44un1__p6_0[] = {
  147065. 6,
  147066. 5,
  147067. 7,
  147068. 4,
  147069. 8,
  147070. 3,
  147071. 9,
  147072. 2,
  147073. 10,
  147074. 1,
  147075. 11,
  147076. 0,
  147077. 12,
  147078. };
  147079. static long _vq_lengthlist__44un1__p6_0[] = {
  147080. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  147081. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  147082. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  147083. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  147084. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  147085. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  147086. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  147087. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  147088. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  147089. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  147090. 16, 0,15,18,18, 0,16, 0, 0,
  147091. };
  147092. static float _vq_quantthresh__44un1__p6_0[] = {
  147093. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147094. 12.5, 17.5, 22.5, 27.5,
  147095. };
  147096. static long _vq_quantmap__44un1__p6_0[] = {
  147097. 11, 9, 7, 5, 3, 1, 0, 2,
  147098. 4, 6, 8, 10, 12,
  147099. };
  147100. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  147101. _vq_quantthresh__44un1__p6_0,
  147102. _vq_quantmap__44un1__p6_0,
  147103. 13,
  147104. 13
  147105. };
  147106. static static_codebook _44un1__p6_0 = {
  147107. 2, 169,
  147108. _vq_lengthlist__44un1__p6_0,
  147109. 1, -526516224, 1616117760, 4, 0,
  147110. _vq_quantlist__44un1__p6_0,
  147111. NULL,
  147112. &_vq_auxt__44un1__p6_0,
  147113. NULL,
  147114. 0
  147115. };
  147116. static long _vq_quantlist__44un1__p6_1[] = {
  147117. 2,
  147118. 1,
  147119. 3,
  147120. 0,
  147121. 4,
  147122. };
  147123. static long _vq_lengthlist__44un1__p6_1[] = {
  147124. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  147125. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  147126. };
  147127. static float _vq_quantthresh__44un1__p6_1[] = {
  147128. -1.5, -0.5, 0.5, 1.5,
  147129. };
  147130. static long _vq_quantmap__44un1__p6_1[] = {
  147131. 3, 1, 0, 2, 4,
  147132. };
  147133. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  147134. _vq_quantthresh__44un1__p6_1,
  147135. _vq_quantmap__44un1__p6_1,
  147136. 5,
  147137. 5
  147138. };
  147139. static static_codebook _44un1__p6_1 = {
  147140. 2, 25,
  147141. _vq_lengthlist__44un1__p6_1,
  147142. 1, -533725184, 1611661312, 3, 0,
  147143. _vq_quantlist__44un1__p6_1,
  147144. NULL,
  147145. &_vq_auxt__44un1__p6_1,
  147146. NULL,
  147147. 0
  147148. };
  147149. static long _vq_quantlist__44un1__p7_0[] = {
  147150. 2,
  147151. 1,
  147152. 3,
  147153. 0,
  147154. 4,
  147155. };
  147156. static long _vq_lengthlist__44un1__p7_0[] = {
  147157. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  147158. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  147159. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147160. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147161. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147162. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147163. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147164. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  147165. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147166. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147167. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  147168. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147169. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147170. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147171. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147172. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  147173. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147174. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  147175. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147176. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147177. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147178. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147179. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147180. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147181. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147182. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147183. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147184. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147185. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147186. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147187. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147188. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147189. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147190. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147191. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147192. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147193. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147194. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147195. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147196. 10,
  147197. };
  147198. static float _vq_quantthresh__44un1__p7_0[] = {
  147199. -253.5, -84.5, 84.5, 253.5,
  147200. };
  147201. static long _vq_quantmap__44un1__p7_0[] = {
  147202. 3, 1, 0, 2, 4,
  147203. };
  147204. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  147205. _vq_quantthresh__44un1__p7_0,
  147206. _vq_quantmap__44un1__p7_0,
  147207. 5,
  147208. 5
  147209. };
  147210. static static_codebook _44un1__p7_0 = {
  147211. 4, 625,
  147212. _vq_lengthlist__44un1__p7_0,
  147213. 1, -518709248, 1626677248, 3, 0,
  147214. _vq_quantlist__44un1__p7_0,
  147215. NULL,
  147216. &_vq_auxt__44un1__p7_0,
  147217. NULL,
  147218. 0
  147219. };
  147220. static long _vq_quantlist__44un1__p7_1[] = {
  147221. 6,
  147222. 5,
  147223. 7,
  147224. 4,
  147225. 8,
  147226. 3,
  147227. 9,
  147228. 2,
  147229. 10,
  147230. 1,
  147231. 11,
  147232. 0,
  147233. 12,
  147234. };
  147235. static long _vq_lengthlist__44un1__p7_1[] = {
  147236. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  147237. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  147238. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  147239. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  147240. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  147241. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  147242. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  147243. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  147244. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  147245. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  147246. 12,13,13,12,13,13,14,14,14,
  147247. };
  147248. static float _vq_quantthresh__44un1__p7_1[] = {
  147249. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147250. 32.5, 45.5, 58.5, 71.5,
  147251. };
  147252. static long _vq_quantmap__44un1__p7_1[] = {
  147253. 11, 9, 7, 5, 3, 1, 0, 2,
  147254. 4, 6, 8, 10, 12,
  147255. };
  147256. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  147257. _vq_quantthresh__44un1__p7_1,
  147258. _vq_quantmap__44un1__p7_1,
  147259. 13,
  147260. 13
  147261. };
  147262. static static_codebook _44un1__p7_1 = {
  147263. 2, 169,
  147264. _vq_lengthlist__44un1__p7_1,
  147265. 1, -523010048, 1618608128, 4, 0,
  147266. _vq_quantlist__44un1__p7_1,
  147267. NULL,
  147268. &_vq_auxt__44un1__p7_1,
  147269. NULL,
  147270. 0
  147271. };
  147272. static long _vq_quantlist__44un1__p7_2[] = {
  147273. 6,
  147274. 5,
  147275. 7,
  147276. 4,
  147277. 8,
  147278. 3,
  147279. 9,
  147280. 2,
  147281. 10,
  147282. 1,
  147283. 11,
  147284. 0,
  147285. 12,
  147286. };
  147287. static long _vq_lengthlist__44un1__p7_2[] = {
  147288. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  147289. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  147290. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  147291. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  147292. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  147293. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  147294. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  147295. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  147296. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  147297. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  147298. 9, 9, 9,10,10,10,10,10,10,
  147299. };
  147300. static float _vq_quantthresh__44un1__p7_2[] = {
  147301. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147302. 2.5, 3.5, 4.5, 5.5,
  147303. };
  147304. static long _vq_quantmap__44un1__p7_2[] = {
  147305. 11, 9, 7, 5, 3, 1, 0, 2,
  147306. 4, 6, 8, 10, 12,
  147307. };
  147308. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  147309. _vq_quantthresh__44un1__p7_2,
  147310. _vq_quantmap__44un1__p7_2,
  147311. 13,
  147312. 13
  147313. };
  147314. static static_codebook _44un1__p7_2 = {
  147315. 2, 169,
  147316. _vq_lengthlist__44un1__p7_2,
  147317. 1, -531103744, 1611661312, 4, 0,
  147318. _vq_quantlist__44un1__p7_2,
  147319. NULL,
  147320. &_vq_auxt__44un1__p7_2,
  147321. NULL,
  147322. 0
  147323. };
  147324. static long _huff_lengthlist__44un1__short[] = {
  147325. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  147326. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  147327. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  147328. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  147329. };
  147330. static static_codebook _huff_book__44un1__short = {
  147331. 2, 64,
  147332. _huff_lengthlist__44un1__short,
  147333. 0, 0, 0, 0, 0,
  147334. NULL,
  147335. NULL,
  147336. NULL,
  147337. NULL,
  147338. 0
  147339. };
  147340. /********* End of inlined file: res_books_uncoupled.h *********/
  147341. /***** residue backends *********************************************/
  147342. static vorbis_info_residue0 _residue_44_low_un={
  147343. 0,-1, -1, 8,-1,
  147344. {0},
  147345. {-1},
  147346. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  147347. { -1, 25, -1, 45, -1, -1, -1}
  147348. };
  147349. static vorbis_info_residue0 _residue_44_mid_un={
  147350. 0,-1, -1, 10,-1,
  147351. /* 0 1 2 3 4 5 6 7 8 9 */
  147352. {0},
  147353. {-1},
  147354. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  147355. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  147356. };
  147357. static vorbis_info_residue0 _residue_44_hi_un={
  147358. 0,-1, -1, 10,-1,
  147359. /* 0 1 2 3 4 5 6 7 8 9 */
  147360. {0},
  147361. {-1},
  147362. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  147363. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  147364. };
  147365. /* mapping conventions:
  147366. only one submap (this would change for efficient 5.1 support for example)*/
  147367. /* Four psychoacoustic profiles are used, one for each blocktype */
  147368. static vorbis_info_mapping0 _map_nominal_u[2]={
  147369. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  147370. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  147371. };
  147372. static static_bookblock _resbook_44u_n1={
  147373. {
  147374. {0},
  147375. {0,0,&_44un1__p1_0},
  147376. {0,0,&_44un1__p2_0},
  147377. {0,0,&_44un1__p3_0},
  147378. {0,0,&_44un1__p4_0},
  147379. {0,0,&_44un1__p5_0},
  147380. {&_44un1__p6_0,&_44un1__p6_1},
  147381. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  147382. }
  147383. };
  147384. static static_bookblock _resbook_44u_0={
  147385. {
  147386. {0},
  147387. {0,0,&_44u0__p1_0},
  147388. {0,0,&_44u0__p2_0},
  147389. {0,0,&_44u0__p3_0},
  147390. {0,0,&_44u0__p4_0},
  147391. {0,0,&_44u0__p5_0},
  147392. {&_44u0__p6_0,&_44u0__p6_1},
  147393. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  147394. }
  147395. };
  147396. static static_bookblock _resbook_44u_1={
  147397. {
  147398. {0},
  147399. {0,0,&_44u1__p1_0},
  147400. {0,0,&_44u1__p2_0},
  147401. {0,0,&_44u1__p3_0},
  147402. {0,0,&_44u1__p4_0},
  147403. {0,0,&_44u1__p5_0},
  147404. {&_44u1__p6_0,&_44u1__p6_1},
  147405. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  147406. }
  147407. };
  147408. static static_bookblock _resbook_44u_2={
  147409. {
  147410. {0},
  147411. {0,0,&_44u2__p1_0},
  147412. {0,0,&_44u2__p2_0},
  147413. {0,0,&_44u2__p3_0},
  147414. {0,0,&_44u2__p4_0},
  147415. {0,0,&_44u2__p5_0},
  147416. {&_44u2__p6_0,&_44u2__p6_1},
  147417. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  147418. }
  147419. };
  147420. static static_bookblock _resbook_44u_3={
  147421. {
  147422. {0},
  147423. {0,0,&_44u3__p1_0},
  147424. {0,0,&_44u3__p2_0},
  147425. {0,0,&_44u3__p3_0},
  147426. {0,0,&_44u3__p4_0},
  147427. {0,0,&_44u3__p5_0},
  147428. {&_44u3__p6_0,&_44u3__p6_1},
  147429. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  147430. }
  147431. };
  147432. static static_bookblock _resbook_44u_4={
  147433. {
  147434. {0},
  147435. {0,0,&_44u4__p1_0},
  147436. {0,0,&_44u4__p2_0},
  147437. {0,0,&_44u4__p3_0},
  147438. {0,0,&_44u4__p4_0},
  147439. {0,0,&_44u4__p5_0},
  147440. {&_44u4__p6_0,&_44u4__p6_1},
  147441. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  147442. }
  147443. };
  147444. static static_bookblock _resbook_44u_5={
  147445. {
  147446. {0},
  147447. {0,0,&_44u5__p1_0},
  147448. {0,0,&_44u5__p2_0},
  147449. {0,0,&_44u5__p3_0},
  147450. {0,0,&_44u5__p4_0},
  147451. {0,0,&_44u5__p5_0},
  147452. {0,0,&_44u5__p6_0},
  147453. {&_44u5__p7_0,&_44u5__p7_1},
  147454. {&_44u5__p8_0,&_44u5__p8_1},
  147455. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  147456. }
  147457. };
  147458. static static_bookblock _resbook_44u_6={
  147459. {
  147460. {0},
  147461. {0,0,&_44u6__p1_0},
  147462. {0,0,&_44u6__p2_0},
  147463. {0,0,&_44u6__p3_0},
  147464. {0,0,&_44u6__p4_0},
  147465. {0,0,&_44u6__p5_0},
  147466. {0,0,&_44u6__p6_0},
  147467. {&_44u6__p7_0,&_44u6__p7_1},
  147468. {&_44u6__p8_0,&_44u6__p8_1},
  147469. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  147470. }
  147471. };
  147472. static static_bookblock _resbook_44u_7={
  147473. {
  147474. {0},
  147475. {0,0,&_44u7__p1_0},
  147476. {0,0,&_44u7__p2_0},
  147477. {0,0,&_44u7__p3_0},
  147478. {0,0,&_44u7__p4_0},
  147479. {0,0,&_44u7__p5_0},
  147480. {0,0,&_44u7__p6_0},
  147481. {&_44u7__p7_0,&_44u7__p7_1},
  147482. {&_44u7__p8_0,&_44u7__p8_1},
  147483. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  147484. }
  147485. };
  147486. static static_bookblock _resbook_44u_8={
  147487. {
  147488. {0},
  147489. {0,0,&_44u8_p1_0},
  147490. {0,0,&_44u8_p2_0},
  147491. {0,0,&_44u8_p3_0},
  147492. {0,0,&_44u8_p4_0},
  147493. {&_44u8_p5_0,&_44u8_p5_1},
  147494. {&_44u8_p6_0,&_44u8_p6_1},
  147495. {&_44u8_p7_0,&_44u8_p7_1},
  147496. {&_44u8_p8_0,&_44u8_p8_1},
  147497. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  147498. }
  147499. };
  147500. static static_bookblock _resbook_44u_9={
  147501. {
  147502. {0},
  147503. {0,0,&_44u9_p1_0},
  147504. {0,0,&_44u9_p2_0},
  147505. {0,0,&_44u9_p3_0},
  147506. {0,0,&_44u9_p4_0},
  147507. {&_44u9_p5_0,&_44u9_p5_1},
  147508. {&_44u9_p6_0,&_44u9_p6_1},
  147509. {&_44u9_p7_0,&_44u9_p7_1},
  147510. {&_44u9_p8_0,&_44u9_p8_1},
  147511. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  147512. }
  147513. };
  147514. static vorbis_residue_template _res_44u_n1[]={
  147515. {1,0, &_residue_44_low_un,
  147516. &_huff_book__44un1__short,&_huff_book__44un1__short,
  147517. &_resbook_44u_n1,&_resbook_44u_n1},
  147518. {1,0, &_residue_44_low_un,
  147519. &_huff_book__44un1__long,&_huff_book__44un1__long,
  147520. &_resbook_44u_n1,&_resbook_44u_n1}
  147521. };
  147522. static vorbis_residue_template _res_44u_0[]={
  147523. {1,0, &_residue_44_low_un,
  147524. &_huff_book__44u0__short,&_huff_book__44u0__short,
  147525. &_resbook_44u_0,&_resbook_44u_0},
  147526. {1,0, &_residue_44_low_un,
  147527. &_huff_book__44u0__long,&_huff_book__44u0__long,
  147528. &_resbook_44u_0,&_resbook_44u_0}
  147529. };
  147530. static vorbis_residue_template _res_44u_1[]={
  147531. {1,0, &_residue_44_low_un,
  147532. &_huff_book__44u1__short,&_huff_book__44u1__short,
  147533. &_resbook_44u_1,&_resbook_44u_1},
  147534. {1,0, &_residue_44_low_un,
  147535. &_huff_book__44u1__long,&_huff_book__44u1__long,
  147536. &_resbook_44u_1,&_resbook_44u_1}
  147537. };
  147538. static vorbis_residue_template _res_44u_2[]={
  147539. {1,0, &_residue_44_low_un,
  147540. &_huff_book__44u2__short,&_huff_book__44u2__short,
  147541. &_resbook_44u_2,&_resbook_44u_2},
  147542. {1,0, &_residue_44_low_un,
  147543. &_huff_book__44u2__long,&_huff_book__44u2__long,
  147544. &_resbook_44u_2,&_resbook_44u_2}
  147545. };
  147546. static vorbis_residue_template _res_44u_3[]={
  147547. {1,0, &_residue_44_low_un,
  147548. &_huff_book__44u3__short,&_huff_book__44u3__short,
  147549. &_resbook_44u_3,&_resbook_44u_3},
  147550. {1,0, &_residue_44_low_un,
  147551. &_huff_book__44u3__long,&_huff_book__44u3__long,
  147552. &_resbook_44u_3,&_resbook_44u_3}
  147553. };
  147554. static vorbis_residue_template _res_44u_4[]={
  147555. {1,0, &_residue_44_low_un,
  147556. &_huff_book__44u4__short,&_huff_book__44u4__short,
  147557. &_resbook_44u_4,&_resbook_44u_4},
  147558. {1,0, &_residue_44_low_un,
  147559. &_huff_book__44u4__long,&_huff_book__44u4__long,
  147560. &_resbook_44u_4,&_resbook_44u_4}
  147561. };
  147562. static vorbis_residue_template _res_44u_5[]={
  147563. {1,0, &_residue_44_mid_un,
  147564. &_huff_book__44u5__short,&_huff_book__44u5__short,
  147565. &_resbook_44u_5,&_resbook_44u_5},
  147566. {1,0, &_residue_44_mid_un,
  147567. &_huff_book__44u5__long,&_huff_book__44u5__long,
  147568. &_resbook_44u_5,&_resbook_44u_5}
  147569. };
  147570. static vorbis_residue_template _res_44u_6[]={
  147571. {1,0, &_residue_44_mid_un,
  147572. &_huff_book__44u6__short,&_huff_book__44u6__short,
  147573. &_resbook_44u_6,&_resbook_44u_6},
  147574. {1,0, &_residue_44_mid_un,
  147575. &_huff_book__44u6__long,&_huff_book__44u6__long,
  147576. &_resbook_44u_6,&_resbook_44u_6}
  147577. };
  147578. static vorbis_residue_template _res_44u_7[]={
  147579. {1,0, &_residue_44_mid_un,
  147580. &_huff_book__44u7__short,&_huff_book__44u7__short,
  147581. &_resbook_44u_7,&_resbook_44u_7},
  147582. {1,0, &_residue_44_mid_un,
  147583. &_huff_book__44u7__long,&_huff_book__44u7__long,
  147584. &_resbook_44u_7,&_resbook_44u_7}
  147585. };
  147586. static vorbis_residue_template _res_44u_8[]={
  147587. {1,0, &_residue_44_hi_un,
  147588. &_huff_book__44u8__short,&_huff_book__44u8__short,
  147589. &_resbook_44u_8,&_resbook_44u_8},
  147590. {1,0, &_residue_44_hi_un,
  147591. &_huff_book__44u8__long,&_huff_book__44u8__long,
  147592. &_resbook_44u_8,&_resbook_44u_8}
  147593. };
  147594. static vorbis_residue_template _res_44u_9[]={
  147595. {1,0, &_residue_44_hi_un,
  147596. &_huff_book__44u9__short,&_huff_book__44u9__short,
  147597. &_resbook_44u_9,&_resbook_44u_9},
  147598. {1,0, &_residue_44_hi_un,
  147599. &_huff_book__44u9__long,&_huff_book__44u9__long,
  147600. &_resbook_44u_9,&_resbook_44u_9}
  147601. };
  147602. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  147603. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  147604. { _map_nominal_u, _res_44u_0 }, /* 0 */
  147605. { _map_nominal_u, _res_44u_1 }, /* 1 */
  147606. { _map_nominal_u, _res_44u_2 }, /* 2 */
  147607. { _map_nominal_u, _res_44u_3 }, /* 3 */
  147608. { _map_nominal_u, _res_44u_4 }, /* 4 */
  147609. { _map_nominal_u, _res_44u_5 }, /* 5 */
  147610. { _map_nominal_u, _res_44u_6 }, /* 6 */
  147611. { _map_nominal_u, _res_44u_7 }, /* 7 */
  147612. { _map_nominal_u, _res_44u_8 }, /* 8 */
  147613. { _map_nominal_u, _res_44u_9 }, /* 9 */
  147614. };
  147615. /********* End of inlined file: residue_44u.h *********/
  147616. static double rate_mapping_44_un[12]={
  147617. 32000.,48000.,60000.,70000.,80000.,86000.,
  147618. 96000.,110000.,120000.,140000.,160000.,240001.
  147619. };
  147620. ve_setup_data_template ve_setup_44_uncoupled={
  147621. 11,
  147622. rate_mapping_44_un,
  147623. quality_mapping_44,
  147624. -1,
  147625. 40000,
  147626. 50000,
  147627. blocksize_short_44,
  147628. blocksize_long_44,
  147629. _psy_tone_masteratt_44,
  147630. _psy_tone_0dB,
  147631. _psy_tone_suppress,
  147632. _vp_tonemask_adj_otherblock,
  147633. _vp_tonemask_adj_longblock,
  147634. _vp_tonemask_adj_otherblock,
  147635. _psy_noiseguards_44,
  147636. _psy_noisebias_impulse,
  147637. _psy_noisebias_padding,
  147638. _psy_noisebias_trans,
  147639. _psy_noisebias_long,
  147640. _psy_noise_suppress,
  147641. _psy_compand_44,
  147642. _psy_compand_short_mapping,
  147643. _psy_compand_long_mapping,
  147644. {_noise_start_short_44,_noise_start_long_44},
  147645. {_noise_part_short_44,_noise_part_long_44},
  147646. _noise_thresh_44,
  147647. _psy_ath_floater,
  147648. _psy_ath_abs,
  147649. _psy_lowpass_44,
  147650. _psy_global_44,
  147651. _global_mapping_44,
  147652. NULL,
  147653. _floor_books,
  147654. _floor,
  147655. _floor_short_mapping_44,
  147656. _floor_long_mapping_44,
  147657. _mapres_template_44_uncoupled
  147658. };
  147659. /********* End of inlined file: setup_44u.h *********/
  147660. /********* Start of inlined file: setup_32.h *********/
  147661. static double rate_mapping_32[12]={
  147662. 18000.,28000.,35000.,45000.,56000.,60000.,
  147663. 75000.,90000.,100000.,115000.,150000.,190000.,
  147664. };
  147665. static double rate_mapping_32_un[12]={
  147666. 30000.,42000.,52000.,64000.,72000.,78000.,
  147667. 86000.,92000.,110000.,120000.,140000.,190000.,
  147668. };
  147669. static double _psy_lowpass_32[12]={
  147670. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  147671. };
  147672. ve_setup_data_template ve_setup_32_stereo={
  147673. 11,
  147674. rate_mapping_32,
  147675. quality_mapping_44,
  147676. 2,
  147677. 26000,
  147678. 40000,
  147679. blocksize_short_44,
  147680. blocksize_long_44,
  147681. _psy_tone_masteratt_44,
  147682. _psy_tone_0dB,
  147683. _psy_tone_suppress,
  147684. _vp_tonemask_adj_otherblock,
  147685. _vp_tonemask_adj_longblock,
  147686. _vp_tonemask_adj_otherblock,
  147687. _psy_noiseguards_44,
  147688. _psy_noisebias_impulse,
  147689. _psy_noisebias_padding,
  147690. _psy_noisebias_trans,
  147691. _psy_noisebias_long,
  147692. _psy_noise_suppress,
  147693. _psy_compand_44,
  147694. _psy_compand_short_mapping,
  147695. _psy_compand_long_mapping,
  147696. {_noise_start_short_44,_noise_start_long_44},
  147697. {_noise_part_short_44,_noise_part_long_44},
  147698. _noise_thresh_44,
  147699. _psy_ath_floater,
  147700. _psy_ath_abs,
  147701. _psy_lowpass_32,
  147702. _psy_global_44,
  147703. _global_mapping_44,
  147704. _psy_stereo_modes_44,
  147705. _floor_books,
  147706. _floor,
  147707. _floor_short_mapping_44,
  147708. _floor_long_mapping_44,
  147709. _mapres_template_44_stereo
  147710. };
  147711. ve_setup_data_template ve_setup_32_uncoupled={
  147712. 11,
  147713. rate_mapping_32_un,
  147714. quality_mapping_44,
  147715. -1,
  147716. 26000,
  147717. 40000,
  147718. blocksize_short_44,
  147719. blocksize_long_44,
  147720. _psy_tone_masteratt_44,
  147721. _psy_tone_0dB,
  147722. _psy_tone_suppress,
  147723. _vp_tonemask_adj_otherblock,
  147724. _vp_tonemask_adj_longblock,
  147725. _vp_tonemask_adj_otherblock,
  147726. _psy_noiseguards_44,
  147727. _psy_noisebias_impulse,
  147728. _psy_noisebias_padding,
  147729. _psy_noisebias_trans,
  147730. _psy_noisebias_long,
  147731. _psy_noise_suppress,
  147732. _psy_compand_44,
  147733. _psy_compand_short_mapping,
  147734. _psy_compand_long_mapping,
  147735. {_noise_start_short_44,_noise_start_long_44},
  147736. {_noise_part_short_44,_noise_part_long_44},
  147737. _noise_thresh_44,
  147738. _psy_ath_floater,
  147739. _psy_ath_abs,
  147740. _psy_lowpass_32,
  147741. _psy_global_44,
  147742. _global_mapping_44,
  147743. NULL,
  147744. _floor_books,
  147745. _floor,
  147746. _floor_short_mapping_44,
  147747. _floor_long_mapping_44,
  147748. _mapres_template_44_uncoupled
  147749. };
  147750. /********* End of inlined file: setup_32.h *********/
  147751. /********* Start of inlined file: setup_8.h *********/
  147752. /********* Start of inlined file: psych_8.h *********/
  147753. static att3 _psy_tone_masteratt_8[3]={
  147754. {{ 32, 25, 12}, 0, 0}, /* 0 */
  147755. {{ 30, 25, 12}, 0, 0}, /* 0 */
  147756. {{ 20, 0, -14}, 0, 0}, /* 0 */
  147757. };
  147758. static vp_adjblock _vp_tonemask_adj_8[3]={
  147759. /* adjust for mode zero */
  147760. /* 63 125 250 500 1 2 4 8 16 */
  147761. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  147762. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  147763. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  147764. };
  147765. static noise3 _psy_noisebias_8[3]={
  147766. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  147767. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  147768. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  147769. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  147770. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  147771. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  147772. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  147773. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  147774. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  147775. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  147776. };
  147777. /* stereo mode by base quality level */
  147778. static adj_stereo _psy_stereo_modes_8[3]={
  147779. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  147780. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147781. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147782. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  147783. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147784. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147785. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147786. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  147787. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147788. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147789. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147790. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  147791. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147792. };
  147793. static noiseguard _psy_noiseguards_8[2]={
  147794. {10,10,-1},
  147795. {10,10,-1},
  147796. };
  147797. static compandblock _psy_compand_8[2]={
  147798. {{
  147799. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  147800. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  147801. 12,12,13,13,14,14,15, 15, /* 23dB */
  147802. 16,16,17,17,17,18,18, 19, /* 31dB */
  147803. 19,19,20,21,22,23,24, 25, /* 39dB */
  147804. }},
  147805. {{
  147806. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  147807. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  147808. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  147809. 9,10,11,12,13,14,15, 16, /* 31dB */
  147810. 17,18,19,20,21,22,23, 24, /* 39dB */
  147811. }},
  147812. };
  147813. static double _psy_lowpass_8[3]={3.,4.,4.};
  147814. static int _noise_start_8[2]={
  147815. 64,64,
  147816. };
  147817. static int _noise_part_8[2]={
  147818. 8,8,
  147819. };
  147820. static int _psy_ath_floater_8[3]={
  147821. -100,-100,-105,
  147822. };
  147823. static int _psy_ath_abs_8[3]={
  147824. -130,-130,-140,
  147825. };
  147826. /********* End of inlined file: psych_8.h *********/
  147827. /********* Start of inlined file: residue_8.h *********/
  147828. /***** residue backends *********************************************/
  147829. static static_bookblock _resbook_8s_0={
  147830. {
  147831. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  147832. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  147833. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  147834. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  147835. }
  147836. };
  147837. static static_bookblock _resbook_8s_1={
  147838. {
  147839. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  147840. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  147841. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  147842. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  147843. }
  147844. };
  147845. static vorbis_residue_template _res_8s_0[]={
  147846. {2,0, &_residue_44_mid,
  147847. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  147848. &_resbook_8s_0,&_resbook_8s_0},
  147849. };
  147850. static vorbis_residue_template _res_8s_1[]={
  147851. {2,0, &_residue_44_mid,
  147852. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  147853. &_resbook_8s_1,&_resbook_8s_1},
  147854. };
  147855. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  147856. { _map_nominal, _res_8s_0 }, /* 0 */
  147857. { _map_nominal, _res_8s_1 }, /* 1 */
  147858. };
  147859. static static_bookblock _resbook_8u_0={
  147860. {
  147861. {0},
  147862. {0,0,&_8u0__p1_0},
  147863. {0,0,&_8u0__p2_0},
  147864. {0,0,&_8u0__p3_0},
  147865. {0,0,&_8u0__p4_0},
  147866. {0,0,&_8u0__p5_0},
  147867. {&_8u0__p6_0,&_8u0__p6_1},
  147868. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  147869. }
  147870. };
  147871. static static_bookblock _resbook_8u_1={
  147872. {
  147873. {0},
  147874. {0,0,&_8u1__p1_0},
  147875. {0,0,&_8u1__p2_0},
  147876. {0,0,&_8u1__p3_0},
  147877. {0,0,&_8u1__p4_0},
  147878. {0,0,&_8u1__p5_0},
  147879. {0,0,&_8u1__p6_0},
  147880. {&_8u1__p7_0,&_8u1__p7_1},
  147881. {&_8u1__p8_0,&_8u1__p8_1},
  147882. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  147883. }
  147884. };
  147885. static vorbis_residue_template _res_8u_0[]={
  147886. {1,0, &_residue_44_low_un,
  147887. &_huff_book__8u0__single,&_huff_book__8u0__single,
  147888. &_resbook_8u_0,&_resbook_8u_0},
  147889. };
  147890. static vorbis_residue_template _res_8u_1[]={
  147891. {1,0, &_residue_44_mid_un,
  147892. &_huff_book__8u1__single,&_huff_book__8u1__single,
  147893. &_resbook_8u_1,&_resbook_8u_1},
  147894. };
  147895. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  147896. { _map_nominal_u, _res_8u_0 }, /* 0 */
  147897. { _map_nominal_u, _res_8u_1 }, /* 1 */
  147898. };
  147899. /********* End of inlined file: residue_8.h *********/
  147900. static int blocksize_8[2]={
  147901. 512,512
  147902. };
  147903. static int _floor_mapping_8[2]={
  147904. 6,6,
  147905. };
  147906. static double rate_mapping_8[3]={
  147907. 6000.,9000.,32000.,
  147908. };
  147909. static double rate_mapping_8_uncoupled[3]={
  147910. 8000.,14000.,42000.,
  147911. };
  147912. static double quality_mapping_8[3]={
  147913. -.1,.0,1.
  147914. };
  147915. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  147916. static double _global_mapping_8[3]={ 1., 2., 3. };
  147917. ve_setup_data_template ve_setup_8_stereo={
  147918. 2,
  147919. rate_mapping_8,
  147920. quality_mapping_8,
  147921. 2,
  147922. 8000,
  147923. 9000,
  147924. blocksize_8,
  147925. blocksize_8,
  147926. _psy_tone_masteratt_8,
  147927. _psy_tone_0dB,
  147928. _psy_tone_suppress,
  147929. _vp_tonemask_adj_8,
  147930. NULL,
  147931. _vp_tonemask_adj_8,
  147932. _psy_noiseguards_8,
  147933. _psy_noisebias_8,
  147934. _psy_noisebias_8,
  147935. NULL,
  147936. NULL,
  147937. _psy_noise_suppress,
  147938. _psy_compand_8,
  147939. _psy_compand_8_mapping,
  147940. NULL,
  147941. {_noise_start_8,_noise_start_8},
  147942. {_noise_part_8,_noise_part_8},
  147943. _noise_thresh_5only,
  147944. _psy_ath_floater_8,
  147945. _psy_ath_abs_8,
  147946. _psy_lowpass_8,
  147947. _psy_global_44,
  147948. _global_mapping_8,
  147949. _psy_stereo_modes_8,
  147950. _floor_books,
  147951. _floor,
  147952. _floor_mapping_8,
  147953. NULL,
  147954. _mapres_template_8_stereo
  147955. };
  147956. ve_setup_data_template ve_setup_8_uncoupled={
  147957. 2,
  147958. rate_mapping_8_uncoupled,
  147959. quality_mapping_8,
  147960. -1,
  147961. 8000,
  147962. 9000,
  147963. blocksize_8,
  147964. blocksize_8,
  147965. _psy_tone_masteratt_8,
  147966. _psy_tone_0dB,
  147967. _psy_tone_suppress,
  147968. _vp_tonemask_adj_8,
  147969. NULL,
  147970. _vp_tonemask_adj_8,
  147971. _psy_noiseguards_8,
  147972. _psy_noisebias_8,
  147973. _psy_noisebias_8,
  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_5only,
  147983. _psy_ath_floater_8,
  147984. _psy_ath_abs_8,
  147985. _psy_lowpass_8,
  147986. _psy_global_44,
  147987. _global_mapping_8,
  147988. _psy_stereo_modes_8,
  147989. _floor_books,
  147990. _floor,
  147991. _floor_mapping_8,
  147992. NULL,
  147993. _mapres_template_8_uncoupled
  147994. };
  147995. /********* End of inlined file: setup_8.h *********/
  147996. /********* Start of inlined file: setup_11.h *********/
  147997. /********* Start of inlined file: psych_11.h *********/
  147998. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  147999. static att3 _psy_tone_masteratt_11[3]={
  148000. {{ 30, 25, 12}, 0, 0}, /* 0 */
  148001. {{ 30, 25, 12}, 0, 0}, /* 0 */
  148002. {{ 20, 0, -14}, 0, 0}, /* 0 */
  148003. };
  148004. static vp_adjblock _vp_tonemask_adj_11[3]={
  148005. /* adjust for mode zero */
  148006. /* 63 125 250 500 1 2 4 8 16 */
  148007. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  148008. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  148009. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  148010. };
  148011. static noise3 _psy_noisebias_11[3]={
  148012. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148013. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  148014. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  148015. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  148016. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  148017. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  148018. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  148019. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  148020. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  148021. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  148022. };
  148023. static double _noise_thresh_11[3]={ .3,.5,.5 };
  148024. /********* End of inlined file: psych_11.h *********/
  148025. static int blocksize_11[2]={
  148026. 512,512
  148027. };
  148028. static int _floor_mapping_11[2]={
  148029. 6,6,
  148030. };
  148031. static double rate_mapping_11[3]={
  148032. 8000.,13000.,44000.,
  148033. };
  148034. static double rate_mapping_11_uncoupled[3]={
  148035. 12000.,20000.,50000.,
  148036. };
  148037. static double quality_mapping_11[3]={
  148038. -.1,.0,1.
  148039. };
  148040. ve_setup_data_template ve_setup_11_stereo={
  148041. 2,
  148042. rate_mapping_11,
  148043. quality_mapping_11,
  148044. 2,
  148045. 9000,
  148046. 15000,
  148047. blocksize_11,
  148048. blocksize_11,
  148049. _psy_tone_masteratt_11,
  148050. _psy_tone_0dB,
  148051. _psy_tone_suppress,
  148052. _vp_tonemask_adj_11,
  148053. NULL,
  148054. _vp_tonemask_adj_11,
  148055. _psy_noiseguards_8,
  148056. _psy_noisebias_11,
  148057. _psy_noisebias_11,
  148058. NULL,
  148059. NULL,
  148060. _psy_noise_suppress,
  148061. _psy_compand_8,
  148062. _psy_compand_8_mapping,
  148063. NULL,
  148064. {_noise_start_8,_noise_start_8},
  148065. {_noise_part_8,_noise_part_8},
  148066. _noise_thresh_11,
  148067. _psy_ath_floater_8,
  148068. _psy_ath_abs_8,
  148069. _psy_lowpass_11,
  148070. _psy_global_44,
  148071. _global_mapping_8,
  148072. _psy_stereo_modes_8,
  148073. _floor_books,
  148074. _floor,
  148075. _floor_mapping_11,
  148076. NULL,
  148077. _mapres_template_8_stereo
  148078. };
  148079. ve_setup_data_template ve_setup_11_uncoupled={
  148080. 2,
  148081. rate_mapping_11_uncoupled,
  148082. quality_mapping_11,
  148083. -1,
  148084. 9000,
  148085. 15000,
  148086. blocksize_11,
  148087. blocksize_11,
  148088. _psy_tone_masteratt_11,
  148089. _psy_tone_0dB,
  148090. _psy_tone_suppress,
  148091. _vp_tonemask_adj_11,
  148092. NULL,
  148093. _vp_tonemask_adj_11,
  148094. _psy_noiseguards_8,
  148095. _psy_noisebias_11,
  148096. _psy_noisebias_11,
  148097. NULL,
  148098. NULL,
  148099. _psy_noise_suppress,
  148100. _psy_compand_8,
  148101. _psy_compand_8_mapping,
  148102. NULL,
  148103. {_noise_start_8,_noise_start_8},
  148104. {_noise_part_8,_noise_part_8},
  148105. _noise_thresh_11,
  148106. _psy_ath_floater_8,
  148107. _psy_ath_abs_8,
  148108. _psy_lowpass_11,
  148109. _psy_global_44,
  148110. _global_mapping_8,
  148111. _psy_stereo_modes_8,
  148112. _floor_books,
  148113. _floor,
  148114. _floor_mapping_11,
  148115. NULL,
  148116. _mapres_template_8_uncoupled
  148117. };
  148118. /********* End of inlined file: setup_11.h *********/
  148119. /********* Start of inlined file: setup_16.h *********/
  148120. /********* Start of inlined file: psych_16.h *********/
  148121. /* stereo mode by base quality level */
  148122. static adj_stereo _psy_stereo_modes_16[4]={
  148123. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  148124. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148125. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148126. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  148127. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148128. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148129. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148130. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  148131. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148132. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148133. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  148134. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  148135. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148136. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  148137. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  148138. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  148139. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  148140. };
  148141. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  148142. static att3 _psy_tone_masteratt_16[4]={
  148143. {{ 30, 25, 12}, 0, 0}, /* 0 */
  148144. {{ 25, 22, 12}, 0, 0}, /* 0 */
  148145. {{ 20, 12, 0}, 0, 0}, /* 0 */
  148146. {{ 15, 0, -14}, 0, 0}, /* 0 */
  148147. };
  148148. static vp_adjblock _vp_tonemask_adj_16[4]={
  148149. /* adjust for mode zero */
  148150. /* 63 125 250 500 1 2 4 8 16 */
  148151. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  148152. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  148153. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  148154. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  148155. };
  148156. static noise3 _psy_noisebias_16_short[4]={
  148157. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148158. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  148159. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  148160. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  148161. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  148162. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  148163. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  148164. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  148165. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  148166. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148167. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  148168. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  148169. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148170. };
  148171. static noise3 _psy_noisebias_16_impulse[4]={
  148172. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148173. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  148174. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  148175. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  148176. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  148177. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  148178. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  148179. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  148180. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  148181. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148182. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  148183. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  148184. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148185. };
  148186. static noise3 _psy_noisebias_16[4]={
  148187. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  148188. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  148189. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  148190. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  148191. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  148192. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  148193. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  148194. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  148195. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  148196. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148197. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  148198. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  148199. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  148200. };
  148201. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  148202. static int _noise_start_16[3]={ 256,256,9999 };
  148203. static int _noise_part_16[4]={ 8,8,8,8 };
  148204. static int _psy_ath_floater_16[4]={
  148205. -100,-100,-100,-105,
  148206. };
  148207. static int _psy_ath_abs_16[4]={
  148208. -130,-130,-130,-140,
  148209. };
  148210. /********* End of inlined file: psych_16.h *********/
  148211. /********* Start of inlined file: residue_16.h *********/
  148212. /***** residue backends *********************************************/
  148213. static static_bookblock _resbook_16s_0={
  148214. {
  148215. {0},
  148216. {0,0,&_16c0_s_p1_0},
  148217. {0,0,&_16c0_s_p2_0},
  148218. {0,0,&_16c0_s_p3_0},
  148219. {0,0,&_16c0_s_p4_0},
  148220. {0,0,&_16c0_s_p5_0},
  148221. {0,0,&_16c0_s_p6_0},
  148222. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  148223. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  148224. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  148225. }
  148226. };
  148227. static static_bookblock _resbook_16s_1={
  148228. {
  148229. {0},
  148230. {0,0,&_16c1_s_p1_0},
  148231. {0,0,&_16c1_s_p2_0},
  148232. {0,0,&_16c1_s_p3_0},
  148233. {0,0,&_16c1_s_p4_0},
  148234. {0,0,&_16c1_s_p5_0},
  148235. {0,0,&_16c1_s_p6_0},
  148236. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  148237. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  148238. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  148239. }
  148240. };
  148241. static static_bookblock _resbook_16s_2={
  148242. {
  148243. {0},
  148244. {0,0,&_16c2_s_p1_0},
  148245. {0,0,&_16c2_s_p2_0},
  148246. {0,0,&_16c2_s_p3_0},
  148247. {0,0,&_16c2_s_p4_0},
  148248. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  148249. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  148250. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  148251. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  148252. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  148253. }
  148254. };
  148255. static vorbis_residue_template _res_16s_0[]={
  148256. {2,0, &_residue_44_mid,
  148257. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  148258. &_resbook_16s_0,&_resbook_16s_0},
  148259. };
  148260. static vorbis_residue_template _res_16s_1[]={
  148261. {2,0, &_residue_44_mid,
  148262. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  148263. &_resbook_16s_1,&_resbook_16s_1},
  148264. {2,0, &_residue_44_mid,
  148265. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  148266. &_resbook_16s_1,&_resbook_16s_1}
  148267. };
  148268. static vorbis_residue_template _res_16s_2[]={
  148269. {2,0, &_residue_44_high,
  148270. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  148271. &_resbook_16s_2,&_resbook_16s_2},
  148272. {2,0, &_residue_44_high,
  148273. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  148274. &_resbook_16s_2,&_resbook_16s_2}
  148275. };
  148276. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  148277. { _map_nominal, _res_16s_0 }, /* 0 */
  148278. { _map_nominal, _res_16s_1 }, /* 1 */
  148279. { _map_nominal, _res_16s_2 }, /* 2 */
  148280. };
  148281. static static_bookblock _resbook_16u_0={
  148282. {
  148283. {0},
  148284. {0,0,&_16u0__p1_0},
  148285. {0,0,&_16u0__p2_0},
  148286. {0,0,&_16u0__p3_0},
  148287. {0,0,&_16u0__p4_0},
  148288. {0,0,&_16u0__p5_0},
  148289. {&_16u0__p6_0,&_16u0__p6_1},
  148290. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  148291. }
  148292. };
  148293. static static_bookblock _resbook_16u_1={
  148294. {
  148295. {0},
  148296. {0,0,&_16u1__p1_0},
  148297. {0,0,&_16u1__p2_0},
  148298. {0,0,&_16u1__p3_0},
  148299. {0,0,&_16u1__p4_0},
  148300. {0,0,&_16u1__p5_0},
  148301. {0,0,&_16u1__p6_0},
  148302. {&_16u1__p7_0,&_16u1__p7_1},
  148303. {&_16u1__p8_0,&_16u1__p8_1},
  148304. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  148305. }
  148306. };
  148307. static static_bookblock _resbook_16u_2={
  148308. {
  148309. {0},
  148310. {0,0,&_16u2_p1_0},
  148311. {0,0,&_16u2_p2_0},
  148312. {0,0,&_16u2_p3_0},
  148313. {0,0,&_16u2_p4_0},
  148314. {&_16u2_p5_0,&_16u2_p5_1},
  148315. {&_16u2_p6_0,&_16u2_p6_1},
  148316. {&_16u2_p7_0,&_16u2_p7_1},
  148317. {&_16u2_p8_0,&_16u2_p8_1},
  148318. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  148319. }
  148320. };
  148321. static vorbis_residue_template _res_16u_0[]={
  148322. {1,0, &_residue_44_low_un,
  148323. &_huff_book__16u0__single,&_huff_book__16u0__single,
  148324. &_resbook_16u_0,&_resbook_16u_0},
  148325. };
  148326. static vorbis_residue_template _res_16u_1[]={
  148327. {1,0, &_residue_44_mid_un,
  148328. &_huff_book__16u1__short,&_huff_book__16u1__short,
  148329. &_resbook_16u_1,&_resbook_16u_1},
  148330. {1,0, &_residue_44_mid_un,
  148331. &_huff_book__16u1__long,&_huff_book__16u1__long,
  148332. &_resbook_16u_1,&_resbook_16u_1}
  148333. };
  148334. static vorbis_residue_template _res_16u_2[]={
  148335. {1,0, &_residue_44_hi_un,
  148336. &_huff_book__16u2__short,&_huff_book__16u2__short,
  148337. &_resbook_16u_2,&_resbook_16u_2},
  148338. {1,0, &_residue_44_hi_un,
  148339. &_huff_book__16u2__long,&_huff_book__16u2__long,
  148340. &_resbook_16u_2,&_resbook_16u_2}
  148341. };
  148342. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  148343. { _map_nominal_u, _res_16u_0 }, /* 0 */
  148344. { _map_nominal_u, _res_16u_1 }, /* 1 */
  148345. { _map_nominal_u, _res_16u_2 }, /* 2 */
  148346. };
  148347. /********* End of inlined file: residue_16.h *********/
  148348. static int blocksize_16_short[3]={
  148349. 1024,512,512
  148350. };
  148351. static int blocksize_16_long[3]={
  148352. 1024,1024,1024
  148353. };
  148354. static int _floor_mapping_16_short[3]={
  148355. 9,3,3
  148356. };
  148357. static int _floor_mapping_16[3]={
  148358. 9,9,9
  148359. };
  148360. static double rate_mapping_16[4]={
  148361. 12000.,20000.,44000.,86000.
  148362. };
  148363. static double rate_mapping_16_uncoupled[4]={
  148364. 16000.,28000.,64000.,100000.
  148365. };
  148366. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  148367. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  148368. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  148369. ve_setup_data_template ve_setup_16_stereo={
  148370. 3,
  148371. rate_mapping_16,
  148372. quality_mapping_16,
  148373. 2,
  148374. 15000,
  148375. 19000,
  148376. blocksize_16_short,
  148377. blocksize_16_long,
  148378. _psy_tone_masteratt_16,
  148379. _psy_tone_0dB,
  148380. _psy_tone_suppress,
  148381. _vp_tonemask_adj_16,
  148382. _vp_tonemask_adj_16,
  148383. _vp_tonemask_adj_16,
  148384. _psy_noiseguards_8,
  148385. _psy_noisebias_16_impulse,
  148386. _psy_noisebias_16_short,
  148387. _psy_noisebias_16_short,
  148388. _psy_noisebias_16,
  148389. _psy_noise_suppress,
  148390. _psy_compand_8,
  148391. _psy_compand_16_mapping,
  148392. _psy_compand_16_mapping,
  148393. {_noise_start_16,_noise_start_16},
  148394. { _noise_part_16, _noise_part_16},
  148395. _noise_thresh_16,
  148396. _psy_ath_floater_16,
  148397. _psy_ath_abs_16,
  148398. _psy_lowpass_16,
  148399. _psy_global_44,
  148400. _global_mapping_16,
  148401. _psy_stereo_modes_16,
  148402. _floor_books,
  148403. _floor,
  148404. _floor_mapping_16_short,
  148405. _floor_mapping_16,
  148406. _mapres_template_16_stereo
  148407. };
  148408. ve_setup_data_template ve_setup_16_uncoupled={
  148409. 3,
  148410. rate_mapping_16_uncoupled,
  148411. quality_mapping_16,
  148412. -1,
  148413. 15000,
  148414. 19000,
  148415. blocksize_16_short,
  148416. blocksize_16_long,
  148417. _psy_tone_masteratt_16,
  148418. _psy_tone_0dB,
  148419. _psy_tone_suppress,
  148420. _vp_tonemask_adj_16,
  148421. _vp_tonemask_adj_16,
  148422. _vp_tonemask_adj_16,
  148423. _psy_noiseguards_8,
  148424. _psy_noisebias_16_impulse,
  148425. _psy_noisebias_16_short,
  148426. _psy_noisebias_16_short,
  148427. _psy_noisebias_16,
  148428. _psy_noise_suppress,
  148429. _psy_compand_8,
  148430. _psy_compand_16_mapping,
  148431. _psy_compand_16_mapping,
  148432. {_noise_start_16,_noise_start_16},
  148433. { _noise_part_16, _noise_part_16},
  148434. _noise_thresh_16,
  148435. _psy_ath_floater_16,
  148436. _psy_ath_abs_16,
  148437. _psy_lowpass_16,
  148438. _psy_global_44,
  148439. _global_mapping_16,
  148440. _psy_stereo_modes_16,
  148441. _floor_books,
  148442. _floor,
  148443. _floor_mapping_16_short,
  148444. _floor_mapping_16,
  148445. _mapres_template_16_uncoupled
  148446. };
  148447. /********* End of inlined file: setup_16.h *********/
  148448. /********* Start of inlined file: setup_22.h *********/
  148449. static double rate_mapping_22[4]={
  148450. 15000.,20000.,44000.,86000.
  148451. };
  148452. static double rate_mapping_22_uncoupled[4]={
  148453. 16000.,28000.,50000.,90000.
  148454. };
  148455. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  148456. ve_setup_data_template ve_setup_22_stereo={
  148457. 3,
  148458. rate_mapping_22,
  148459. quality_mapping_16,
  148460. 2,
  148461. 19000,
  148462. 26000,
  148463. blocksize_16_short,
  148464. blocksize_16_long,
  148465. _psy_tone_masteratt_16,
  148466. _psy_tone_0dB,
  148467. _psy_tone_suppress,
  148468. _vp_tonemask_adj_16,
  148469. _vp_tonemask_adj_16,
  148470. _vp_tonemask_adj_16,
  148471. _psy_noiseguards_8,
  148472. _psy_noisebias_16_impulse,
  148473. _psy_noisebias_16_short,
  148474. _psy_noisebias_16_short,
  148475. _psy_noisebias_16,
  148476. _psy_noise_suppress,
  148477. _psy_compand_8,
  148478. _psy_compand_8_mapping,
  148479. _psy_compand_8_mapping,
  148480. {_noise_start_16,_noise_start_16},
  148481. { _noise_part_16, _noise_part_16},
  148482. _noise_thresh_16,
  148483. _psy_ath_floater_16,
  148484. _psy_ath_abs_16,
  148485. _psy_lowpass_22,
  148486. _psy_global_44,
  148487. _global_mapping_16,
  148488. _psy_stereo_modes_16,
  148489. _floor_books,
  148490. _floor,
  148491. _floor_mapping_16_short,
  148492. _floor_mapping_16,
  148493. _mapres_template_16_stereo
  148494. };
  148495. ve_setup_data_template ve_setup_22_uncoupled={
  148496. 3,
  148497. rate_mapping_22_uncoupled,
  148498. quality_mapping_16,
  148499. -1,
  148500. 19000,
  148501. 26000,
  148502. blocksize_16_short,
  148503. blocksize_16_long,
  148504. _psy_tone_masteratt_16,
  148505. _psy_tone_0dB,
  148506. _psy_tone_suppress,
  148507. _vp_tonemask_adj_16,
  148508. _vp_tonemask_adj_16,
  148509. _vp_tonemask_adj_16,
  148510. _psy_noiseguards_8,
  148511. _psy_noisebias_16_impulse,
  148512. _psy_noisebias_16_short,
  148513. _psy_noisebias_16_short,
  148514. _psy_noisebias_16,
  148515. _psy_noise_suppress,
  148516. _psy_compand_8,
  148517. _psy_compand_8_mapping,
  148518. _psy_compand_8_mapping,
  148519. {_noise_start_16,_noise_start_16},
  148520. { _noise_part_16, _noise_part_16},
  148521. _noise_thresh_16,
  148522. _psy_ath_floater_16,
  148523. _psy_ath_abs_16,
  148524. _psy_lowpass_22,
  148525. _psy_global_44,
  148526. _global_mapping_16,
  148527. _psy_stereo_modes_16,
  148528. _floor_books,
  148529. _floor,
  148530. _floor_mapping_16_short,
  148531. _floor_mapping_16,
  148532. _mapres_template_16_uncoupled
  148533. };
  148534. /********* End of inlined file: setup_22.h *********/
  148535. /********* Start of inlined file: setup_X.h *********/
  148536. static double rate_mapping_X[12]={
  148537. -1.,-1.,-1.,-1.,-1.,-1.,
  148538. -1.,-1.,-1.,-1.,-1.,-1.
  148539. };
  148540. ve_setup_data_template ve_setup_X_stereo={
  148541. 11,
  148542. rate_mapping_X,
  148543. quality_mapping_44,
  148544. 2,
  148545. 50000,
  148546. 200000,
  148547. blocksize_short_44,
  148548. blocksize_long_44,
  148549. _psy_tone_masteratt_44,
  148550. _psy_tone_0dB,
  148551. _psy_tone_suppress,
  148552. _vp_tonemask_adj_otherblock,
  148553. _vp_tonemask_adj_longblock,
  148554. _vp_tonemask_adj_otherblock,
  148555. _psy_noiseguards_44,
  148556. _psy_noisebias_impulse,
  148557. _psy_noisebias_padding,
  148558. _psy_noisebias_trans,
  148559. _psy_noisebias_long,
  148560. _psy_noise_suppress,
  148561. _psy_compand_44,
  148562. _psy_compand_short_mapping,
  148563. _psy_compand_long_mapping,
  148564. {_noise_start_short_44,_noise_start_long_44},
  148565. {_noise_part_short_44,_noise_part_long_44},
  148566. _noise_thresh_44,
  148567. _psy_ath_floater,
  148568. _psy_ath_abs,
  148569. _psy_lowpass_44,
  148570. _psy_global_44,
  148571. _global_mapping_44,
  148572. _psy_stereo_modes_44,
  148573. _floor_books,
  148574. _floor,
  148575. _floor_short_mapping_44,
  148576. _floor_long_mapping_44,
  148577. _mapres_template_44_stereo
  148578. };
  148579. ve_setup_data_template ve_setup_X_uncoupled={
  148580. 11,
  148581. rate_mapping_X,
  148582. quality_mapping_44,
  148583. -1,
  148584. 50000,
  148585. 200000,
  148586. blocksize_short_44,
  148587. blocksize_long_44,
  148588. _psy_tone_masteratt_44,
  148589. _psy_tone_0dB,
  148590. _psy_tone_suppress,
  148591. _vp_tonemask_adj_otherblock,
  148592. _vp_tonemask_adj_longblock,
  148593. _vp_tonemask_adj_otherblock,
  148594. _psy_noiseguards_44,
  148595. _psy_noisebias_impulse,
  148596. _psy_noisebias_padding,
  148597. _psy_noisebias_trans,
  148598. _psy_noisebias_long,
  148599. _psy_noise_suppress,
  148600. _psy_compand_44,
  148601. _psy_compand_short_mapping,
  148602. _psy_compand_long_mapping,
  148603. {_noise_start_short_44,_noise_start_long_44},
  148604. {_noise_part_short_44,_noise_part_long_44},
  148605. _noise_thresh_44,
  148606. _psy_ath_floater,
  148607. _psy_ath_abs,
  148608. _psy_lowpass_44,
  148609. _psy_global_44,
  148610. _global_mapping_44,
  148611. NULL,
  148612. _floor_books,
  148613. _floor,
  148614. _floor_short_mapping_44,
  148615. _floor_long_mapping_44,
  148616. _mapres_template_44_uncoupled
  148617. };
  148618. ve_setup_data_template ve_setup_XX_stereo={
  148619. 2,
  148620. rate_mapping_X,
  148621. quality_mapping_8,
  148622. 2,
  148623. 0,
  148624. 8000,
  148625. blocksize_8,
  148626. blocksize_8,
  148627. _psy_tone_masteratt_8,
  148628. _psy_tone_0dB,
  148629. _psy_tone_suppress,
  148630. _vp_tonemask_adj_8,
  148631. NULL,
  148632. _vp_tonemask_adj_8,
  148633. _psy_noiseguards_8,
  148634. _psy_noisebias_8,
  148635. _psy_noisebias_8,
  148636. NULL,
  148637. NULL,
  148638. _psy_noise_suppress,
  148639. _psy_compand_8,
  148640. _psy_compand_8_mapping,
  148641. NULL,
  148642. {_noise_start_8,_noise_start_8},
  148643. {_noise_part_8,_noise_part_8},
  148644. _noise_thresh_5only,
  148645. _psy_ath_floater_8,
  148646. _psy_ath_abs_8,
  148647. _psy_lowpass_8,
  148648. _psy_global_44,
  148649. _global_mapping_8,
  148650. _psy_stereo_modes_8,
  148651. _floor_books,
  148652. _floor,
  148653. _floor_mapping_8,
  148654. NULL,
  148655. _mapres_template_8_stereo
  148656. };
  148657. ve_setup_data_template ve_setup_XX_uncoupled={
  148658. 2,
  148659. rate_mapping_X,
  148660. quality_mapping_8,
  148661. -1,
  148662. 0,
  148663. 8000,
  148664. blocksize_8,
  148665. blocksize_8,
  148666. _psy_tone_masteratt_8,
  148667. _psy_tone_0dB,
  148668. _psy_tone_suppress,
  148669. _vp_tonemask_adj_8,
  148670. NULL,
  148671. _vp_tonemask_adj_8,
  148672. _psy_noiseguards_8,
  148673. _psy_noisebias_8,
  148674. _psy_noisebias_8,
  148675. NULL,
  148676. NULL,
  148677. _psy_noise_suppress,
  148678. _psy_compand_8,
  148679. _psy_compand_8_mapping,
  148680. NULL,
  148681. {_noise_start_8,_noise_start_8},
  148682. {_noise_part_8,_noise_part_8},
  148683. _noise_thresh_5only,
  148684. _psy_ath_floater_8,
  148685. _psy_ath_abs_8,
  148686. _psy_lowpass_8,
  148687. _psy_global_44,
  148688. _global_mapping_8,
  148689. _psy_stereo_modes_8,
  148690. _floor_books,
  148691. _floor,
  148692. _floor_mapping_8,
  148693. NULL,
  148694. _mapres_template_8_uncoupled
  148695. };
  148696. /********* End of inlined file: setup_X.h *********/
  148697. static ve_setup_data_template *setup_list[]={
  148698. &ve_setup_44_stereo,
  148699. &ve_setup_44_uncoupled,
  148700. &ve_setup_32_stereo,
  148701. &ve_setup_32_uncoupled,
  148702. &ve_setup_22_stereo,
  148703. &ve_setup_22_uncoupled,
  148704. &ve_setup_16_stereo,
  148705. &ve_setup_16_uncoupled,
  148706. &ve_setup_11_stereo,
  148707. &ve_setup_11_uncoupled,
  148708. &ve_setup_8_stereo,
  148709. &ve_setup_8_uncoupled,
  148710. &ve_setup_X_stereo,
  148711. &ve_setup_X_uncoupled,
  148712. &ve_setup_XX_stereo,
  148713. &ve_setup_XX_uncoupled,
  148714. 0
  148715. };
  148716. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  148717. if(vi && vi->codec_setup){
  148718. vi->version=0;
  148719. vi->channels=ch;
  148720. vi->rate=rate;
  148721. return(0);
  148722. }
  148723. return(OV_EINVAL);
  148724. }
  148725. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  148726. static_codebook ***books,
  148727. vorbis_info_floor1 *in,
  148728. int *x){
  148729. int i,k,is=s;
  148730. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  148731. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148732. memcpy(f,in+x[is],sizeof(*f));
  148733. /* fill in the lowpass field, even if it's temporary */
  148734. f->n=ci->blocksizes[block]>>1;
  148735. /* books */
  148736. {
  148737. int partitions=f->partitions;
  148738. int maxclass=-1;
  148739. int maxbook=-1;
  148740. for(i=0;i<partitions;i++)
  148741. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  148742. for(i=0;i<=maxclass;i++){
  148743. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  148744. f->class_book[i]+=ci->books;
  148745. for(k=0;k<(1<<f->class_subs[i]);k++){
  148746. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  148747. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  148748. }
  148749. }
  148750. for(i=0;i<=maxbook;i++)
  148751. ci->book_param[ci->books++]=books[x[is]][i];
  148752. }
  148753. /* for now, we're only using floor 1 */
  148754. ci->floor_type[ci->floors]=1;
  148755. ci->floor_param[ci->floors]=f;
  148756. ci->floors++;
  148757. return;
  148758. }
  148759. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  148760. vorbis_info_psy_global *in,
  148761. double *x){
  148762. int i,is=s;
  148763. double ds=s-is;
  148764. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148765. vorbis_info_psy_global *g=&ci->psy_g_param;
  148766. memcpy(g,in+(int)x[is],sizeof(*g));
  148767. ds=x[is]*(1.-ds)+x[is+1]*ds;
  148768. is=(int)ds;
  148769. ds-=is;
  148770. if(ds==0 && is>0){
  148771. is--;
  148772. ds=1.;
  148773. }
  148774. /* interpolate the trigger threshholds */
  148775. for(i=0;i<4;i++){
  148776. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  148777. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  148778. }
  148779. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  148780. return;
  148781. }
  148782. static void vorbis_encode_global_stereo(vorbis_info *vi,
  148783. highlevel_encode_setup *hi,
  148784. adj_stereo *p){
  148785. float s=hi->stereo_point_setting;
  148786. int i,is=s;
  148787. double ds=s-is;
  148788. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148789. vorbis_info_psy_global *g=&ci->psy_g_param;
  148790. if(p){
  148791. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  148792. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  148793. if(hi->managed){
  148794. /* interpolate the kHz threshholds */
  148795. for(i=0;i<PACKETBLOBS;i++){
  148796. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  148797. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148798. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148799. g->coupling_pkHz[i]=kHz;
  148800. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  148801. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148802. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148803. }
  148804. }else{
  148805. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  148806. for(i=0;i<PACKETBLOBS;i++){
  148807. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148808. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148809. g->coupling_pkHz[i]=kHz;
  148810. }
  148811. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  148812. for(i=0;i<PACKETBLOBS;i++){
  148813. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148814. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148815. }
  148816. }
  148817. }else{
  148818. for(i=0;i<PACKETBLOBS;i++){
  148819. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  148820. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  148821. }
  148822. }
  148823. return;
  148824. }
  148825. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  148826. int *nn_start,
  148827. int *nn_partition,
  148828. double *nn_thresh,
  148829. int block){
  148830. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148831. vorbis_info_psy *p=ci->psy_param[block];
  148832. highlevel_encode_setup *hi=&ci->hi;
  148833. int is=s;
  148834. if(block>=ci->psys)
  148835. ci->psys=block+1;
  148836. if(!p){
  148837. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  148838. ci->psy_param[block]=p;
  148839. }
  148840. memcpy(p,&_psy_info_template,sizeof(*p));
  148841. p->blockflag=block>>1;
  148842. if(hi->noise_normalize_p){
  148843. p->normal_channel_p=1;
  148844. p->normal_point_p=1;
  148845. p->normal_start=nn_start[is];
  148846. p->normal_partition=nn_partition[is];
  148847. p->normal_thresh=nn_thresh[is];
  148848. }
  148849. return;
  148850. }
  148851. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  148852. att3 *att,
  148853. int *max,
  148854. vp_adjblock *in){
  148855. int i,is=s;
  148856. double ds=s-is;
  148857. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148858. vorbis_info_psy *p=ci->psy_param[block];
  148859. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  148860. filling the values in here */
  148861. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  148862. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  148863. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  148864. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  148865. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  148866. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  148867. for(i=0;i<P_BANDS;i++)
  148868. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  148869. return;
  148870. }
  148871. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  148872. compandblock *in, double *x){
  148873. int i,is=s;
  148874. double ds=s-is;
  148875. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148876. vorbis_info_psy *p=ci->psy_param[block];
  148877. ds=x[is]*(1.-ds)+x[is+1]*ds;
  148878. is=(int)ds;
  148879. ds-=is;
  148880. if(ds==0 && is>0){
  148881. is--;
  148882. ds=1.;
  148883. }
  148884. /* interpolate the compander settings */
  148885. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  148886. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  148887. return;
  148888. }
  148889. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  148890. int *suppress){
  148891. int is=s;
  148892. double ds=s-is;
  148893. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148894. vorbis_info_psy *p=ci->psy_param[block];
  148895. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  148896. return;
  148897. }
  148898. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  148899. int *suppress,
  148900. noise3 *in,
  148901. noiseguard *guard,
  148902. double userbias){
  148903. int i,is=s,j;
  148904. double ds=s-is;
  148905. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148906. vorbis_info_psy *p=ci->psy_param[block];
  148907. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  148908. p->noisewindowlomin=guard[block].lo;
  148909. p->noisewindowhimin=guard[block].hi;
  148910. p->noisewindowfixed=guard[block].fixed;
  148911. for(j=0;j<P_NOISECURVES;j++)
  148912. for(i=0;i<P_BANDS;i++)
  148913. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  148914. /* impulse blocks may take a user specified bias to boost the
  148915. nominal/high noise encoding depth */
  148916. for(j=0;j<P_NOISECURVES;j++){
  148917. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  148918. for(i=0;i<P_BANDS;i++){
  148919. p->noiseoff[j][i]+=userbias;
  148920. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  148921. }
  148922. }
  148923. return;
  148924. }
  148925. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  148926. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148927. vorbis_info_psy *p=ci->psy_param[block];
  148928. p->ath_adjatt=ci->hi.ath_floating_dB;
  148929. p->ath_maxatt=ci->hi.ath_absolute_dB;
  148930. return;
  148931. }
  148932. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  148933. int i;
  148934. for(i=0;i<ci->books;i++)
  148935. if(ci->book_param[i]==book)return(i);
  148936. return(ci->books++);
  148937. }
  148938. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  148939. int *shortb,int *longb){
  148940. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148941. int is=s;
  148942. int blockshort=shortb[is];
  148943. int blocklong=longb[is];
  148944. ci->blocksizes[0]=blockshort;
  148945. ci->blocksizes[1]=blocklong;
  148946. }
  148947. static void vorbis_encode_residue_setup(vorbis_info *vi,
  148948. int number, int block,
  148949. vorbis_residue_template *res){
  148950. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148951. int i,n;
  148952. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  148953. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  148954. memcpy(r,res->res,sizeof(*r));
  148955. if(ci->residues<=number)ci->residues=number+1;
  148956. switch(ci->blocksizes[block]){
  148957. case 64:case 128:case 256:
  148958. r->grouping=16;
  148959. break;
  148960. default:
  148961. r->grouping=32;
  148962. break;
  148963. }
  148964. ci->residue_type[number]=res->res_type;
  148965. /* to be adjusted by lowpass/pointlimit later */
  148966. n=r->end=ci->blocksizes[block]>>1;
  148967. if(res->res_type==2)
  148968. n=r->end*=vi->channels;
  148969. /* fill in all the books */
  148970. {
  148971. int booklist=0,k;
  148972. if(ci->hi.managed){
  148973. for(i=0;i<r->partitions;i++)
  148974. for(k=0;k<3;k++)
  148975. if(res->books_base_managed->books[i][k])
  148976. r->secondstages[i]|=(1<<k);
  148977. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  148978. ci->book_param[r->groupbook]=res->book_aux_managed;
  148979. for(i=0;i<r->partitions;i++){
  148980. for(k=0;k<3;k++){
  148981. if(res->books_base_managed->books[i][k]){
  148982. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  148983. r->booklist[booklist++]=bookid;
  148984. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  148985. }
  148986. }
  148987. }
  148988. }else{
  148989. for(i=0;i<r->partitions;i++)
  148990. for(k=0;k<3;k++)
  148991. if(res->books_base->books[i][k])
  148992. r->secondstages[i]|=(1<<k);
  148993. r->groupbook=book_dup_or_new(ci,res->book_aux);
  148994. ci->book_param[r->groupbook]=res->book_aux;
  148995. for(i=0;i<r->partitions;i++){
  148996. for(k=0;k<3;k++){
  148997. if(res->books_base->books[i][k]){
  148998. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  148999. r->booklist[booklist++]=bookid;
  149000. ci->book_param[bookid]=res->books_base->books[i][k];
  149001. }
  149002. }
  149003. }
  149004. }
  149005. }
  149006. /* lowpass setup/pointlimit */
  149007. {
  149008. double freq=ci->hi.lowpass_kHz*1000.;
  149009. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  149010. double nyq=vi->rate/2.;
  149011. long blocksize=ci->blocksizes[block]>>1;
  149012. /* lowpass needs to be set in the floor and the residue. */
  149013. if(freq>nyq)freq=nyq;
  149014. /* in the floor, the granularity can be very fine; it doesn't alter
  149015. the encoding structure, only the samples used to fit the floor
  149016. approximation */
  149017. f->n=freq/nyq*blocksize;
  149018. /* this res may by limited by the maximum pointlimit of the mode,
  149019. not the lowpass. the floor is always lowpass limited. */
  149020. if(res->limit_type){
  149021. if(ci->hi.managed)
  149022. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  149023. else
  149024. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  149025. if(freq>nyq)freq=nyq;
  149026. }
  149027. /* in the residue, we're constrained, physically, by partition
  149028. boundaries. We still lowpass 'wherever', but we have to round up
  149029. here to next boundary, or the vorbis spec will round it *down* to
  149030. previous boundary in encode/decode */
  149031. if(ci->residue_type[block]==2)
  149032. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  149033. r->grouping;
  149034. else
  149035. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  149036. r->grouping;
  149037. }
  149038. }
  149039. /* we assume two maps in this encoder */
  149040. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  149041. vorbis_mapping_template *maps){
  149042. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149043. int i,j,is=s,modes=2;
  149044. vorbis_info_mapping0 *map=maps[is].map;
  149045. vorbis_info_mode *mode=_mode_template;
  149046. vorbis_residue_template *res=maps[is].res;
  149047. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  149048. for(i=0;i<modes;i++){
  149049. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  149050. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  149051. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  149052. if(i>=ci->modes)ci->modes=i+1;
  149053. ci->map_type[i]=0;
  149054. memcpy(ci->map_param[i],map+i,sizeof(*map));
  149055. if(i>=ci->maps)ci->maps=i+1;
  149056. for(j=0;j<map[i].submaps;j++)
  149057. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  149058. ,res+map[i].residuesubmap[j]);
  149059. }
  149060. }
  149061. static double setting_to_approx_bitrate(vorbis_info *vi){
  149062. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149063. highlevel_encode_setup *hi=&ci->hi;
  149064. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  149065. int is=hi->base_setting;
  149066. double ds=hi->base_setting-is;
  149067. int ch=vi->channels;
  149068. double *r=setup->rate_mapping;
  149069. if(r==NULL)
  149070. return(-1);
  149071. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  149072. }
  149073. static void get_setup_template(vorbis_info *vi,
  149074. long ch,long srate,
  149075. double req,int q_or_bitrate){
  149076. int i=0,j;
  149077. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  149078. highlevel_encode_setup *hi=&ci->hi;
  149079. if(q_or_bitrate)req/=ch;
  149080. while(setup_list[i]){
  149081. if(setup_list[i]->coupling_restriction==-1 ||
  149082. setup_list[i]->coupling_restriction==ch){
  149083. if(srate>=setup_list[i]->samplerate_min_restriction &&
  149084. srate<=setup_list[i]->samplerate_max_restriction){
  149085. int mappings=setup_list[i]->mappings;
  149086. double *map=(q_or_bitrate?
  149087. setup_list[i]->rate_mapping:
  149088. setup_list[i]->quality_mapping);
  149089. /* the template matches. Does the requested quality mode
  149090. fall within this template's modes? */
  149091. if(req<map[0]){++i;continue;}
  149092. if(req>map[setup_list[i]->mappings]){++i;continue;}
  149093. for(j=0;j<mappings;j++)
  149094. if(req>=map[j] && req<map[j+1])break;
  149095. /* an all-points match */
  149096. hi->setup=setup_list[i];
  149097. if(j==mappings)
  149098. hi->base_setting=j-.001;
  149099. else{
  149100. float low=map[j];
  149101. float high=map[j+1];
  149102. float del=(req-low)/(high-low);
  149103. hi->base_setting=j+del;
  149104. }
  149105. return;
  149106. }
  149107. }
  149108. i++;
  149109. }
  149110. hi->setup=NULL;
  149111. }
  149112. /* encoders will need to use vorbis_info_init beforehand and call
  149113. vorbis_info clear when all done */
  149114. /* two interfaces; this, more detailed one, and later a convenience
  149115. layer on top */
  149116. /* the final setup call */
  149117. int vorbis_encode_setup_init(vorbis_info *vi){
  149118. int i0=0,singleblock=0;
  149119. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  149120. ve_setup_data_template *setup=NULL;
  149121. highlevel_encode_setup *hi=&ci->hi;
  149122. if(ci==NULL)return(OV_EINVAL);
  149123. if(!hi->impulse_block_p)i0=1;
  149124. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  149125. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  149126. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  149127. /* again, bound this to avoid the app shooting itself int he foot
  149128. too badly */
  149129. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  149130. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  149131. /* get the appropriate setup template; matches the fetch in previous
  149132. stages */
  149133. setup=(ve_setup_data_template *)hi->setup;
  149134. if(setup==NULL)return(OV_EINVAL);
  149135. hi->set_in_stone=1;
  149136. /* choose block sizes from configured sizes as well as paying
  149137. attention to long_block_p and short_block_p. If the configured
  149138. short and long blocks are the same length, we set long_block_p
  149139. and unset short_block_p */
  149140. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  149141. setup->blocksize_short,
  149142. setup->blocksize_long);
  149143. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  149144. /* floor setup; choose proper floor params. Allocated on the floor
  149145. stack in order; if we alloc only long floor, it's 0 */
  149146. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  149147. setup->floor_books,
  149148. setup->floor_params,
  149149. setup->floor_short_mapping);
  149150. if(!singleblock)
  149151. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  149152. setup->floor_books,
  149153. setup->floor_params,
  149154. setup->floor_long_mapping);
  149155. /* setup of [mostly] short block detection and stereo*/
  149156. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  149157. setup->global_params,
  149158. setup->global_mapping);
  149159. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  149160. /* basic psych setup and noise normalization */
  149161. vorbis_encode_psyset_setup(vi,hi->short_setting,
  149162. setup->psy_noise_normal_start[0],
  149163. setup->psy_noise_normal_partition[0],
  149164. setup->psy_noise_normal_thresh,
  149165. 0);
  149166. vorbis_encode_psyset_setup(vi,hi->short_setting,
  149167. setup->psy_noise_normal_start[0],
  149168. setup->psy_noise_normal_partition[0],
  149169. setup->psy_noise_normal_thresh,
  149170. 1);
  149171. if(!singleblock){
  149172. vorbis_encode_psyset_setup(vi,hi->long_setting,
  149173. setup->psy_noise_normal_start[1],
  149174. setup->psy_noise_normal_partition[1],
  149175. setup->psy_noise_normal_thresh,
  149176. 2);
  149177. vorbis_encode_psyset_setup(vi,hi->long_setting,
  149178. setup->psy_noise_normal_start[1],
  149179. setup->psy_noise_normal_partition[1],
  149180. setup->psy_noise_normal_thresh,
  149181. 3);
  149182. }
  149183. /* tone masking setup */
  149184. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  149185. setup->psy_tone_masteratt,
  149186. setup->psy_tone_0dB,
  149187. setup->psy_tone_adj_impulse);
  149188. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  149189. setup->psy_tone_masteratt,
  149190. setup->psy_tone_0dB,
  149191. setup->psy_tone_adj_other);
  149192. if(!singleblock){
  149193. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  149194. setup->psy_tone_masteratt,
  149195. setup->psy_tone_0dB,
  149196. setup->psy_tone_adj_other);
  149197. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  149198. setup->psy_tone_masteratt,
  149199. setup->psy_tone_0dB,
  149200. setup->psy_tone_adj_long);
  149201. }
  149202. /* noise companding setup */
  149203. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  149204. setup->psy_noise_compand,
  149205. setup->psy_noise_compand_short_mapping);
  149206. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  149207. setup->psy_noise_compand,
  149208. setup->psy_noise_compand_short_mapping);
  149209. if(!singleblock){
  149210. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  149211. setup->psy_noise_compand,
  149212. setup->psy_noise_compand_long_mapping);
  149213. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  149214. setup->psy_noise_compand,
  149215. setup->psy_noise_compand_long_mapping);
  149216. }
  149217. /* peak guarding setup */
  149218. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  149219. setup->psy_tone_dBsuppress);
  149220. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  149221. setup->psy_tone_dBsuppress);
  149222. if(!singleblock){
  149223. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  149224. setup->psy_tone_dBsuppress);
  149225. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  149226. setup->psy_tone_dBsuppress);
  149227. }
  149228. /* noise bias setup */
  149229. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  149230. setup->psy_noise_dBsuppress,
  149231. setup->psy_noise_bias_impulse,
  149232. setup->psy_noiseguards,
  149233. (i0==0?hi->impulse_noisetune:0.));
  149234. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  149235. setup->psy_noise_dBsuppress,
  149236. setup->psy_noise_bias_padding,
  149237. setup->psy_noiseguards,0.);
  149238. if(!singleblock){
  149239. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  149240. setup->psy_noise_dBsuppress,
  149241. setup->psy_noise_bias_trans,
  149242. setup->psy_noiseguards,0.);
  149243. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  149244. setup->psy_noise_dBsuppress,
  149245. setup->psy_noise_bias_long,
  149246. setup->psy_noiseguards,0.);
  149247. }
  149248. vorbis_encode_ath_setup(vi,0);
  149249. vorbis_encode_ath_setup(vi,1);
  149250. if(!singleblock){
  149251. vorbis_encode_ath_setup(vi,2);
  149252. vorbis_encode_ath_setup(vi,3);
  149253. }
  149254. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  149255. /* set bitrate readonlies and management */
  149256. if(hi->bitrate_av>0)
  149257. vi->bitrate_nominal=hi->bitrate_av;
  149258. else{
  149259. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  149260. }
  149261. vi->bitrate_lower=hi->bitrate_min;
  149262. vi->bitrate_upper=hi->bitrate_max;
  149263. if(hi->bitrate_av)
  149264. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  149265. else
  149266. vi->bitrate_window=0.;
  149267. if(hi->managed){
  149268. ci->bi.avg_rate=hi->bitrate_av;
  149269. ci->bi.min_rate=hi->bitrate_min;
  149270. ci->bi.max_rate=hi->bitrate_max;
  149271. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  149272. ci->bi.reservoir_bias=
  149273. hi->bitrate_reservoir_bias;
  149274. ci->bi.slew_damp=hi->bitrate_av_damp;
  149275. }
  149276. return(0);
  149277. }
  149278. static int vorbis_encode_setup_setting(vorbis_info *vi,
  149279. long channels,
  149280. long rate){
  149281. int ret=0,i,is;
  149282. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149283. highlevel_encode_setup *hi=&ci->hi;
  149284. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  149285. double ds;
  149286. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  149287. if(ret)return(ret);
  149288. is=hi->base_setting;
  149289. ds=hi->base_setting-is;
  149290. hi->short_setting=hi->base_setting;
  149291. hi->long_setting=hi->base_setting;
  149292. hi->managed=0;
  149293. hi->impulse_block_p=1;
  149294. hi->noise_normalize_p=1;
  149295. hi->stereo_point_setting=hi->base_setting;
  149296. hi->lowpass_kHz=
  149297. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  149298. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  149299. setup->psy_ath_float[is+1]*ds;
  149300. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  149301. setup->psy_ath_abs[is+1]*ds;
  149302. hi->amplitude_track_dBpersec=-6.;
  149303. hi->trigger_setting=hi->base_setting;
  149304. for(i=0;i<4;i++){
  149305. hi->block[i].tone_mask_setting=hi->base_setting;
  149306. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  149307. hi->block[i].noise_bias_setting=hi->base_setting;
  149308. hi->block[i].noise_compand_setting=hi->base_setting;
  149309. }
  149310. return(ret);
  149311. }
  149312. int vorbis_encode_setup_vbr(vorbis_info *vi,
  149313. long channels,
  149314. long rate,
  149315. float quality){
  149316. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  149317. highlevel_encode_setup *hi=&ci->hi;
  149318. quality+=.0000001;
  149319. if(quality>=1.)quality=.9999;
  149320. get_setup_template(vi,channels,rate,quality,0);
  149321. if(!hi->setup)return OV_EIMPL;
  149322. return vorbis_encode_setup_setting(vi,channels,rate);
  149323. }
  149324. int vorbis_encode_init_vbr(vorbis_info *vi,
  149325. long channels,
  149326. long rate,
  149327. float base_quality /* 0. to 1. */
  149328. ){
  149329. int ret=0;
  149330. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  149331. if(ret){
  149332. vorbis_info_clear(vi);
  149333. return ret;
  149334. }
  149335. ret=vorbis_encode_setup_init(vi);
  149336. if(ret)
  149337. vorbis_info_clear(vi);
  149338. return(ret);
  149339. }
  149340. int vorbis_encode_setup_managed(vorbis_info *vi,
  149341. long channels,
  149342. long rate,
  149343. long max_bitrate,
  149344. long nominal_bitrate,
  149345. long min_bitrate){
  149346. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149347. highlevel_encode_setup *hi=&ci->hi;
  149348. double tnominal=nominal_bitrate;
  149349. int ret=0;
  149350. if(nominal_bitrate<=0.){
  149351. if(max_bitrate>0.){
  149352. if(min_bitrate>0.)
  149353. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  149354. else
  149355. nominal_bitrate=max_bitrate*.875;
  149356. }else{
  149357. if(min_bitrate>0.){
  149358. nominal_bitrate=min_bitrate;
  149359. }else{
  149360. return(OV_EINVAL);
  149361. }
  149362. }
  149363. }
  149364. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  149365. if(!hi->setup)return OV_EIMPL;
  149366. ret=vorbis_encode_setup_setting(vi,channels,rate);
  149367. if(ret){
  149368. vorbis_info_clear(vi);
  149369. return ret;
  149370. }
  149371. /* initialize management with sane defaults */
  149372. hi->managed=1;
  149373. hi->bitrate_min=min_bitrate;
  149374. hi->bitrate_max=max_bitrate;
  149375. hi->bitrate_av=tnominal;
  149376. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  149377. hi->bitrate_reservoir=nominal_bitrate*2;
  149378. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  149379. return(ret);
  149380. }
  149381. int vorbis_encode_init(vorbis_info *vi,
  149382. long channels,
  149383. long rate,
  149384. long max_bitrate,
  149385. long nominal_bitrate,
  149386. long min_bitrate){
  149387. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  149388. max_bitrate,
  149389. nominal_bitrate,
  149390. min_bitrate);
  149391. if(ret){
  149392. vorbis_info_clear(vi);
  149393. return(ret);
  149394. }
  149395. ret=vorbis_encode_setup_init(vi);
  149396. if(ret)
  149397. vorbis_info_clear(vi);
  149398. return(ret);
  149399. }
  149400. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  149401. if(vi){
  149402. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  149403. highlevel_encode_setup *hi=&ci->hi;
  149404. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  149405. if(setp && hi->set_in_stone)return(OV_EINVAL);
  149406. switch(number){
  149407. /* now deprecated *****************/
  149408. case OV_ECTL_RATEMANAGE_GET:
  149409. {
  149410. struct ovectl_ratemanage_arg *ai=
  149411. (struct ovectl_ratemanage_arg *)arg;
  149412. ai->management_active=hi->managed;
  149413. ai->bitrate_hard_window=ai->bitrate_av_window=
  149414. (double)hi->bitrate_reservoir/vi->rate;
  149415. ai->bitrate_av_window_center=1.;
  149416. ai->bitrate_hard_min=hi->bitrate_min;
  149417. ai->bitrate_hard_max=hi->bitrate_max;
  149418. ai->bitrate_av_lo=hi->bitrate_av;
  149419. ai->bitrate_av_hi=hi->bitrate_av;
  149420. }
  149421. return(0);
  149422. /* now deprecated *****************/
  149423. case OV_ECTL_RATEMANAGE_SET:
  149424. {
  149425. struct ovectl_ratemanage_arg *ai=
  149426. (struct ovectl_ratemanage_arg *)arg;
  149427. if(ai==NULL){
  149428. hi->managed=0;
  149429. }else{
  149430. hi->managed=ai->management_active;
  149431. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  149432. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  149433. }
  149434. }
  149435. return 0;
  149436. /* now deprecated *****************/
  149437. case OV_ECTL_RATEMANAGE_AVG:
  149438. {
  149439. struct ovectl_ratemanage_arg *ai=
  149440. (struct ovectl_ratemanage_arg *)arg;
  149441. if(ai==NULL){
  149442. hi->bitrate_av=0;
  149443. }else{
  149444. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  149445. }
  149446. }
  149447. return(0);
  149448. /* now deprecated *****************/
  149449. case OV_ECTL_RATEMANAGE_HARD:
  149450. {
  149451. struct ovectl_ratemanage_arg *ai=
  149452. (struct ovectl_ratemanage_arg *)arg;
  149453. if(ai==NULL){
  149454. hi->bitrate_min=0;
  149455. hi->bitrate_max=0;
  149456. }else{
  149457. hi->bitrate_min=ai->bitrate_hard_min;
  149458. hi->bitrate_max=ai->bitrate_hard_max;
  149459. hi->bitrate_reservoir=ai->bitrate_hard_window*
  149460. (hi->bitrate_max+hi->bitrate_min)*.5;
  149461. }
  149462. if(hi->bitrate_reservoir<128.)
  149463. hi->bitrate_reservoir=128.;
  149464. }
  149465. return(0);
  149466. /* replacement ratemanage interface */
  149467. case OV_ECTL_RATEMANAGE2_GET:
  149468. {
  149469. struct ovectl_ratemanage2_arg *ai=
  149470. (struct ovectl_ratemanage2_arg *)arg;
  149471. if(ai==NULL)return OV_EINVAL;
  149472. ai->management_active=hi->managed;
  149473. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  149474. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  149475. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  149476. ai->bitrate_average_damping=hi->bitrate_av_damp;
  149477. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  149478. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  149479. }
  149480. return (0);
  149481. case OV_ECTL_RATEMANAGE2_SET:
  149482. {
  149483. struct ovectl_ratemanage2_arg *ai=
  149484. (struct ovectl_ratemanage2_arg *)arg;
  149485. if(ai==NULL){
  149486. hi->managed=0;
  149487. }else{
  149488. /* sanity check; only catch invariant violations */
  149489. if(ai->bitrate_limit_min_kbps>0 &&
  149490. ai->bitrate_average_kbps>0 &&
  149491. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  149492. return OV_EINVAL;
  149493. if(ai->bitrate_limit_max_kbps>0 &&
  149494. ai->bitrate_average_kbps>0 &&
  149495. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  149496. return OV_EINVAL;
  149497. if(ai->bitrate_limit_min_kbps>0 &&
  149498. ai->bitrate_limit_max_kbps>0 &&
  149499. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  149500. return OV_EINVAL;
  149501. if(ai->bitrate_average_damping <= 0.)
  149502. return OV_EINVAL;
  149503. if(ai->bitrate_limit_reservoir_bits < 0)
  149504. return OV_EINVAL;
  149505. if(ai->bitrate_limit_reservoir_bias < 0.)
  149506. return OV_EINVAL;
  149507. if(ai->bitrate_limit_reservoir_bias > 1.)
  149508. return OV_EINVAL;
  149509. hi->managed=ai->management_active;
  149510. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  149511. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  149512. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  149513. hi->bitrate_av_damp=ai->bitrate_average_damping;
  149514. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  149515. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  149516. }
  149517. }
  149518. return 0;
  149519. case OV_ECTL_LOWPASS_GET:
  149520. {
  149521. double *farg=(double *)arg;
  149522. *farg=hi->lowpass_kHz;
  149523. }
  149524. return(0);
  149525. case OV_ECTL_LOWPASS_SET:
  149526. {
  149527. double *farg=(double *)arg;
  149528. hi->lowpass_kHz=*farg;
  149529. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  149530. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  149531. }
  149532. return(0);
  149533. case OV_ECTL_IBLOCK_GET:
  149534. {
  149535. double *farg=(double *)arg;
  149536. *farg=hi->impulse_noisetune;
  149537. }
  149538. return(0);
  149539. case OV_ECTL_IBLOCK_SET:
  149540. {
  149541. double *farg=(double *)arg;
  149542. hi->impulse_noisetune=*farg;
  149543. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  149544. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  149545. }
  149546. return(0);
  149547. }
  149548. return(OV_EIMPL);
  149549. }
  149550. return(OV_EINVAL);
  149551. }
  149552. #endif
  149553. /********* End of inlined file: vorbisenc.c *********/
  149554. /********* Start of inlined file: vorbisfile.c *********/
  149555. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  149556. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  149557. // tasks..
  149558. #ifdef _MSC_VER
  149559. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  149560. #endif
  149561. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  149562. #if JUCE_USE_OGGVORBIS
  149563. #include <stdlib.h>
  149564. #include <stdio.h>
  149565. #include <errno.h>
  149566. #include <string.h>
  149567. #include <math.h>
  149568. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  149569. one logical bitstream arranged end to end (the only form of Ogg
  149570. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  149571. multiplexing] is not allowed in Vorbis) */
  149572. /* A Vorbis file can be played beginning to end (streamed) without
  149573. worrying ahead of time about chaining (see decoder_example.c). If
  149574. we have the whole file, however, and want random access
  149575. (seeking/scrubbing) or desire to know the total length/time of a
  149576. file, we need to account for the possibility of chaining. */
  149577. /* We can handle things a number of ways; we can determine the entire
  149578. bitstream structure right off the bat, or find pieces on demand.
  149579. This example determines and caches structure for the entire
  149580. bitstream, but builds a virtual decoder on the fly when moving
  149581. between links in the chain. */
  149582. /* There are also different ways to implement seeking. Enough
  149583. information exists in an Ogg bitstream to seek to
  149584. sample-granularity positions in the output. Or, one can seek by
  149585. picking some portion of the stream roughly in the desired area if
  149586. we only want coarse navigation through the stream. */
  149587. /*************************************************************************
  149588. * Many, many internal helpers. The intention is not to be confusing;
  149589. * rampant duplication and monolithic function implementation would be
  149590. * harder to understand anyway. The high level functions are last. Begin
  149591. * grokking near the end of the file */
  149592. /* read a little more data from the file/pipe into the ogg_sync framer
  149593. */
  149594. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  149595. over 8k gets what they deserve */
  149596. static long _get_data(OggVorbis_File *vf){
  149597. errno=0;
  149598. if(vf->datasource){
  149599. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  149600. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  149601. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  149602. if(bytes==0 && errno)return(-1);
  149603. return(bytes);
  149604. }else
  149605. return(0);
  149606. }
  149607. /* save a tiny smidge of verbosity to make the code more readable */
  149608. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  149609. if(vf->datasource){
  149610. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  149611. vf->offset=offset;
  149612. ogg_sync_reset(&vf->oy);
  149613. }else{
  149614. /* shouldn't happen unless someone writes a broken callback */
  149615. return;
  149616. }
  149617. }
  149618. /* The read/seek functions track absolute position within the stream */
  149619. /* from the head of the stream, get the next page. boundary specifies
  149620. if the function is allowed to fetch more data from the stream (and
  149621. how much) or only use internally buffered data.
  149622. boundary: -1) unbounded search
  149623. 0) read no additional data; use cached only
  149624. n) search for a new page beginning for n bytes
  149625. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  149626. n) found a page at absolute offset n */
  149627. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  149628. ogg_int64_t boundary){
  149629. if(boundary>0)boundary+=vf->offset;
  149630. while(1){
  149631. long more;
  149632. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  149633. more=ogg_sync_pageseek(&vf->oy,og);
  149634. if(more<0){
  149635. /* skipped n bytes */
  149636. vf->offset-=more;
  149637. }else{
  149638. if(more==0){
  149639. /* send more paramedics */
  149640. if(!boundary)return(OV_FALSE);
  149641. {
  149642. long ret=_get_data(vf);
  149643. if(ret==0)return(OV_EOF);
  149644. if(ret<0)return(OV_EREAD);
  149645. }
  149646. }else{
  149647. /* got a page. Return the offset at the page beginning,
  149648. advance the internal offset past the page end */
  149649. ogg_int64_t ret=vf->offset;
  149650. vf->offset+=more;
  149651. return(ret);
  149652. }
  149653. }
  149654. }
  149655. }
  149656. /* find the latest page beginning before the current stream cursor
  149657. position. Much dirtier than the above as Ogg doesn't have any
  149658. backward search linkage. no 'readp' as it will certainly have to
  149659. read. */
  149660. /* returns offset or OV_EREAD, OV_FAULT */
  149661. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  149662. ogg_int64_t begin=vf->offset;
  149663. ogg_int64_t end=begin;
  149664. ogg_int64_t ret;
  149665. ogg_int64_t offset=-1;
  149666. while(offset==-1){
  149667. begin-=CHUNKSIZE;
  149668. if(begin<0)
  149669. begin=0;
  149670. _seek_helper(vf,begin);
  149671. while(vf->offset<end){
  149672. ret=_get_next_page(vf,og,end-vf->offset);
  149673. if(ret==OV_EREAD)return(OV_EREAD);
  149674. if(ret<0){
  149675. break;
  149676. }else{
  149677. offset=ret;
  149678. }
  149679. }
  149680. }
  149681. /* we have the offset. Actually snork and hold the page now */
  149682. _seek_helper(vf,offset);
  149683. ret=_get_next_page(vf,og,CHUNKSIZE);
  149684. if(ret<0)
  149685. /* this shouldn't be possible */
  149686. return(OV_EFAULT);
  149687. return(offset);
  149688. }
  149689. /* finds each bitstream link one at a time using a bisection search
  149690. (has to begin by knowing the offset of the lb's initial page).
  149691. Recurses for each link so it can alloc the link storage after
  149692. finding them all, then unroll and fill the cache at the same time */
  149693. static int _bisect_forward_serialno(OggVorbis_File *vf,
  149694. ogg_int64_t begin,
  149695. ogg_int64_t searched,
  149696. ogg_int64_t end,
  149697. long currentno,
  149698. long m){
  149699. ogg_int64_t endsearched=end;
  149700. ogg_int64_t next=end;
  149701. ogg_page og;
  149702. ogg_int64_t ret;
  149703. /* the below guards against garbage seperating the last and
  149704. first pages of two links. */
  149705. while(searched<endsearched){
  149706. ogg_int64_t bisect;
  149707. if(endsearched-searched<CHUNKSIZE){
  149708. bisect=searched;
  149709. }else{
  149710. bisect=(searched+endsearched)/2;
  149711. }
  149712. _seek_helper(vf,bisect);
  149713. ret=_get_next_page(vf,&og,-1);
  149714. if(ret==OV_EREAD)return(OV_EREAD);
  149715. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  149716. endsearched=bisect;
  149717. if(ret>=0)next=ret;
  149718. }else{
  149719. searched=ret+og.header_len+og.body_len;
  149720. }
  149721. }
  149722. _seek_helper(vf,next);
  149723. ret=_get_next_page(vf,&og,-1);
  149724. if(ret==OV_EREAD)return(OV_EREAD);
  149725. if(searched>=end || ret<0){
  149726. vf->links=m+1;
  149727. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  149728. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  149729. vf->offsets[m+1]=searched;
  149730. }else{
  149731. ret=_bisect_forward_serialno(vf,next,vf->offset,
  149732. end,ogg_page_serialno(&og),m+1);
  149733. if(ret==OV_EREAD)return(OV_EREAD);
  149734. }
  149735. vf->offsets[m]=begin;
  149736. vf->serialnos[m]=currentno;
  149737. return(0);
  149738. }
  149739. /* uses the local ogg_stream storage in vf; this is important for
  149740. non-streaming input sources */
  149741. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  149742. long *serialno,ogg_page *og_ptr){
  149743. ogg_page og;
  149744. ogg_packet op;
  149745. int i,ret;
  149746. if(!og_ptr){
  149747. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  149748. if(llret==OV_EREAD)return(OV_EREAD);
  149749. if(llret<0)return OV_ENOTVORBIS;
  149750. og_ptr=&og;
  149751. }
  149752. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  149753. if(serialno)*serialno=vf->os.serialno;
  149754. vf->ready_state=STREAMSET;
  149755. /* extract the initial header from the first page and verify that the
  149756. Ogg bitstream is in fact Vorbis data */
  149757. vorbis_info_init(vi);
  149758. vorbis_comment_init(vc);
  149759. i=0;
  149760. while(i<3){
  149761. ogg_stream_pagein(&vf->os,og_ptr);
  149762. while(i<3){
  149763. int result=ogg_stream_packetout(&vf->os,&op);
  149764. if(result==0)break;
  149765. if(result==-1){
  149766. ret=OV_EBADHEADER;
  149767. goto bail_header;
  149768. }
  149769. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  149770. goto bail_header;
  149771. }
  149772. i++;
  149773. }
  149774. if(i<3)
  149775. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  149776. ret=OV_EBADHEADER;
  149777. goto bail_header;
  149778. }
  149779. }
  149780. return 0;
  149781. bail_header:
  149782. vorbis_info_clear(vi);
  149783. vorbis_comment_clear(vc);
  149784. vf->ready_state=OPENED;
  149785. return ret;
  149786. }
  149787. /* last step of the OggVorbis_File initialization; get all the
  149788. vorbis_info structs and PCM positions. Only called by the seekable
  149789. initialization (local stream storage is hacked slightly; pay
  149790. attention to how that's done) */
  149791. /* this is void and does not propogate errors up because we want to be
  149792. able to open and use damaged bitstreams as well as we can. Just
  149793. watch out for missing information for links in the OggVorbis_File
  149794. struct */
  149795. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  149796. ogg_page og;
  149797. int i;
  149798. ogg_int64_t ret;
  149799. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  149800. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  149801. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  149802. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  149803. for(i=0;i<vf->links;i++){
  149804. if(i==0){
  149805. /* we already grabbed the initial header earlier. Just set the offset */
  149806. vf->dataoffsets[i]=dataoffset;
  149807. _seek_helper(vf,dataoffset);
  149808. }else{
  149809. /* seek to the location of the initial header */
  149810. _seek_helper(vf,vf->offsets[i]);
  149811. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  149812. vf->dataoffsets[i]=-1;
  149813. }else{
  149814. vf->dataoffsets[i]=vf->offset;
  149815. }
  149816. }
  149817. /* fetch beginning PCM offset */
  149818. if(vf->dataoffsets[i]!=-1){
  149819. ogg_int64_t accumulated=0;
  149820. long lastblock=-1;
  149821. int result;
  149822. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  149823. while(1){
  149824. ogg_packet op;
  149825. ret=_get_next_page(vf,&og,-1);
  149826. if(ret<0)
  149827. /* this should not be possible unless the file is
  149828. truncated/mangled */
  149829. break;
  149830. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  149831. break;
  149832. /* count blocksizes of all frames in the page */
  149833. ogg_stream_pagein(&vf->os,&og);
  149834. while((result=ogg_stream_packetout(&vf->os,&op))){
  149835. if(result>0){ /* ignore holes */
  149836. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  149837. if(lastblock!=-1)
  149838. accumulated+=(lastblock+thisblock)>>2;
  149839. lastblock=thisblock;
  149840. }
  149841. }
  149842. if(ogg_page_granulepos(&og)!=-1){
  149843. /* pcm offset of last packet on the first audio page */
  149844. accumulated= ogg_page_granulepos(&og)-accumulated;
  149845. break;
  149846. }
  149847. }
  149848. /* less than zero? This is a stream with samples trimmed off
  149849. the beginning, a normal occurrence; set the offset to zero */
  149850. if(accumulated<0)accumulated=0;
  149851. vf->pcmlengths[i*2]=accumulated;
  149852. }
  149853. /* get the PCM length of this link. To do this,
  149854. get the last page of the stream */
  149855. {
  149856. ogg_int64_t end=vf->offsets[i+1];
  149857. _seek_helper(vf,end);
  149858. while(1){
  149859. ret=_get_prev_page(vf,&og);
  149860. if(ret<0){
  149861. /* this should not be possible */
  149862. vorbis_info_clear(vf->vi+i);
  149863. vorbis_comment_clear(vf->vc+i);
  149864. break;
  149865. }
  149866. if(ogg_page_granulepos(&og)!=-1){
  149867. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  149868. break;
  149869. }
  149870. vf->offset=ret;
  149871. }
  149872. }
  149873. }
  149874. }
  149875. static int _make_decode_ready(OggVorbis_File *vf){
  149876. if(vf->ready_state>STREAMSET)return 0;
  149877. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  149878. if(vf->seekable){
  149879. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  149880. return OV_EBADLINK;
  149881. }else{
  149882. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  149883. return OV_EBADLINK;
  149884. }
  149885. vorbis_block_init(&vf->vd,&vf->vb);
  149886. vf->ready_state=INITSET;
  149887. vf->bittrack=0.f;
  149888. vf->samptrack=0.f;
  149889. return 0;
  149890. }
  149891. static int _open_seekable2(OggVorbis_File *vf){
  149892. long serialno=vf->current_serialno;
  149893. ogg_int64_t dataoffset=vf->offset, end;
  149894. ogg_page og;
  149895. /* we're partially open and have a first link header state in
  149896. storage in vf */
  149897. /* we can seek, so set out learning all about this file */
  149898. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  149899. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  149900. /* We get the offset for the last page of the physical bitstream.
  149901. Most OggVorbis files will contain a single logical bitstream */
  149902. end=_get_prev_page(vf,&og);
  149903. if(end<0)return(end);
  149904. /* more than one logical bitstream? */
  149905. if(ogg_page_serialno(&og)!=serialno){
  149906. /* Chained bitstream. Bisect-search each logical bitstream
  149907. section. Do so based on serial number only */
  149908. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  149909. }else{
  149910. /* Only one logical bitstream */
  149911. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  149912. }
  149913. /* the initial header memory is referenced by vf after; don't free it */
  149914. _prefetch_all_headers(vf,dataoffset);
  149915. return(ov_raw_seek(vf,0));
  149916. }
  149917. /* clear out the current logical bitstream decoder */
  149918. static void _decode_clear(OggVorbis_File *vf){
  149919. vorbis_dsp_clear(&vf->vd);
  149920. vorbis_block_clear(&vf->vb);
  149921. vf->ready_state=OPENED;
  149922. }
  149923. /* fetch and process a packet. Handles the case where we're at a
  149924. bitstream boundary and dumps the decoding machine. If the decoding
  149925. machine is unloaded, it loads it. It also keeps pcm_offset up to
  149926. date (seek and read both use this. seek uses a special hack with
  149927. readp).
  149928. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  149929. 0) need more data (only if readp==0)
  149930. 1) got a packet
  149931. */
  149932. static int _fetch_and_process_packet(OggVorbis_File *vf,
  149933. ogg_packet *op_in,
  149934. int readp,
  149935. int spanp){
  149936. ogg_page og;
  149937. /* handle one packet. Try to fetch it from current stream state */
  149938. /* extract packets from page */
  149939. while(1){
  149940. /* process a packet if we can. If the machine isn't loaded,
  149941. neither is a page */
  149942. if(vf->ready_state==INITSET){
  149943. while(1) {
  149944. ogg_packet op;
  149945. ogg_packet *op_ptr=(op_in?op_in:&op);
  149946. int result=ogg_stream_packetout(&vf->os,op_ptr);
  149947. ogg_int64_t granulepos;
  149948. op_in=NULL;
  149949. if(result==-1)return(OV_HOLE); /* hole in the data. */
  149950. if(result>0){
  149951. /* got a packet. process it */
  149952. granulepos=op_ptr->granulepos;
  149953. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  149954. header handling. The
  149955. header packets aren't
  149956. audio, so if/when we
  149957. submit them,
  149958. vorbis_synthesis will
  149959. reject them */
  149960. /* suck in the synthesis data and track bitrate */
  149961. {
  149962. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  149963. /* for proper use of libvorbis within libvorbisfile,
  149964. oldsamples will always be zero. */
  149965. if(oldsamples)return(OV_EFAULT);
  149966. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  149967. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  149968. vf->bittrack+=op_ptr->bytes*8;
  149969. }
  149970. /* update the pcm offset. */
  149971. if(granulepos!=-1 && !op_ptr->e_o_s){
  149972. int link=(vf->seekable?vf->current_link:0);
  149973. int i,samples;
  149974. /* this packet has a pcm_offset on it (the last packet
  149975. completed on a page carries the offset) After processing
  149976. (above), we know the pcm position of the *last* sample
  149977. ready to be returned. Find the offset of the *first*
  149978. As an aside, this trick is inaccurate if we begin
  149979. reading anew right at the last page; the end-of-stream
  149980. granulepos declares the last frame in the stream, and the
  149981. last packet of the last page may be a partial frame.
  149982. So, we need a previous granulepos from an in-sequence page
  149983. to have a reference point. Thus the !op_ptr->e_o_s clause
  149984. above */
  149985. if(vf->seekable && link>0)
  149986. granulepos-=vf->pcmlengths[link*2];
  149987. if(granulepos<0)granulepos=0; /* actually, this
  149988. shouldn't be possible
  149989. here unless the stream
  149990. is very broken */
  149991. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  149992. granulepos-=samples;
  149993. for(i=0;i<link;i++)
  149994. granulepos+=vf->pcmlengths[i*2+1];
  149995. vf->pcm_offset=granulepos;
  149996. }
  149997. return(1);
  149998. }
  149999. }
  150000. else
  150001. break;
  150002. }
  150003. }
  150004. if(vf->ready_state>=OPENED){
  150005. ogg_int64_t ret;
  150006. if(!readp)return(0);
  150007. if((ret=_get_next_page(vf,&og,-1))<0){
  150008. return(OV_EOF); /* eof.
  150009. leave unitialized */
  150010. }
  150011. /* bitrate tracking; add the header's bytes here, the body bytes
  150012. are done by packet above */
  150013. vf->bittrack+=og.header_len*8;
  150014. /* has our decoding just traversed a bitstream boundary? */
  150015. if(vf->ready_state==INITSET){
  150016. if(vf->current_serialno!=ogg_page_serialno(&og)){
  150017. if(!spanp)
  150018. return(OV_EOF);
  150019. _decode_clear(vf);
  150020. if(!vf->seekable){
  150021. vorbis_info_clear(vf->vi);
  150022. vorbis_comment_clear(vf->vc);
  150023. }
  150024. }
  150025. }
  150026. }
  150027. /* Do we need to load a new machine before submitting the page? */
  150028. /* This is different in the seekable and non-seekable cases.
  150029. In the seekable case, we already have all the header
  150030. information loaded and cached; we just initialize the machine
  150031. with it and continue on our merry way.
  150032. In the non-seekable (streaming) case, we'll only be at a
  150033. boundary if we just left the previous logical bitstream and
  150034. we're now nominally at the header of the next bitstream
  150035. */
  150036. if(vf->ready_state!=INITSET){
  150037. int link;
  150038. if(vf->ready_state<STREAMSET){
  150039. if(vf->seekable){
  150040. vf->current_serialno=ogg_page_serialno(&og);
  150041. /* match the serialno to bitstream section. We use this rather than
  150042. offset positions to avoid problems near logical bitstream
  150043. boundaries */
  150044. for(link=0;link<vf->links;link++)
  150045. if(vf->serialnos[link]==vf->current_serialno)break;
  150046. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  150047. stream. error out,
  150048. leave machine
  150049. uninitialized */
  150050. vf->current_link=link;
  150051. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  150052. vf->ready_state=STREAMSET;
  150053. }else{
  150054. /* we're streaming */
  150055. /* fetch the three header packets, build the info struct */
  150056. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  150057. if(ret)return(ret);
  150058. vf->current_link++;
  150059. link=0;
  150060. }
  150061. }
  150062. {
  150063. int ret=_make_decode_ready(vf);
  150064. if(ret<0)return ret;
  150065. }
  150066. }
  150067. ogg_stream_pagein(&vf->os,&og);
  150068. }
  150069. }
  150070. /* if, eg, 64 bit stdio is configured by default, this will build with
  150071. fseek64 */
  150072. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  150073. if(f==NULL)return(-1);
  150074. return fseek(f,off,whence);
  150075. }
  150076. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  150077. long ibytes, ov_callbacks callbacks){
  150078. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  150079. int ret;
  150080. memset(vf,0,sizeof(*vf));
  150081. vf->datasource=f;
  150082. vf->callbacks = callbacks;
  150083. /* init the framing state */
  150084. ogg_sync_init(&vf->oy);
  150085. /* perhaps some data was previously read into a buffer for testing
  150086. against other stream types. Allow initialization from this
  150087. previously read data (as we may be reading from a non-seekable
  150088. stream) */
  150089. if(initial){
  150090. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  150091. memcpy(buffer,initial,ibytes);
  150092. ogg_sync_wrote(&vf->oy,ibytes);
  150093. }
  150094. /* can we seek? Stevens suggests the seek test was portable */
  150095. if(offsettest!=-1)vf->seekable=1;
  150096. /* No seeking yet; Set up a 'single' (current) logical bitstream
  150097. entry for partial open */
  150098. vf->links=1;
  150099. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  150100. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  150101. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  150102. /* Try to fetch the headers, maintaining all the storage */
  150103. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  150104. vf->datasource=NULL;
  150105. ov_clear(vf);
  150106. }else
  150107. vf->ready_state=PARTOPEN;
  150108. return(ret);
  150109. }
  150110. static int _ov_open2(OggVorbis_File *vf){
  150111. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  150112. vf->ready_state=OPENED;
  150113. if(vf->seekable){
  150114. int ret=_open_seekable2(vf);
  150115. if(ret){
  150116. vf->datasource=NULL;
  150117. ov_clear(vf);
  150118. }
  150119. return(ret);
  150120. }else
  150121. vf->ready_state=STREAMSET;
  150122. return 0;
  150123. }
  150124. /* clear out the OggVorbis_File struct */
  150125. int ov_clear(OggVorbis_File *vf){
  150126. if(vf){
  150127. vorbis_block_clear(&vf->vb);
  150128. vorbis_dsp_clear(&vf->vd);
  150129. ogg_stream_clear(&vf->os);
  150130. if(vf->vi && vf->links){
  150131. int i;
  150132. for(i=0;i<vf->links;i++){
  150133. vorbis_info_clear(vf->vi+i);
  150134. vorbis_comment_clear(vf->vc+i);
  150135. }
  150136. _ogg_free(vf->vi);
  150137. _ogg_free(vf->vc);
  150138. }
  150139. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  150140. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  150141. if(vf->serialnos)_ogg_free(vf->serialnos);
  150142. if(vf->offsets)_ogg_free(vf->offsets);
  150143. ogg_sync_clear(&vf->oy);
  150144. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  150145. memset(vf,0,sizeof(*vf));
  150146. }
  150147. #ifdef DEBUG_LEAKS
  150148. _VDBG_dump();
  150149. #endif
  150150. return(0);
  150151. }
  150152. /* inspects the OggVorbis file and finds/documents all the logical
  150153. bitstreams contained in it. Tries to be tolerant of logical
  150154. bitstream sections that are truncated/woogie.
  150155. return: -1) error
  150156. 0) OK
  150157. */
  150158. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  150159. ov_callbacks callbacks){
  150160. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  150161. if(ret)return ret;
  150162. return _ov_open2(vf);
  150163. }
  150164. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  150165. ov_callbacks callbacks = {
  150166. (size_t (*)(void *, size_t, size_t, void *)) fread,
  150167. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  150168. (int (*)(void *)) fclose,
  150169. (long (*)(void *)) ftell
  150170. };
  150171. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  150172. }
  150173. /* cheap hack for game usage where downsampling is desirable; there's
  150174. no need for SRC as we can just do it cheaply in libvorbis. */
  150175. int ov_halfrate(OggVorbis_File *vf,int flag){
  150176. int i;
  150177. if(vf->vi==NULL)return OV_EINVAL;
  150178. if(!vf->seekable)return OV_EINVAL;
  150179. if(vf->ready_state>=STREAMSET)
  150180. _decode_clear(vf); /* clear out stream state; later on libvorbis
  150181. will be able to swap this on the fly, but
  150182. for now dumping the decode machine is needed
  150183. to reinit the MDCT lookups. 1.1 libvorbis
  150184. is planned to be able to switch on the fly */
  150185. for(i=0;i<vf->links;i++){
  150186. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  150187. ov_halfrate(vf,0);
  150188. return OV_EINVAL;
  150189. }
  150190. }
  150191. return 0;
  150192. }
  150193. int ov_halfrate_p(OggVorbis_File *vf){
  150194. if(vf->vi==NULL)return OV_EINVAL;
  150195. return vorbis_synthesis_halfrate_p(vf->vi);
  150196. }
  150197. /* Only partially open the vorbis file; test for Vorbisness, and load
  150198. the headers for the first chain. Do not seek (although test for
  150199. seekability). Use ov_test_open to finish opening the file, else
  150200. ov_clear to close/free it. Same return codes as open. */
  150201. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  150202. ov_callbacks callbacks)
  150203. {
  150204. return _ov_open1(f,vf,initial,ibytes,callbacks);
  150205. }
  150206. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  150207. ov_callbacks callbacks = {
  150208. (size_t (*)(void *, size_t, size_t, void *)) fread,
  150209. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  150210. (int (*)(void *)) fclose,
  150211. (long (*)(void *)) ftell
  150212. };
  150213. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  150214. }
  150215. int ov_test_open(OggVorbis_File *vf){
  150216. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  150217. return _ov_open2(vf);
  150218. }
  150219. /* How many logical bitstreams in this physical bitstream? */
  150220. long ov_streams(OggVorbis_File *vf){
  150221. return vf->links;
  150222. }
  150223. /* Is the FILE * associated with vf seekable? */
  150224. long ov_seekable(OggVorbis_File *vf){
  150225. return vf->seekable;
  150226. }
  150227. /* returns the bitrate for a given logical bitstream or the entire
  150228. physical bitstream. If the file is open for random access, it will
  150229. find the *actual* average bitrate. If the file is streaming, it
  150230. returns the nominal bitrate (if set) else the average of the
  150231. upper/lower bounds (if set) else -1 (unset).
  150232. If you want the actual bitrate field settings, get them from the
  150233. vorbis_info structs */
  150234. long ov_bitrate(OggVorbis_File *vf,int i){
  150235. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150236. if(i>=vf->links)return(OV_EINVAL);
  150237. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  150238. if(i<0){
  150239. ogg_int64_t bits=0;
  150240. int i;
  150241. float br;
  150242. for(i=0;i<vf->links;i++)
  150243. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  150244. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  150245. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  150246. * so this is slightly transformed to make it work.
  150247. */
  150248. br = bits/ov_time_total(vf,-1);
  150249. return(rint(br));
  150250. }else{
  150251. if(vf->seekable){
  150252. /* return the actual bitrate */
  150253. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  150254. }else{
  150255. /* return nominal if set */
  150256. if(vf->vi[i].bitrate_nominal>0){
  150257. return vf->vi[i].bitrate_nominal;
  150258. }else{
  150259. if(vf->vi[i].bitrate_upper>0){
  150260. if(vf->vi[i].bitrate_lower>0){
  150261. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  150262. }else{
  150263. return vf->vi[i].bitrate_upper;
  150264. }
  150265. }
  150266. return(OV_FALSE);
  150267. }
  150268. }
  150269. }
  150270. }
  150271. /* returns the actual bitrate since last call. returns -1 if no
  150272. additional data to offer since last call (or at beginning of stream),
  150273. EINVAL if stream is only partially open
  150274. */
  150275. long ov_bitrate_instant(OggVorbis_File *vf){
  150276. int link=(vf->seekable?vf->current_link:0);
  150277. long ret;
  150278. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150279. if(vf->samptrack==0)return(OV_FALSE);
  150280. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  150281. vf->bittrack=0.f;
  150282. vf->samptrack=0.f;
  150283. return(ret);
  150284. }
  150285. /* Guess */
  150286. long ov_serialnumber(OggVorbis_File *vf,int i){
  150287. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  150288. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  150289. if(i<0){
  150290. return(vf->current_serialno);
  150291. }else{
  150292. return(vf->serialnos[i]);
  150293. }
  150294. }
  150295. /* returns: total raw (compressed) length of content if i==-1
  150296. raw (compressed) length of that logical bitstream for i==0 to n
  150297. OV_EINVAL if the stream is not seekable (we can't know the length)
  150298. or if stream is only partially open
  150299. */
  150300. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  150301. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150302. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  150303. if(i<0){
  150304. ogg_int64_t acc=0;
  150305. int i;
  150306. for(i=0;i<vf->links;i++)
  150307. acc+=ov_raw_total(vf,i);
  150308. return(acc);
  150309. }else{
  150310. return(vf->offsets[i+1]-vf->offsets[i]);
  150311. }
  150312. }
  150313. /* returns: total PCM length (samples) of content if i==-1 PCM length
  150314. (samples) of that logical bitstream for i==0 to n
  150315. OV_EINVAL if the stream is not seekable (we can't know the
  150316. length) or only partially open
  150317. */
  150318. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  150319. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150320. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  150321. if(i<0){
  150322. ogg_int64_t acc=0;
  150323. int i;
  150324. for(i=0;i<vf->links;i++)
  150325. acc+=ov_pcm_total(vf,i);
  150326. return(acc);
  150327. }else{
  150328. return(vf->pcmlengths[i*2+1]);
  150329. }
  150330. }
  150331. /* returns: total seconds of content if i==-1
  150332. seconds in that logical bitstream for i==0 to n
  150333. OV_EINVAL if the stream is not seekable (we can't know the
  150334. length) or only partially open
  150335. */
  150336. double ov_time_total(OggVorbis_File *vf,int i){
  150337. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150338. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  150339. if(i<0){
  150340. double acc=0;
  150341. int i;
  150342. for(i=0;i<vf->links;i++)
  150343. acc+=ov_time_total(vf,i);
  150344. return(acc);
  150345. }else{
  150346. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  150347. }
  150348. }
  150349. /* seek to an offset relative to the *compressed* data. This also
  150350. scans packets to update the PCM cursor. It will cross a logical
  150351. bitstream boundary, but only if it can't get any packets out of the
  150352. tail of the bitstream we seek to (so no surprises).
  150353. returns zero on success, nonzero on failure */
  150354. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  150355. ogg_stream_state work_os;
  150356. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150357. if(!vf->seekable)
  150358. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  150359. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  150360. /* don't yet clear out decoding machine (if it's initialized), in
  150361. the case we're in the same link. Restart the decode lapping, and
  150362. let _fetch_and_process_packet deal with a potential bitstream
  150363. boundary */
  150364. vf->pcm_offset=-1;
  150365. ogg_stream_reset_serialno(&vf->os,
  150366. vf->current_serialno); /* must set serialno */
  150367. vorbis_synthesis_restart(&vf->vd);
  150368. _seek_helper(vf,pos);
  150369. /* we need to make sure the pcm_offset is set, but we don't want to
  150370. advance the raw cursor past good packets just to get to the first
  150371. with a granulepos. That's not equivalent behavior to beginning
  150372. decoding as immediately after the seek position as possible.
  150373. So, a hack. We use two stream states; a local scratch state and
  150374. the shared vf->os stream state. We use the local state to
  150375. scan, and the shared state as a buffer for later decode.
  150376. Unfortuantely, on the last page we still advance to last packet
  150377. because the granulepos on the last page is not necessarily on a
  150378. packet boundary, and we need to make sure the granpos is
  150379. correct.
  150380. */
  150381. {
  150382. ogg_page og;
  150383. ogg_packet op;
  150384. int lastblock=0;
  150385. int accblock=0;
  150386. int thisblock;
  150387. int eosflag;
  150388. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  150389. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  150390. return from not necessarily
  150391. starting from the beginning */
  150392. while(1){
  150393. if(vf->ready_state>=STREAMSET){
  150394. /* snarf/scan a packet if we can */
  150395. int result=ogg_stream_packetout(&work_os,&op);
  150396. if(result>0){
  150397. if(vf->vi[vf->current_link].codec_setup){
  150398. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  150399. if(thisblock<0){
  150400. ogg_stream_packetout(&vf->os,NULL);
  150401. thisblock=0;
  150402. }else{
  150403. if(eosflag)
  150404. ogg_stream_packetout(&vf->os,NULL);
  150405. else
  150406. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  150407. }
  150408. if(op.granulepos!=-1){
  150409. int i,link=vf->current_link;
  150410. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  150411. if(granulepos<0)granulepos=0;
  150412. for(i=0;i<link;i++)
  150413. granulepos+=vf->pcmlengths[i*2+1];
  150414. vf->pcm_offset=granulepos-accblock;
  150415. break;
  150416. }
  150417. lastblock=thisblock;
  150418. continue;
  150419. }else
  150420. ogg_stream_packetout(&vf->os,NULL);
  150421. }
  150422. }
  150423. if(!lastblock){
  150424. if(_get_next_page(vf,&og,-1)<0){
  150425. vf->pcm_offset=ov_pcm_total(vf,-1);
  150426. break;
  150427. }
  150428. }else{
  150429. /* huh? Bogus stream with packets but no granulepos */
  150430. vf->pcm_offset=-1;
  150431. break;
  150432. }
  150433. /* has our decoding just traversed a bitstream boundary? */
  150434. if(vf->ready_state>=STREAMSET)
  150435. if(vf->current_serialno!=ogg_page_serialno(&og)){
  150436. _decode_clear(vf); /* clear out stream state */
  150437. ogg_stream_clear(&work_os);
  150438. }
  150439. if(vf->ready_state<STREAMSET){
  150440. int link;
  150441. vf->current_serialno=ogg_page_serialno(&og);
  150442. for(link=0;link<vf->links;link++)
  150443. if(vf->serialnos[link]==vf->current_serialno)break;
  150444. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  150445. error out, leave
  150446. machine uninitialized */
  150447. vf->current_link=link;
  150448. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  150449. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  150450. vf->ready_state=STREAMSET;
  150451. }
  150452. ogg_stream_pagein(&vf->os,&og);
  150453. ogg_stream_pagein(&work_os,&og);
  150454. eosflag=ogg_page_eos(&og);
  150455. }
  150456. }
  150457. ogg_stream_clear(&work_os);
  150458. vf->bittrack=0.f;
  150459. vf->samptrack=0.f;
  150460. return(0);
  150461. seek_error:
  150462. /* dump the machine so we're in a known state */
  150463. vf->pcm_offset=-1;
  150464. ogg_stream_clear(&work_os);
  150465. _decode_clear(vf);
  150466. return OV_EBADLINK;
  150467. }
  150468. /* Page granularity seek (faster than sample granularity because we
  150469. don't do the last bit of decode to find a specific sample).
  150470. Seek to the last [granule marked] page preceeding the specified pos
  150471. location, such that decoding past the returned point will quickly
  150472. arrive at the requested position. */
  150473. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  150474. int link=-1;
  150475. ogg_int64_t result=0;
  150476. ogg_int64_t total=ov_pcm_total(vf,-1);
  150477. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150478. if(!vf->seekable)return(OV_ENOSEEK);
  150479. if(pos<0 || pos>total)return(OV_EINVAL);
  150480. /* which bitstream section does this pcm offset occur in? */
  150481. for(link=vf->links-1;link>=0;link--){
  150482. total-=vf->pcmlengths[link*2+1];
  150483. if(pos>=total)break;
  150484. }
  150485. /* search within the logical bitstream for the page with the highest
  150486. pcm_pos preceeding (or equal to) pos. There is a danger here;
  150487. missing pages or incorrect frame number information in the
  150488. bitstream could make our task impossible. Account for that (it
  150489. would be an error condition) */
  150490. /* new search algorithm by HB (Nicholas Vinen) */
  150491. {
  150492. ogg_int64_t end=vf->offsets[link+1];
  150493. ogg_int64_t begin=vf->offsets[link];
  150494. ogg_int64_t begintime = vf->pcmlengths[link*2];
  150495. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  150496. ogg_int64_t target=pos-total+begintime;
  150497. ogg_int64_t best=begin;
  150498. ogg_page og;
  150499. while(begin<end){
  150500. ogg_int64_t bisect;
  150501. if(end-begin<CHUNKSIZE){
  150502. bisect=begin;
  150503. }else{
  150504. /* take a (pretty decent) guess. */
  150505. bisect=begin +
  150506. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  150507. if(bisect<=begin)
  150508. bisect=begin+1;
  150509. }
  150510. _seek_helper(vf,bisect);
  150511. while(begin<end){
  150512. result=_get_next_page(vf,&og,end-vf->offset);
  150513. if(result==OV_EREAD) goto seek_error;
  150514. if(result<0){
  150515. if(bisect<=begin+1)
  150516. end=begin; /* found it */
  150517. else{
  150518. if(bisect==0) goto seek_error;
  150519. bisect-=CHUNKSIZE;
  150520. if(bisect<=begin)bisect=begin+1;
  150521. _seek_helper(vf,bisect);
  150522. }
  150523. }else{
  150524. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  150525. if(granulepos==-1)continue;
  150526. if(granulepos<target){
  150527. best=result; /* raw offset of packet with granulepos */
  150528. begin=vf->offset; /* raw offset of next page */
  150529. begintime=granulepos;
  150530. if(target-begintime>44100)break;
  150531. bisect=begin; /* *not* begin + 1 */
  150532. }else{
  150533. if(bisect<=begin+1)
  150534. end=begin; /* found it */
  150535. else{
  150536. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  150537. end=result;
  150538. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  150539. if(bisect<=begin)bisect=begin+1;
  150540. _seek_helper(vf,bisect);
  150541. }else{
  150542. end=result;
  150543. endtime=granulepos;
  150544. break;
  150545. }
  150546. }
  150547. }
  150548. }
  150549. }
  150550. }
  150551. /* found our page. seek to it, update pcm offset. Easier case than
  150552. raw_seek, don't keep packets preceeding granulepos. */
  150553. {
  150554. ogg_page og;
  150555. ogg_packet op;
  150556. /* seek */
  150557. _seek_helper(vf,best);
  150558. vf->pcm_offset=-1;
  150559. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  150560. if(link!=vf->current_link){
  150561. /* Different link; dump entire decode machine */
  150562. _decode_clear(vf);
  150563. vf->current_link=link;
  150564. vf->current_serialno=ogg_page_serialno(&og);
  150565. vf->ready_state=STREAMSET;
  150566. }else{
  150567. vorbis_synthesis_restart(&vf->vd);
  150568. }
  150569. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  150570. ogg_stream_pagein(&vf->os,&og);
  150571. /* pull out all but last packet; the one with granulepos */
  150572. while(1){
  150573. result=ogg_stream_packetpeek(&vf->os,&op);
  150574. if(result==0){
  150575. /* !!! the packet finishing this page originated on a
  150576. preceeding page. Keep fetching previous pages until we
  150577. get one with a granulepos or without the 'continued' flag
  150578. set. Then just use raw_seek for simplicity. */
  150579. _seek_helper(vf,best);
  150580. while(1){
  150581. result=_get_prev_page(vf,&og);
  150582. if(result<0) goto seek_error;
  150583. if(ogg_page_granulepos(&og)>-1 ||
  150584. !ogg_page_continued(&og)){
  150585. return ov_raw_seek(vf,result);
  150586. }
  150587. vf->offset=result;
  150588. }
  150589. }
  150590. if(result<0){
  150591. result = OV_EBADPACKET;
  150592. goto seek_error;
  150593. }
  150594. if(op.granulepos!=-1){
  150595. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  150596. if(vf->pcm_offset<0)vf->pcm_offset=0;
  150597. vf->pcm_offset+=total;
  150598. break;
  150599. }else
  150600. result=ogg_stream_packetout(&vf->os,NULL);
  150601. }
  150602. }
  150603. }
  150604. /* verify result */
  150605. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  150606. result=OV_EFAULT;
  150607. goto seek_error;
  150608. }
  150609. vf->bittrack=0.f;
  150610. vf->samptrack=0.f;
  150611. return(0);
  150612. seek_error:
  150613. /* dump machine so we're in a known state */
  150614. vf->pcm_offset=-1;
  150615. _decode_clear(vf);
  150616. return (int)result;
  150617. }
  150618. /* seek to a sample offset relative to the decompressed pcm stream
  150619. returns zero on success, nonzero on failure */
  150620. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  150621. int thisblock,lastblock=0;
  150622. int ret=ov_pcm_seek_page(vf,pos);
  150623. if(ret<0)return(ret);
  150624. if((ret=_make_decode_ready(vf)))return ret;
  150625. /* discard leading packets we don't need for the lapping of the
  150626. position we want; don't decode them */
  150627. while(1){
  150628. ogg_packet op;
  150629. ogg_page og;
  150630. int ret=ogg_stream_packetpeek(&vf->os,&op);
  150631. if(ret>0){
  150632. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  150633. if(thisblock<0){
  150634. ogg_stream_packetout(&vf->os,NULL);
  150635. continue; /* non audio packet */
  150636. }
  150637. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  150638. if(vf->pcm_offset+((thisblock+
  150639. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  150640. /* remove the packet from packet queue and track its granulepos */
  150641. ogg_stream_packetout(&vf->os,NULL);
  150642. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  150643. only tracking, no
  150644. pcm_decode */
  150645. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  150646. /* end of logical stream case is hard, especially with exact
  150647. length positioning. */
  150648. if(op.granulepos>-1){
  150649. int i;
  150650. /* always believe the stream markers */
  150651. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  150652. if(vf->pcm_offset<0)vf->pcm_offset=0;
  150653. for(i=0;i<vf->current_link;i++)
  150654. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  150655. }
  150656. lastblock=thisblock;
  150657. }else{
  150658. if(ret<0 && ret!=OV_HOLE)break;
  150659. /* suck in a new page */
  150660. if(_get_next_page(vf,&og,-1)<0)break;
  150661. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  150662. if(vf->ready_state<STREAMSET){
  150663. int link;
  150664. vf->current_serialno=ogg_page_serialno(&og);
  150665. for(link=0;link<vf->links;link++)
  150666. if(vf->serialnos[link]==vf->current_serialno)break;
  150667. if(link==vf->links)return(OV_EBADLINK);
  150668. vf->current_link=link;
  150669. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  150670. vf->ready_state=STREAMSET;
  150671. ret=_make_decode_ready(vf);
  150672. if(ret)return ret;
  150673. lastblock=0;
  150674. }
  150675. ogg_stream_pagein(&vf->os,&og);
  150676. }
  150677. }
  150678. vf->bittrack=0.f;
  150679. vf->samptrack=0.f;
  150680. /* discard samples until we reach the desired position. Crossing a
  150681. logical bitstream boundary with abandon is OK. */
  150682. while(vf->pcm_offset<pos){
  150683. ogg_int64_t target=pos-vf->pcm_offset;
  150684. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  150685. if(samples>target)samples=target;
  150686. vorbis_synthesis_read(&vf->vd,samples);
  150687. vf->pcm_offset+=samples;
  150688. if(samples<target)
  150689. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  150690. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  150691. }
  150692. return 0;
  150693. }
  150694. /* seek to a playback time relative to the decompressed pcm stream
  150695. returns zero on success, nonzero on failure */
  150696. int ov_time_seek(OggVorbis_File *vf,double seconds){
  150697. /* translate time to PCM position and call ov_pcm_seek */
  150698. int link=-1;
  150699. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  150700. double time_total=ov_time_total(vf,-1);
  150701. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150702. if(!vf->seekable)return(OV_ENOSEEK);
  150703. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  150704. /* which bitstream section does this time offset occur in? */
  150705. for(link=vf->links-1;link>=0;link--){
  150706. pcm_total-=vf->pcmlengths[link*2+1];
  150707. time_total-=ov_time_total(vf,link);
  150708. if(seconds>=time_total)break;
  150709. }
  150710. /* enough information to convert time offset to pcm offset */
  150711. {
  150712. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  150713. return(ov_pcm_seek(vf,target));
  150714. }
  150715. }
  150716. /* page-granularity version of ov_time_seek
  150717. returns zero on success, nonzero on failure */
  150718. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  150719. /* translate time to PCM position and call ov_pcm_seek */
  150720. int link=-1;
  150721. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  150722. double time_total=ov_time_total(vf,-1);
  150723. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150724. if(!vf->seekable)return(OV_ENOSEEK);
  150725. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  150726. /* which bitstream section does this time offset occur in? */
  150727. for(link=vf->links-1;link>=0;link--){
  150728. pcm_total-=vf->pcmlengths[link*2+1];
  150729. time_total-=ov_time_total(vf,link);
  150730. if(seconds>=time_total)break;
  150731. }
  150732. /* enough information to convert time offset to pcm offset */
  150733. {
  150734. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  150735. return(ov_pcm_seek_page(vf,target));
  150736. }
  150737. }
  150738. /* tell the current stream offset cursor. Note that seek followed by
  150739. tell will likely not give the set offset due to caching */
  150740. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  150741. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150742. return(vf->offset);
  150743. }
  150744. /* return PCM offset (sample) of next PCM sample to be read */
  150745. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  150746. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150747. return(vf->pcm_offset);
  150748. }
  150749. /* return time offset (seconds) of next PCM sample to be read */
  150750. double ov_time_tell(OggVorbis_File *vf){
  150751. int link=0;
  150752. ogg_int64_t pcm_total=0;
  150753. double time_total=0.f;
  150754. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150755. if(vf->seekable){
  150756. pcm_total=ov_pcm_total(vf,-1);
  150757. time_total=ov_time_total(vf,-1);
  150758. /* which bitstream section does this time offset occur in? */
  150759. for(link=vf->links-1;link>=0;link--){
  150760. pcm_total-=vf->pcmlengths[link*2+1];
  150761. time_total-=ov_time_total(vf,link);
  150762. if(vf->pcm_offset>=pcm_total)break;
  150763. }
  150764. }
  150765. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  150766. }
  150767. /* link: -1) return the vorbis_info struct for the bitstream section
  150768. currently being decoded
  150769. 0-n) to request information for a specific bitstream section
  150770. In the case of a non-seekable bitstream, any call returns the
  150771. current bitstream. NULL in the case that the machine is not
  150772. initialized */
  150773. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  150774. if(vf->seekable){
  150775. if(link<0)
  150776. if(vf->ready_state>=STREAMSET)
  150777. return vf->vi+vf->current_link;
  150778. else
  150779. return vf->vi;
  150780. else
  150781. if(link>=vf->links)
  150782. return NULL;
  150783. else
  150784. return vf->vi+link;
  150785. }else{
  150786. return vf->vi;
  150787. }
  150788. }
  150789. /* grr, strong typing, grr, no templates/inheritence, grr */
  150790. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  150791. if(vf->seekable){
  150792. if(link<0)
  150793. if(vf->ready_state>=STREAMSET)
  150794. return vf->vc+vf->current_link;
  150795. else
  150796. return vf->vc;
  150797. else
  150798. if(link>=vf->links)
  150799. return NULL;
  150800. else
  150801. return vf->vc+link;
  150802. }else{
  150803. return vf->vc;
  150804. }
  150805. }
  150806. static int host_is_big_endian() {
  150807. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  150808. unsigned char *bytewise = (unsigned char *)&pattern;
  150809. if (bytewise[0] == 0xfe) return 1;
  150810. return 0;
  150811. }
  150812. /* up to this point, everything could more or less hide the multiple
  150813. logical bitstream nature of chaining from the toplevel application
  150814. if the toplevel application didn't particularly care. However, at
  150815. the point that we actually read audio back, the multiple-section
  150816. nature must surface: Multiple bitstream sections do not necessarily
  150817. have to have the same number of channels or sampling rate.
  150818. ov_read returns the sequential logical bitstream number currently
  150819. being decoded along with the PCM data in order that the toplevel
  150820. application can take action on channel/sample rate changes. This
  150821. number will be incremented even for streamed (non-seekable) streams
  150822. (for seekable streams, it represents the actual logical bitstream
  150823. index within the physical bitstream. Note that the accessor
  150824. functions above are aware of this dichotomy).
  150825. input values: buffer) a buffer to hold packed PCM data for return
  150826. length) the byte length requested to be placed into buffer
  150827. bigendianp) should the data be packed LSB first (0) or
  150828. MSB first (1)
  150829. word) word size for output. currently 1 (byte) or
  150830. 2 (16 bit short)
  150831. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  150832. 0) EOF
  150833. n) number of bytes of PCM actually returned. The
  150834. below works on a packet-by-packet basis, so the
  150835. return length is not related to the 'length' passed
  150836. in, just guaranteed to fit.
  150837. *section) set to the logical bitstream number */
  150838. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  150839. int bigendianp,int word,int sgned,int *bitstream){
  150840. int i,j;
  150841. int host_endian = host_is_big_endian();
  150842. float **pcm;
  150843. long samples;
  150844. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150845. while(1){
  150846. if(vf->ready_state==INITSET){
  150847. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  150848. if(samples)break;
  150849. }
  150850. /* suck in another packet */
  150851. {
  150852. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  150853. if(ret==OV_EOF)
  150854. return(0);
  150855. if(ret<=0)
  150856. return(ret);
  150857. }
  150858. }
  150859. if(samples>0){
  150860. /* yay! proceed to pack data into the byte buffer */
  150861. long channels=ov_info(vf,-1)->channels;
  150862. long bytespersample=word * channels;
  150863. vorbis_fpu_control fpu;
  150864. (void) fpu; // (to avoid a warning about it being unused)
  150865. if(samples>length/bytespersample)samples=length/bytespersample;
  150866. if(samples <= 0)
  150867. return OV_EINVAL;
  150868. /* a tight loop to pack each size */
  150869. {
  150870. int val;
  150871. if(word==1){
  150872. int off=(sgned?0:128);
  150873. vorbis_fpu_setround(&fpu);
  150874. for(j=0;j<samples;j++)
  150875. for(i=0;i<channels;i++){
  150876. val=vorbis_ftoi(pcm[i][j]*128.f);
  150877. if(val>127)val=127;
  150878. else if(val<-128)val=-128;
  150879. *buffer++=val+off;
  150880. }
  150881. vorbis_fpu_restore(fpu);
  150882. }else{
  150883. int off=(sgned?0:32768);
  150884. if(host_endian==bigendianp){
  150885. if(sgned){
  150886. vorbis_fpu_setround(&fpu);
  150887. for(i=0;i<channels;i++) { /* It's faster in this order */
  150888. float *src=pcm[i];
  150889. short *dest=((short *)buffer)+i;
  150890. for(j=0;j<samples;j++) {
  150891. val=vorbis_ftoi(src[j]*32768.f);
  150892. if(val>32767)val=32767;
  150893. else if(val<-32768)val=-32768;
  150894. *dest=val;
  150895. dest+=channels;
  150896. }
  150897. }
  150898. vorbis_fpu_restore(fpu);
  150899. }else{
  150900. vorbis_fpu_setround(&fpu);
  150901. for(i=0;i<channels;i++) {
  150902. float *src=pcm[i];
  150903. short *dest=((short *)buffer)+i;
  150904. for(j=0;j<samples;j++) {
  150905. val=vorbis_ftoi(src[j]*32768.f);
  150906. if(val>32767)val=32767;
  150907. else if(val<-32768)val=-32768;
  150908. *dest=val+off;
  150909. dest+=channels;
  150910. }
  150911. }
  150912. vorbis_fpu_restore(fpu);
  150913. }
  150914. }else if(bigendianp){
  150915. vorbis_fpu_setround(&fpu);
  150916. for(j=0;j<samples;j++)
  150917. for(i=0;i<channels;i++){
  150918. val=vorbis_ftoi(pcm[i][j]*32768.f);
  150919. if(val>32767)val=32767;
  150920. else if(val<-32768)val=-32768;
  150921. val+=off;
  150922. *buffer++=(val>>8);
  150923. *buffer++=(val&0xff);
  150924. }
  150925. vorbis_fpu_restore(fpu);
  150926. }else{
  150927. int val;
  150928. vorbis_fpu_setround(&fpu);
  150929. for(j=0;j<samples;j++)
  150930. for(i=0;i<channels;i++){
  150931. val=vorbis_ftoi(pcm[i][j]*32768.f);
  150932. if(val>32767)val=32767;
  150933. else if(val<-32768)val=-32768;
  150934. val+=off;
  150935. *buffer++=(val&0xff);
  150936. *buffer++=(val>>8);
  150937. }
  150938. vorbis_fpu_restore(fpu);
  150939. }
  150940. }
  150941. }
  150942. vorbis_synthesis_read(&vf->vd,samples);
  150943. vf->pcm_offset+=samples;
  150944. if(bitstream)*bitstream=vf->current_link;
  150945. return(samples*bytespersample);
  150946. }else{
  150947. return(samples);
  150948. }
  150949. }
  150950. /* input values: pcm_channels) a float vector per channel of output
  150951. length) the sample length being read by the app
  150952. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  150953. 0) EOF
  150954. n) number of samples of PCM actually returned. The
  150955. below works on a packet-by-packet basis, so the
  150956. return length is not related to the 'length' passed
  150957. in, just guaranteed to fit.
  150958. *section) set to the logical bitstream number */
  150959. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  150960. int *bitstream){
  150961. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150962. while(1){
  150963. if(vf->ready_state==INITSET){
  150964. float **pcm;
  150965. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  150966. if(samples){
  150967. if(pcm_channels)*pcm_channels=pcm;
  150968. if(samples>length)samples=length;
  150969. vorbis_synthesis_read(&vf->vd,samples);
  150970. vf->pcm_offset+=samples;
  150971. if(bitstream)*bitstream=vf->current_link;
  150972. return samples;
  150973. }
  150974. }
  150975. /* suck in another packet */
  150976. {
  150977. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  150978. if(ret==OV_EOF)return(0);
  150979. if(ret<=0)return(ret);
  150980. }
  150981. }
  150982. }
  150983. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  150984. extern void _analysis_output_always(char *base,int i,float *v,int n,int bark,int dB,
  150985. ogg_int64_t off);
  150986. static void _ov_splice(float **pcm,float **lappcm,
  150987. int n1, int n2,
  150988. int ch1, int ch2,
  150989. float *w1, float *w2){
  150990. int i,j;
  150991. float *w=w1;
  150992. int n=n1;
  150993. if(n1>n2){
  150994. n=n2;
  150995. w=w2;
  150996. }
  150997. /* splice */
  150998. for(j=0;j<ch1 && j<ch2;j++){
  150999. float *s=lappcm[j];
  151000. float *d=pcm[j];
  151001. for(i=0;i<n;i++){
  151002. float wd=w[i]*w[i];
  151003. float ws=1.-wd;
  151004. d[i]=d[i]*wd + s[i]*ws;
  151005. }
  151006. }
  151007. /* window from zero */
  151008. for(;j<ch2;j++){
  151009. float *d=pcm[j];
  151010. for(i=0;i<n;i++){
  151011. float wd=w[i]*w[i];
  151012. d[i]=d[i]*wd;
  151013. }
  151014. }
  151015. }
  151016. /* make sure vf is INITSET */
  151017. static int _ov_initset(OggVorbis_File *vf){
  151018. while(1){
  151019. if(vf->ready_state==INITSET)break;
  151020. /* suck in another packet */
  151021. {
  151022. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  151023. if(ret<0 && ret!=OV_HOLE)return(ret);
  151024. }
  151025. }
  151026. return 0;
  151027. }
  151028. /* make sure vf is INITSET and that we have a primed buffer; if
  151029. we're crosslapping at a stream section boundary, this also makes
  151030. sure we're sanity checking against the right stream information */
  151031. static int _ov_initprime(OggVorbis_File *vf){
  151032. vorbis_dsp_state *vd=&vf->vd;
  151033. while(1){
  151034. if(vf->ready_state==INITSET)
  151035. if(vorbis_synthesis_pcmout(vd,NULL))break;
  151036. /* suck in another packet */
  151037. {
  151038. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  151039. if(ret<0 && ret!=OV_HOLE)return(ret);
  151040. }
  151041. }
  151042. return 0;
  151043. }
  151044. /* grab enough data for lapping from vf; this may be in the form of
  151045. unreturned, already-decoded pcm, remaining PCM we will need to
  151046. decode, or synthetic postextrapolation from last packets. */
  151047. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  151048. float **lappcm,int lapsize){
  151049. int lapcount=0,i;
  151050. float **pcm;
  151051. /* try first to decode the lapping data */
  151052. while(lapcount<lapsize){
  151053. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  151054. if(samples){
  151055. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  151056. for(i=0;i<vi->channels;i++)
  151057. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  151058. lapcount+=samples;
  151059. vorbis_synthesis_read(vd,samples);
  151060. }else{
  151061. /* suck in another packet */
  151062. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  151063. if(ret==OV_EOF)break;
  151064. }
  151065. }
  151066. if(lapcount<lapsize){
  151067. /* failed to get lapping data from normal decode; pry it from the
  151068. postextrapolation buffering, or the second half of the MDCT
  151069. from the last packet */
  151070. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  151071. if(samples==0){
  151072. for(i=0;i<vi->channels;i++)
  151073. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  151074. lapcount=lapsize;
  151075. }else{
  151076. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  151077. for(i=0;i<vi->channels;i++)
  151078. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  151079. lapcount+=samples;
  151080. }
  151081. }
  151082. }
  151083. /* this sets up crosslapping of a sample by using trailing data from
  151084. sample 1 and lapping it into the windowing buffer of sample 2 */
  151085. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  151086. vorbis_info *vi1,*vi2;
  151087. float **lappcm;
  151088. float **pcm;
  151089. float *w1,*w2;
  151090. int n1,n2,i,ret,hs1,hs2;
  151091. if(vf1==vf2)return(0); /* degenerate case */
  151092. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  151093. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  151094. /* the relevant overlap buffers must be pre-checked and pre-primed
  151095. before looking at settings in the event that priming would cross
  151096. a bitstream boundary. So, do it now */
  151097. ret=_ov_initset(vf1);
  151098. if(ret)return(ret);
  151099. ret=_ov_initprime(vf2);
  151100. if(ret)return(ret);
  151101. vi1=ov_info(vf1,-1);
  151102. vi2=ov_info(vf2,-1);
  151103. hs1=ov_halfrate_p(vf1);
  151104. hs2=ov_halfrate_p(vf2);
  151105. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  151106. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  151107. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  151108. w1=vorbis_window(&vf1->vd,0);
  151109. w2=vorbis_window(&vf2->vd,0);
  151110. for(i=0;i<vi1->channels;i++)
  151111. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  151112. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  151113. /* have a lapping buffer from vf1; now to splice it into the lapping
  151114. buffer of vf2 */
  151115. /* consolidate and expose the buffer. */
  151116. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  151117. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  151118. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  151119. /* splice */
  151120. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  151121. /* done */
  151122. return(0);
  151123. }
  151124. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  151125. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  151126. vorbis_info *vi;
  151127. float **lappcm;
  151128. float **pcm;
  151129. float *w1,*w2;
  151130. int n1,n2,ch1,ch2,hs;
  151131. int i,ret;
  151132. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151133. ret=_ov_initset(vf);
  151134. if(ret)return(ret);
  151135. vi=ov_info(vf,-1);
  151136. hs=ov_halfrate_p(vf);
  151137. ch1=vi->channels;
  151138. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  151139. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  151140. persistent; even if the decode state
  151141. from this link gets dumped, this
  151142. window array continues to exist */
  151143. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  151144. for(i=0;i<ch1;i++)
  151145. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  151146. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  151147. /* have lapping data; seek and prime the buffer */
  151148. ret=localseek(vf,pos);
  151149. if(ret)return ret;
  151150. ret=_ov_initprime(vf);
  151151. if(ret)return(ret);
  151152. /* Guard against cross-link changes; they're perfectly legal */
  151153. vi=ov_info(vf,-1);
  151154. ch2=vi->channels;
  151155. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  151156. w2=vorbis_window(&vf->vd,0);
  151157. /* consolidate and expose the buffer. */
  151158. vorbis_synthesis_lapout(&vf->vd,&pcm);
  151159. /* splice */
  151160. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  151161. /* done */
  151162. return(0);
  151163. }
  151164. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  151165. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  151166. }
  151167. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  151168. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  151169. }
  151170. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  151171. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  151172. }
  151173. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  151174. int (*localseek)(OggVorbis_File *,double)){
  151175. vorbis_info *vi;
  151176. float **lappcm;
  151177. float **pcm;
  151178. float *w1,*w2;
  151179. int n1,n2,ch1,ch2,hs;
  151180. int i,ret;
  151181. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151182. ret=_ov_initset(vf);
  151183. if(ret)return(ret);
  151184. vi=ov_info(vf,-1);
  151185. hs=ov_halfrate_p(vf);
  151186. ch1=vi->channels;
  151187. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  151188. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  151189. persistent; even if the decode state
  151190. from this link gets dumped, this
  151191. window array continues to exist */
  151192. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  151193. for(i=0;i<ch1;i++)
  151194. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  151195. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  151196. /* have lapping data; seek and prime the buffer */
  151197. ret=localseek(vf,pos);
  151198. if(ret)return ret;
  151199. ret=_ov_initprime(vf);
  151200. if(ret)return(ret);
  151201. /* Guard against cross-link changes; they're perfectly legal */
  151202. vi=ov_info(vf,-1);
  151203. ch2=vi->channels;
  151204. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  151205. w2=vorbis_window(&vf->vd,0);
  151206. /* consolidate and expose the buffer. */
  151207. vorbis_synthesis_lapout(&vf->vd,&pcm);
  151208. /* splice */
  151209. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  151210. /* done */
  151211. return(0);
  151212. }
  151213. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  151214. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  151215. }
  151216. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  151217. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  151218. }
  151219. #endif
  151220. /********* End of inlined file: vorbisfile.c *********/
  151221. /********* Start of inlined file: window.c *********/
  151222. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  151223. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  151224. // tasks..
  151225. #ifdef _MSC_VER
  151226. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  151227. #endif
  151228. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  151229. #if JUCE_USE_OGGVORBIS
  151230. #include <stdlib.h>
  151231. #include <math.h>
  151232. static float vwin64[32] = {
  151233. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  151234. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  151235. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  151236. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  151237. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  151238. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  151239. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  151240. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  151241. };
  151242. static float vwin128[64] = {
  151243. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  151244. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  151245. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  151246. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  151247. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  151248. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  151249. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  151250. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  151251. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  151252. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  151253. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  151254. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  151255. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  151256. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  151257. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  151258. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  151259. };
  151260. static float vwin256[128] = {
  151261. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  151262. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  151263. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  151264. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  151265. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  151266. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  151267. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  151268. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  151269. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  151270. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  151271. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  151272. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  151273. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  151274. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  151275. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  151276. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  151277. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  151278. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  151279. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  151280. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  151281. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  151282. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  151283. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  151284. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  151285. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  151286. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  151287. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  151288. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  151289. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  151290. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  151291. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  151292. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  151293. };
  151294. static float vwin512[256] = {
  151295. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  151296. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  151297. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  151298. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  151299. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  151300. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  151301. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  151302. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  151303. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  151304. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  151305. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  151306. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  151307. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  151308. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  151309. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  151310. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  151311. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  151312. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  151313. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  151314. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  151315. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  151316. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  151317. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  151318. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  151319. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  151320. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  151321. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  151322. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  151323. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  151324. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  151325. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  151326. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  151327. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  151328. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  151329. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  151330. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  151331. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  151332. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  151333. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  151334. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  151335. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  151336. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  151337. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  151338. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  151339. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  151340. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  151341. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  151342. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  151343. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  151344. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  151345. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  151346. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  151347. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  151348. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  151349. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  151350. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  151351. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  151352. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  151353. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  151354. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  151355. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  151356. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  151357. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  151358. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  151359. };
  151360. static float vwin1024[512] = {
  151361. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  151362. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  151363. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  151364. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  151365. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  151366. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  151367. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  151368. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  151369. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  151370. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  151371. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  151372. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  151373. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  151374. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  151375. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  151376. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  151377. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  151378. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  151379. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  151380. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  151381. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  151382. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  151383. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  151384. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  151385. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  151386. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  151387. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  151388. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  151389. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  151390. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  151391. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  151392. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  151393. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  151394. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  151395. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  151396. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  151397. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  151398. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  151399. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  151400. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  151401. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  151402. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  151403. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  151404. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  151405. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  151406. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  151407. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  151408. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  151409. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  151410. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  151411. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  151412. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  151413. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  151414. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  151415. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  151416. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  151417. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  151418. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  151419. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  151420. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  151421. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  151422. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  151423. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  151424. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  151425. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  151426. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  151427. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  151428. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  151429. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  151430. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  151431. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  151432. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  151433. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  151434. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  151435. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  151436. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  151437. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  151438. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  151439. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  151440. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  151441. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  151442. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  151443. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  151444. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  151445. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  151446. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  151447. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  151448. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  151449. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  151450. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  151451. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  151452. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  151453. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  151454. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  151455. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  151456. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  151457. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  151458. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  151459. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  151460. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  151461. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  151462. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  151463. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  151464. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  151465. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  151466. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  151467. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  151468. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  151469. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  151470. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  151471. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  151472. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  151473. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  151474. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  151475. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  151476. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  151477. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  151478. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  151479. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  151480. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  151481. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  151482. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  151483. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  151484. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  151485. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  151486. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  151487. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  151488. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  151489. };
  151490. static float vwin2048[1024] = {
  151491. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  151492. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  151493. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  151494. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  151495. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  151496. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  151497. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  151498. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  151499. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  151500. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  151501. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  151502. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  151503. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  151504. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  151505. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  151506. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  151507. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  151508. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  151509. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  151510. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  151511. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  151512. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  151513. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  151514. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  151515. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  151516. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  151517. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  151518. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  151519. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  151520. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  151521. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  151522. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  151523. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  151524. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  151525. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  151526. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  151527. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  151528. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  151529. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  151530. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  151531. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  151532. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  151533. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  151534. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  151535. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  151536. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  151537. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  151538. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  151539. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  151540. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  151541. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  151542. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  151543. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  151544. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  151545. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  151546. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  151547. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  151548. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  151549. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  151550. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  151551. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  151552. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  151553. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  151554. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  151555. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  151556. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  151557. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  151558. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  151559. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  151560. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  151561. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  151562. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  151563. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  151564. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  151565. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  151566. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  151567. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  151568. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  151569. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  151570. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  151571. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  151572. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  151573. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  151574. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  151575. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  151576. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  151577. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  151578. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  151579. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  151580. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  151581. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  151582. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  151583. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  151584. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  151585. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  151586. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  151587. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  151588. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  151589. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  151590. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  151591. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  151592. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  151593. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  151594. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  151595. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  151596. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  151597. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  151598. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  151599. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  151600. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  151601. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  151602. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  151603. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  151604. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  151605. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  151606. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  151607. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  151608. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  151609. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  151610. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  151611. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  151612. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  151613. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  151614. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  151615. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  151616. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  151617. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  151618. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  151619. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  151620. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  151621. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  151622. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  151623. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  151624. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  151625. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  151626. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  151627. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  151628. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  151629. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  151630. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  151631. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  151632. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  151633. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  151634. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  151635. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  151636. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  151637. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  151638. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  151639. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  151640. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  151641. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  151642. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  151643. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  151644. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  151645. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  151646. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  151647. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  151648. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  151649. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  151650. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  151651. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  151652. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  151653. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  151654. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  151655. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  151656. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  151657. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  151658. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  151659. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  151660. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  151661. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  151662. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  151663. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  151664. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  151665. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  151666. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  151667. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  151668. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  151669. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  151670. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  151671. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  151672. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  151673. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  151674. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  151675. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  151676. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  151677. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  151678. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  151679. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  151680. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  151681. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  151682. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  151683. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  151684. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  151685. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  151686. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  151687. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  151688. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  151689. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  151690. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  151691. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  151692. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  151693. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  151694. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  151695. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  151696. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  151697. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  151698. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  151699. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  151700. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  151701. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  151702. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  151703. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  151704. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  151705. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  151706. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  151707. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  151708. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  151709. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  151710. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  151711. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  151712. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  151713. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  151714. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  151715. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  151716. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  151717. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  151718. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  151719. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  151720. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  151721. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  151722. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  151723. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  151724. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  151725. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  151726. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  151727. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  151728. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  151729. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  151730. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  151731. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  151732. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  151733. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  151734. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  151735. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  151736. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  151737. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  151738. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  151739. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  151740. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  151741. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  151742. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  151743. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  151744. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  151745. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  151746. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  151747. };
  151748. static float vwin4096[2048] = {
  151749. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  151750. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  151751. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  151752. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  151753. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  151754. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  151755. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  151756. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  151757. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  151758. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  151759. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  151760. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  151761. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  151762. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  151763. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  151764. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  151765. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  151766. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  151767. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  151768. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  151769. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  151770. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  151771. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  151772. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  151773. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  151774. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  151775. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  151776. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  151777. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  151778. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  151779. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  151780. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  151781. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  151782. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  151783. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  151784. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  151785. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  151786. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  151787. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  151788. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  151789. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  151790. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  151791. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  151792. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  151793. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  151794. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  151795. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  151796. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  151797. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  151798. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  151799. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  151800. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  151801. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  151802. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  151803. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  151804. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  151805. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  151806. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  151807. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  151808. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  151809. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  151810. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  151811. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  151812. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  151813. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  151814. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  151815. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  151816. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  151817. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  151818. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  151819. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  151820. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  151821. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  151822. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  151823. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  151824. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  151825. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  151826. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  151827. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  151828. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  151829. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  151830. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  151831. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  151832. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  151833. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  151834. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  151835. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  151836. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  151837. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  151838. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  151839. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  151840. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  151841. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  151842. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  151843. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  151844. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  151845. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  151846. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  151847. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  151848. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  151849. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  151850. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  151851. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  151852. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  151853. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  151854. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  151855. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  151856. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  151857. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  151858. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  151859. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  151860. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  151861. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  151862. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  151863. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  151864. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  151865. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  151866. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  151867. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  151868. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  151869. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  151870. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  151871. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  151872. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  151873. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  151874. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  151875. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  151876. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  151877. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  151878. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  151879. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  151880. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  151881. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  151882. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  151883. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  151884. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  151885. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  151886. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  151887. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  151888. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  151889. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  151890. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  151891. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  151892. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  151893. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  151894. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  151895. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  151896. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  151897. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  151898. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  151899. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  151900. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  151901. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  151902. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  151903. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  151904. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  151905. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  151906. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  151907. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  151908. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  151909. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  151910. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  151911. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  151912. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  151913. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  151914. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  151915. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  151916. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  151917. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  151918. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  151919. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  151920. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  151921. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  151922. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  151923. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  151924. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  151925. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  151926. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  151927. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  151928. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  151929. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  151930. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  151931. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  151932. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  151933. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  151934. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  151935. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  151936. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  151937. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  151938. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  151939. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  151940. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  151941. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  151942. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  151943. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  151944. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  151945. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  151946. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  151947. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  151948. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  151949. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  151950. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  151951. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  151952. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  151953. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  151954. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  151955. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  151956. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  151957. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  151958. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  151959. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  151960. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  151961. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  151962. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  151963. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  151964. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  151965. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  151966. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  151967. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  151968. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  151969. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  151970. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  151971. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  151972. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  151973. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  151974. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  151975. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  151976. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  151977. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  151978. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  151979. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  151980. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  151981. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  151982. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  151983. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  151984. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  151985. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  151986. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  151987. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  151988. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  151989. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  151990. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  151991. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  151992. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  151993. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  151994. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  151995. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  151996. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  151997. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  151998. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  151999. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  152000. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  152001. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  152002. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  152003. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  152004. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  152005. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  152006. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  152007. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  152008. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  152009. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  152010. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  152011. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  152012. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  152013. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  152014. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  152015. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  152016. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  152017. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  152018. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  152019. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  152020. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  152021. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  152022. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  152023. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  152024. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  152025. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  152026. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  152027. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  152028. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  152029. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  152030. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  152031. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  152032. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  152033. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  152034. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  152035. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  152036. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  152037. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  152038. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  152039. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  152040. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  152041. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  152042. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  152043. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  152044. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  152045. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  152046. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  152047. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  152048. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  152049. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  152050. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  152051. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  152052. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  152053. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  152054. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  152055. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  152056. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  152057. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  152058. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  152059. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  152060. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  152061. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  152062. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  152063. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  152064. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  152065. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  152066. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  152067. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  152068. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  152069. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  152070. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  152071. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  152072. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  152073. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  152074. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  152075. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  152076. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  152077. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  152078. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  152079. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  152080. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  152081. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  152082. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  152083. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  152084. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  152085. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  152086. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  152087. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  152088. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  152089. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  152090. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  152091. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  152092. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  152093. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  152094. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  152095. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  152096. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  152097. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  152098. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  152099. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  152100. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  152101. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  152102. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  152103. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  152104. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  152105. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  152106. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  152107. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  152108. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  152109. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  152110. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  152111. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  152112. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  152113. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  152114. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  152115. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  152116. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  152117. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  152118. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  152119. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  152120. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  152121. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  152122. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  152123. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  152124. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  152125. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  152126. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  152127. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  152128. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  152129. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  152130. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  152131. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  152132. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  152133. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  152134. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  152135. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  152136. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  152137. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  152138. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  152139. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  152140. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  152141. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  152142. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  152143. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  152144. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  152145. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  152146. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  152147. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  152148. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  152149. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  152150. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  152151. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  152152. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  152153. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  152154. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  152155. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  152156. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  152157. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  152158. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  152159. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  152160. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  152161. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  152162. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  152163. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  152164. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  152165. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  152166. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  152167. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  152168. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  152169. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  152170. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  152171. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  152172. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  152173. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  152174. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  152175. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  152176. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  152177. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  152178. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  152179. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  152180. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  152181. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  152182. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  152183. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  152184. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  152185. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  152186. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  152187. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  152188. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  152189. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  152190. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  152191. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  152192. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  152193. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  152194. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  152195. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  152196. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  152197. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  152198. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  152199. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  152200. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  152201. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  152202. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  152203. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  152204. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  152205. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  152206. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  152207. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  152208. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  152209. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  152210. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  152211. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  152212. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  152213. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  152214. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  152215. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  152216. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  152217. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  152218. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  152219. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  152220. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  152221. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  152222. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  152223. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  152224. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  152225. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  152226. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  152227. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  152228. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  152229. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  152230. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  152231. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  152232. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  152233. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  152234. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  152235. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  152236. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  152237. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  152238. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  152239. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  152240. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  152241. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  152242. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  152243. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  152244. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  152245. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  152246. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  152247. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  152248. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  152249. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  152250. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  152251. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  152252. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  152253. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  152254. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  152255. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  152256. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  152257. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  152258. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  152259. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  152260. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  152261. };
  152262. static float vwin8192[4096] = {
  152263. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  152264. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  152265. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  152266. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  152267. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  152268. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  152269. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  152270. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  152271. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  152272. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  152273. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  152274. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  152275. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  152276. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  152277. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  152278. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  152279. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  152280. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  152281. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  152282. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  152283. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  152284. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  152285. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  152286. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  152287. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  152288. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  152289. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  152290. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  152291. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  152292. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  152293. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  152294. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  152295. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  152296. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  152297. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  152298. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  152299. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  152300. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  152301. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  152302. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  152303. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  152304. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  152305. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  152306. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  152307. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  152308. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  152309. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  152310. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  152311. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  152312. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  152313. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  152314. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  152315. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  152316. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  152317. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  152318. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  152319. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  152320. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  152321. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  152322. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  152323. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  152324. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  152325. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  152326. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  152327. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  152328. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  152329. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  152330. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  152331. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  152332. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  152333. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  152334. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  152335. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  152336. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  152337. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  152338. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  152339. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  152340. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  152341. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  152342. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  152343. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  152344. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  152345. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  152346. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  152347. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  152348. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  152349. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  152350. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  152351. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  152352. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  152353. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  152354. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  152355. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  152356. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  152357. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  152358. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  152359. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  152360. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  152361. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  152362. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  152363. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  152364. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  152365. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  152366. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  152367. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  152368. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  152369. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  152370. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  152371. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  152372. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  152373. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  152374. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  152375. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  152376. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  152377. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  152378. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  152379. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  152380. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  152381. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  152382. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  152383. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  152384. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  152385. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  152386. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  152387. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  152388. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  152389. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  152390. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  152391. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  152392. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  152393. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  152394. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  152395. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  152396. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  152397. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  152398. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  152399. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  152400. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  152401. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  152402. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  152403. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  152404. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  152405. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  152406. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  152407. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  152408. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  152409. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  152410. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  152411. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  152412. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  152413. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  152414. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  152415. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  152416. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  152417. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  152418. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  152419. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  152420. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  152421. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  152422. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  152423. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  152424. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  152425. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  152426. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  152427. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  152428. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  152429. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  152430. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  152431. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  152432. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  152433. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  152434. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  152435. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  152436. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  152437. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  152438. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  152439. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  152440. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  152441. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  152442. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  152443. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  152444. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  152445. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  152446. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  152447. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  152448. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  152449. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  152450. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  152451. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  152452. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  152453. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  152454. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  152455. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  152456. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  152457. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  152458. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  152459. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  152460. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  152461. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  152462. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  152463. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  152464. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  152465. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  152466. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  152467. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  152468. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  152469. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  152470. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  152471. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  152472. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  152473. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  152474. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  152475. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  152476. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  152477. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  152478. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  152479. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  152480. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  152481. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  152482. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  152483. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  152484. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  152485. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  152486. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  152487. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  152488. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  152489. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  152490. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  152491. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  152492. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  152493. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  152494. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  152495. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  152496. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  152497. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  152498. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  152499. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  152500. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  152501. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  152502. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  152503. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  152504. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  152505. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  152506. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  152507. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  152508. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  152509. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  152510. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  152511. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  152512. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  152513. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  152514. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  152515. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  152516. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  152517. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  152518. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  152519. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  152520. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  152521. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  152522. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  152523. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  152524. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  152525. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  152526. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  152527. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  152528. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  152529. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  152530. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  152531. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  152532. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  152533. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  152534. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  152535. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  152536. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  152537. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  152538. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  152539. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  152540. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  152541. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  152542. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  152543. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  152544. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  152545. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  152546. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  152547. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  152548. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  152549. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  152550. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  152551. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  152552. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  152553. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  152554. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  152555. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  152556. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  152557. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  152558. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  152559. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  152560. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  152561. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  152562. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  152563. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  152564. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  152565. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  152566. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  152567. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  152568. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  152569. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  152570. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  152571. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  152572. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  152573. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  152574. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  152575. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  152576. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  152577. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  152578. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  152579. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  152580. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  152581. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  152582. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  152583. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  152584. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  152585. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  152586. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  152587. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  152588. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  152589. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  152590. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  152591. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  152592. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  152593. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  152594. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  152595. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  152596. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  152597. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  152598. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  152599. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  152600. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  152601. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  152602. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  152603. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  152604. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  152605. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  152606. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  152607. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  152608. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  152609. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  152610. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  152611. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  152612. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  152613. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  152614. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  152615. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  152616. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  152617. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  152618. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  152619. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  152620. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  152621. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  152622. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  152623. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  152624. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  152625. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  152626. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  152627. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  152628. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  152629. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  152630. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  152631. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  152632. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  152633. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  152634. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  152635. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  152636. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  152637. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  152638. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  152639. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  152640. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  152641. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  152642. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  152643. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  152644. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  152645. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  152646. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  152647. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  152648. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  152649. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  152650. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  152651. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  152652. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  152653. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  152654. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  152655. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  152656. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  152657. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  152658. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  152659. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  152660. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  152661. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  152662. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  152663. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  152664. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  152665. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  152666. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  152667. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  152668. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  152669. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  152670. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  152671. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  152672. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  152673. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  152674. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  152675. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  152676. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  152677. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  152678. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  152679. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  152680. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  152681. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  152682. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  152683. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  152684. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  152685. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  152686. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  152687. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  152688. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  152689. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  152690. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  152691. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  152692. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  152693. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  152694. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  152695. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  152696. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  152697. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  152698. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  152699. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  152700. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  152701. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  152702. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  152703. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  152704. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  152705. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  152706. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  152707. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  152708. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  152709. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  152710. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  152711. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  152712. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  152713. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  152714. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  152715. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  152716. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  152717. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  152718. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  152719. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  152720. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  152721. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  152722. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  152723. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  152724. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  152725. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  152726. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  152727. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  152728. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  152729. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  152730. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  152731. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  152732. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  152733. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  152734. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  152735. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  152736. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  152737. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  152738. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  152739. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  152740. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  152741. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  152742. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  152743. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  152744. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  152745. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  152746. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  152747. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  152748. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  152749. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  152750. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  152751. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  152752. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  152753. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  152754. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  152755. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  152756. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  152757. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  152758. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  152759. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  152760. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  152761. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  152762. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  152763. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  152764. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  152765. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  152766. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  152767. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  152768. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  152769. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  152770. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  152771. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  152772. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  152773. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  152774. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  152775. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  152776. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  152777. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  152778. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  152779. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  152780. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  152781. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  152782. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  152783. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  152784. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  152785. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  152786. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  152787. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  152788. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  152789. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  152790. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  152791. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  152792. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  152793. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  152794. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  152795. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  152796. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  152797. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  152798. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  152799. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  152800. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  152801. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  152802. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  152803. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  152804. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  152805. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  152806. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  152807. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  152808. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  152809. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  152810. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  152811. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  152812. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  152813. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  152814. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  152815. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  152816. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  152817. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  152818. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  152819. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  152820. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  152821. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  152822. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  152823. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  152824. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  152825. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  152826. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  152827. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  152828. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  152829. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  152830. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  152831. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  152832. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  152833. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  152834. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  152835. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  152836. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  152837. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  152838. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  152839. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  152840. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  152841. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  152842. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  152843. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  152844. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  152845. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  152846. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  152847. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  152848. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  152849. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  152850. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  152851. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  152852. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  152853. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  152854. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  152855. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  152856. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  152857. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  152858. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  152859. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  152860. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  152861. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  152862. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  152863. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  152864. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  152865. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  152866. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  152867. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  152868. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  152869. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  152870. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  152871. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  152872. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  152873. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  152874. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  152875. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  152876. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  152877. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  152878. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  152879. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  152880. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  152881. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  152882. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  152883. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  152884. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  152885. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  152886. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  152887. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  152888. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  152889. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  152890. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  152891. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  152892. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  152893. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  152894. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  152895. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  152896. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  152897. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  152898. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  152899. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  152900. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  152901. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  152902. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  152903. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  152904. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  152905. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  152906. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  152907. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  152908. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  152909. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  152910. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  152911. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  152912. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  152913. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  152914. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  152915. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  152916. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  152917. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  152918. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  152919. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  152920. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  152921. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  152922. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  152923. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  152924. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  152925. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  152926. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  152927. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  152928. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  152929. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  152930. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  152931. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  152932. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  152933. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  152934. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  152935. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  152936. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  152937. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  152938. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  152939. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  152940. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  152941. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  152942. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  152943. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  152944. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  152945. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  152946. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  152947. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  152948. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  152949. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  152950. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  152951. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  152952. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  152953. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  152954. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  152955. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  152956. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  152957. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  152958. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  152959. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  152960. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  152961. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  152962. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  152963. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  152964. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  152965. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  152966. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  152967. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  152968. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  152969. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  152970. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  152971. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  152972. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  152973. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  152974. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  152975. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  152976. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  152977. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  152978. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  152979. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  152980. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  152981. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  152982. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  152983. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  152984. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  152985. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  152986. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  152987. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  152988. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  152989. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  152990. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  152991. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  152992. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  152993. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  152994. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  152995. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  152996. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  152997. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  152998. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  152999. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  153000. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  153001. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  153002. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  153003. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  153004. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  153005. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  153006. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  153007. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  153008. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  153009. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  153010. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  153011. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  153012. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  153013. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  153014. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  153015. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  153016. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  153017. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  153018. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  153019. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  153020. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  153021. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  153022. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  153023. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  153024. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  153025. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  153026. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  153027. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  153028. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  153029. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  153030. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  153031. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  153032. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  153033. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  153034. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  153035. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  153036. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  153037. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  153038. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  153039. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  153040. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  153041. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  153042. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  153043. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  153044. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  153045. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  153046. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  153047. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  153048. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  153049. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  153050. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  153051. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  153052. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  153053. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  153054. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  153055. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  153056. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  153057. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  153058. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  153059. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  153060. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  153061. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  153062. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  153063. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  153064. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  153065. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  153066. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  153067. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  153068. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  153069. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  153070. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  153071. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  153072. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  153073. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  153074. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  153075. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  153076. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  153077. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  153078. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  153079. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  153080. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  153081. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  153082. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  153083. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  153084. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  153085. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  153086. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  153087. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  153088. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  153089. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  153090. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  153091. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  153092. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  153093. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  153094. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  153095. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  153096. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  153097. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  153098. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  153099. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  153100. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  153101. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  153102. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  153103. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  153104. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  153105. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  153106. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  153107. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  153108. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  153109. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  153110. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  153111. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  153112. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  153113. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  153114. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  153115. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  153116. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  153117. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  153118. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  153119. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  153120. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  153121. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  153122. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  153123. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  153124. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  153125. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  153126. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  153127. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  153128. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  153129. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  153130. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  153131. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  153132. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  153133. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  153134. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  153135. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  153136. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  153137. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  153138. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  153139. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  153140. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  153141. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  153142. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  153143. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  153144. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  153145. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  153146. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  153147. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  153148. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  153149. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  153150. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  153151. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  153152. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  153153. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  153154. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  153155. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  153156. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  153157. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  153158. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  153159. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  153160. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  153161. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  153162. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  153163. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  153164. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  153165. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  153166. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  153167. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  153168. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  153169. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  153170. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  153171. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  153172. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  153173. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  153174. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  153175. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  153176. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  153177. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  153178. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  153179. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  153180. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  153181. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  153182. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  153183. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  153184. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  153185. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  153186. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  153187. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  153188. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  153189. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  153190. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  153191. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  153192. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  153193. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  153194. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  153195. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  153196. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  153197. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  153198. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  153199. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  153200. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  153201. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  153202. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  153203. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  153204. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  153205. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  153206. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  153207. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  153208. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  153209. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  153210. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  153211. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  153212. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  153213. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  153214. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  153215. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  153216. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  153217. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  153218. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  153219. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  153220. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  153221. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  153222. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  153223. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  153224. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  153225. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  153226. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  153227. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  153228. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  153229. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  153230. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  153231. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  153232. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  153233. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  153234. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  153235. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  153236. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  153237. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  153238. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  153239. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  153240. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  153241. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  153242. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  153243. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  153244. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  153245. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  153246. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  153247. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  153248. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  153249. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  153250. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  153251. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  153252. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  153253. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  153254. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  153255. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  153256. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  153257. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  153258. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  153259. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  153260. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  153261. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  153262. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  153263. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  153264. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  153265. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  153266. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  153267. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  153268. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  153269. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  153270. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  153271. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  153272. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  153273. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  153274. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  153275. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  153276. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  153277. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  153278. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  153279. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  153280. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  153281. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  153282. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  153283. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  153284. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  153285. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  153286. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  153287. };
  153288. static float *vwin[8] = {
  153289. vwin64,
  153290. vwin128,
  153291. vwin256,
  153292. vwin512,
  153293. vwin1024,
  153294. vwin2048,
  153295. vwin4096,
  153296. vwin8192,
  153297. };
  153298. float *_vorbis_window_get(int n){
  153299. return vwin[n];
  153300. }
  153301. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  153302. int lW,int W,int nW){
  153303. lW=(W?lW:0);
  153304. nW=(W?nW:0);
  153305. {
  153306. float *windowLW=vwin[winno[lW]];
  153307. float *windowNW=vwin[winno[nW]];
  153308. long n=blocksizes[W];
  153309. long ln=blocksizes[lW];
  153310. long rn=blocksizes[nW];
  153311. long leftbegin=n/4-ln/4;
  153312. long leftend=leftbegin+ln/2;
  153313. long rightbegin=n/2+n/4-rn/4;
  153314. long rightend=rightbegin+rn/2;
  153315. int i,p;
  153316. for(i=0;i<leftbegin;i++)
  153317. d[i]=0.f;
  153318. for(p=0;i<leftend;i++,p++)
  153319. d[i]*=windowLW[p];
  153320. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  153321. d[i]*=windowNW[p];
  153322. for(;i<n;i++)
  153323. d[i]=0.f;
  153324. }
  153325. }
  153326. #endif
  153327. /********* End of inlined file: window.c *********/
  153328. }
  153329. BEGIN_JUCE_NAMESPACE
  153330. using namespace OggVorbisNamespace;
  153331. #define oggFormatName TRANS("Ogg-Vorbis file")
  153332. static const tchar* const oggExtensions[] = { T(".ogg"), 0 };
  153333. class OggReader : public AudioFormatReader
  153334. {
  153335. OggVorbis_File ovFile;
  153336. ov_callbacks callbacks;
  153337. AudioSampleBuffer reservoir;
  153338. int reservoirStart, samplesInReservoir;
  153339. public:
  153340. OggReader (InputStream* const inp)
  153341. : AudioFormatReader (inp, oggFormatName),
  153342. reservoir (2, 4096),
  153343. reservoirStart (0),
  153344. samplesInReservoir (0)
  153345. {
  153346. sampleRate = 0;
  153347. usesFloatingPointData = true;
  153348. callbacks.read_func = &oggReadCallback;
  153349. callbacks.seek_func = &oggSeekCallback;
  153350. callbacks.close_func = &oggCloseCallback;
  153351. callbacks.tell_func = &oggTellCallback;
  153352. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  153353. if (err == 0)
  153354. {
  153355. vorbis_info* info = ov_info (&ovFile, -1);
  153356. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  153357. numChannels = info->channels;
  153358. bitsPerSample = 16;
  153359. sampleRate = info->rate;
  153360. reservoir.setSize (numChannels,
  153361. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  153362. }
  153363. }
  153364. ~OggReader()
  153365. {
  153366. ov_clear (&ovFile);
  153367. }
  153368. bool read (int** destSamples,
  153369. int64 startSampleInFile,
  153370. int numSamples)
  153371. {
  153372. int startOffsetInDestBuffer = 0;
  153373. if (startSampleInFile < 0)
  153374. {
  153375. const int silence = (int) jmin (-startSampleInFile, (int64) numSamples);
  153376. int** destChan = destSamples;
  153377. for (int i = 2; --i >= 0;)
  153378. {
  153379. if (*destChan != 0)
  153380. {
  153381. zeromem (*destChan, sizeof (int) * silence);
  153382. ++destChan;
  153383. }
  153384. }
  153385. startOffsetInDestBuffer += silence;
  153386. numSamples -= silence;
  153387. }
  153388. while (numSamples > 0)
  153389. {
  153390. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  153391. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  153392. {
  153393. // got a few samples overlapping, so use them before seeking..
  153394. const int numToUse = jmin (numSamples, numAvailable);
  153395. for (unsigned int i = 0; i < numChannels; ++i)
  153396. {
  153397. if (destSamples[i] == 0)
  153398. break;
  153399. memcpy (destSamples[i] + startOffsetInDestBuffer,
  153400. reservoir.getSampleData (jmin (i, reservoir.getNumChannels()),
  153401. (int) (startSampleInFile - reservoirStart)),
  153402. sizeof (float) * numToUse);
  153403. }
  153404. startSampleInFile += numToUse;
  153405. numSamples -= numToUse;
  153406. startOffsetInDestBuffer += numToUse;
  153407. if (numSamples == 0)
  153408. break;
  153409. }
  153410. if (startSampleInFile < reservoirStart
  153411. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  153412. {
  153413. // buffer miss, so refill the reservoir
  153414. int bitStream = 0;
  153415. reservoirStart = jmax (0, (int) startSampleInFile);
  153416. samplesInReservoir = reservoir.getNumSamples();
  153417. if (reservoirStart != (int) ov_pcm_tell (&ovFile))
  153418. ov_pcm_seek (&ovFile, reservoirStart);
  153419. int offset = 0;
  153420. int numToRead = samplesInReservoir;
  153421. while (numToRead > 0)
  153422. {
  153423. float** dataIn = 0;
  153424. const int samps = ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  153425. if (samps == 0)
  153426. break;
  153427. jassert (samps <= numToRead);
  153428. for (int i = jmin (numChannels, reservoir.getNumChannels()); --i >= 0;)
  153429. {
  153430. memcpy (reservoir.getSampleData (i, offset),
  153431. dataIn[i],
  153432. sizeof (float) * samps);
  153433. }
  153434. numToRead -= samps;
  153435. offset += samps;
  153436. }
  153437. if (numToRead > 0)
  153438. reservoir.clear (offset, numToRead);
  153439. }
  153440. }
  153441. return true;
  153442. }
  153443. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  153444. {
  153445. return (size_t) (((InputStream*) datasource)->read (ptr, (int) (size * nmemb)) / size);
  153446. }
  153447. static int oggSeekCallback (void* datasource, ogg_int64_t offset, int whence)
  153448. {
  153449. InputStream* const in = (InputStream*) datasource;
  153450. if (whence == SEEK_CUR)
  153451. offset += in->getPosition();
  153452. else if (whence == SEEK_END)
  153453. offset += in->getTotalLength();
  153454. in->setPosition (offset);
  153455. return 0;
  153456. }
  153457. static int oggCloseCallback (void*)
  153458. {
  153459. return 0;
  153460. }
  153461. static long oggTellCallback (void* datasource)
  153462. {
  153463. return (long) ((InputStream*) datasource)->getPosition();
  153464. }
  153465. juce_UseDebuggingNewOperator
  153466. };
  153467. class OggWriter : public AudioFormatWriter
  153468. {
  153469. ogg_stream_state os;
  153470. ogg_page og;
  153471. ogg_packet op;
  153472. vorbis_info vi;
  153473. vorbis_comment vc;
  153474. vorbis_dsp_state vd;
  153475. vorbis_block vb;
  153476. public:
  153477. bool ok;
  153478. OggWriter (OutputStream* const out,
  153479. const double sampleRate,
  153480. const int numChannels,
  153481. const int bitsPerSample,
  153482. const int qualityIndex)
  153483. : AudioFormatWriter (out, oggFormatName,
  153484. sampleRate,
  153485. numChannels,
  153486. bitsPerSample)
  153487. {
  153488. ok = false;
  153489. vorbis_info_init (&vi);
  153490. if (vorbis_encode_init_vbr (&vi,
  153491. numChannels,
  153492. (int) sampleRate,
  153493. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  153494. {
  153495. vorbis_comment_init (&vc);
  153496. if (JUCEApplication::getInstance() != 0)
  153497. vorbis_comment_add_tag (&vc, "ENCODER",
  153498. (char*) (const char*) JUCEApplication::getInstance()->getApplicationName());
  153499. vorbis_analysis_init (&vd, &vi);
  153500. vorbis_block_init (&vd, &vb);
  153501. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  153502. ogg_packet header;
  153503. ogg_packet header_comm;
  153504. ogg_packet header_code;
  153505. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  153506. ogg_stream_packetin (&os, &header);
  153507. ogg_stream_packetin (&os, &header_comm);
  153508. ogg_stream_packetin (&os, &header_code);
  153509. for (;;)
  153510. {
  153511. if (ogg_stream_flush (&os, &og) == 0)
  153512. break;
  153513. output->write (og.header, og.header_len);
  153514. output->write (og.body, og.body_len);
  153515. }
  153516. ok = true;
  153517. }
  153518. }
  153519. ~OggWriter()
  153520. {
  153521. if (ok)
  153522. {
  153523. ogg_stream_clear (&os);
  153524. vorbis_block_clear (&vb);
  153525. vorbis_dsp_clear (&vd);
  153526. vorbis_comment_clear (&vc);
  153527. vorbis_info_clear (&vi);
  153528. output->flush();
  153529. }
  153530. else
  153531. {
  153532. vorbis_info_clear (&vi);
  153533. output = 0; // to stop the base class deleting this, as it needs to be returned
  153534. // to the caller of createWriter()
  153535. }
  153536. }
  153537. bool write (const int** samplesToWrite, int numSamples)
  153538. {
  153539. if (! ok)
  153540. return false;
  153541. if (numSamples > 0)
  153542. {
  153543. const double gain = 1.0 / 0x80000000u;
  153544. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  153545. for (int i = numChannels; --i >= 0;)
  153546. {
  153547. float* const dst = vorbisBuffer[i];
  153548. const int* const src = samplesToWrite [i];
  153549. if (src != 0 && dst != 0)
  153550. {
  153551. for (int j = 0; j < numSamples; ++j)
  153552. dst[j] = (float) (src[j] * gain);
  153553. }
  153554. }
  153555. }
  153556. vorbis_analysis_wrote (&vd, numSamples);
  153557. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  153558. {
  153559. vorbis_analysis (&vb, 0);
  153560. vorbis_bitrate_addblock (&vb);
  153561. while (vorbis_bitrate_flushpacket (&vd, &op))
  153562. {
  153563. ogg_stream_packetin (&os, &op);
  153564. for (;;)
  153565. {
  153566. if (ogg_stream_pageout (&os, &og) == 0)
  153567. break;
  153568. output->write (og.header, og.header_len);
  153569. output->write (og.body, og.body_len);
  153570. if (ogg_page_eos (&og))
  153571. break;
  153572. }
  153573. }
  153574. }
  153575. return true;
  153576. }
  153577. juce_UseDebuggingNewOperator
  153578. };
  153579. OggVorbisAudioFormat::OggVorbisAudioFormat()
  153580. : AudioFormat (oggFormatName, (const tchar**) oggExtensions)
  153581. {
  153582. }
  153583. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  153584. {
  153585. }
  153586. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  153587. {
  153588. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  153589. return Array <int> (rates);
  153590. }
  153591. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  153592. {
  153593. Array <int> depths;
  153594. depths.add (32);
  153595. return depths;
  153596. }
  153597. bool OggVorbisAudioFormat::canDoStereo()
  153598. {
  153599. return true;
  153600. }
  153601. bool OggVorbisAudioFormat::canDoMono()
  153602. {
  153603. return true;
  153604. }
  153605. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  153606. const bool deleteStreamIfOpeningFails)
  153607. {
  153608. OggReader* r = new OggReader (in);
  153609. if (r->sampleRate == 0)
  153610. {
  153611. if (! deleteStreamIfOpeningFails)
  153612. r->input = 0;
  153613. deleteAndZero (r);
  153614. }
  153615. return r;
  153616. }
  153617. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  153618. double sampleRate,
  153619. unsigned int numChannels,
  153620. int bitsPerSample,
  153621. const StringPairArray& /*metadataValues*/,
  153622. int qualityOptionIndex)
  153623. {
  153624. OggWriter* w = new OggWriter (out,
  153625. sampleRate,
  153626. numChannels,
  153627. bitsPerSample,
  153628. qualityOptionIndex);
  153629. if (! w->ok)
  153630. deleteAndZero (w);
  153631. return w;
  153632. }
  153633. bool OggVorbisAudioFormat::isCompressed()
  153634. {
  153635. return true;
  153636. }
  153637. const StringArray OggVorbisAudioFormat::getQualityOptions()
  153638. {
  153639. StringArray s;
  153640. s.add ("Low Quality");
  153641. s.add ("Medium Quality");
  153642. s.add ("High Quality");
  153643. return s;
  153644. }
  153645. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  153646. {
  153647. FileInputStream* const in = source.createInputStream();
  153648. if (in != 0)
  153649. {
  153650. AudioFormatReader* const r = createReaderFor (in, true);
  153651. if (r != 0)
  153652. {
  153653. const int64 numSamps = r->lengthInSamples;
  153654. delete r;
  153655. const int64 fileNumSamps = source.getSize() / 4;
  153656. const double ratio = numSamps / (double) fileNumSamps;
  153657. if (ratio > 12.0)
  153658. return 0;
  153659. else if (ratio > 6.0)
  153660. return 1;
  153661. else
  153662. return 2;
  153663. }
  153664. }
  153665. return 1;
  153666. }
  153667. END_JUCE_NAMESPACE
  153668. #endif
  153669. /********* End of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  153670. /********* Start of inlined file: juce_JPEGLoader.cpp *********/
  153671. #if JUCE_MSVC
  153672. #pragma warning (push)
  153673. #endif
  153674. namespace jpeglibNamespace
  153675. {
  153676. extern "C"
  153677. {
  153678. #define JPEG_INTERNALS
  153679. #undef FAR
  153680. /********* Start of inlined file: jpeglib.h *********/
  153681. #ifndef JPEGLIB_H
  153682. #define JPEGLIB_H
  153683. /*
  153684. * First we include the configuration files that record how this
  153685. * installation of the JPEG library is set up. jconfig.h can be
  153686. * generated automatically for many systems. jmorecfg.h contains
  153687. * manual configuration options that most people need not worry about.
  153688. */
  153689. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  153690. /********* Start of inlined file: jconfig.h *********/
  153691. /* see jconfig.doc for explanations */
  153692. // disable all the warnings under MSVC
  153693. #ifdef _MSC_VER
  153694. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  153695. #endif
  153696. #ifdef __BORLANDC__
  153697. #pragma warn -8057
  153698. #pragma warn -8019
  153699. #pragma warn -8004
  153700. #pragma warn -8008
  153701. #endif
  153702. #define HAVE_PROTOTYPES
  153703. #define HAVE_UNSIGNED_CHAR
  153704. #define HAVE_UNSIGNED_SHORT
  153705. /* #define void char */
  153706. /* #define const */
  153707. #undef CHAR_IS_UNSIGNED
  153708. #define HAVE_STDDEF_H
  153709. #define HAVE_STDLIB_H
  153710. #undef NEED_BSD_STRINGS
  153711. #undef NEED_SYS_TYPES_H
  153712. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  153713. #undef NEED_SHORT_EXTERNAL_NAMES
  153714. #undef INCOMPLETE_TYPES_BROKEN
  153715. /* Define "boolean" as unsigned char, not int, per Windows custom */
  153716. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  153717. typedef unsigned char boolean;
  153718. #endif
  153719. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  153720. #ifdef JPEG_INTERNALS
  153721. #undef RIGHT_SHIFT_IS_UNSIGNED
  153722. #endif /* JPEG_INTERNALS */
  153723. #ifdef JPEG_CJPEG_DJPEG
  153724. #define BMP_SUPPORTED /* BMP image file format */
  153725. #define GIF_SUPPORTED /* GIF image file format */
  153726. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  153727. #undef RLE_SUPPORTED /* Utah RLE image file format */
  153728. #define TARGA_SUPPORTED /* Targa image file format */
  153729. #define TWO_FILE_COMMANDLINE /* optional */
  153730. #define USE_SETMODE /* Microsoft has setmode() */
  153731. #undef NEED_SIGNAL_CATCHER
  153732. #undef DONT_USE_B_MODE
  153733. #undef PROGRESS_REPORT /* optional */
  153734. #endif /* JPEG_CJPEG_DJPEG */
  153735. /********* End of inlined file: jconfig.h *********/
  153736. /* widely used configuration options */
  153737. #endif
  153738. /********* Start of inlined file: jmorecfg.h *********/
  153739. /*
  153740. * Define BITS_IN_JSAMPLE as either
  153741. * 8 for 8-bit sample values (the usual setting)
  153742. * 12 for 12-bit sample values
  153743. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  153744. * JPEG standard, and the IJG code does not support anything else!
  153745. * We do not support run-time selection of data precision, sorry.
  153746. */
  153747. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  153748. /*
  153749. * Maximum number of components (color channels) allowed in JPEG image.
  153750. * To meet the letter of the JPEG spec, set this to 255. However, darn
  153751. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  153752. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  153753. * really short on memory. (Each allowed component costs a hundred or so
  153754. * bytes of storage, whether actually used in an image or not.)
  153755. */
  153756. #define MAX_COMPONENTS 10 /* maximum number of image components */
  153757. /*
  153758. * Basic data types.
  153759. * You may need to change these if you have a machine with unusual data
  153760. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  153761. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  153762. * but it had better be at least 16.
  153763. */
  153764. /* Representation of a single sample (pixel element value).
  153765. * We frequently allocate large arrays of these, so it's important to keep
  153766. * them small. But if you have memory to burn and access to char or short
  153767. * arrays is very slow on your hardware, you might want to change these.
  153768. */
  153769. #if BITS_IN_JSAMPLE == 8
  153770. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  153771. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  153772. */
  153773. #ifdef HAVE_UNSIGNED_CHAR
  153774. typedef unsigned char JSAMPLE;
  153775. #define GETJSAMPLE(value) ((int) (value))
  153776. #else /* not HAVE_UNSIGNED_CHAR */
  153777. typedef char JSAMPLE;
  153778. #ifdef CHAR_IS_UNSIGNED
  153779. #define GETJSAMPLE(value) ((int) (value))
  153780. #else
  153781. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  153782. #endif /* CHAR_IS_UNSIGNED */
  153783. #endif /* HAVE_UNSIGNED_CHAR */
  153784. #define MAXJSAMPLE 255
  153785. #define CENTERJSAMPLE 128
  153786. #endif /* BITS_IN_JSAMPLE == 8 */
  153787. #if BITS_IN_JSAMPLE == 12
  153788. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  153789. * On nearly all machines "short" will do nicely.
  153790. */
  153791. typedef short JSAMPLE;
  153792. #define GETJSAMPLE(value) ((int) (value))
  153793. #define MAXJSAMPLE 4095
  153794. #define CENTERJSAMPLE 2048
  153795. #endif /* BITS_IN_JSAMPLE == 12 */
  153796. /* Representation of a DCT frequency coefficient.
  153797. * This should be a signed value of at least 16 bits; "short" is usually OK.
  153798. * Again, we allocate large arrays of these, but you can change to int
  153799. * if you have memory to burn and "short" is really slow.
  153800. */
  153801. typedef short JCOEF;
  153802. /* Compressed datastreams are represented as arrays of JOCTET.
  153803. * These must be EXACTLY 8 bits wide, at least once they are written to
  153804. * external storage. Note that when using the stdio data source/destination
  153805. * managers, this is also the data type passed to fread/fwrite.
  153806. */
  153807. #ifdef HAVE_UNSIGNED_CHAR
  153808. typedef unsigned char JOCTET;
  153809. #define GETJOCTET(value) (value)
  153810. #else /* not HAVE_UNSIGNED_CHAR */
  153811. typedef char JOCTET;
  153812. #ifdef CHAR_IS_UNSIGNED
  153813. #define GETJOCTET(value) (value)
  153814. #else
  153815. #define GETJOCTET(value) ((value) & 0xFF)
  153816. #endif /* CHAR_IS_UNSIGNED */
  153817. #endif /* HAVE_UNSIGNED_CHAR */
  153818. /* These typedefs are used for various table entries and so forth.
  153819. * They must be at least as wide as specified; but making them too big
  153820. * won't cost a huge amount of memory, so we don't provide special
  153821. * extraction code like we did for JSAMPLE. (In other words, these
  153822. * typedefs live at a different point on the speed/space tradeoff curve.)
  153823. */
  153824. /* UINT8 must hold at least the values 0..255. */
  153825. #ifdef HAVE_UNSIGNED_CHAR
  153826. typedef unsigned char UINT8;
  153827. #else /* not HAVE_UNSIGNED_CHAR */
  153828. #ifdef CHAR_IS_UNSIGNED
  153829. typedef char UINT8;
  153830. #else /* not CHAR_IS_UNSIGNED */
  153831. typedef short UINT8;
  153832. #endif /* CHAR_IS_UNSIGNED */
  153833. #endif /* HAVE_UNSIGNED_CHAR */
  153834. /* UINT16 must hold at least the values 0..65535. */
  153835. #ifdef HAVE_UNSIGNED_SHORT
  153836. typedef unsigned short UINT16;
  153837. #else /* not HAVE_UNSIGNED_SHORT */
  153838. typedef unsigned int UINT16;
  153839. #endif /* HAVE_UNSIGNED_SHORT */
  153840. /* INT16 must hold at least the values -32768..32767. */
  153841. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  153842. typedef short INT16;
  153843. #endif
  153844. /* INT32 must hold at least signed 32-bit values. */
  153845. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  153846. typedef long INT32;
  153847. #endif
  153848. /* Datatype used for image dimensions. The JPEG standard only supports
  153849. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  153850. * "unsigned int" is sufficient on all machines. However, if you need to
  153851. * handle larger images and you don't mind deviating from the spec, you
  153852. * can change this datatype.
  153853. */
  153854. typedef unsigned int JDIMENSION;
  153855. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  153856. /* These macros are used in all function definitions and extern declarations.
  153857. * You could modify them if you need to change function linkage conventions;
  153858. * in particular, you'll need to do that to make the library a Windows DLL.
  153859. * Another application is to make all functions global for use with debuggers
  153860. * or code profilers that require it.
  153861. */
  153862. /* a function called through method pointers: */
  153863. #define METHODDEF(type) static type
  153864. /* a function used only in its module: */
  153865. #define LOCAL(type) static type
  153866. /* a function referenced thru EXTERNs: */
  153867. #define GLOBAL(type) type
  153868. /* a reference to a GLOBAL function: */
  153869. #define EXTERN(type) extern type
  153870. /* This macro is used to declare a "method", that is, a function pointer.
  153871. * We want to supply prototype parameters if the compiler can cope.
  153872. * Note that the arglist parameter must be parenthesized!
  153873. * Again, you can customize this if you need special linkage keywords.
  153874. */
  153875. #ifdef HAVE_PROTOTYPES
  153876. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  153877. #else
  153878. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  153879. #endif
  153880. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  153881. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  153882. * by just saying "FAR *" where such a pointer is needed. In a few places
  153883. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  153884. */
  153885. #ifdef NEED_FAR_POINTERS
  153886. #define FAR far
  153887. #else
  153888. #define FAR
  153889. #endif
  153890. /*
  153891. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  153892. * in standard header files. Or you may have conflicts with application-
  153893. * specific header files that you want to include together with these files.
  153894. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  153895. */
  153896. #ifndef HAVE_BOOLEAN
  153897. typedef int boolean;
  153898. #endif
  153899. #ifndef FALSE /* in case these macros already exist */
  153900. #define FALSE 0 /* values of boolean */
  153901. #endif
  153902. #ifndef TRUE
  153903. #define TRUE 1
  153904. #endif
  153905. /*
  153906. * The remaining options affect code selection within the JPEG library,
  153907. * but they don't need to be visible to most applications using the library.
  153908. * To minimize application namespace pollution, the symbols won't be
  153909. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  153910. */
  153911. #ifdef JPEG_INTERNALS
  153912. #define JPEG_INTERNAL_OPTIONS
  153913. #endif
  153914. #ifdef JPEG_INTERNAL_OPTIONS
  153915. /*
  153916. * These defines indicate whether to include various optional functions.
  153917. * Undefining some of these symbols will produce a smaller but less capable
  153918. * library. Note that you can leave certain source files out of the
  153919. * compilation/linking process if you've #undef'd the corresponding symbols.
  153920. * (You may HAVE to do that if your compiler doesn't like null source files.)
  153921. */
  153922. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  153923. /* Capability options common to encoder and decoder: */
  153924. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  153925. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  153926. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  153927. /* Encoder capability options: */
  153928. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  153929. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  153930. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  153931. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  153932. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  153933. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  153934. * precision, so jchuff.c normally uses entropy optimization to compute
  153935. * usable tables for higher precision. If you don't want to do optimization,
  153936. * you'll have to supply different default Huffman tables.
  153937. * The exact same statements apply for progressive JPEG: the default tables
  153938. * don't work for progressive mode. (This may get fixed, however.)
  153939. */
  153940. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  153941. /* Decoder capability options: */
  153942. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  153943. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  153944. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  153945. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  153946. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  153947. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  153948. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  153949. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  153950. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  153951. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  153952. /* more capability options later, no doubt */
  153953. /*
  153954. * Ordering of RGB data in scanlines passed to or from the application.
  153955. * If your application wants to deal with data in the order B,G,R, just
  153956. * change these macros. You can also deal with formats such as R,G,B,X
  153957. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  153958. * the offsets will also change the order in which colormap data is organized.
  153959. * RESTRICTIONS:
  153960. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  153961. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  153962. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  153963. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  153964. * is not 3 (they don't understand about dummy color components!). So you
  153965. * can't use color quantization if you change that value.
  153966. */
  153967. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  153968. #define RGB_GREEN 1 /* Offset of Green */
  153969. #define RGB_BLUE 2 /* Offset of Blue */
  153970. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  153971. /* Definitions for speed-related optimizations. */
  153972. /* If your compiler supports inline functions, define INLINE
  153973. * as the inline keyword; otherwise define it as empty.
  153974. */
  153975. #ifndef INLINE
  153976. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  153977. #define INLINE __inline__
  153978. #endif
  153979. #ifndef INLINE
  153980. #define INLINE /* default is to define it as empty */
  153981. #endif
  153982. #endif
  153983. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  153984. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  153985. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  153986. */
  153987. #ifndef MULTIPLIER
  153988. #define MULTIPLIER int /* type for fastest integer multiply */
  153989. #endif
  153990. /* FAST_FLOAT should be either float or double, whichever is done faster
  153991. * by your compiler. (Note that this type is only used in the floating point
  153992. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  153993. * Typically, float is faster in ANSI C compilers, while double is faster in
  153994. * pre-ANSI compilers (because they insist on converting to double anyway).
  153995. * The code below therefore chooses float if we have ANSI-style prototypes.
  153996. */
  153997. #ifndef FAST_FLOAT
  153998. #ifdef HAVE_PROTOTYPES
  153999. #define FAST_FLOAT float
  154000. #else
  154001. #define FAST_FLOAT double
  154002. #endif
  154003. #endif
  154004. #endif /* JPEG_INTERNAL_OPTIONS */
  154005. /********* End of inlined file: jmorecfg.h *********/
  154006. /* seldom changed options */
  154007. /* Version ID for the JPEG library.
  154008. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  154009. */
  154010. #define JPEG_LIB_VERSION 62 /* Version 6b */
  154011. /* Various constants determining the sizes of things.
  154012. * All of these are specified by the JPEG standard, so don't change them
  154013. * if you want to be compatible.
  154014. */
  154015. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  154016. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  154017. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  154018. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  154019. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  154020. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  154021. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  154022. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  154023. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  154024. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  154025. * to handle it. We even let you do this from the jconfig.h file. However,
  154026. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  154027. * sometimes emits noncompliant files doesn't mean you should too.
  154028. */
  154029. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  154030. #ifndef D_MAX_BLOCKS_IN_MCU
  154031. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  154032. #endif
  154033. /* Data structures for images (arrays of samples and of DCT coefficients).
  154034. * On 80x86 machines, the image arrays are too big for near pointers,
  154035. * but the pointer arrays can fit in near memory.
  154036. */
  154037. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  154038. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  154039. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  154040. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  154041. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  154042. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  154043. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  154044. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  154045. /* Types for JPEG compression parameters and working tables. */
  154046. /* DCT coefficient quantization tables. */
  154047. typedef struct {
  154048. /* This array gives the coefficient quantizers in natural array order
  154049. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  154050. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  154051. */
  154052. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  154053. /* This field is used only during compression. It's initialized FALSE when
  154054. * the table is created, and set TRUE when it's been output to the file.
  154055. * You could suppress output of a table by setting this to TRUE.
  154056. * (See jpeg_suppress_tables for an example.)
  154057. */
  154058. boolean sent_table; /* TRUE when table has been output */
  154059. } JQUANT_TBL;
  154060. /* Huffman coding tables. */
  154061. typedef struct {
  154062. /* These two fields directly represent the contents of a JPEG DHT marker */
  154063. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  154064. /* length k bits; bits[0] is unused */
  154065. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  154066. /* This field is used only during compression. It's initialized FALSE when
  154067. * the table is created, and set TRUE when it's been output to the file.
  154068. * You could suppress output of a table by setting this to TRUE.
  154069. * (See jpeg_suppress_tables for an example.)
  154070. */
  154071. boolean sent_table; /* TRUE when table has been output */
  154072. } JHUFF_TBL;
  154073. /* Basic info about one component (color channel). */
  154074. typedef struct {
  154075. /* These values are fixed over the whole image. */
  154076. /* For compression, they must be supplied by parameter setup; */
  154077. /* for decompression, they are read from the SOF marker. */
  154078. int component_id; /* identifier for this component (0..255) */
  154079. int component_index; /* its index in SOF or cinfo->comp_info[] */
  154080. int h_samp_factor; /* horizontal sampling factor (1..4) */
  154081. int v_samp_factor; /* vertical sampling factor (1..4) */
  154082. int quant_tbl_no; /* quantization table selector (0..3) */
  154083. /* These values may vary between scans. */
  154084. /* For compression, they must be supplied by parameter setup; */
  154085. /* for decompression, they are read from the SOS marker. */
  154086. /* The decompressor output side may not use these variables. */
  154087. int dc_tbl_no; /* DC entropy table selector (0..3) */
  154088. int ac_tbl_no; /* AC entropy table selector (0..3) */
  154089. /* Remaining fields should be treated as private by applications. */
  154090. /* These values are computed during compression or decompression startup: */
  154091. /* Component's size in DCT blocks.
  154092. * Any dummy blocks added to complete an MCU are not counted; therefore
  154093. * these values do not depend on whether a scan is interleaved or not.
  154094. */
  154095. JDIMENSION width_in_blocks;
  154096. JDIMENSION height_in_blocks;
  154097. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  154098. * For decompression this is the size of the output from one DCT block,
  154099. * reflecting any scaling we choose to apply during the IDCT step.
  154100. * Values of 1,2,4,8 are likely to be supported. Note that different
  154101. * components may receive different IDCT scalings.
  154102. */
  154103. int DCT_scaled_size;
  154104. /* The downsampled dimensions are the component's actual, unpadded number
  154105. * of samples at the main buffer (preprocessing/compression interface), thus
  154106. * downsampled_width = ceil(image_width * Hi/Hmax)
  154107. * and similarly for height. For decompression, IDCT scaling is included, so
  154108. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  154109. */
  154110. JDIMENSION downsampled_width; /* actual width in samples */
  154111. JDIMENSION downsampled_height; /* actual height in samples */
  154112. /* This flag is used only for decompression. In cases where some of the
  154113. * components will be ignored (eg grayscale output from YCbCr image),
  154114. * we can skip most computations for the unused components.
  154115. */
  154116. boolean component_needed; /* do we need the value of this component? */
  154117. /* These values are computed before starting a scan of the component. */
  154118. /* The decompressor output side may not use these variables. */
  154119. int MCU_width; /* number of blocks per MCU, horizontally */
  154120. int MCU_height; /* number of blocks per MCU, vertically */
  154121. int MCU_blocks; /* MCU_width * MCU_height */
  154122. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  154123. int last_col_width; /* # of non-dummy blocks across in last MCU */
  154124. int last_row_height; /* # of non-dummy blocks down in last MCU */
  154125. /* Saved quantization table for component; NULL if none yet saved.
  154126. * See jdinput.c comments about the need for this information.
  154127. * This field is currently used only for decompression.
  154128. */
  154129. JQUANT_TBL * quant_table;
  154130. /* Private per-component storage for DCT or IDCT subsystem. */
  154131. void * dct_table;
  154132. } jpeg_component_info;
  154133. /* The script for encoding a multiple-scan file is an array of these: */
  154134. typedef struct {
  154135. int comps_in_scan; /* number of components encoded in this scan */
  154136. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  154137. int Ss, Se; /* progressive JPEG spectral selection parms */
  154138. int Ah, Al; /* progressive JPEG successive approx. parms */
  154139. } jpeg_scan_info;
  154140. /* The decompressor can save APPn and COM markers in a list of these: */
  154141. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  154142. struct jpeg_marker_struct {
  154143. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  154144. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  154145. unsigned int original_length; /* # bytes of data in the file */
  154146. unsigned int data_length; /* # bytes of data saved at data[] */
  154147. JOCTET FAR * data; /* the data contained in the marker */
  154148. /* the marker length word is not counted in data_length or original_length */
  154149. };
  154150. /* Known color spaces. */
  154151. typedef enum {
  154152. JCS_UNKNOWN, /* error/unspecified */
  154153. JCS_GRAYSCALE, /* monochrome */
  154154. JCS_RGB, /* red/green/blue */
  154155. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  154156. JCS_CMYK, /* C/M/Y/K */
  154157. JCS_YCCK /* Y/Cb/Cr/K */
  154158. } J_COLOR_SPACE;
  154159. /* DCT/IDCT algorithm options. */
  154160. typedef enum {
  154161. JDCT_ISLOW, /* slow but accurate integer algorithm */
  154162. JDCT_IFAST, /* faster, less accurate integer method */
  154163. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  154164. } J_DCT_METHOD;
  154165. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  154166. #define JDCT_DEFAULT JDCT_ISLOW
  154167. #endif
  154168. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  154169. #define JDCT_FASTEST JDCT_IFAST
  154170. #endif
  154171. /* Dithering options for decompression. */
  154172. typedef enum {
  154173. JDITHER_NONE, /* no dithering */
  154174. JDITHER_ORDERED, /* simple ordered dither */
  154175. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  154176. } J_DITHER_MODE;
  154177. /* Common fields between JPEG compression and decompression master structs. */
  154178. #define jpeg_common_fields \
  154179. struct jpeg_error_mgr * err; /* Error handler module */\
  154180. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  154181. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  154182. void * client_data; /* Available for use by application */\
  154183. boolean is_decompressor; /* So common code can tell which is which */\
  154184. int global_state /* For checking call sequence validity */
  154185. /* Routines that are to be used by both halves of the library are declared
  154186. * to receive a pointer to this structure. There are no actual instances of
  154187. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  154188. */
  154189. struct jpeg_common_struct {
  154190. jpeg_common_fields; /* Fields common to both master struct types */
  154191. /* Additional fields follow in an actual jpeg_compress_struct or
  154192. * jpeg_decompress_struct. All three structs must agree on these
  154193. * initial fields! (This would be a lot cleaner in C++.)
  154194. */
  154195. };
  154196. typedef struct jpeg_common_struct * j_common_ptr;
  154197. typedef struct jpeg_compress_struct * j_compress_ptr;
  154198. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  154199. /* Master record for a compression instance */
  154200. struct jpeg_compress_struct {
  154201. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  154202. /* Destination for compressed data */
  154203. struct jpeg_destination_mgr * dest;
  154204. /* Description of source image --- these fields must be filled in by
  154205. * outer application before starting compression. in_color_space must
  154206. * be correct before you can even call jpeg_set_defaults().
  154207. */
  154208. JDIMENSION image_width; /* input image width */
  154209. JDIMENSION image_height; /* input image height */
  154210. int input_components; /* # of color components in input image */
  154211. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  154212. double input_gamma; /* image gamma of input image */
  154213. /* Compression parameters --- these fields must be set before calling
  154214. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  154215. * initialize everything to reasonable defaults, then changing anything
  154216. * the application specifically wants to change. That way you won't get
  154217. * burnt when new parameters are added. Also note that there are several
  154218. * helper routines to simplify changing parameters.
  154219. */
  154220. int data_precision; /* bits of precision in image data */
  154221. int num_components; /* # of color components in JPEG image */
  154222. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  154223. jpeg_component_info * comp_info;
  154224. /* comp_info[i] describes component that appears i'th in SOF */
  154225. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  154226. /* ptrs to coefficient quantization tables, or NULL if not defined */
  154227. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  154228. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  154229. /* ptrs to Huffman coding tables, or NULL if not defined */
  154230. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  154231. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  154232. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  154233. int num_scans; /* # of entries in scan_info array */
  154234. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  154235. /* The default value of scan_info is NULL, which causes a single-scan
  154236. * sequential JPEG file to be emitted. To create a multi-scan file,
  154237. * set num_scans and scan_info to point to an array of scan definitions.
  154238. */
  154239. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  154240. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  154241. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  154242. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  154243. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  154244. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  154245. /* The restart interval can be specified in absolute MCUs by setting
  154246. * restart_interval, or in MCU rows by setting restart_in_rows
  154247. * (in which case the correct restart_interval will be figured
  154248. * for each scan).
  154249. */
  154250. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  154251. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  154252. /* Parameters controlling emission of special markers. */
  154253. boolean write_JFIF_header; /* should a JFIF marker be written? */
  154254. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  154255. UINT8 JFIF_minor_version;
  154256. /* These three values are not used by the JPEG code, merely copied */
  154257. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  154258. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  154259. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  154260. UINT8 density_unit; /* JFIF code for pixel size units */
  154261. UINT16 X_density; /* Horizontal pixel density */
  154262. UINT16 Y_density; /* Vertical pixel density */
  154263. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  154264. /* State variable: index of next scanline to be written to
  154265. * jpeg_write_scanlines(). Application may use this to control its
  154266. * processing loop, e.g., "while (next_scanline < image_height)".
  154267. */
  154268. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  154269. /* Remaining fields are known throughout compressor, but generally
  154270. * should not be touched by a surrounding application.
  154271. */
  154272. /*
  154273. * These fields are computed during compression startup
  154274. */
  154275. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  154276. int max_h_samp_factor; /* largest h_samp_factor */
  154277. int max_v_samp_factor; /* largest v_samp_factor */
  154278. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  154279. /* The coefficient controller receives data in units of MCU rows as defined
  154280. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  154281. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  154282. * "iMCU" (interleaved MCU) row.
  154283. */
  154284. /*
  154285. * These fields are valid during any one scan.
  154286. * They describe the components and MCUs actually appearing in the scan.
  154287. */
  154288. int comps_in_scan; /* # of JPEG components in this scan */
  154289. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  154290. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  154291. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  154292. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  154293. int blocks_in_MCU; /* # of DCT blocks per MCU */
  154294. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  154295. /* MCU_membership[i] is index in cur_comp_info of component owning */
  154296. /* i'th block in an MCU */
  154297. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  154298. /*
  154299. * Links to compression subobjects (methods and private variables of modules)
  154300. */
  154301. struct jpeg_comp_master * master;
  154302. struct jpeg_c_main_controller * main;
  154303. struct jpeg_c_prep_controller * prep;
  154304. struct jpeg_c_coef_controller * coef;
  154305. struct jpeg_marker_writer * marker;
  154306. struct jpeg_color_converter * cconvert;
  154307. struct jpeg_downsampler * downsample;
  154308. struct jpeg_forward_dct * fdct;
  154309. struct jpeg_entropy_encoder * entropy;
  154310. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  154311. int script_space_size;
  154312. };
  154313. /* Master record for a decompression instance */
  154314. struct jpeg_decompress_struct {
  154315. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  154316. /* Source of compressed data */
  154317. struct jpeg_source_mgr * src;
  154318. /* Basic description of image --- filled in by jpeg_read_header(). */
  154319. /* Application may inspect these values to decide how to process image. */
  154320. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  154321. JDIMENSION image_height; /* nominal image height */
  154322. int num_components; /* # of color components in JPEG image */
  154323. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  154324. /* Decompression processing parameters --- these fields must be set before
  154325. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  154326. * them to default values.
  154327. */
  154328. J_COLOR_SPACE out_color_space; /* colorspace for output */
  154329. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  154330. double output_gamma; /* image gamma wanted in output */
  154331. boolean buffered_image; /* TRUE=multiple output passes */
  154332. boolean raw_data_out; /* TRUE=downsampled data wanted */
  154333. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  154334. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  154335. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  154336. boolean quantize_colors; /* TRUE=colormapped output wanted */
  154337. /* the following are ignored if not quantize_colors: */
  154338. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  154339. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  154340. int desired_number_of_colors; /* max # colors to use in created colormap */
  154341. /* these are significant only in buffered-image mode: */
  154342. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  154343. boolean enable_external_quant;/* enable future use of external colormap */
  154344. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  154345. /* Description of actual output image that will be returned to application.
  154346. * These fields are computed by jpeg_start_decompress().
  154347. * You can also use jpeg_calc_output_dimensions() to determine these values
  154348. * in advance of calling jpeg_start_decompress().
  154349. */
  154350. JDIMENSION output_width; /* scaled image width */
  154351. JDIMENSION output_height; /* scaled image height */
  154352. int out_color_components; /* # of color components in out_color_space */
  154353. int output_components; /* # of color components returned */
  154354. /* output_components is 1 (a colormap index) when quantizing colors;
  154355. * otherwise it equals out_color_components.
  154356. */
  154357. int rec_outbuf_height; /* min recommended height of scanline buffer */
  154358. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  154359. * high, space and time will be wasted due to unnecessary data copying.
  154360. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  154361. */
  154362. /* When quantizing colors, the output colormap is described by these fields.
  154363. * The application can supply a colormap by setting colormap non-NULL before
  154364. * calling jpeg_start_decompress; otherwise a colormap is created during
  154365. * jpeg_start_decompress or jpeg_start_output.
  154366. * The map has out_color_components rows and actual_number_of_colors columns.
  154367. */
  154368. int actual_number_of_colors; /* number of entries in use */
  154369. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  154370. /* State variables: these variables indicate the progress of decompression.
  154371. * The application may examine these but must not modify them.
  154372. */
  154373. /* Row index of next scanline to be read from jpeg_read_scanlines().
  154374. * Application may use this to control its processing loop, e.g.,
  154375. * "while (output_scanline < output_height)".
  154376. */
  154377. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  154378. /* Current input scan number and number of iMCU rows completed in scan.
  154379. * These indicate the progress of the decompressor input side.
  154380. */
  154381. int input_scan_number; /* Number of SOS markers seen so far */
  154382. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  154383. /* The "output scan number" is the notional scan being displayed by the
  154384. * output side. The decompressor will not allow output scan/row number
  154385. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  154386. */
  154387. int output_scan_number; /* Nominal scan number being displayed */
  154388. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  154389. /* Current progression status. coef_bits[c][i] indicates the precision
  154390. * with which component c's DCT coefficient i (in zigzag order) is known.
  154391. * It is -1 when no data has yet been received, otherwise it is the point
  154392. * transform (shift) value for the most recent scan of the coefficient
  154393. * (thus, 0 at completion of the progression).
  154394. * This pointer is NULL when reading a non-progressive file.
  154395. */
  154396. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  154397. /* Internal JPEG parameters --- the application usually need not look at
  154398. * these fields. Note that the decompressor output side may not use
  154399. * any parameters that can change between scans.
  154400. */
  154401. /* Quantization and Huffman tables are carried forward across input
  154402. * datastreams when processing abbreviated JPEG datastreams.
  154403. */
  154404. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  154405. /* ptrs to coefficient quantization tables, or NULL if not defined */
  154406. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  154407. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  154408. /* ptrs to Huffman coding tables, or NULL if not defined */
  154409. /* These parameters are never carried across datastreams, since they
  154410. * are given in SOF/SOS markers or defined to be reset by SOI.
  154411. */
  154412. int data_precision; /* bits of precision in image data */
  154413. jpeg_component_info * comp_info;
  154414. /* comp_info[i] describes component that appears i'th in SOF */
  154415. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  154416. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  154417. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  154418. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  154419. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  154420. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  154421. /* These fields record data obtained from optional markers recognized by
  154422. * the JPEG library.
  154423. */
  154424. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  154425. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  154426. UINT8 JFIF_major_version; /* JFIF version number */
  154427. UINT8 JFIF_minor_version;
  154428. UINT8 density_unit; /* JFIF code for pixel size units */
  154429. UINT16 X_density; /* Horizontal pixel density */
  154430. UINT16 Y_density; /* Vertical pixel density */
  154431. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  154432. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  154433. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  154434. /* Aside from the specific data retained from APPn markers known to the
  154435. * library, the uninterpreted contents of any or all APPn and COM markers
  154436. * can be saved in a list for examination by the application.
  154437. */
  154438. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  154439. /* Remaining fields are known throughout decompressor, but generally
  154440. * should not be touched by a surrounding application.
  154441. */
  154442. /*
  154443. * These fields are computed during decompression startup
  154444. */
  154445. int max_h_samp_factor; /* largest h_samp_factor */
  154446. int max_v_samp_factor; /* largest v_samp_factor */
  154447. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  154448. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  154449. /* The coefficient controller's input and output progress is measured in
  154450. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  154451. * in fully interleaved JPEG scans, but are used whether the scan is
  154452. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  154453. * rows of each component. Therefore, the IDCT output contains
  154454. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  154455. */
  154456. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  154457. /*
  154458. * These fields are valid during any one scan.
  154459. * They describe the components and MCUs actually appearing in the scan.
  154460. * Note that the decompressor output side must not use these fields.
  154461. */
  154462. int comps_in_scan; /* # of JPEG components in this scan */
  154463. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  154464. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  154465. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  154466. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  154467. int blocks_in_MCU; /* # of DCT blocks per MCU */
  154468. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  154469. /* MCU_membership[i] is index in cur_comp_info of component owning */
  154470. /* i'th block in an MCU */
  154471. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  154472. /* This field is shared between entropy decoder and marker parser.
  154473. * It is either zero or the code of a JPEG marker that has been
  154474. * read from the data source, but has not yet been processed.
  154475. */
  154476. int unread_marker;
  154477. /*
  154478. * Links to decompression subobjects (methods, private variables of modules)
  154479. */
  154480. struct jpeg_decomp_master * master;
  154481. struct jpeg_d_main_controller * main;
  154482. struct jpeg_d_coef_controller * coef;
  154483. struct jpeg_d_post_controller * post;
  154484. struct jpeg_input_controller * inputctl;
  154485. struct jpeg_marker_reader * marker;
  154486. struct jpeg_entropy_decoder * entropy;
  154487. struct jpeg_inverse_dct * idct;
  154488. struct jpeg_upsampler * upsample;
  154489. struct jpeg_color_deconverter * cconvert;
  154490. struct jpeg_color_quantizer * cquantize;
  154491. };
  154492. /* "Object" declarations for JPEG modules that may be supplied or called
  154493. * directly by the surrounding application.
  154494. * As with all objects in the JPEG library, these structs only define the
  154495. * publicly visible methods and state variables of a module. Additional
  154496. * private fields may exist after the public ones.
  154497. */
  154498. /* Error handler object */
  154499. struct jpeg_error_mgr {
  154500. /* Error exit handler: does not return to caller */
  154501. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  154502. /* Conditionally emit a trace or warning message */
  154503. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  154504. /* Routine that actually outputs a trace or error message */
  154505. JMETHOD(void, output_message, (j_common_ptr cinfo));
  154506. /* Format a message string for the most recent JPEG error or message */
  154507. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  154508. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  154509. /* Reset error state variables at start of a new image */
  154510. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  154511. /* The message ID code and any parameters are saved here.
  154512. * A message can have one string parameter or up to 8 int parameters.
  154513. */
  154514. int msg_code;
  154515. #define JMSG_STR_PARM_MAX 80
  154516. union {
  154517. int i[8];
  154518. char s[JMSG_STR_PARM_MAX];
  154519. } msg_parm;
  154520. /* Standard state variables for error facility */
  154521. int trace_level; /* max msg_level that will be displayed */
  154522. /* For recoverable corrupt-data errors, we emit a warning message,
  154523. * but keep going unless emit_message chooses to abort. emit_message
  154524. * should count warnings in num_warnings. The surrounding application
  154525. * can check for bad data by seeing if num_warnings is nonzero at the
  154526. * end of processing.
  154527. */
  154528. long num_warnings; /* number of corrupt-data warnings */
  154529. /* These fields point to the table(s) of error message strings.
  154530. * An application can change the table pointer to switch to a different
  154531. * message list (typically, to change the language in which errors are
  154532. * reported). Some applications may wish to add additional error codes
  154533. * that will be handled by the JPEG library error mechanism; the second
  154534. * table pointer is used for this purpose.
  154535. *
  154536. * First table includes all errors generated by JPEG library itself.
  154537. * Error code 0 is reserved for a "no such error string" message.
  154538. */
  154539. const char * const * jpeg_message_table; /* Library errors */
  154540. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  154541. /* Second table can be added by application (see cjpeg/djpeg for example).
  154542. * It contains strings numbered first_addon_message..last_addon_message.
  154543. */
  154544. const char * const * addon_message_table; /* Non-library errors */
  154545. int first_addon_message; /* code for first string in addon table */
  154546. int last_addon_message; /* code for last string in addon table */
  154547. };
  154548. /* Progress monitor object */
  154549. struct jpeg_progress_mgr {
  154550. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  154551. long pass_counter; /* work units completed in this pass */
  154552. long pass_limit; /* total number of work units in this pass */
  154553. int completed_passes; /* passes completed so far */
  154554. int total_passes; /* total number of passes expected */
  154555. };
  154556. /* Data destination object for compression */
  154557. struct jpeg_destination_mgr {
  154558. JOCTET * next_output_byte; /* => next byte to write in buffer */
  154559. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  154560. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  154561. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  154562. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  154563. };
  154564. /* Data source object for decompression */
  154565. struct jpeg_source_mgr {
  154566. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  154567. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  154568. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  154569. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  154570. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  154571. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  154572. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  154573. };
  154574. /* Memory manager object.
  154575. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  154576. * and "really big" objects (virtual arrays with backing store if needed).
  154577. * The memory manager does not allow individual objects to be freed; rather,
  154578. * each created object is assigned to a pool, and whole pools can be freed
  154579. * at once. This is faster and more convenient than remembering exactly what
  154580. * to free, especially where malloc()/free() are not too speedy.
  154581. * NB: alloc routines never return NULL. They exit to error_exit if not
  154582. * successful.
  154583. */
  154584. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  154585. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  154586. #define JPOOL_NUMPOOLS 2
  154587. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  154588. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  154589. struct jpeg_memory_mgr {
  154590. /* Method pointers */
  154591. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  154592. size_t sizeofobject));
  154593. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  154594. size_t sizeofobject));
  154595. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  154596. JDIMENSION samplesperrow,
  154597. JDIMENSION numrows));
  154598. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  154599. JDIMENSION blocksperrow,
  154600. JDIMENSION numrows));
  154601. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  154602. int pool_id,
  154603. boolean pre_zero,
  154604. JDIMENSION samplesperrow,
  154605. JDIMENSION numrows,
  154606. JDIMENSION maxaccess));
  154607. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  154608. int pool_id,
  154609. boolean pre_zero,
  154610. JDIMENSION blocksperrow,
  154611. JDIMENSION numrows,
  154612. JDIMENSION maxaccess));
  154613. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  154614. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  154615. jvirt_sarray_ptr ptr,
  154616. JDIMENSION start_row,
  154617. JDIMENSION num_rows,
  154618. boolean writable));
  154619. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  154620. jvirt_barray_ptr ptr,
  154621. JDIMENSION start_row,
  154622. JDIMENSION num_rows,
  154623. boolean writable));
  154624. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  154625. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  154626. /* Limit on memory allocation for this JPEG object. (Note that this is
  154627. * merely advisory, not a guaranteed maximum; it only affects the space
  154628. * used for virtual-array buffers.) May be changed by outer application
  154629. * after creating the JPEG object.
  154630. */
  154631. long max_memory_to_use;
  154632. /* Maximum allocation request accepted by alloc_large. */
  154633. long max_alloc_chunk;
  154634. };
  154635. /* Routine signature for application-supplied marker processing methods.
  154636. * Need not pass marker code since it is stored in cinfo->unread_marker.
  154637. */
  154638. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  154639. /* Declarations for routines called by application.
  154640. * The JPP macro hides prototype parameters from compilers that can't cope.
  154641. * Note JPP requires double parentheses.
  154642. */
  154643. #ifdef HAVE_PROTOTYPES
  154644. #define JPP(arglist) arglist
  154645. #else
  154646. #define JPP(arglist) ()
  154647. #endif
  154648. /* Short forms of external names for systems with brain-damaged linkers.
  154649. * We shorten external names to be unique in the first six letters, which
  154650. * is good enough for all known systems.
  154651. * (If your compiler itself needs names to be unique in less than 15
  154652. * characters, you are out of luck. Get a better compiler.)
  154653. */
  154654. #ifdef NEED_SHORT_EXTERNAL_NAMES
  154655. #define jpeg_std_error jStdError
  154656. #define jpeg_CreateCompress jCreaCompress
  154657. #define jpeg_CreateDecompress jCreaDecompress
  154658. #define jpeg_destroy_compress jDestCompress
  154659. #define jpeg_destroy_decompress jDestDecompress
  154660. #define jpeg_stdio_dest jStdDest
  154661. #define jpeg_stdio_src jStdSrc
  154662. #define jpeg_set_defaults jSetDefaults
  154663. #define jpeg_set_colorspace jSetColorspace
  154664. #define jpeg_default_colorspace jDefColorspace
  154665. #define jpeg_set_quality jSetQuality
  154666. #define jpeg_set_linear_quality jSetLQuality
  154667. #define jpeg_add_quant_table jAddQuantTable
  154668. #define jpeg_quality_scaling jQualityScaling
  154669. #define jpeg_simple_progression jSimProgress
  154670. #define jpeg_suppress_tables jSuppressTables
  154671. #define jpeg_alloc_quant_table jAlcQTable
  154672. #define jpeg_alloc_huff_table jAlcHTable
  154673. #define jpeg_start_compress jStrtCompress
  154674. #define jpeg_write_scanlines jWrtScanlines
  154675. #define jpeg_finish_compress jFinCompress
  154676. #define jpeg_write_raw_data jWrtRawData
  154677. #define jpeg_write_marker jWrtMarker
  154678. #define jpeg_write_m_header jWrtMHeader
  154679. #define jpeg_write_m_byte jWrtMByte
  154680. #define jpeg_write_tables jWrtTables
  154681. #define jpeg_read_header jReadHeader
  154682. #define jpeg_start_decompress jStrtDecompress
  154683. #define jpeg_read_scanlines jReadScanlines
  154684. #define jpeg_finish_decompress jFinDecompress
  154685. #define jpeg_read_raw_data jReadRawData
  154686. #define jpeg_has_multiple_scans jHasMultScn
  154687. #define jpeg_start_output jStrtOutput
  154688. #define jpeg_finish_output jFinOutput
  154689. #define jpeg_input_complete jInComplete
  154690. #define jpeg_new_colormap jNewCMap
  154691. #define jpeg_consume_input jConsumeInput
  154692. #define jpeg_calc_output_dimensions jCalcDimensions
  154693. #define jpeg_save_markers jSaveMarkers
  154694. #define jpeg_set_marker_processor jSetMarker
  154695. #define jpeg_read_coefficients jReadCoefs
  154696. #define jpeg_write_coefficients jWrtCoefs
  154697. #define jpeg_copy_critical_parameters jCopyCrit
  154698. #define jpeg_abort_compress jAbrtCompress
  154699. #define jpeg_abort_decompress jAbrtDecompress
  154700. #define jpeg_abort jAbort
  154701. #define jpeg_destroy jDestroy
  154702. #define jpeg_resync_to_restart jResyncRestart
  154703. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  154704. /* Default error-management setup */
  154705. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  154706. JPP((struct jpeg_error_mgr * err));
  154707. /* Initialization of JPEG compression objects.
  154708. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  154709. * names that applications should call. These expand to calls on
  154710. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  154711. * passed for version mismatch checking.
  154712. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  154713. */
  154714. #define jpeg_create_compress(cinfo) \
  154715. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  154716. (size_t) sizeof(struct jpeg_compress_struct))
  154717. #define jpeg_create_decompress(cinfo) \
  154718. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  154719. (size_t) sizeof(struct jpeg_decompress_struct))
  154720. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  154721. int version, size_t structsize));
  154722. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  154723. int version, size_t structsize));
  154724. /* Destruction of JPEG compression objects */
  154725. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  154726. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  154727. /* Standard data source and destination managers: stdio streams. */
  154728. /* Caller is responsible for opening the file before and closing after. */
  154729. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  154730. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  154731. /* Default parameter setup for compression */
  154732. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  154733. /* Compression parameter setup aids */
  154734. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  154735. J_COLOR_SPACE colorspace));
  154736. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  154737. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  154738. boolean force_baseline));
  154739. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  154740. int scale_factor,
  154741. boolean force_baseline));
  154742. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  154743. const unsigned int *basic_table,
  154744. int scale_factor,
  154745. boolean force_baseline));
  154746. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  154747. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  154748. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  154749. boolean suppress));
  154750. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  154751. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  154752. /* Main entry points for compression */
  154753. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  154754. boolean write_all_tables));
  154755. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  154756. JSAMPARRAY scanlines,
  154757. JDIMENSION num_lines));
  154758. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  154759. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  154760. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  154761. JSAMPIMAGE data,
  154762. JDIMENSION num_lines));
  154763. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  154764. EXTERN(void) jpeg_write_marker
  154765. JPP((j_compress_ptr cinfo, int marker,
  154766. const JOCTET * dataptr, unsigned int datalen));
  154767. /* Same, but piecemeal. */
  154768. EXTERN(void) jpeg_write_m_header
  154769. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  154770. EXTERN(void) jpeg_write_m_byte
  154771. JPP((j_compress_ptr cinfo, int val));
  154772. /* Alternate compression function: just write an abbreviated table file */
  154773. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  154774. /* Decompression startup: read start of JPEG datastream to see what's there */
  154775. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  154776. boolean require_image));
  154777. /* Return value is one of: */
  154778. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  154779. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  154780. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  154781. /* If you pass require_image = TRUE (normal case), you need not check for
  154782. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  154783. * JPEG_SUSPENDED is only possible if you use a data source module that can
  154784. * give a suspension return (the stdio source module doesn't).
  154785. */
  154786. /* Main entry points for decompression */
  154787. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  154788. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  154789. JSAMPARRAY scanlines,
  154790. JDIMENSION max_lines));
  154791. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  154792. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  154793. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  154794. JSAMPIMAGE data,
  154795. JDIMENSION max_lines));
  154796. /* Additional entry points for buffered-image mode. */
  154797. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  154798. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  154799. int scan_number));
  154800. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  154801. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  154802. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  154803. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  154804. /* Return value is one of: */
  154805. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  154806. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  154807. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  154808. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  154809. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  154810. /* Precalculate output dimensions for current decompression parameters. */
  154811. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  154812. /* Control saving of COM and APPn markers into marker_list. */
  154813. EXTERN(void) jpeg_save_markers
  154814. JPP((j_decompress_ptr cinfo, int marker_code,
  154815. unsigned int length_limit));
  154816. /* Install a special processing method for COM or APPn markers. */
  154817. EXTERN(void) jpeg_set_marker_processor
  154818. JPP((j_decompress_ptr cinfo, int marker_code,
  154819. jpeg_marker_parser_method routine));
  154820. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  154821. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  154822. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  154823. jvirt_barray_ptr * coef_arrays));
  154824. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  154825. j_compress_ptr dstinfo));
  154826. /* If you choose to abort compression or decompression before completing
  154827. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  154828. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  154829. * if you're done with the JPEG object, but if you want to clean it up and
  154830. * reuse it, call this:
  154831. */
  154832. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  154833. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  154834. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  154835. * flavor of JPEG object. These may be more convenient in some places.
  154836. */
  154837. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  154838. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  154839. /* Default restart-marker-resync procedure for use by data source modules */
  154840. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  154841. int desired));
  154842. /* These marker codes are exported since applications and data source modules
  154843. * are likely to want to use them.
  154844. */
  154845. #define JPEG_RST0 0xD0 /* RST0 marker code */
  154846. #define JPEG_EOI 0xD9 /* EOI marker code */
  154847. #define JPEG_APP0 0xE0 /* APP0 marker code */
  154848. #define JPEG_COM 0xFE /* COM marker code */
  154849. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  154850. * for structure definitions that are never filled in, keep it quiet by
  154851. * supplying dummy definitions for the various substructures.
  154852. */
  154853. #ifdef INCOMPLETE_TYPES_BROKEN
  154854. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  154855. struct jvirt_sarray_control { long dummy; };
  154856. struct jvirt_barray_control { long dummy; };
  154857. struct jpeg_comp_master { long dummy; };
  154858. struct jpeg_c_main_controller { long dummy; };
  154859. struct jpeg_c_prep_controller { long dummy; };
  154860. struct jpeg_c_coef_controller { long dummy; };
  154861. struct jpeg_marker_writer { long dummy; };
  154862. struct jpeg_color_converter { long dummy; };
  154863. struct jpeg_downsampler { long dummy; };
  154864. struct jpeg_forward_dct { long dummy; };
  154865. struct jpeg_entropy_encoder { long dummy; };
  154866. struct jpeg_decomp_master { long dummy; };
  154867. struct jpeg_d_main_controller { long dummy; };
  154868. struct jpeg_d_coef_controller { long dummy; };
  154869. struct jpeg_d_post_controller { long dummy; };
  154870. struct jpeg_input_controller { long dummy; };
  154871. struct jpeg_marker_reader { long dummy; };
  154872. struct jpeg_entropy_decoder { long dummy; };
  154873. struct jpeg_inverse_dct { long dummy; };
  154874. struct jpeg_upsampler { long dummy; };
  154875. struct jpeg_color_deconverter { long dummy; };
  154876. struct jpeg_color_quantizer { long dummy; };
  154877. #endif /* JPEG_INTERNALS */
  154878. #endif /* INCOMPLETE_TYPES_BROKEN */
  154879. /*
  154880. * The JPEG library modules define JPEG_INTERNALS before including this file.
  154881. * The internal structure declarations are read only when that is true.
  154882. * Applications using the library should not include jpegint.h, but may wish
  154883. * to include jerror.h.
  154884. */
  154885. #ifdef JPEG_INTERNALS
  154886. /********* Start of inlined file: jpegint.h *********/
  154887. /* Declarations for both compression & decompression */
  154888. typedef enum { /* Operating modes for buffer controllers */
  154889. JBUF_PASS_THRU, /* Plain stripwise operation */
  154890. /* Remaining modes require a full-image buffer to have been created */
  154891. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  154892. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  154893. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  154894. } J_BUF_MODE;
  154895. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  154896. #define CSTATE_START 100 /* after create_compress */
  154897. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  154898. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  154899. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  154900. #define DSTATE_START 200 /* after create_decompress */
  154901. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  154902. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  154903. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  154904. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  154905. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  154906. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  154907. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  154908. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  154909. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  154910. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  154911. /* Declarations for compression modules */
  154912. /* Master control module */
  154913. struct jpeg_comp_master {
  154914. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  154915. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  154916. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  154917. /* State variables made visible to other modules */
  154918. boolean call_pass_startup; /* True if pass_startup must be called */
  154919. boolean is_last_pass; /* True during last pass */
  154920. };
  154921. /* Main buffer control (downsampled-data buffer) */
  154922. struct jpeg_c_main_controller {
  154923. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  154924. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  154925. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  154926. JDIMENSION in_rows_avail));
  154927. };
  154928. /* Compression preprocessing (downsampling input buffer control) */
  154929. struct jpeg_c_prep_controller {
  154930. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  154931. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  154932. JSAMPARRAY input_buf,
  154933. JDIMENSION *in_row_ctr,
  154934. JDIMENSION in_rows_avail,
  154935. JSAMPIMAGE output_buf,
  154936. JDIMENSION *out_row_group_ctr,
  154937. JDIMENSION out_row_groups_avail));
  154938. };
  154939. /* Coefficient buffer control */
  154940. struct jpeg_c_coef_controller {
  154941. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  154942. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  154943. JSAMPIMAGE input_buf));
  154944. };
  154945. /* Colorspace conversion */
  154946. struct jpeg_color_converter {
  154947. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  154948. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  154949. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  154950. JDIMENSION output_row, int num_rows));
  154951. };
  154952. /* Downsampling */
  154953. struct jpeg_downsampler {
  154954. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  154955. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  154956. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  154957. JSAMPIMAGE output_buf,
  154958. JDIMENSION out_row_group_index));
  154959. boolean need_context_rows; /* TRUE if need rows above & below */
  154960. };
  154961. /* Forward DCT (also controls coefficient quantization) */
  154962. struct jpeg_forward_dct {
  154963. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  154964. /* perhaps this should be an array??? */
  154965. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  154966. jpeg_component_info * compptr,
  154967. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  154968. JDIMENSION start_row, JDIMENSION start_col,
  154969. JDIMENSION num_blocks));
  154970. };
  154971. /* Entropy encoding */
  154972. struct jpeg_entropy_encoder {
  154973. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  154974. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  154975. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  154976. };
  154977. /* Marker writing */
  154978. struct jpeg_marker_writer {
  154979. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  154980. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  154981. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  154982. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  154983. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  154984. /* These routines are exported to allow insertion of extra markers */
  154985. /* Probably only COM and APPn markers should be written this way */
  154986. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  154987. unsigned int datalen));
  154988. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  154989. };
  154990. /* Declarations for decompression modules */
  154991. /* Master control module */
  154992. struct jpeg_decomp_master {
  154993. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  154994. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  154995. /* State variables made visible to other modules */
  154996. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  154997. };
  154998. /* Input control module */
  154999. struct jpeg_input_controller {
  155000. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  155001. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  155002. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  155003. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  155004. /* State variables made visible to other modules */
  155005. boolean has_multiple_scans; /* True if file has multiple scans */
  155006. boolean eoi_reached; /* True when EOI has been consumed */
  155007. };
  155008. /* Main buffer control (downsampled-data buffer) */
  155009. struct jpeg_d_main_controller {
  155010. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  155011. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  155012. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  155013. JDIMENSION out_rows_avail));
  155014. };
  155015. /* Coefficient buffer control */
  155016. struct jpeg_d_coef_controller {
  155017. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  155018. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  155019. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  155020. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  155021. JSAMPIMAGE output_buf));
  155022. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  155023. jvirt_barray_ptr *coef_arrays;
  155024. };
  155025. /* Decompression postprocessing (color quantization buffer control) */
  155026. struct jpeg_d_post_controller {
  155027. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  155028. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  155029. JSAMPIMAGE input_buf,
  155030. JDIMENSION *in_row_group_ctr,
  155031. JDIMENSION in_row_groups_avail,
  155032. JSAMPARRAY output_buf,
  155033. JDIMENSION *out_row_ctr,
  155034. JDIMENSION out_rows_avail));
  155035. };
  155036. /* Marker reading & parsing */
  155037. struct jpeg_marker_reader {
  155038. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  155039. /* Read markers until SOS or EOI.
  155040. * Returns same codes as are defined for jpeg_consume_input:
  155041. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  155042. */
  155043. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  155044. /* Read a restart marker --- exported for use by entropy decoder only */
  155045. jpeg_marker_parser_method read_restart_marker;
  155046. /* State of marker reader --- nominally internal, but applications
  155047. * supplying COM or APPn handlers might like to know the state.
  155048. */
  155049. boolean saw_SOI; /* found SOI? */
  155050. boolean saw_SOF; /* found SOF? */
  155051. int next_restart_num; /* next restart number expected (0-7) */
  155052. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  155053. };
  155054. /* Entropy decoding */
  155055. struct jpeg_entropy_decoder {
  155056. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  155057. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  155058. JBLOCKROW *MCU_data));
  155059. /* This is here to share code between baseline and progressive decoders; */
  155060. /* other modules probably should not use it */
  155061. boolean insufficient_data; /* set TRUE after emitting warning */
  155062. };
  155063. /* Inverse DCT (also performs dequantization) */
  155064. typedef JMETHOD(void, inverse_DCT_method_ptr,
  155065. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  155066. JCOEFPTR coef_block,
  155067. JSAMPARRAY output_buf, JDIMENSION output_col));
  155068. struct jpeg_inverse_dct {
  155069. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  155070. /* It is useful to allow each component to have a separate IDCT method. */
  155071. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  155072. };
  155073. /* Upsampling (note that upsampler must also call color converter) */
  155074. struct jpeg_upsampler {
  155075. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  155076. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  155077. JSAMPIMAGE input_buf,
  155078. JDIMENSION *in_row_group_ctr,
  155079. JDIMENSION in_row_groups_avail,
  155080. JSAMPARRAY output_buf,
  155081. JDIMENSION *out_row_ctr,
  155082. JDIMENSION out_rows_avail));
  155083. boolean need_context_rows; /* TRUE if need rows above & below */
  155084. };
  155085. /* Colorspace conversion */
  155086. struct jpeg_color_deconverter {
  155087. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  155088. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  155089. JSAMPIMAGE input_buf, JDIMENSION input_row,
  155090. JSAMPARRAY output_buf, int num_rows));
  155091. };
  155092. /* Color quantization or color precision reduction */
  155093. struct jpeg_color_quantizer {
  155094. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  155095. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  155096. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  155097. int num_rows));
  155098. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  155099. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  155100. };
  155101. /* Miscellaneous useful macros */
  155102. #undef MAX
  155103. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  155104. #undef MIN
  155105. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  155106. /* We assume that right shift corresponds to signed division by 2 with
  155107. * rounding towards minus infinity. This is correct for typical "arithmetic
  155108. * shift" instructions that shift in copies of the sign bit. But some
  155109. * C compilers implement >> with an unsigned shift. For these machines you
  155110. * must define RIGHT_SHIFT_IS_UNSIGNED.
  155111. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  155112. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  155113. * included in the variables of any routine using RIGHT_SHIFT.
  155114. */
  155115. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  155116. #define SHIFT_TEMPS INT32 shift_temp;
  155117. #define RIGHT_SHIFT(x,shft) \
  155118. ((shift_temp = (x)) < 0 ? \
  155119. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  155120. (shift_temp >> (shft)))
  155121. #else
  155122. #define SHIFT_TEMPS
  155123. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  155124. #endif
  155125. /* Short forms of external names for systems with brain-damaged linkers. */
  155126. #ifdef NEED_SHORT_EXTERNAL_NAMES
  155127. #define jinit_compress_master jICompress
  155128. #define jinit_c_master_control jICMaster
  155129. #define jinit_c_main_controller jICMainC
  155130. #define jinit_c_prep_controller jICPrepC
  155131. #define jinit_c_coef_controller jICCoefC
  155132. #define jinit_color_converter jICColor
  155133. #define jinit_downsampler jIDownsampler
  155134. #define jinit_forward_dct jIFDCT
  155135. #define jinit_huff_encoder jIHEncoder
  155136. #define jinit_phuff_encoder jIPHEncoder
  155137. #define jinit_marker_writer jIMWriter
  155138. #define jinit_master_decompress jIDMaster
  155139. #define jinit_d_main_controller jIDMainC
  155140. #define jinit_d_coef_controller jIDCoefC
  155141. #define jinit_d_post_controller jIDPostC
  155142. #define jinit_input_controller jIInCtlr
  155143. #define jinit_marker_reader jIMReader
  155144. #define jinit_huff_decoder jIHDecoder
  155145. #define jinit_phuff_decoder jIPHDecoder
  155146. #define jinit_inverse_dct jIIDCT
  155147. #define jinit_upsampler jIUpsampler
  155148. #define jinit_color_deconverter jIDColor
  155149. #define jinit_1pass_quantizer jI1Quant
  155150. #define jinit_2pass_quantizer jI2Quant
  155151. #define jinit_merged_upsampler jIMUpsampler
  155152. #define jinit_memory_mgr jIMemMgr
  155153. #define jdiv_round_up jDivRound
  155154. #define jround_up jRound
  155155. #define jcopy_sample_rows jCopySamples
  155156. #define jcopy_block_row jCopyBlocks
  155157. #define jzero_far jZeroFar
  155158. #define jpeg_zigzag_order jZIGTable
  155159. #define jpeg_natural_order jZAGTable
  155160. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  155161. /* Compression module initialization routines */
  155162. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  155163. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  155164. boolean transcode_only));
  155165. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  155166. boolean need_full_buffer));
  155167. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  155168. boolean need_full_buffer));
  155169. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  155170. boolean need_full_buffer));
  155171. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  155172. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  155173. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  155174. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  155175. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  155176. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  155177. /* Decompression module initialization routines */
  155178. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  155179. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  155180. boolean need_full_buffer));
  155181. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  155182. boolean need_full_buffer));
  155183. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  155184. boolean need_full_buffer));
  155185. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  155186. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  155187. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  155188. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  155189. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  155190. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  155191. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  155192. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  155193. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  155194. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  155195. /* Memory manager initialization */
  155196. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  155197. /* Utility routines in jutils.c */
  155198. EXTERN(long) jdiv_round_up JPP((long a, long b));
  155199. EXTERN(long) jround_up JPP((long a, long b));
  155200. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  155201. JSAMPARRAY output_array, int dest_row,
  155202. int num_rows, JDIMENSION num_cols));
  155203. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  155204. JDIMENSION num_blocks));
  155205. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  155206. /* Constant tables in jutils.c */
  155207. #if 0 /* This table is not actually needed in v6a */
  155208. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  155209. #endif
  155210. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  155211. /* Suppress undefined-structure complaints if necessary. */
  155212. #ifdef INCOMPLETE_TYPES_BROKEN
  155213. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  155214. struct jvirt_sarray_control { long dummy; };
  155215. struct jvirt_barray_control { long dummy; };
  155216. #endif
  155217. #endif /* INCOMPLETE_TYPES_BROKEN */
  155218. /********* End of inlined file: jpegint.h *********/
  155219. /* fetch private declarations */
  155220. /********* Start of inlined file: jerror.h *********/
  155221. /*
  155222. * To define the enum list of message codes, include this file without
  155223. * defining macro JMESSAGE. To create a message string table, include it
  155224. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  155225. */
  155226. #ifndef JMESSAGE
  155227. #ifndef JERROR_H
  155228. /* First time through, define the enum list */
  155229. #define JMAKE_ENUM_LIST
  155230. #else
  155231. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  155232. #define JMESSAGE(code,string)
  155233. #endif /* JERROR_H */
  155234. #endif /* JMESSAGE */
  155235. #ifdef JMAKE_ENUM_LIST
  155236. typedef enum {
  155237. #define JMESSAGE(code,string) code ,
  155238. #endif /* JMAKE_ENUM_LIST */
  155239. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  155240. /* For maintenance convenience, list is alphabetical by message code name */
  155241. JMESSAGE(JERR_ARITH_NOTIMPL,
  155242. "Sorry, there are legal restrictions on arithmetic coding")
  155243. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  155244. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  155245. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  155246. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  155247. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  155248. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  155249. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  155250. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  155251. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  155252. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  155253. JMESSAGE(JERR_BAD_LIB_VERSION,
  155254. "Wrong JPEG library version: library is %d, caller expects %d")
  155255. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  155256. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  155257. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  155258. JMESSAGE(JERR_BAD_PROGRESSION,
  155259. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  155260. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  155261. "Invalid progressive parameters at scan script entry %d")
  155262. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  155263. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  155264. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  155265. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  155266. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  155267. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  155268. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  155269. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  155270. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  155271. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  155272. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  155273. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  155274. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  155275. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  155276. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  155277. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  155278. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  155279. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  155280. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  155281. JMESSAGE(JERR_FILE_READ, "Input file read error")
  155282. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  155283. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  155284. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  155285. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  155286. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  155287. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  155288. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  155289. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  155290. "Cannot transcode due to multiple use of quantization table %d")
  155291. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  155292. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  155293. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  155294. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  155295. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  155296. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  155297. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  155298. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  155299. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  155300. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  155301. JMESSAGE(JERR_QUANT_COMPONENTS,
  155302. "Cannot quantize more than %d color components")
  155303. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  155304. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  155305. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  155306. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  155307. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  155308. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  155309. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  155310. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  155311. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  155312. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  155313. JMESSAGE(JERR_TFILE_WRITE,
  155314. "Write failed on temporary file --- out of disk space?")
  155315. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  155316. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  155317. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  155318. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  155319. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  155320. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  155321. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  155322. JMESSAGE(JMSG_VERSION, JVERSION)
  155323. JMESSAGE(JTRC_16BIT_TABLES,
  155324. "Caution: quantization tables are too coarse for baseline JPEG")
  155325. JMESSAGE(JTRC_ADOBE,
  155326. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  155327. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  155328. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  155329. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  155330. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  155331. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  155332. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  155333. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  155334. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  155335. JMESSAGE(JTRC_EOI, "End Of Image")
  155336. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  155337. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  155338. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  155339. "Warning: thumbnail image size does not match data length %u")
  155340. JMESSAGE(JTRC_JFIF_EXTENSION,
  155341. "JFIF extension marker: type 0x%02x, length %u")
  155342. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  155343. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  155344. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  155345. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  155346. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  155347. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  155348. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  155349. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  155350. JMESSAGE(JTRC_RST, "RST%d")
  155351. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  155352. "Smoothing not supported with nonstandard sampling ratios")
  155353. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  155354. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  155355. JMESSAGE(JTRC_SOI, "Start of Image")
  155356. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  155357. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  155358. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  155359. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  155360. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  155361. JMESSAGE(JTRC_THUMB_JPEG,
  155362. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  155363. JMESSAGE(JTRC_THUMB_PALETTE,
  155364. "JFIF extension marker: palette thumbnail image, length %u")
  155365. JMESSAGE(JTRC_THUMB_RGB,
  155366. "JFIF extension marker: RGB thumbnail image, length %u")
  155367. JMESSAGE(JTRC_UNKNOWN_IDS,
  155368. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  155369. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  155370. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  155371. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  155372. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  155373. "Inconsistent progression sequence for component %d coefficient %d")
  155374. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  155375. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  155376. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  155377. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  155378. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  155379. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  155380. JMESSAGE(JWRN_MUST_RESYNC,
  155381. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  155382. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  155383. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  155384. #ifdef JMAKE_ENUM_LIST
  155385. JMSG_LASTMSGCODE
  155386. } J_MESSAGE_CODE;
  155387. #undef JMAKE_ENUM_LIST
  155388. #endif /* JMAKE_ENUM_LIST */
  155389. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  155390. #undef JMESSAGE
  155391. #ifndef JERROR_H
  155392. #define JERROR_H
  155393. /* Macros to simplify using the error and trace message stuff */
  155394. /* The first parameter is either type of cinfo pointer */
  155395. /* Fatal errors (print message and exit) */
  155396. #define ERREXIT(cinfo,code) \
  155397. ((cinfo)->err->msg_code = (code), \
  155398. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155399. #define ERREXIT1(cinfo,code,p1) \
  155400. ((cinfo)->err->msg_code = (code), \
  155401. (cinfo)->err->msg_parm.i[0] = (p1), \
  155402. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155403. #define ERREXIT2(cinfo,code,p1,p2) \
  155404. ((cinfo)->err->msg_code = (code), \
  155405. (cinfo)->err->msg_parm.i[0] = (p1), \
  155406. (cinfo)->err->msg_parm.i[1] = (p2), \
  155407. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155408. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  155409. ((cinfo)->err->msg_code = (code), \
  155410. (cinfo)->err->msg_parm.i[0] = (p1), \
  155411. (cinfo)->err->msg_parm.i[1] = (p2), \
  155412. (cinfo)->err->msg_parm.i[2] = (p3), \
  155413. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155414. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  155415. ((cinfo)->err->msg_code = (code), \
  155416. (cinfo)->err->msg_parm.i[0] = (p1), \
  155417. (cinfo)->err->msg_parm.i[1] = (p2), \
  155418. (cinfo)->err->msg_parm.i[2] = (p3), \
  155419. (cinfo)->err->msg_parm.i[3] = (p4), \
  155420. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155421. #define ERREXITS(cinfo,code,str) \
  155422. ((cinfo)->err->msg_code = (code), \
  155423. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  155424. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  155425. #define MAKESTMT(stuff) do { stuff } while (0)
  155426. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  155427. #define WARNMS(cinfo,code) \
  155428. ((cinfo)->err->msg_code = (code), \
  155429. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  155430. #define WARNMS1(cinfo,code,p1) \
  155431. ((cinfo)->err->msg_code = (code), \
  155432. (cinfo)->err->msg_parm.i[0] = (p1), \
  155433. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  155434. #define WARNMS2(cinfo,code,p1,p2) \
  155435. ((cinfo)->err->msg_code = (code), \
  155436. (cinfo)->err->msg_parm.i[0] = (p1), \
  155437. (cinfo)->err->msg_parm.i[1] = (p2), \
  155438. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  155439. /* Informational/debugging messages */
  155440. #define TRACEMS(cinfo,lvl,code) \
  155441. ((cinfo)->err->msg_code = (code), \
  155442. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  155443. #define TRACEMS1(cinfo,lvl,code,p1) \
  155444. ((cinfo)->err->msg_code = (code), \
  155445. (cinfo)->err->msg_parm.i[0] = (p1), \
  155446. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  155447. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  155448. ((cinfo)->err->msg_code = (code), \
  155449. (cinfo)->err->msg_parm.i[0] = (p1), \
  155450. (cinfo)->err->msg_parm.i[1] = (p2), \
  155451. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  155452. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  155453. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  155454. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  155455. (cinfo)->err->msg_code = (code); \
  155456. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  155457. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  155458. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  155459. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  155460. (cinfo)->err->msg_code = (code); \
  155461. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  155462. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  155463. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  155464. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  155465. _mp[4] = (p5); \
  155466. (cinfo)->err->msg_code = (code); \
  155467. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  155468. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  155469. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  155470. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  155471. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  155472. (cinfo)->err->msg_code = (code); \
  155473. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  155474. #define TRACEMSS(cinfo,lvl,code,str) \
  155475. ((cinfo)->err->msg_code = (code), \
  155476. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  155477. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  155478. #endif /* JERROR_H */
  155479. /********* End of inlined file: jerror.h *********/
  155480. /* fetch error codes too */
  155481. #endif
  155482. #endif /* JPEGLIB_H */
  155483. /********* End of inlined file: jpeglib.h *********/
  155484. /********* Start of inlined file: jcapimin.c *********/
  155485. #define JPEG_INTERNALS
  155486. /********* Start of inlined file: jinclude.h *********/
  155487. /* Include auto-config file to find out which system include files we need. */
  155488. #ifndef __jinclude_h__
  155489. #define __jinclude_h__
  155490. /********* Start of inlined file: jconfig.h *********/
  155491. /* see jconfig.doc for explanations */
  155492. // disable all the warnings under MSVC
  155493. #ifdef _MSC_VER
  155494. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  155495. #endif
  155496. #ifdef __BORLANDC__
  155497. #pragma warn -8057
  155498. #pragma warn -8019
  155499. #pragma warn -8004
  155500. #pragma warn -8008
  155501. #endif
  155502. #define HAVE_PROTOTYPES
  155503. #define HAVE_UNSIGNED_CHAR
  155504. #define HAVE_UNSIGNED_SHORT
  155505. /* #define void char */
  155506. /* #define const */
  155507. #undef CHAR_IS_UNSIGNED
  155508. #define HAVE_STDDEF_H
  155509. #define HAVE_STDLIB_H
  155510. #undef NEED_BSD_STRINGS
  155511. #undef NEED_SYS_TYPES_H
  155512. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  155513. #undef NEED_SHORT_EXTERNAL_NAMES
  155514. #undef INCOMPLETE_TYPES_BROKEN
  155515. /* Define "boolean" as unsigned char, not int, per Windows custom */
  155516. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  155517. typedef unsigned char boolean;
  155518. #endif
  155519. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  155520. #ifdef JPEG_INTERNALS
  155521. #undef RIGHT_SHIFT_IS_UNSIGNED
  155522. #endif /* JPEG_INTERNALS */
  155523. #ifdef JPEG_CJPEG_DJPEG
  155524. #define BMP_SUPPORTED /* BMP image file format */
  155525. #define GIF_SUPPORTED /* GIF image file format */
  155526. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  155527. #undef RLE_SUPPORTED /* Utah RLE image file format */
  155528. #define TARGA_SUPPORTED /* Targa image file format */
  155529. #define TWO_FILE_COMMANDLINE /* optional */
  155530. #define USE_SETMODE /* Microsoft has setmode() */
  155531. #undef NEED_SIGNAL_CATCHER
  155532. #undef DONT_USE_B_MODE
  155533. #undef PROGRESS_REPORT /* optional */
  155534. #endif /* JPEG_CJPEG_DJPEG */
  155535. /********* End of inlined file: jconfig.h *********/
  155536. /* auto configuration options */
  155537. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  155538. /*
  155539. * We need the NULL macro and size_t typedef.
  155540. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  155541. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  155542. * pull in <sys/types.h> as well.
  155543. * Note that the core JPEG library does not require <stdio.h>;
  155544. * only the default error handler and data source/destination modules do.
  155545. * But we must pull it in because of the references to FILE in jpeglib.h.
  155546. * You can remove those references if you want to compile without <stdio.h>.
  155547. */
  155548. #ifdef HAVE_STDDEF_H
  155549. #include <stddef.h>
  155550. #endif
  155551. #ifdef HAVE_STDLIB_H
  155552. #include <stdlib.h>
  155553. #endif
  155554. #ifdef NEED_SYS_TYPES_H
  155555. #include <sys/types.h>
  155556. #endif
  155557. #include <stdio.h>
  155558. /*
  155559. * We need memory copying and zeroing functions, plus strncpy().
  155560. * ANSI and System V implementations declare these in <string.h>.
  155561. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  155562. * Some systems may declare memset and memcpy in <memory.h>.
  155563. *
  155564. * NOTE: we assume the size parameters to these functions are of type size_t.
  155565. * Change the casts in these macros if not!
  155566. */
  155567. #ifdef NEED_BSD_STRINGS
  155568. #include <strings.h>
  155569. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  155570. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  155571. #else /* not BSD, assume ANSI/SysV string lib */
  155572. #include <string.h>
  155573. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  155574. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  155575. #endif
  155576. /*
  155577. * In ANSI C, and indeed any rational implementation, size_t is also the
  155578. * type returned by sizeof(). However, it seems there are some irrational
  155579. * implementations out there, in which sizeof() returns an int even though
  155580. * size_t is defined as long or unsigned long. To ensure consistent results
  155581. * we always use this SIZEOF() macro in place of using sizeof() directly.
  155582. */
  155583. #define SIZEOF(object) ((size_t) sizeof(object))
  155584. /*
  155585. * The modules that use fread() and fwrite() always invoke them through
  155586. * these macros. On some systems you may need to twiddle the argument casts.
  155587. * CAUTION: argument order is different from underlying functions!
  155588. */
  155589. #define JFREAD(file,buf,sizeofbuf) \
  155590. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  155591. #define JFWRITE(file,buf,sizeofbuf) \
  155592. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  155593. typedef enum { /* JPEG marker codes */
  155594. M_SOF0 = 0xc0,
  155595. M_SOF1 = 0xc1,
  155596. M_SOF2 = 0xc2,
  155597. M_SOF3 = 0xc3,
  155598. M_SOF5 = 0xc5,
  155599. M_SOF6 = 0xc6,
  155600. M_SOF7 = 0xc7,
  155601. M_JPG = 0xc8,
  155602. M_SOF9 = 0xc9,
  155603. M_SOF10 = 0xca,
  155604. M_SOF11 = 0xcb,
  155605. M_SOF13 = 0xcd,
  155606. M_SOF14 = 0xce,
  155607. M_SOF15 = 0xcf,
  155608. M_DHT = 0xc4,
  155609. M_DAC = 0xcc,
  155610. M_RST0 = 0xd0,
  155611. M_RST1 = 0xd1,
  155612. M_RST2 = 0xd2,
  155613. M_RST3 = 0xd3,
  155614. M_RST4 = 0xd4,
  155615. M_RST5 = 0xd5,
  155616. M_RST6 = 0xd6,
  155617. M_RST7 = 0xd7,
  155618. M_SOI = 0xd8,
  155619. M_EOI = 0xd9,
  155620. M_SOS = 0xda,
  155621. M_DQT = 0xdb,
  155622. M_DNL = 0xdc,
  155623. M_DRI = 0xdd,
  155624. M_DHP = 0xde,
  155625. M_EXP = 0xdf,
  155626. M_APP0 = 0xe0,
  155627. M_APP1 = 0xe1,
  155628. M_APP2 = 0xe2,
  155629. M_APP3 = 0xe3,
  155630. M_APP4 = 0xe4,
  155631. M_APP5 = 0xe5,
  155632. M_APP6 = 0xe6,
  155633. M_APP7 = 0xe7,
  155634. M_APP8 = 0xe8,
  155635. M_APP9 = 0xe9,
  155636. M_APP10 = 0xea,
  155637. M_APP11 = 0xeb,
  155638. M_APP12 = 0xec,
  155639. M_APP13 = 0xed,
  155640. M_APP14 = 0xee,
  155641. M_APP15 = 0xef,
  155642. M_JPG0 = 0xf0,
  155643. M_JPG13 = 0xfd,
  155644. M_COM = 0xfe,
  155645. M_TEM = 0x01,
  155646. M_ERROR = 0x100
  155647. } JPEG_MARKER;
  155648. /*
  155649. * Figure F.12: extend sign bit.
  155650. * On some machines, a shift and add will be faster than a table lookup.
  155651. */
  155652. #ifdef AVOID_TABLES
  155653. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  155654. #else
  155655. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  155656. static const int extend_test[16] = /* entry n is 2**(n-1) */
  155657. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  155658. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  155659. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  155660. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  155661. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  155662. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  155663. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  155664. #endif /* AVOID_TABLES */
  155665. #endif
  155666. /********* End of inlined file: jinclude.h *********/
  155667. /*
  155668. * Initialization of a JPEG compression object.
  155669. * The error manager must already be set up (in case memory manager fails).
  155670. */
  155671. GLOBAL(void)
  155672. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  155673. {
  155674. int i;
  155675. /* Guard against version mismatches between library and caller. */
  155676. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  155677. if (version != JPEG_LIB_VERSION)
  155678. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  155679. if (structsize != SIZEOF(struct jpeg_compress_struct))
  155680. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  155681. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  155682. /* For debugging purposes, we zero the whole master structure.
  155683. * But the application has already set the err pointer, and may have set
  155684. * client_data, so we have to save and restore those fields.
  155685. * Note: if application hasn't set client_data, tools like Purify may
  155686. * complain here.
  155687. */
  155688. {
  155689. struct jpeg_error_mgr * err = cinfo->err;
  155690. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  155691. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  155692. cinfo->err = err;
  155693. cinfo->client_data = client_data;
  155694. }
  155695. cinfo->is_decompressor = FALSE;
  155696. /* Initialize a memory manager instance for this object */
  155697. jinit_memory_mgr((j_common_ptr) cinfo);
  155698. /* Zero out pointers to permanent structures. */
  155699. cinfo->progress = NULL;
  155700. cinfo->dest = NULL;
  155701. cinfo->comp_info = NULL;
  155702. for (i = 0; i < NUM_QUANT_TBLS; i++)
  155703. cinfo->quant_tbl_ptrs[i] = NULL;
  155704. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  155705. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  155706. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  155707. }
  155708. cinfo->script_space = NULL;
  155709. cinfo->input_gamma = 1.0; /* in case application forgets */
  155710. /* OK, I'm ready */
  155711. cinfo->global_state = CSTATE_START;
  155712. }
  155713. /*
  155714. * Destruction of a JPEG compression object
  155715. */
  155716. GLOBAL(void)
  155717. jpeg_destroy_compress (j_compress_ptr cinfo)
  155718. {
  155719. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  155720. }
  155721. /*
  155722. * Abort processing of a JPEG compression operation,
  155723. * but don't destroy the object itself.
  155724. */
  155725. GLOBAL(void)
  155726. jpeg_abort_compress (j_compress_ptr cinfo)
  155727. {
  155728. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  155729. }
  155730. /*
  155731. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  155732. * Marks all currently defined tables as already written (if suppress)
  155733. * or not written (if !suppress). This will control whether they get emitted
  155734. * by a subsequent jpeg_start_compress call.
  155735. *
  155736. * This routine is exported for use by applications that want to produce
  155737. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  155738. * since it is called by jpeg_start_compress, we put it here --- otherwise
  155739. * jcparam.o would be linked whether the application used it or not.
  155740. */
  155741. GLOBAL(void)
  155742. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  155743. {
  155744. int i;
  155745. JQUANT_TBL * qtbl;
  155746. JHUFF_TBL * htbl;
  155747. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  155748. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  155749. qtbl->sent_table = suppress;
  155750. }
  155751. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  155752. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  155753. htbl->sent_table = suppress;
  155754. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  155755. htbl->sent_table = suppress;
  155756. }
  155757. }
  155758. /*
  155759. * Finish JPEG compression.
  155760. *
  155761. * If a multipass operating mode was selected, this may do a great deal of
  155762. * work including most of the actual output.
  155763. */
  155764. GLOBAL(void)
  155765. jpeg_finish_compress (j_compress_ptr cinfo)
  155766. {
  155767. JDIMENSION iMCU_row;
  155768. if (cinfo->global_state == CSTATE_SCANNING ||
  155769. cinfo->global_state == CSTATE_RAW_OK) {
  155770. /* Terminate first pass */
  155771. if (cinfo->next_scanline < cinfo->image_height)
  155772. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  155773. (*cinfo->master->finish_pass) (cinfo);
  155774. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  155775. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155776. /* Perform any remaining passes */
  155777. while (! cinfo->master->is_last_pass) {
  155778. (*cinfo->master->prepare_for_pass) (cinfo);
  155779. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  155780. if (cinfo->progress != NULL) {
  155781. cinfo->progress->pass_counter = (long) iMCU_row;
  155782. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  155783. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  155784. }
  155785. /* We bypass the main controller and invoke coef controller directly;
  155786. * all work is being done from the coefficient buffer.
  155787. */
  155788. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  155789. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  155790. }
  155791. (*cinfo->master->finish_pass) (cinfo);
  155792. }
  155793. /* Write EOI, do final cleanup */
  155794. (*cinfo->marker->write_file_trailer) (cinfo);
  155795. (*cinfo->dest->term_destination) (cinfo);
  155796. /* We can use jpeg_abort to release memory and reset global_state */
  155797. jpeg_abort((j_common_ptr) cinfo);
  155798. }
  155799. /*
  155800. * Write a special marker.
  155801. * This is only recommended for writing COM or APPn markers.
  155802. * Must be called after jpeg_start_compress() and before
  155803. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  155804. */
  155805. GLOBAL(void)
  155806. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  155807. const JOCTET *dataptr, unsigned int datalen)
  155808. {
  155809. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  155810. if (cinfo->next_scanline != 0 ||
  155811. (cinfo->global_state != CSTATE_SCANNING &&
  155812. cinfo->global_state != CSTATE_RAW_OK &&
  155813. cinfo->global_state != CSTATE_WRCOEFS))
  155814. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155815. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  155816. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  155817. while (datalen--) {
  155818. (*write_marker_byte) (cinfo, *dataptr);
  155819. dataptr++;
  155820. }
  155821. }
  155822. /* Same, but piecemeal. */
  155823. GLOBAL(void)
  155824. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  155825. {
  155826. if (cinfo->next_scanline != 0 ||
  155827. (cinfo->global_state != CSTATE_SCANNING &&
  155828. cinfo->global_state != CSTATE_RAW_OK &&
  155829. cinfo->global_state != CSTATE_WRCOEFS))
  155830. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155831. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  155832. }
  155833. GLOBAL(void)
  155834. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  155835. {
  155836. (*cinfo->marker->write_marker_byte) (cinfo, val);
  155837. }
  155838. /*
  155839. * Alternate compression function: just write an abbreviated table file.
  155840. * Before calling this, all parameters and a data destination must be set up.
  155841. *
  155842. * To produce a pair of files containing abbreviated tables and abbreviated
  155843. * image data, one would proceed as follows:
  155844. *
  155845. * initialize JPEG object
  155846. * set JPEG parameters
  155847. * set destination to table file
  155848. * jpeg_write_tables(cinfo);
  155849. * set destination to image file
  155850. * jpeg_start_compress(cinfo, FALSE);
  155851. * write data...
  155852. * jpeg_finish_compress(cinfo);
  155853. *
  155854. * jpeg_write_tables has the side effect of marking all tables written
  155855. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  155856. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  155857. */
  155858. GLOBAL(void)
  155859. jpeg_write_tables (j_compress_ptr cinfo)
  155860. {
  155861. if (cinfo->global_state != CSTATE_START)
  155862. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155863. /* (Re)initialize error mgr and destination modules */
  155864. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  155865. (*cinfo->dest->init_destination) (cinfo);
  155866. /* Initialize the marker writer ... bit of a crock to do it here. */
  155867. jinit_marker_writer(cinfo);
  155868. /* Write them tables! */
  155869. (*cinfo->marker->write_tables_only) (cinfo);
  155870. /* And clean up. */
  155871. (*cinfo->dest->term_destination) (cinfo);
  155872. /*
  155873. * In library releases up through v6a, we called jpeg_abort() here to free
  155874. * any working memory allocated by the destination manager and marker
  155875. * writer. Some applications had a problem with that: they allocated space
  155876. * of their own from the library memory manager, and didn't want it to go
  155877. * away during write_tables. So now we do nothing. This will cause a
  155878. * memory leak if an app calls write_tables repeatedly without doing a full
  155879. * compression cycle or otherwise resetting the JPEG object. However, that
  155880. * seems less bad than unexpectedly freeing memory in the normal case.
  155881. * An app that prefers the old behavior can call jpeg_abort for itself after
  155882. * each call to jpeg_write_tables().
  155883. */
  155884. }
  155885. /********* End of inlined file: jcapimin.c *********/
  155886. /********* Start of inlined file: jcapistd.c *********/
  155887. #define JPEG_INTERNALS
  155888. /*
  155889. * Compression initialization.
  155890. * Before calling this, all parameters and a data destination must be set up.
  155891. *
  155892. * We require a write_all_tables parameter as a failsafe check when writing
  155893. * multiple datastreams from the same compression object. Since prior runs
  155894. * will have left all the tables marked sent_table=TRUE, a subsequent run
  155895. * would emit an abbreviated stream (no tables) by default. This may be what
  155896. * is wanted, but for safety's sake it should not be the default behavior:
  155897. * programmers should have to make a deliberate choice to emit abbreviated
  155898. * images. Therefore the documentation and examples should encourage people
  155899. * to pass write_all_tables=TRUE; then it will take active thought to do the
  155900. * wrong thing.
  155901. */
  155902. GLOBAL(void)
  155903. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  155904. {
  155905. if (cinfo->global_state != CSTATE_START)
  155906. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155907. if (write_all_tables)
  155908. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  155909. /* (Re)initialize error mgr and destination modules */
  155910. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  155911. (*cinfo->dest->init_destination) (cinfo);
  155912. /* Perform master selection of active modules */
  155913. jinit_compress_master(cinfo);
  155914. /* Set up for the first pass */
  155915. (*cinfo->master->prepare_for_pass) (cinfo);
  155916. /* Ready for application to drive first pass through jpeg_write_scanlines
  155917. * or jpeg_write_raw_data.
  155918. */
  155919. cinfo->next_scanline = 0;
  155920. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  155921. }
  155922. /*
  155923. * Write some scanlines of data to the JPEG compressor.
  155924. *
  155925. * The return value will be the number of lines actually written.
  155926. * This should be less than the supplied num_lines only in case that
  155927. * the data destination module has requested suspension of the compressor,
  155928. * or if more than image_height scanlines are passed in.
  155929. *
  155930. * Note: we warn about excess calls to jpeg_write_scanlines() since
  155931. * this likely signals an application programmer error. However,
  155932. * excess scanlines passed in the last valid call are *silently* ignored,
  155933. * so that the application need not adjust num_lines for end-of-image
  155934. * when using a multiple-scanline buffer.
  155935. */
  155936. GLOBAL(JDIMENSION)
  155937. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  155938. JDIMENSION num_lines)
  155939. {
  155940. JDIMENSION row_ctr, rows_left;
  155941. if (cinfo->global_state != CSTATE_SCANNING)
  155942. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155943. if (cinfo->next_scanline >= cinfo->image_height)
  155944. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  155945. /* Call progress monitor hook if present */
  155946. if (cinfo->progress != NULL) {
  155947. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  155948. cinfo->progress->pass_limit = (long) cinfo->image_height;
  155949. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  155950. }
  155951. /* Give master control module another chance if this is first call to
  155952. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  155953. * delayed so that application can write COM, etc, markers between
  155954. * jpeg_start_compress and jpeg_write_scanlines.
  155955. */
  155956. if (cinfo->master->call_pass_startup)
  155957. (*cinfo->master->pass_startup) (cinfo);
  155958. /* Ignore any extra scanlines at bottom of image. */
  155959. rows_left = cinfo->image_height - cinfo->next_scanline;
  155960. if (num_lines > rows_left)
  155961. num_lines = rows_left;
  155962. row_ctr = 0;
  155963. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  155964. cinfo->next_scanline += row_ctr;
  155965. return row_ctr;
  155966. }
  155967. /*
  155968. * Alternate entry point to write raw data.
  155969. * Processes exactly one iMCU row per call, unless suspended.
  155970. */
  155971. GLOBAL(JDIMENSION)
  155972. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  155973. JDIMENSION num_lines)
  155974. {
  155975. JDIMENSION lines_per_iMCU_row;
  155976. if (cinfo->global_state != CSTATE_RAW_OK)
  155977. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155978. if (cinfo->next_scanline >= cinfo->image_height) {
  155979. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  155980. return 0;
  155981. }
  155982. /* Call progress monitor hook if present */
  155983. if (cinfo->progress != NULL) {
  155984. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  155985. cinfo->progress->pass_limit = (long) cinfo->image_height;
  155986. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  155987. }
  155988. /* Give master control module another chance if this is first call to
  155989. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  155990. * delayed so that application can write COM, etc, markers between
  155991. * jpeg_start_compress and jpeg_write_raw_data.
  155992. */
  155993. if (cinfo->master->call_pass_startup)
  155994. (*cinfo->master->pass_startup) (cinfo);
  155995. /* Verify that at least one iMCU row has been passed. */
  155996. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  155997. if (num_lines < lines_per_iMCU_row)
  155998. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  155999. /* Directly compress the row. */
  156000. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  156001. /* If compressor did not consume the whole row, suspend processing. */
  156002. return 0;
  156003. }
  156004. /* OK, we processed one iMCU row. */
  156005. cinfo->next_scanline += lines_per_iMCU_row;
  156006. return lines_per_iMCU_row;
  156007. }
  156008. /********* End of inlined file: jcapistd.c *********/
  156009. /********* Start of inlined file: jccoefct.c *********/
  156010. #define JPEG_INTERNALS
  156011. /* We use a full-image coefficient buffer when doing Huffman optimization,
  156012. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  156013. * step is run during the first pass, and subsequent passes need only read
  156014. * the buffered coefficients.
  156015. */
  156016. #ifdef ENTROPY_OPT_SUPPORTED
  156017. #define FULL_COEF_BUFFER_SUPPORTED
  156018. #else
  156019. #ifdef C_MULTISCAN_FILES_SUPPORTED
  156020. #define FULL_COEF_BUFFER_SUPPORTED
  156021. #endif
  156022. #endif
  156023. /* Private buffer controller object */
  156024. typedef struct {
  156025. struct jpeg_c_coef_controller pub; /* public fields */
  156026. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  156027. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  156028. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  156029. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  156030. /* For single-pass compression, it's sufficient to buffer just one MCU
  156031. * (although this may prove a bit slow in practice). We allocate a
  156032. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  156033. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  156034. * it's not really very big; this is to keep the module interfaces unchanged
  156035. * when a large coefficient buffer is necessary.)
  156036. * In multi-pass modes, this array points to the current MCU's blocks
  156037. * within the virtual arrays.
  156038. */
  156039. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  156040. /* In multi-pass modes, we need a virtual block array for each component. */
  156041. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  156042. } my_coef_controller;
  156043. typedef my_coef_controller * my_coef_ptr;
  156044. /* Forward declarations */
  156045. METHODDEF(boolean) compress_data
  156046. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  156047. #ifdef FULL_COEF_BUFFER_SUPPORTED
  156048. METHODDEF(boolean) compress_first_pass
  156049. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  156050. METHODDEF(boolean) compress_output
  156051. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  156052. #endif
  156053. LOCAL(void)
  156054. start_iMCU_row (j_compress_ptr cinfo)
  156055. /* Reset within-iMCU-row counters for a new row */
  156056. {
  156057. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  156058. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  156059. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  156060. * But at the bottom of the image, process only what's left.
  156061. */
  156062. if (cinfo->comps_in_scan > 1) {
  156063. coef->MCU_rows_per_iMCU_row = 1;
  156064. } else {
  156065. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  156066. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  156067. else
  156068. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  156069. }
  156070. coef->mcu_ctr = 0;
  156071. coef->MCU_vert_offset = 0;
  156072. }
  156073. /*
  156074. * Initialize for a processing pass.
  156075. */
  156076. METHODDEF(void)
  156077. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  156078. {
  156079. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  156080. coef->iMCU_row_num = 0;
  156081. start_iMCU_row(cinfo);
  156082. switch (pass_mode) {
  156083. case JBUF_PASS_THRU:
  156084. if (coef->whole_image[0] != NULL)
  156085. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  156086. coef->pub.compress_data = compress_data;
  156087. break;
  156088. #ifdef FULL_COEF_BUFFER_SUPPORTED
  156089. case JBUF_SAVE_AND_PASS:
  156090. if (coef->whole_image[0] == NULL)
  156091. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  156092. coef->pub.compress_data = compress_first_pass;
  156093. break;
  156094. case JBUF_CRANK_DEST:
  156095. if (coef->whole_image[0] == NULL)
  156096. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  156097. coef->pub.compress_data = compress_output;
  156098. break;
  156099. #endif
  156100. default:
  156101. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  156102. break;
  156103. }
  156104. }
  156105. /*
  156106. * Process some data in the single-pass case.
  156107. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  156108. * per call, ie, v_samp_factor block rows for each component in the image.
  156109. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  156110. *
  156111. * NB: input_buf contains a plane for each component in image,
  156112. * which we index according to the component's SOF position.
  156113. */
  156114. METHODDEF(boolean)
  156115. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  156116. {
  156117. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  156118. JDIMENSION MCU_col_num; /* index of current MCU within row */
  156119. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  156120. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  156121. int blkn, bi, ci, yindex, yoffset, blockcnt;
  156122. JDIMENSION ypos, xpos;
  156123. jpeg_component_info *compptr;
  156124. /* Loop to write as much as one whole iMCU row */
  156125. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  156126. yoffset++) {
  156127. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  156128. MCU_col_num++) {
  156129. /* Determine where data comes from in input_buf and do the DCT thing.
  156130. * Each call on forward_DCT processes a horizontal row of DCT blocks
  156131. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  156132. * sequentially. Dummy blocks at the right or bottom edge are filled in
  156133. * specially. The data in them does not matter for image reconstruction,
  156134. * so we fill them with values that will encode to the smallest amount of
  156135. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  156136. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  156137. */
  156138. blkn = 0;
  156139. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  156140. compptr = cinfo->cur_comp_info[ci];
  156141. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  156142. : compptr->last_col_width;
  156143. xpos = MCU_col_num * compptr->MCU_sample_width;
  156144. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  156145. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  156146. if (coef->iMCU_row_num < last_iMCU_row ||
  156147. yoffset+yindex < compptr->last_row_height) {
  156148. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  156149. input_buf[compptr->component_index],
  156150. coef->MCU_buffer[blkn],
  156151. ypos, xpos, (JDIMENSION) blockcnt);
  156152. if (blockcnt < compptr->MCU_width) {
  156153. /* Create some dummy blocks at the right edge of the image. */
  156154. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  156155. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  156156. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  156157. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  156158. }
  156159. }
  156160. } else {
  156161. /* Create a row of dummy blocks at the bottom of the image. */
  156162. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  156163. compptr->MCU_width * SIZEOF(JBLOCK));
  156164. for (bi = 0; bi < compptr->MCU_width; bi++) {
  156165. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  156166. }
  156167. }
  156168. blkn += compptr->MCU_width;
  156169. ypos += DCTSIZE;
  156170. }
  156171. }
  156172. /* Try to write the MCU. In event of a suspension failure, we will
  156173. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  156174. */
  156175. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  156176. /* Suspension forced; update state counters and exit */
  156177. coef->MCU_vert_offset = yoffset;
  156178. coef->mcu_ctr = MCU_col_num;
  156179. return FALSE;
  156180. }
  156181. }
  156182. /* Completed an MCU row, but perhaps not an iMCU row */
  156183. coef->mcu_ctr = 0;
  156184. }
  156185. /* Completed the iMCU row, advance counters for next one */
  156186. coef->iMCU_row_num++;
  156187. start_iMCU_row(cinfo);
  156188. return TRUE;
  156189. }
  156190. #ifdef FULL_COEF_BUFFER_SUPPORTED
  156191. /*
  156192. * Process some data in the first pass of a multi-pass case.
  156193. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  156194. * per call, ie, v_samp_factor block rows for each component in the image.
  156195. * This amount of data is read from the source buffer, DCT'd and quantized,
  156196. * and saved into the virtual arrays. We also generate suitable dummy blocks
  156197. * as needed at the right and lower edges. (The dummy blocks are constructed
  156198. * in the virtual arrays, which have been padded appropriately.) This makes
  156199. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  156200. *
  156201. * We must also emit the data to the entropy encoder. This is conveniently
  156202. * done by calling compress_output() after we've loaded the current strip
  156203. * of the virtual arrays.
  156204. *
  156205. * NB: input_buf contains a plane for each component in image. All
  156206. * components are DCT'd and loaded into the virtual arrays in this pass.
  156207. * However, it may be that only a subset of the components are emitted to
  156208. * the entropy encoder during this first pass; be careful about looking
  156209. * at the scan-dependent variables (MCU dimensions, etc).
  156210. */
  156211. METHODDEF(boolean)
  156212. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  156213. {
  156214. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  156215. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  156216. JDIMENSION blocks_across, MCUs_across, MCUindex;
  156217. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  156218. JCOEF lastDC;
  156219. jpeg_component_info *compptr;
  156220. JBLOCKARRAY buffer;
  156221. JBLOCKROW thisblockrow, lastblockrow;
  156222. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  156223. ci++, compptr++) {
  156224. /* Align the virtual buffer for this component. */
  156225. buffer = (*cinfo->mem->access_virt_barray)
  156226. ((j_common_ptr) cinfo, coef->whole_image[ci],
  156227. coef->iMCU_row_num * compptr->v_samp_factor,
  156228. (JDIMENSION) compptr->v_samp_factor, TRUE);
  156229. /* Count non-dummy DCT block rows in this iMCU row. */
  156230. if (coef->iMCU_row_num < last_iMCU_row)
  156231. block_rows = compptr->v_samp_factor;
  156232. else {
  156233. /* NB: can't use last_row_height here, since may not be set! */
  156234. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  156235. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  156236. }
  156237. blocks_across = compptr->width_in_blocks;
  156238. h_samp_factor = compptr->h_samp_factor;
  156239. /* Count number of dummy blocks to be added at the right margin. */
  156240. ndummy = (int) (blocks_across % h_samp_factor);
  156241. if (ndummy > 0)
  156242. ndummy = h_samp_factor - ndummy;
  156243. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  156244. * on forward_DCT processes a complete horizontal row of DCT blocks.
  156245. */
  156246. for (block_row = 0; block_row < block_rows; block_row++) {
  156247. thisblockrow = buffer[block_row];
  156248. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  156249. input_buf[ci], thisblockrow,
  156250. (JDIMENSION) (block_row * DCTSIZE),
  156251. (JDIMENSION) 0, blocks_across);
  156252. if (ndummy > 0) {
  156253. /* Create dummy blocks at the right edge of the image. */
  156254. thisblockrow += blocks_across; /* => first dummy block */
  156255. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  156256. lastDC = thisblockrow[-1][0];
  156257. for (bi = 0; bi < ndummy; bi++) {
  156258. thisblockrow[bi][0] = lastDC;
  156259. }
  156260. }
  156261. }
  156262. /* If at end of image, create dummy block rows as needed.
  156263. * The tricky part here is that within each MCU, we want the DC values
  156264. * of the dummy blocks to match the last real block's DC value.
  156265. * This squeezes a few more bytes out of the resulting file...
  156266. */
  156267. if (coef->iMCU_row_num == last_iMCU_row) {
  156268. blocks_across += ndummy; /* include lower right corner */
  156269. MCUs_across = blocks_across / h_samp_factor;
  156270. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  156271. block_row++) {
  156272. thisblockrow = buffer[block_row];
  156273. lastblockrow = buffer[block_row-1];
  156274. jzero_far((void FAR *) thisblockrow,
  156275. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  156276. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  156277. lastDC = lastblockrow[h_samp_factor-1][0];
  156278. for (bi = 0; bi < h_samp_factor; bi++) {
  156279. thisblockrow[bi][0] = lastDC;
  156280. }
  156281. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  156282. lastblockrow += h_samp_factor;
  156283. }
  156284. }
  156285. }
  156286. }
  156287. /* NB: compress_output will increment iMCU_row_num if successful.
  156288. * A suspension return will result in redoing all the work above next time.
  156289. */
  156290. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  156291. return compress_output(cinfo, input_buf);
  156292. }
  156293. /*
  156294. * Process some data in subsequent passes of a multi-pass case.
  156295. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  156296. * per call, ie, v_samp_factor block rows for each component in the scan.
  156297. * The data is obtained from the virtual arrays and fed to the entropy coder.
  156298. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  156299. *
  156300. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  156301. */
  156302. METHODDEF(boolean)
  156303. compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  156304. {
  156305. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  156306. JDIMENSION MCU_col_num; /* index of current MCU within row */
  156307. int blkn, ci, xindex, yindex, yoffset;
  156308. JDIMENSION start_col;
  156309. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  156310. JBLOCKROW buffer_ptr;
  156311. jpeg_component_info *compptr;
  156312. /* Align the virtual buffers for the components used in this scan.
  156313. * NB: during first pass, this is safe only because the buffers will
  156314. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  156315. */
  156316. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  156317. compptr = cinfo->cur_comp_info[ci];
  156318. buffer[ci] = (*cinfo->mem->access_virt_barray)
  156319. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  156320. coef->iMCU_row_num * compptr->v_samp_factor,
  156321. (JDIMENSION) compptr->v_samp_factor, FALSE);
  156322. }
  156323. /* Loop to process one whole iMCU row */
  156324. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  156325. yoffset++) {
  156326. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  156327. MCU_col_num++) {
  156328. /* Construct list of pointers to DCT blocks belonging to this MCU */
  156329. blkn = 0; /* index of current DCT block within MCU */
  156330. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  156331. compptr = cinfo->cur_comp_info[ci];
  156332. start_col = MCU_col_num * compptr->MCU_width;
  156333. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  156334. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  156335. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  156336. coef->MCU_buffer[blkn++] = buffer_ptr++;
  156337. }
  156338. }
  156339. }
  156340. /* Try to write the MCU. */
  156341. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  156342. /* Suspension forced; update state counters and exit */
  156343. coef->MCU_vert_offset = yoffset;
  156344. coef->mcu_ctr = MCU_col_num;
  156345. return FALSE;
  156346. }
  156347. }
  156348. /* Completed an MCU row, but perhaps not an iMCU row */
  156349. coef->mcu_ctr = 0;
  156350. }
  156351. /* Completed the iMCU row, advance counters for next one */
  156352. coef->iMCU_row_num++;
  156353. start_iMCU_row(cinfo);
  156354. return TRUE;
  156355. }
  156356. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  156357. /*
  156358. * Initialize coefficient buffer controller.
  156359. */
  156360. GLOBAL(void)
  156361. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  156362. {
  156363. my_coef_ptr coef;
  156364. coef = (my_coef_ptr)
  156365. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156366. SIZEOF(my_coef_controller));
  156367. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  156368. coef->pub.start_pass = start_pass_coef;
  156369. /* Create the coefficient buffer. */
  156370. if (need_full_buffer) {
  156371. #ifdef FULL_COEF_BUFFER_SUPPORTED
  156372. /* Allocate a full-image virtual array for each component, */
  156373. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  156374. int ci;
  156375. jpeg_component_info *compptr;
  156376. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  156377. ci++, compptr++) {
  156378. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  156379. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  156380. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  156381. (long) compptr->h_samp_factor),
  156382. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  156383. (long) compptr->v_samp_factor),
  156384. (JDIMENSION) compptr->v_samp_factor);
  156385. }
  156386. #else
  156387. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  156388. #endif
  156389. } else {
  156390. /* We only need a single-MCU buffer. */
  156391. JBLOCKROW buffer;
  156392. int i;
  156393. buffer = (JBLOCKROW)
  156394. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156395. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  156396. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  156397. coef->MCU_buffer[i] = buffer + i;
  156398. }
  156399. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  156400. }
  156401. }
  156402. /********* End of inlined file: jccoefct.c *********/
  156403. /********* Start of inlined file: jccolor.c *********/
  156404. #define JPEG_INTERNALS
  156405. /* Private subobject */
  156406. typedef struct {
  156407. struct jpeg_color_converter pub; /* public fields */
  156408. /* Private state for RGB->YCC conversion */
  156409. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  156410. } my_color_converter;
  156411. typedef my_color_converter * my_cconvert_ptr;
  156412. /**************** RGB -> YCbCr conversion: most common case **************/
  156413. /*
  156414. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  156415. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  156416. * The conversion equations to be implemented are therefore
  156417. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  156418. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  156419. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  156420. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  156421. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  156422. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  156423. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  156424. * were not represented exactly. Now we sacrifice exact representation of
  156425. * maximum red and maximum blue in order to get exact grayscales.
  156426. *
  156427. * To avoid floating-point arithmetic, we represent the fractional constants
  156428. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  156429. * the products by 2^16, with appropriate rounding, to get the correct answer.
  156430. *
  156431. * For even more speed, we avoid doing any multiplications in the inner loop
  156432. * by precalculating the constants times R,G,B for all possible values.
  156433. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  156434. * for 12-bit samples it is still acceptable. It's not very reasonable for
  156435. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  156436. * colorspace anyway.
  156437. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  156438. * in the tables to save adding them separately in the inner loop.
  156439. */
  156440. #define SCALEBITS 16 /* speediest right-shift on some machines */
  156441. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  156442. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  156443. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  156444. /* We allocate one big table and divide it up into eight parts, instead of
  156445. * doing eight alloc_small requests. This lets us use a single table base
  156446. * address, which can be held in a register in the inner loops on many
  156447. * machines (more than can hold all eight addresses, anyway).
  156448. */
  156449. #define R_Y_OFF 0 /* offset to R => Y section */
  156450. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  156451. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  156452. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  156453. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  156454. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  156455. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  156456. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  156457. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  156458. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  156459. /*
  156460. * Initialize for RGB->YCC colorspace conversion.
  156461. */
  156462. METHODDEF(void)
  156463. rgb_ycc_start (j_compress_ptr cinfo)
  156464. {
  156465. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  156466. INT32 * rgb_ycc_tab;
  156467. INT32 i;
  156468. /* Allocate and fill in the conversion tables. */
  156469. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  156470. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156471. (TABLE_SIZE * SIZEOF(INT32)));
  156472. for (i = 0; i <= MAXJSAMPLE; i++) {
  156473. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  156474. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  156475. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  156476. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  156477. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  156478. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  156479. * This ensures that the maximum output will round to MAXJSAMPLE
  156480. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  156481. */
  156482. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  156483. /* B=>Cb and R=>Cr tables are the same
  156484. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  156485. */
  156486. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  156487. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  156488. }
  156489. }
  156490. /*
  156491. * Convert some rows of samples to the JPEG colorspace.
  156492. *
  156493. * Note that we change from the application's interleaved-pixel format
  156494. * to our internal noninterleaved, one-plane-per-component format.
  156495. * The input buffer is therefore three times as wide as the output buffer.
  156496. *
  156497. * A starting row offset is provided only for the output buffer. The caller
  156498. * can easily adjust the passed input_buf value to accommodate any row
  156499. * offset required on that side.
  156500. */
  156501. METHODDEF(void)
  156502. rgb_ycc_convert (j_compress_ptr cinfo,
  156503. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156504. JDIMENSION output_row, int num_rows)
  156505. {
  156506. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  156507. register int r, g, b;
  156508. register INT32 * ctab = cconvert->rgb_ycc_tab;
  156509. register JSAMPROW inptr;
  156510. register JSAMPROW outptr0, outptr1, outptr2;
  156511. register JDIMENSION col;
  156512. JDIMENSION num_cols = cinfo->image_width;
  156513. while (--num_rows >= 0) {
  156514. inptr = *input_buf++;
  156515. outptr0 = output_buf[0][output_row];
  156516. outptr1 = output_buf[1][output_row];
  156517. outptr2 = output_buf[2][output_row];
  156518. output_row++;
  156519. for (col = 0; col < num_cols; col++) {
  156520. r = GETJSAMPLE(inptr[RGB_RED]);
  156521. g = GETJSAMPLE(inptr[RGB_GREEN]);
  156522. b = GETJSAMPLE(inptr[RGB_BLUE]);
  156523. inptr += RGB_PIXELSIZE;
  156524. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  156525. * must be too; we do not need an explicit range-limiting operation.
  156526. * Hence the value being shifted is never negative, and we don't
  156527. * need the general RIGHT_SHIFT macro.
  156528. */
  156529. /* Y */
  156530. outptr0[col] = (JSAMPLE)
  156531. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  156532. >> SCALEBITS);
  156533. /* Cb */
  156534. outptr1[col] = (JSAMPLE)
  156535. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  156536. >> SCALEBITS);
  156537. /* Cr */
  156538. outptr2[col] = (JSAMPLE)
  156539. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  156540. >> SCALEBITS);
  156541. }
  156542. }
  156543. }
  156544. /**************** Cases other than RGB -> YCbCr **************/
  156545. /*
  156546. * Convert some rows of samples to the JPEG colorspace.
  156547. * This version handles RGB->grayscale conversion, which is the same
  156548. * as the RGB->Y portion of RGB->YCbCr.
  156549. * We assume rgb_ycc_start has been called (we only use the Y tables).
  156550. */
  156551. METHODDEF(void)
  156552. rgb_gray_convert (j_compress_ptr cinfo,
  156553. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156554. JDIMENSION output_row, int num_rows)
  156555. {
  156556. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  156557. register int r, g, b;
  156558. register INT32 * ctab = cconvert->rgb_ycc_tab;
  156559. register JSAMPROW inptr;
  156560. register JSAMPROW outptr;
  156561. register JDIMENSION col;
  156562. JDIMENSION num_cols = cinfo->image_width;
  156563. while (--num_rows >= 0) {
  156564. inptr = *input_buf++;
  156565. outptr = output_buf[0][output_row];
  156566. output_row++;
  156567. for (col = 0; col < num_cols; col++) {
  156568. r = GETJSAMPLE(inptr[RGB_RED]);
  156569. g = GETJSAMPLE(inptr[RGB_GREEN]);
  156570. b = GETJSAMPLE(inptr[RGB_BLUE]);
  156571. inptr += RGB_PIXELSIZE;
  156572. /* Y */
  156573. outptr[col] = (JSAMPLE)
  156574. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  156575. >> SCALEBITS);
  156576. }
  156577. }
  156578. }
  156579. /*
  156580. * Convert some rows of samples to the JPEG colorspace.
  156581. * This version handles Adobe-style CMYK->YCCK conversion,
  156582. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  156583. * conversion as above, while passing K (black) unchanged.
  156584. * We assume rgb_ycc_start has been called.
  156585. */
  156586. METHODDEF(void)
  156587. cmyk_ycck_convert (j_compress_ptr cinfo,
  156588. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156589. JDIMENSION output_row, int num_rows)
  156590. {
  156591. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  156592. register int r, g, b;
  156593. register INT32 * ctab = cconvert->rgb_ycc_tab;
  156594. register JSAMPROW inptr;
  156595. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  156596. register JDIMENSION col;
  156597. JDIMENSION num_cols = cinfo->image_width;
  156598. while (--num_rows >= 0) {
  156599. inptr = *input_buf++;
  156600. outptr0 = output_buf[0][output_row];
  156601. outptr1 = output_buf[1][output_row];
  156602. outptr2 = output_buf[2][output_row];
  156603. outptr3 = output_buf[3][output_row];
  156604. output_row++;
  156605. for (col = 0; col < num_cols; col++) {
  156606. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  156607. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  156608. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  156609. /* K passes through as-is */
  156610. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  156611. inptr += 4;
  156612. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  156613. * must be too; we do not need an explicit range-limiting operation.
  156614. * Hence the value being shifted is never negative, and we don't
  156615. * need the general RIGHT_SHIFT macro.
  156616. */
  156617. /* Y */
  156618. outptr0[col] = (JSAMPLE)
  156619. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  156620. >> SCALEBITS);
  156621. /* Cb */
  156622. outptr1[col] = (JSAMPLE)
  156623. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  156624. >> SCALEBITS);
  156625. /* Cr */
  156626. outptr2[col] = (JSAMPLE)
  156627. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  156628. >> SCALEBITS);
  156629. }
  156630. }
  156631. }
  156632. /*
  156633. * Convert some rows of samples to the JPEG colorspace.
  156634. * This version handles grayscale output with no conversion.
  156635. * The source can be either plain grayscale or YCbCr (since Y == gray).
  156636. */
  156637. METHODDEF(void)
  156638. grayscale_convert (j_compress_ptr cinfo,
  156639. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156640. JDIMENSION output_row, int num_rows)
  156641. {
  156642. register JSAMPROW inptr;
  156643. register JSAMPROW outptr;
  156644. register JDIMENSION col;
  156645. JDIMENSION num_cols = cinfo->image_width;
  156646. int instride = cinfo->input_components;
  156647. while (--num_rows >= 0) {
  156648. inptr = *input_buf++;
  156649. outptr = output_buf[0][output_row];
  156650. output_row++;
  156651. for (col = 0; col < num_cols; col++) {
  156652. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  156653. inptr += instride;
  156654. }
  156655. }
  156656. }
  156657. /*
  156658. * Convert some rows of samples to the JPEG colorspace.
  156659. * This version handles multi-component colorspaces without conversion.
  156660. * We assume input_components == num_components.
  156661. */
  156662. METHODDEF(void)
  156663. null_convert (j_compress_ptr cinfo,
  156664. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156665. JDIMENSION output_row, int num_rows)
  156666. {
  156667. register JSAMPROW inptr;
  156668. register JSAMPROW outptr;
  156669. register JDIMENSION col;
  156670. register int ci;
  156671. int nc = cinfo->num_components;
  156672. JDIMENSION num_cols = cinfo->image_width;
  156673. while (--num_rows >= 0) {
  156674. /* It seems fastest to make a separate pass for each component. */
  156675. for (ci = 0; ci < nc; ci++) {
  156676. inptr = *input_buf;
  156677. outptr = output_buf[ci][output_row];
  156678. for (col = 0; col < num_cols; col++) {
  156679. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  156680. inptr += nc;
  156681. }
  156682. }
  156683. input_buf++;
  156684. output_row++;
  156685. }
  156686. }
  156687. /*
  156688. * Empty method for start_pass.
  156689. */
  156690. METHODDEF(void)
  156691. null_method (j_compress_ptr cinfo)
  156692. {
  156693. /* no work needed */
  156694. }
  156695. /*
  156696. * Module initialization routine for input colorspace conversion.
  156697. */
  156698. GLOBAL(void)
  156699. jinit_color_converter (j_compress_ptr cinfo)
  156700. {
  156701. my_cconvert_ptr cconvert;
  156702. cconvert = (my_cconvert_ptr)
  156703. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156704. SIZEOF(my_color_converter));
  156705. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  156706. /* set start_pass to null method until we find out differently */
  156707. cconvert->pub.start_pass = null_method;
  156708. /* Make sure input_components agrees with in_color_space */
  156709. switch (cinfo->in_color_space) {
  156710. case JCS_GRAYSCALE:
  156711. if (cinfo->input_components != 1)
  156712. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  156713. break;
  156714. case JCS_RGB:
  156715. #if RGB_PIXELSIZE != 3
  156716. if (cinfo->input_components != RGB_PIXELSIZE)
  156717. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  156718. break;
  156719. #endif /* else share code with YCbCr */
  156720. case JCS_YCbCr:
  156721. if (cinfo->input_components != 3)
  156722. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  156723. break;
  156724. case JCS_CMYK:
  156725. case JCS_YCCK:
  156726. if (cinfo->input_components != 4)
  156727. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  156728. break;
  156729. default: /* JCS_UNKNOWN can be anything */
  156730. if (cinfo->input_components < 1)
  156731. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  156732. break;
  156733. }
  156734. /* Check num_components, set conversion method based on requested space */
  156735. switch (cinfo->jpeg_color_space) {
  156736. case JCS_GRAYSCALE:
  156737. if (cinfo->num_components != 1)
  156738. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  156739. if (cinfo->in_color_space == JCS_GRAYSCALE)
  156740. cconvert->pub.color_convert = grayscale_convert;
  156741. else if (cinfo->in_color_space == JCS_RGB) {
  156742. cconvert->pub.start_pass = rgb_ycc_start;
  156743. cconvert->pub.color_convert = rgb_gray_convert;
  156744. } else if (cinfo->in_color_space == JCS_YCbCr)
  156745. cconvert->pub.color_convert = grayscale_convert;
  156746. else
  156747. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156748. break;
  156749. case JCS_RGB:
  156750. if (cinfo->num_components != 3)
  156751. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  156752. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  156753. cconvert->pub.color_convert = null_convert;
  156754. else
  156755. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156756. break;
  156757. case JCS_YCbCr:
  156758. if (cinfo->num_components != 3)
  156759. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  156760. if (cinfo->in_color_space == JCS_RGB) {
  156761. cconvert->pub.start_pass = rgb_ycc_start;
  156762. cconvert->pub.color_convert = rgb_ycc_convert;
  156763. } else if (cinfo->in_color_space == JCS_YCbCr)
  156764. cconvert->pub.color_convert = null_convert;
  156765. else
  156766. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156767. break;
  156768. case JCS_CMYK:
  156769. if (cinfo->num_components != 4)
  156770. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  156771. if (cinfo->in_color_space == JCS_CMYK)
  156772. cconvert->pub.color_convert = null_convert;
  156773. else
  156774. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156775. break;
  156776. case JCS_YCCK:
  156777. if (cinfo->num_components != 4)
  156778. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  156779. if (cinfo->in_color_space == JCS_CMYK) {
  156780. cconvert->pub.start_pass = rgb_ycc_start;
  156781. cconvert->pub.color_convert = cmyk_ycck_convert;
  156782. } else if (cinfo->in_color_space == JCS_YCCK)
  156783. cconvert->pub.color_convert = null_convert;
  156784. else
  156785. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156786. break;
  156787. default: /* allow null conversion of JCS_UNKNOWN */
  156788. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  156789. cinfo->num_components != cinfo->input_components)
  156790. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156791. cconvert->pub.color_convert = null_convert;
  156792. break;
  156793. }
  156794. }
  156795. /********* End of inlined file: jccolor.c *********/
  156796. #undef FIX
  156797. /********* Start of inlined file: jcdctmgr.c *********/
  156798. #define JPEG_INTERNALS
  156799. /********* Start of inlined file: jdct.h *********/
  156800. /*
  156801. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  156802. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  156803. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  156804. * implementations use an array of type FAST_FLOAT, instead.)
  156805. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  156806. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  156807. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  156808. * convention improves accuracy in integer implementations and saves some
  156809. * work in floating-point ones.
  156810. * Quantization of the output coefficients is done by jcdctmgr.c.
  156811. */
  156812. #ifndef __jdct_h__
  156813. #define __jdct_h__
  156814. #if BITS_IN_JSAMPLE == 8
  156815. typedef int DCTELEM; /* 16 or 32 bits is fine */
  156816. #else
  156817. typedef INT32 DCTELEM; /* must have 32 bits */
  156818. #endif
  156819. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  156820. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  156821. /*
  156822. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  156823. * to an output sample array. The routine must dequantize the input data as
  156824. * well as perform the IDCT; for dequantization, it uses the multiplier table
  156825. * pointed to by compptr->dct_table. The output data is to be placed into the
  156826. * sample array starting at a specified column. (Any row offset needed will
  156827. * be applied to the array pointer before it is passed to the IDCT code.)
  156828. * Note that the number of samples emitted by the IDCT routine is
  156829. * DCT_scaled_size * DCT_scaled_size.
  156830. */
  156831. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  156832. /*
  156833. * Each IDCT routine has its own ideas about the best dct_table element type.
  156834. */
  156835. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  156836. #if BITS_IN_JSAMPLE == 8
  156837. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  156838. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  156839. #else
  156840. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  156841. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  156842. #endif
  156843. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  156844. /*
  156845. * Each IDCT routine is responsible for range-limiting its results and
  156846. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  156847. * be quite far out of range if the input data is corrupt, so a bulletproof
  156848. * range-limiting step is required. We use a mask-and-table-lookup method
  156849. * to do the combined operations quickly. See the comments with
  156850. * prepare_range_limit_table (in jdmaster.c) for more info.
  156851. */
  156852. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  156853. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  156854. /* Short forms of external names for systems with brain-damaged linkers. */
  156855. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156856. #define jpeg_fdct_islow jFDislow
  156857. #define jpeg_fdct_ifast jFDifast
  156858. #define jpeg_fdct_float jFDfloat
  156859. #define jpeg_idct_islow jRDislow
  156860. #define jpeg_idct_ifast jRDifast
  156861. #define jpeg_idct_float jRDfloat
  156862. #define jpeg_idct_4x4 jRD4x4
  156863. #define jpeg_idct_2x2 jRD2x2
  156864. #define jpeg_idct_1x1 jRD1x1
  156865. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  156866. /* Extern declarations for the forward and inverse DCT routines. */
  156867. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  156868. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  156869. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  156870. EXTERN(void) jpeg_idct_islow
  156871. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156872. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156873. EXTERN(void) jpeg_idct_ifast
  156874. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156875. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156876. EXTERN(void) jpeg_idct_float
  156877. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156878. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156879. EXTERN(void) jpeg_idct_4x4
  156880. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156881. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156882. EXTERN(void) jpeg_idct_2x2
  156883. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156884. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156885. EXTERN(void) jpeg_idct_1x1
  156886. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156887. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156888. /*
  156889. * Macros for handling fixed-point arithmetic; these are used by many
  156890. * but not all of the DCT/IDCT modules.
  156891. *
  156892. * All values are expected to be of type INT32.
  156893. * Fractional constants are scaled left by CONST_BITS bits.
  156894. * CONST_BITS is defined within each module using these macros,
  156895. * and may differ from one module to the next.
  156896. */
  156897. #define ONE ((INT32) 1)
  156898. #define CONST_SCALE (ONE << CONST_BITS)
  156899. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  156900. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  156901. * thus causing a lot of useless floating-point operations at run time.
  156902. */
  156903. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  156904. /* Descale and correctly round an INT32 value that's scaled by N bits.
  156905. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  156906. * the fudge factor is correct for either sign of X.
  156907. */
  156908. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  156909. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  156910. * This macro is used only when the two inputs will actually be no more than
  156911. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  156912. * full 32x32 multiply. This provides a useful speedup on many machines.
  156913. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  156914. * in C, but some C compilers will do the right thing if you provide the
  156915. * correct combination of casts.
  156916. */
  156917. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  156918. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  156919. #endif
  156920. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  156921. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  156922. #endif
  156923. #ifndef MULTIPLY16C16 /* default definition */
  156924. #define MULTIPLY16C16(var,const) ((var) * (const))
  156925. #endif
  156926. /* Same except both inputs are variables. */
  156927. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  156928. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  156929. #endif
  156930. #ifndef MULTIPLY16V16 /* default definition */
  156931. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  156932. #endif
  156933. #endif
  156934. /********* End of inlined file: jdct.h *********/
  156935. /* Private declarations for DCT subsystem */
  156936. /* Private subobject for this module */
  156937. typedef struct {
  156938. struct jpeg_forward_dct pub; /* public fields */
  156939. /* Pointer to the DCT routine actually in use */
  156940. forward_DCT_method_ptr do_dct;
  156941. /* The actual post-DCT divisors --- not identical to the quant table
  156942. * entries, because of scaling (especially for an unnormalized DCT).
  156943. * Each table is given in normal array order.
  156944. */
  156945. DCTELEM * divisors[NUM_QUANT_TBLS];
  156946. #ifdef DCT_FLOAT_SUPPORTED
  156947. /* Same as above for the floating-point case. */
  156948. float_DCT_method_ptr do_float_dct;
  156949. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  156950. #endif
  156951. } my_fdct_controller;
  156952. typedef my_fdct_controller * my_fdct_ptr;
  156953. /*
  156954. * Initialize for a processing pass.
  156955. * Verify that all referenced Q-tables are present, and set up
  156956. * the divisor table for each one.
  156957. * In the current implementation, DCT of all components is done during
  156958. * the first pass, even if only some components will be output in the
  156959. * first scan. Hence all components should be examined here.
  156960. */
  156961. METHODDEF(void)
  156962. start_pass_fdctmgr (j_compress_ptr cinfo)
  156963. {
  156964. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  156965. int ci, qtblno, i;
  156966. jpeg_component_info *compptr;
  156967. JQUANT_TBL * qtbl;
  156968. DCTELEM * dtbl;
  156969. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  156970. ci++, compptr++) {
  156971. qtblno = compptr->quant_tbl_no;
  156972. /* Make sure specified quantization table is present */
  156973. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  156974. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  156975. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  156976. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  156977. /* Compute divisors for this quant table */
  156978. /* We may do this more than once for same table, but it's not a big deal */
  156979. switch (cinfo->dct_method) {
  156980. #ifdef DCT_ISLOW_SUPPORTED
  156981. case JDCT_ISLOW:
  156982. /* For LL&M IDCT method, divisors are equal to raw quantization
  156983. * coefficients multiplied by 8 (to counteract scaling).
  156984. */
  156985. if (fdct->divisors[qtblno] == NULL) {
  156986. fdct->divisors[qtblno] = (DCTELEM *)
  156987. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156988. DCTSIZE2 * SIZEOF(DCTELEM));
  156989. }
  156990. dtbl = fdct->divisors[qtblno];
  156991. for (i = 0; i < DCTSIZE2; i++) {
  156992. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  156993. }
  156994. break;
  156995. #endif
  156996. #ifdef DCT_IFAST_SUPPORTED
  156997. case JDCT_IFAST:
  156998. {
  156999. /* For AA&N IDCT method, divisors are equal to quantization
  157000. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  157001. * scalefactor[0] = 1
  157002. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  157003. * We apply a further scale factor of 8.
  157004. */
  157005. #define CONST_BITS 14
  157006. static const INT16 aanscales[DCTSIZE2] = {
  157007. /* precomputed values scaled up by 14 bits */
  157008. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  157009. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  157010. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  157011. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  157012. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  157013. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  157014. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  157015. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  157016. };
  157017. SHIFT_TEMPS
  157018. if (fdct->divisors[qtblno] == NULL) {
  157019. fdct->divisors[qtblno] = (DCTELEM *)
  157020. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157021. DCTSIZE2 * SIZEOF(DCTELEM));
  157022. }
  157023. dtbl = fdct->divisors[qtblno];
  157024. for (i = 0; i < DCTSIZE2; i++) {
  157025. dtbl[i] = (DCTELEM)
  157026. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  157027. (INT32) aanscales[i]),
  157028. CONST_BITS-3);
  157029. }
  157030. }
  157031. break;
  157032. #endif
  157033. #ifdef DCT_FLOAT_SUPPORTED
  157034. case JDCT_FLOAT:
  157035. {
  157036. /* For float AA&N IDCT method, divisors are equal to quantization
  157037. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  157038. * scalefactor[0] = 1
  157039. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  157040. * We apply a further scale factor of 8.
  157041. * What's actually stored is 1/divisor so that the inner loop can
  157042. * use a multiplication rather than a division.
  157043. */
  157044. FAST_FLOAT * fdtbl;
  157045. int row, col;
  157046. static const double aanscalefactor[DCTSIZE] = {
  157047. 1.0, 1.387039845, 1.306562965, 1.175875602,
  157048. 1.0, 0.785694958, 0.541196100, 0.275899379
  157049. };
  157050. if (fdct->float_divisors[qtblno] == NULL) {
  157051. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  157052. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157053. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  157054. }
  157055. fdtbl = fdct->float_divisors[qtblno];
  157056. i = 0;
  157057. for (row = 0; row < DCTSIZE; row++) {
  157058. for (col = 0; col < DCTSIZE; col++) {
  157059. fdtbl[i] = (FAST_FLOAT)
  157060. (1.0 / (((double) qtbl->quantval[i] *
  157061. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  157062. i++;
  157063. }
  157064. }
  157065. }
  157066. break;
  157067. #endif
  157068. default:
  157069. ERREXIT(cinfo, JERR_NOT_COMPILED);
  157070. break;
  157071. }
  157072. }
  157073. }
  157074. /*
  157075. * Perform forward DCT on one or more blocks of a component.
  157076. *
  157077. * The input samples are taken from the sample_data[] array starting at
  157078. * position start_row/start_col, and moving to the right for any additional
  157079. * blocks. The quantized coefficients are returned in coef_blocks[].
  157080. */
  157081. METHODDEF(void)
  157082. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  157083. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  157084. JDIMENSION start_row, JDIMENSION start_col,
  157085. JDIMENSION num_blocks)
  157086. /* This version is used for integer DCT implementations. */
  157087. {
  157088. /* This routine is heavily used, so it's worth coding it tightly. */
  157089. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  157090. forward_DCT_method_ptr do_dct = fdct->do_dct;
  157091. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  157092. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  157093. JDIMENSION bi;
  157094. sample_data += start_row; /* fold in the vertical offset once */
  157095. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  157096. /* Load data into workspace, applying unsigned->signed conversion */
  157097. { register DCTELEM *workspaceptr;
  157098. register JSAMPROW elemptr;
  157099. register int elemr;
  157100. workspaceptr = workspace;
  157101. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  157102. elemptr = sample_data[elemr] + start_col;
  157103. #if DCTSIZE == 8 /* unroll the inner loop */
  157104. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157105. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157106. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157107. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157108. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157109. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157110. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157111. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157112. #else
  157113. { register int elemc;
  157114. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  157115. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  157116. }
  157117. }
  157118. #endif
  157119. }
  157120. }
  157121. /* Perform the DCT */
  157122. (*do_dct) (workspace);
  157123. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  157124. { register DCTELEM temp, qval;
  157125. register int i;
  157126. register JCOEFPTR output_ptr = coef_blocks[bi];
  157127. for (i = 0; i < DCTSIZE2; i++) {
  157128. qval = divisors[i];
  157129. temp = workspace[i];
  157130. /* Divide the coefficient value by qval, ensuring proper rounding.
  157131. * Since C does not specify the direction of rounding for negative
  157132. * quotients, we have to force the dividend positive for portability.
  157133. *
  157134. * In most files, at least half of the output values will be zero
  157135. * (at default quantization settings, more like three-quarters...)
  157136. * so we should ensure that this case is fast. On many machines,
  157137. * a comparison is enough cheaper than a divide to make a special test
  157138. * a win. Since both inputs will be nonnegative, we need only test
  157139. * for a < b to discover whether a/b is 0.
  157140. * If your machine's division is fast enough, define FAST_DIVIDE.
  157141. */
  157142. #ifdef FAST_DIVIDE
  157143. #define DIVIDE_BY(a,b) a /= b
  157144. #else
  157145. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  157146. #endif
  157147. if (temp < 0) {
  157148. temp = -temp;
  157149. temp += qval>>1; /* for rounding */
  157150. DIVIDE_BY(temp, qval);
  157151. temp = -temp;
  157152. } else {
  157153. temp += qval>>1; /* for rounding */
  157154. DIVIDE_BY(temp, qval);
  157155. }
  157156. output_ptr[i] = (JCOEF) temp;
  157157. }
  157158. }
  157159. }
  157160. }
  157161. #ifdef DCT_FLOAT_SUPPORTED
  157162. METHODDEF(void)
  157163. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  157164. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  157165. JDIMENSION start_row, JDIMENSION start_col,
  157166. JDIMENSION num_blocks)
  157167. /* This version is used for floating-point DCT implementations. */
  157168. {
  157169. /* This routine is heavily used, so it's worth coding it tightly. */
  157170. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  157171. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  157172. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  157173. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  157174. JDIMENSION bi;
  157175. sample_data += start_row; /* fold in the vertical offset once */
  157176. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  157177. /* Load data into workspace, applying unsigned->signed conversion */
  157178. { register FAST_FLOAT *workspaceptr;
  157179. register JSAMPROW elemptr;
  157180. register int elemr;
  157181. workspaceptr = workspace;
  157182. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  157183. elemptr = sample_data[elemr] + start_col;
  157184. #if DCTSIZE == 8 /* unroll the inner loop */
  157185. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157186. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157187. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157188. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157189. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157190. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157191. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157192. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157193. #else
  157194. { register int elemc;
  157195. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  157196. *workspaceptr++ = (FAST_FLOAT)
  157197. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  157198. }
  157199. }
  157200. #endif
  157201. }
  157202. }
  157203. /* Perform the DCT */
  157204. (*do_dct) (workspace);
  157205. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  157206. { register FAST_FLOAT temp;
  157207. register int i;
  157208. register JCOEFPTR output_ptr = coef_blocks[bi];
  157209. for (i = 0; i < DCTSIZE2; i++) {
  157210. /* Apply the quantization and scaling factor */
  157211. temp = workspace[i] * divisors[i];
  157212. /* Round to nearest integer.
  157213. * Since C does not specify the direction of rounding for negative
  157214. * quotients, we have to force the dividend positive for portability.
  157215. * The maximum coefficient size is +-16K (for 12-bit data), so this
  157216. * code should work for either 16-bit or 32-bit ints.
  157217. */
  157218. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  157219. }
  157220. }
  157221. }
  157222. }
  157223. #endif /* DCT_FLOAT_SUPPORTED */
  157224. /*
  157225. * Initialize FDCT manager.
  157226. */
  157227. GLOBAL(void)
  157228. jinit_forward_dct (j_compress_ptr cinfo)
  157229. {
  157230. my_fdct_ptr fdct;
  157231. int i;
  157232. fdct = (my_fdct_ptr)
  157233. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157234. SIZEOF(my_fdct_controller));
  157235. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  157236. fdct->pub.start_pass = start_pass_fdctmgr;
  157237. switch (cinfo->dct_method) {
  157238. #ifdef DCT_ISLOW_SUPPORTED
  157239. case JDCT_ISLOW:
  157240. fdct->pub.forward_DCT = forward_DCT;
  157241. fdct->do_dct = jpeg_fdct_islow;
  157242. break;
  157243. #endif
  157244. #ifdef DCT_IFAST_SUPPORTED
  157245. case JDCT_IFAST:
  157246. fdct->pub.forward_DCT = forward_DCT;
  157247. fdct->do_dct = jpeg_fdct_ifast;
  157248. break;
  157249. #endif
  157250. #ifdef DCT_FLOAT_SUPPORTED
  157251. case JDCT_FLOAT:
  157252. fdct->pub.forward_DCT = forward_DCT_float;
  157253. fdct->do_float_dct = jpeg_fdct_float;
  157254. break;
  157255. #endif
  157256. default:
  157257. ERREXIT(cinfo, JERR_NOT_COMPILED);
  157258. break;
  157259. }
  157260. /* Mark divisor tables unallocated */
  157261. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  157262. fdct->divisors[i] = NULL;
  157263. #ifdef DCT_FLOAT_SUPPORTED
  157264. fdct->float_divisors[i] = NULL;
  157265. #endif
  157266. }
  157267. }
  157268. /********* End of inlined file: jcdctmgr.c *********/
  157269. #undef CONST_BITS
  157270. /********* Start of inlined file: jchuff.c *********/
  157271. #define JPEG_INTERNALS
  157272. /********* Start of inlined file: jchuff.h *********/
  157273. /* The legal range of a DCT coefficient is
  157274. * -1024 .. +1023 for 8-bit data;
  157275. * -16384 .. +16383 for 12-bit data.
  157276. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  157277. */
  157278. #ifndef _jchuff_h_
  157279. #define _jchuff_h_
  157280. #if BITS_IN_JSAMPLE == 8
  157281. #define MAX_COEF_BITS 10
  157282. #else
  157283. #define MAX_COEF_BITS 14
  157284. #endif
  157285. /* Derived data constructed for each Huffman table */
  157286. typedef struct {
  157287. unsigned int ehufco[256]; /* code for each symbol */
  157288. char ehufsi[256]; /* length of code for each symbol */
  157289. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  157290. } c_derived_tbl;
  157291. /* Short forms of external names for systems with brain-damaged linkers. */
  157292. #ifdef NEED_SHORT_EXTERNAL_NAMES
  157293. #define jpeg_make_c_derived_tbl jMkCDerived
  157294. #define jpeg_gen_optimal_table jGenOptTbl
  157295. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  157296. /* Expand a Huffman table definition into the derived format */
  157297. EXTERN(void) jpeg_make_c_derived_tbl
  157298. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  157299. c_derived_tbl ** pdtbl));
  157300. /* Generate an optimal table definition given the specified counts */
  157301. EXTERN(void) jpeg_gen_optimal_table
  157302. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  157303. #endif
  157304. /********* End of inlined file: jchuff.h *********/
  157305. /* Declarations shared with jcphuff.c */
  157306. /* Expanded entropy encoder object for Huffman encoding.
  157307. *
  157308. * The savable_state subrecord contains fields that change within an MCU,
  157309. * but must not be updated permanently until we complete the MCU.
  157310. */
  157311. typedef struct {
  157312. INT32 put_buffer; /* current bit-accumulation buffer */
  157313. int put_bits; /* # of bits now in it */
  157314. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  157315. } savable_state;
  157316. /* This macro is to work around compilers with missing or broken
  157317. * structure assignment. You'll need to fix this code if you have
  157318. * such a compiler and you change MAX_COMPS_IN_SCAN.
  157319. */
  157320. #ifndef NO_STRUCT_ASSIGN
  157321. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  157322. #else
  157323. #if MAX_COMPS_IN_SCAN == 4
  157324. #define ASSIGN_STATE(dest,src) \
  157325. ((dest).put_buffer = (src).put_buffer, \
  157326. (dest).put_bits = (src).put_bits, \
  157327. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  157328. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  157329. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  157330. (dest).last_dc_val[3] = (src).last_dc_val[3])
  157331. #endif
  157332. #endif
  157333. typedef struct {
  157334. struct jpeg_entropy_encoder pub; /* public fields */
  157335. savable_state saved; /* Bit buffer & DC state at start of MCU */
  157336. /* These fields are NOT loaded into local working state. */
  157337. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  157338. int next_restart_num; /* next restart number to write (0-7) */
  157339. /* Pointers to derived tables (these workspaces have image lifespan) */
  157340. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  157341. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  157342. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  157343. long * dc_count_ptrs[NUM_HUFF_TBLS];
  157344. long * ac_count_ptrs[NUM_HUFF_TBLS];
  157345. #endif
  157346. } huff_entropy_encoder;
  157347. typedef huff_entropy_encoder * huff_entropy_ptr;
  157348. /* Working state while writing an MCU.
  157349. * This struct contains all the fields that are needed by subroutines.
  157350. */
  157351. typedef struct {
  157352. JOCTET * next_output_byte; /* => next byte to write in buffer */
  157353. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  157354. savable_state cur; /* Current bit buffer & DC state */
  157355. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  157356. } working_state;
  157357. /* Forward declarations */
  157358. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  157359. JBLOCKROW *MCU_data));
  157360. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  157361. #ifdef ENTROPY_OPT_SUPPORTED
  157362. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  157363. JBLOCKROW *MCU_data));
  157364. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  157365. #endif
  157366. /*
  157367. * Initialize for a Huffman-compressed scan.
  157368. * If gather_statistics is TRUE, we do not output anything during the scan,
  157369. * just count the Huffman symbols used and generate Huffman code tables.
  157370. */
  157371. METHODDEF(void)
  157372. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  157373. {
  157374. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157375. int ci, dctbl, actbl;
  157376. jpeg_component_info * compptr;
  157377. if (gather_statistics) {
  157378. #ifdef ENTROPY_OPT_SUPPORTED
  157379. entropy->pub.encode_mcu = encode_mcu_gather;
  157380. entropy->pub.finish_pass = finish_pass_gather;
  157381. #else
  157382. ERREXIT(cinfo, JERR_NOT_COMPILED);
  157383. #endif
  157384. } else {
  157385. entropy->pub.encode_mcu = encode_mcu_huff;
  157386. entropy->pub.finish_pass = finish_pass_huff;
  157387. }
  157388. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157389. compptr = cinfo->cur_comp_info[ci];
  157390. dctbl = compptr->dc_tbl_no;
  157391. actbl = compptr->ac_tbl_no;
  157392. if (gather_statistics) {
  157393. #ifdef ENTROPY_OPT_SUPPORTED
  157394. /* Check for invalid table indexes */
  157395. /* (make_c_derived_tbl does this in the other path) */
  157396. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  157397. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  157398. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  157399. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  157400. /* Allocate and zero the statistics tables */
  157401. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  157402. if (entropy->dc_count_ptrs[dctbl] == NULL)
  157403. entropy->dc_count_ptrs[dctbl] = (long *)
  157404. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157405. 257 * SIZEOF(long));
  157406. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  157407. if (entropy->ac_count_ptrs[actbl] == NULL)
  157408. entropy->ac_count_ptrs[actbl] = (long *)
  157409. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157410. 257 * SIZEOF(long));
  157411. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  157412. #endif
  157413. } else {
  157414. /* Compute derived values for Huffman tables */
  157415. /* We may do this more than once for a table, but it's not expensive */
  157416. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  157417. & entropy->dc_derived_tbls[dctbl]);
  157418. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  157419. & entropy->ac_derived_tbls[actbl]);
  157420. }
  157421. /* Initialize DC predictions to 0 */
  157422. entropy->saved.last_dc_val[ci] = 0;
  157423. }
  157424. /* Initialize bit buffer to empty */
  157425. entropy->saved.put_buffer = 0;
  157426. entropy->saved.put_bits = 0;
  157427. /* Initialize restart stuff */
  157428. entropy->restarts_to_go = cinfo->restart_interval;
  157429. entropy->next_restart_num = 0;
  157430. }
  157431. /*
  157432. * Compute the derived values for a Huffman table.
  157433. * This routine also performs some validation checks on the table.
  157434. *
  157435. * Note this is also used by jcphuff.c.
  157436. */
  157437. GLOBAL(void)
  157438. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  157439. c_derived_tbl ** pdtbl)
  157440. {
  157441. JHUFF_TBL *htbl;
  157442. c_derived_tbl *dtbl;
  157443. int p, i, l, lastp, si, maxsymbol;
  157444. char huffsize[257];
  157445. unsigned int huffcode[257];
  157446. unsigned int code;
  157447. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  157448. * paralleling the order of the symbols themselves in htbl->huffval[].
  157449. */
  157450. /* Find the input Huffman table */
  157451. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  157452. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  157453. htbl =
  157454. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  157455. if (htbl == NULL)
  157456. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  157457. /* Allocate a workspace if we haven't already done so. */
  157458. if (*pdtbl == NULL)
  157459. *pdtbl = (c_derived_tbl *)
  157460. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157461. SIZEOF(c_derived_tbl));
  157462. dtbl = *pdtbl;
  157463. /* Figure C.1: make table of Huffman code length for each symbol */
  157464. p = 0;
  157465. for (l = 1; l <= 16; l++) {
  157466. i = (int) htbl->bits[l];
  157467. if (i < 0 || p + i > 256) /* protect against table overrun */
  157468. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  157469. while (i--)
  157470. huffsize[p++] = (char) l;
  157471. }
  157472. huffsize[p] = 0;
  157473. lastp = p;
  157474. /* Figure C.2: generate the codes themselves */
  157475. /* We also validate that the counts represent a legal Huffman code tree. */
  157476. code = 0;
  157477. si = huffsize[0];
  157478. p = 0;
  157479. while (huffsize[p]) {
  157480. while (((int) huffsize[p]) == si) {
  157481. huffcode[p++] = code;
  157482. code++;
  157483. }
  157484. /* code is now 1 more than the last code used for codelength si; but
  157485. * it must still fit in si bits, since no code is allowed to be all ones.
  157486. */
  157487. if (((INT32) code) >= (((INT32) 1) << si))
  157488. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  157489. code <<= 1;
  157490. si++;
  157491. }
  157492. /* Figure C.3: generate encoding tables */
  157493. /* These are code and size indexed by symbol value */
  157494. /* Set all codeless symbols to have code length 0;
  157495. * this lets us detect duplicate VAL entries here, and later
  157496. * allows emit_bits to detect any attempt to emit such symbols.
  157497. */
  157498. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  157499. /* This is also a convenient place to check for out-of-range
  157500. * and duplicated VAL entries. We allow 0..255 for AC symbols
  157501. * but only 0..15 for DC. (We could constrain them further
  157502. * based on data depth and mode, but this seems enough.)
  157503. */
  157504. maxsymbol = isDC ? 15 : 255;
  157505. for (p = 0; p < lastp; p++) {
  157506. i = htbl->huffval[p];
  157507. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  157508. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  157509. dtbl->ehufco[i] = huffcode[p];
  157510. dtbl->ehufsi[i] = huffsize[p];
  157511. }
  157512. }
  157513. /* Outputting bytes to the file */
  157514. /* Emit a byte, taking 'action' if must suspend. */
  157515. #define emit_byte(state,val,action) \
  157516. { *(state)->next_output_byte++ = (JOCTET) (val); \
  157517. if (--(state)->free_in_buffer == 0) \
  157518. if (! dump_buffer(state)) \
  157519. { action; } }
  157520. LOCAL(boolean)
  157521. dump_buffer (working_state * state)
  157522. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  157523. {
  157524. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  157525. if (! (*dest->empty_output_buffer) (state->cinfo))
  157526. return FALSE;
  157527. /* After a successful buffer dump, must reset buffer pointers */
  157528. state->next_output_byte = dest->next_output_byte;
  157529. state->free_in_buffer = dest->free_in_buffer;
  157530. return TRUE;
  157531. }
  157532. /* Outputting bits to the file */
  157533. /* Only the right 24 bits of put_buffer are used; the valid bits are
  157534. * left-justified in this part. At most 16 bits can be passed to emit_bits
  157535. * in one call, and we never retain more than 7 bits in put_buffer
  157536. * between calls, so 24 bits are sufficient.
  157537. */
  157538. INLINE
  157539. LOCAL(boolean)
  157540. emit_bits (working_state * state, unsigned int code, int size)
  157541. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  157542. {
  157543. /* This routine is heavily used, so it's worth coding tightly. */
  157544. register INT32 put_buffer = (INT32) code;
  157545. register int put_bits = state->cur.put_bits;
  157546. /* if size is 0, caller used an invalid Huffman table entry */
  157547. if (size == 0)
  157548. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  157549. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  157550. put_bits += size; /* new number of bits in buffer */
  157551. put_buffer <<= 24 - put_bits; /* align incoming bits */
  157552. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  157553. while (put_bits >= 8) {
  157554. int c = (int) ((put_buffer >> 16) & 0xFF);
  157555. emit_byte(state, c, return FALSE);
  157556. if (c == 0xFF) { /* need to stuff a zero byte? */
  157557. emit_byte(state, 0, return FALSE);
  157558. }
  157559. put_buffer <<= 8;
  157560. put_bits -= 8;
  157561. }
  157562. state->cur.put_buffer = put_buffer; /* update state variables */
  157563. state->cur.put_bits = put_bits;
  157564. return TRUE;
  157565. }
  157566. LOCAL(boolean)
  157567. flush_bits (working_state * state)
  157568. {
  157569. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  157570. return FALSE;
  157571. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  157572. state->cur.put_bits = 0;
  157573. return TRUE;
  157574. }
  157575. /* Encode a single block's worth of coefficients */
  157576. LOCAL(boolean)
  157577. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  157578. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  157579. {
  157580. register int temp, temp2;
  157581. register int nbits;
  157582. register int k, r, i;
  157583. /* Encode the DC coefficient difference per section F.1.2.1 */
  157584. temp = temp2 = block[0] - last_dc_val;
  157585. if (temp < 0) {
  157586. temp = -temp; /* temp is abs value of input */
  157587. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  157588. /* This code assumes we are on a two's complement machine */
  157589. temp2--;
  157590. }
  157591. /* Find the number of bits needed for the magnitude of the coefficient */
  157592. nbits = 0;
  157593. while (temp) {
  157594. nbits++;
  157595. temp >>= 1;
  157596. }
  157597. /* Check for out-of-range coefficient values.
  157598. * Since we're encoding a difference, the range limit is twice as much.
  157599. */
  157600. if (nbits > MAX_COEF_BITS+1)
  157601. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  157602. /* Emit the Huffman-coded symbol for the number of bits */
  157603. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  157604. return FALSE;
  157605. /* Emit that number of bits of the value, if positive, */
  157606. /* or the complement of its magnitude, if negative. */
  157607. if (nbits) /* emit_bits rejects calls with size 0 */
  157608. if (! emit_bits(state, (unsigned int) temp2, nbits))
  157609. return FALSE;
  157610. /* Encode the AC coefficients per section F.1.2.2 */
  157611. r = 0; /* r = run length of zeros */
  157612. for (k = 1; k < DCTSIZE2; k++) {
  157613. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  157614. r++;
  157615. } else {
  157616. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  157617. while (r > 15) {
  157618. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  157619. return FALSE;
  157620. r -= 16;
  157621. }
  157622. temp2 = temp;
  157623. if (temp < 0) {
  157624. temp = -temp; /* temp is abs value of input */
  157625. /* This code assumes we are on a two's complement machine */
  157626. temp2--;
  157627. }
  157628. /* Find the number of bits needed for the magnitude of the coefficient */
  157629. nbits = 1; /* there must be at least one 1 bit */
  157630. while ((temp >>= 1))
  157631. nbits++;
  157632. /* Check for out-of-range coefficient values */
  157633. if (nbits > MAX_COEF_BITS)
  157634. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  157635. /* Emit Huffman symbol for run length / number of bits */
  157636. i = (r << 4) + nbits;
  157637. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  157638. return FALSE;
  157639. /* Emit that number of bits of the value, if positive, */
  157640. /* or the complement of its magnitude, if negative. */
  157641. if (! emit_bits(state, (unsigned int) temp2, nbits))
  157642. return FALSE;
  157643. r = 0;
  157644. }
  157645. }
  157646. /* If the last coef(s) were zero, emit an end-of-block code */
  157647. if (r > 0)
  157648. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  157649. return FALSE;
  157650. return TRUE;
  157651. }
  157652. /*
  157653. * Emit a restart marker & resynchronize predictions.
  157654. */
  157655. LOCAL(boolean)
  157656. emit_restart (working_state * state, int restart_num)
  157657. {
  157658. int ci;
  157659. if (! flush_bits(state))
  157660. return FALSE;
  157661. emit_byte(state, 0xFF, return FALSE);
  157662. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  157663. /* Re-initialize DC predictions to 0 */
  157664. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  157665. state->cur.last_dc_val[ci] = 0;
  157666. /* The restart counter is not updated until we successfully write the MCU. */
  157667. return TRUE;
  157668. }
  157669. /*
  157670. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  157671. */
  157672. METHODDEF(boolean)
  157673. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  157674. {
  157675. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157676. working_state state;
  157677. int blkn, ci;
  157678. jpeg_component_info * compptr;
  157679. /* Load up working state */
  157680. state.next_output_byte = cinfo->dest->next_output_byte;
  157681. state.free_in_buffer = cinfo->dest->free_in_buffer;
  157682. ASSIGN_STATE(state.cur, entropy->saved);
  157683. state.cinfo = cinfo;
  157684. /* Emit restart marker if needed */
  157685. if (cinfo->restart_interval) {
  157686. if (entropy->restarts_to_go == 0)
  157687. if (! emit_restart(&state, entropy->next_restart_num))
  157688. return FALSE;
  157689. }
  157690. /* Encode the MCU data blocks */
  157691. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  157692. ci = cinfo->MCU_membership[blkn];
  157693. compptr = cinfo->cur_comp_info[ci];
  157694. if (! encode_one_block(&state,
  157695. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  157696. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  157697. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  157698. return FALSE;
  157699. /* Update last_dc_val */
  157700. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  157701. }
  157702. /* Completed MCU, so update state */
  157703. cinfo->dest->next_output_byte = state.next_output_byte;
  157704. cinfo->dest->free_in_buffer = state.free_in_buffer;
  157705. ASSIGN_STATE(entropy->saved, state.cur);
  157706. /* Update restart-interval state too */
  157707. if (cinfo->restart_interval) {
  157708. if (entropy->restarts_to_go == 0) {
  157709. entropy->restarts_to_go = cinfo->restart_interval;
  157710. entropy->next_restart_num++;
  157711. entropy->next_restart_num &= 7;
  157712. }
  157713. entropy->restarts_to_go--;
  157714. }
  157715. return TRUE;
  157716. }
  157717. /*
  157718. * Finish up at the end of a Huffman-compressed scan.
  157719. */
  157720. METHODDEF(void)
  157721. finish_pass_huff (j_compress_ptr cinfo)
  157722. {
  157723. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157724. working_state state;
  157725. /* Load up working state ... flush_bits needs it */
  157726. state.next_output_byte = cinfo->dest->next_output_byte;
  157727. state.free_in_buffer = cinfo->dest->free_in_buffer;
  157728. ASSIGN_STATE(state.cur, entropy->saved);
  157729. state.cinfo = cinfo;
  157730. /* Flush out the last data */
  157731. if (! flush_bits(&state))
  157732. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  157733. /* Update state */
  157734. cinfo->dest->next_output_byte = state.next_output_byte;
  157735. cinfo->dest->free_in_buffer = state.free_in_buffer;
  157736. ASSIGN_STATE(entropy->saved, state.cur);
  157737. }
  157738. /*
  157739. * Huffman coding optimization.
  157740. *
  157741. * We first scan the supplied data and count the number of uses of each symbol
  157742. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  157743. * Then we build a Huffman coding tree for the observed counts.
  157744. * Symbols which are not needed at all for the particular image are not
  157745. * assigned any code, which saves space in the DHT marker as well as in
  157746. * the compressed data.
  157747. */
  157748. #ifdef ENTROPY_OPT_SUPPORTED
  157749. /* Process a single block's worth of coefficients */
  157750. LOCAL(void)
  157751. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  157752. long dc_counts[], long ac_counts[])
  157753. {
  157754. register int temp;
  157755. register int nbits;
  157756. register int k, r;
  157757. /* Encode the DC coefficient difference per section F.1.2.1 */
  157758. temp = block[0] - last_dc_val;
  157759. if (temp < 0)
  157760. temp = -temp;
  157761. /* Find the number of bits needed for the magnitude of the coefficient */
  157762. nbits = 0;
  157763. while (temp) {
  157764. nbits++;
  157765. temp >>= 1;
  157766. }
  157767. /* Check for out-of-range coefficient values.
  157768. * Since we're encoding a difference, the range limit is twice as much.
  157769. */
  157770. if (nbits > MAX_COEF_BITS+1)
  157771. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  157772. /* Count the Huffman symbol for the number of bits */
  157773. dc_counts[nbits]++;
  157774. /* Encode the AC coefficients per section F.1.2.2 */
  157775. r = 0; /* r = run length of zeros */
  157776. for (k = 1; k < DCTSIZE2; k++) {
  157777. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  157778. r++;
  157779. } else {
  157780. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  157781. while (r > 15) {
  157782. ac_counts[0xF0]++;
  157783. r -= 16;
  157784. }
  157785. /* Find the number of bits needed for the magnitude of the coefficient */
  157786. if (temp < 0)
  157787. temp = -temp;
  157788. /* Find the number of bits needed for the magnitude of the coefficient */
  157789. nbits = 1; /* there must be at least one 1 bit */
  157790. while ((temp >>= 1))
  157791. nbits++;
  157792. /* Check for out-of-range coefficient values */
  157793. if (nbits > MAX_COEF_BITS)
  157794. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  157795. /* Count Huffman symbol for run length / number of bits */
  157796. ac_counts[(r << 4) + nbits]++;
  157797. r = 0;
  157798. }
  157799. }
  157800. /* If the last coef(s) were zero, emit an end-of-block code */
  157801. if (r > 0)
  157802. ac_counts[0]++;
  157803. }
  157804. /*
  157805. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  157806. * No data is actually output, so no suspension return is possible.
  157807. */
  157808. METHODDEF(boolean)
  157809. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  157810. {
  157811. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157812. int blkn, ci;
  157813. jpeg_component_info * compptr;
  157814. /* Take care of restart intervals if needed */
  157815. if (cinfo->restart_interval) {
  157816. if (entropy->restarts_to_go == 0) {
  157817. /* Re-initialize DC predictions to 0 */
  157818. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  157819. entropy->saved.last_dc_val[ci] = 0;
  157820. /* Update restart state */
  157821. entropy->restarts_to_go = cinfo->restart_interval;
  157822. }
  157823. entropy->restarts_to_go--;
  157824. }
  157825. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  157826. ci = cinfo->MCU_membership[blkn];
  157827. compptr = cinfo->cur_comp_info[ci];
  157828. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  157829. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  157830. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  157831. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  157832. }
  157833. return TRUE;
  157834. }
  157835. /*
  157836. * Generate the best Huffman code table for the given counts, fill htbl.
  157837. * Note this is also used by jcphuff.c.
  157838. *
  157839. * The JPEG standard requires that no symbol be assigned a codeword of all
  157840. * one bits (so that padding bits added at the end of a compressed segment
  157841. * can't look like a valid code). Because of the canonical ordering of
  157842. * codewords, this just means that there must be an unused slot in the
  157843. * longest codeword length category. Section K.2 of the JPEG spec suggests
  157844. * reserving such a slot by pretending that symbol 256 is a valid symbol
  157845. * with count 1. In theory that's not optimal; giving it count zero but
  157846. * including it in the symbol set anyway should give a better Huffman code.
  157847. * But the theoretically better code actually seems to come out worse in
  157848. * practice, because it produces more all-ones bytes (which incur stuffed
  157849. * zero bytes in the final file). In any case the difference is tiny.
  157850. *
  157851. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  157852. * If some symbols have a very small but nonzero probability, the Huffman tree
  157853. * must be adjusted to meet the code length restriction. We currently use
  157854. * the adjustment method suggested in JPEG section K.2. This method is *not*
  157855. * optimal; it may not choose the best possible limited-length code. But
  157856. * typically only very-low-frequency symbols will be given less-than-optimal
  157857. * lengths, so the code is almost optimal. Experimental comparisons against
  157858. * an optimal limited-length-code algorithm indicate that the difference is
  157859. * microscopic --- usually less than a hundredth of a percent of total size.
  157860. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  157861. */
  157862. GLOBAL(void)
  157863. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  157864. {
  157865. #define MAX_CLEN 32 /* assumed maximum initial code length */
  157866. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  157867. int codesize[257]; /* codesize[k] = code length of symbol k */
  157868. int others[257]; /* next symbol in current branch of tree */
  157869. int c1, c2;
  157870. int p, i, j;
  157871. long v;
  157872. /* This algorithm is explained in section K.2 of the JPEG standard */
  157873. MEMZERO(bits, SIZEOF(bits));
  157874. MEMZERO(codesize, SIZEOF(codesize));
  157875. for (i = 0; i < 257; i++)
  157876. others[i] = -1; /* init links to empty */
  157877. freq[256] = 1; /* make sure 256 has a nonzero count */
  157878. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  157879. * that no real symbol is given code-value of all ones, because 256
  157880. * will be placed last in the largest codeword category.
  157881. */
  157882. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  157883. for (;;) {
  157884. /* Find the smallest nonzero frequency, set c1 = its symbol */
  157885. /* In case of ties, take the larger symbol number */
  157886. c1 = -1;
  157887. v = 1000000000L;
  157888. for (i = 0; i <= 256; i++) {
  157889. if (freq[i] && freq[i] <= v) {
  157890. v = freq[i];
  157891. c1 = i;
  157892. }
  157893. }
  157894. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  157895. /* In case of ties, take the larger symbol number */
  157896. c2 = -1;
  157897. v = 1000000000L;
  157898. for (i = 0; i <= 256; i++) {
  157899. if (freq[i] && freq[i] <= v && i != c1) {
  157900. v = freq[i];
  157901. c2 = i;
  157902. }
  157903. }
  157904. /* Done if we've merged everything into one frequency */
  157905. if (c2 < 0)
  157906. break;
  157907. /* Else merge the two counts/trees */
  157908. freq[c1] += freq[c2];
  157909. freq[c2] = 0;
  157910. /* Increment the codesize of everything in c1's tree branch */
  157911. codesize[c1]++;
  157912. while (others[c1] >= 0) {
  157913. c1 = others[c1];
  157914. codesize[c1]++;
  157915. }
  157916. others[c1] = c2; /* chain c2 onto c1's tree branch */
  157917. /* Increment the codesize of everything in c2's tree branch */
  157918. codesize[c2]++;
  157919. while (others[c2] >= 0) {
  157920. c2 = others[c2];
  157921. codesize[c2]++;
  157922. }
  157923. }
  157924. /* Now count the number of symbols of each code length */
  157925. for (i = 0; i <= 256; i++) {
  157926. if (codesize[i]) {
  157927. /* The JPEG standard seems to think that this can't happen, */
  157928. /* but I'm paranoid... */
  157929. if (codesize[i] > MAX_CLEN)
  157930. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  157931. bits[codesize[i]]++;
  157932. }
  157933. }
  157934. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  157935. * Huffman procedure assigned any such lengths, we must adjust the coding.
  157936. * Here is what the JPEG spec says about how this next bit works:
  157937. * Since symbols are paired for the longest Huffman code, the symbols are
  157938. * removed from this length category two at a time. The prefix for the pair
  157939. * (which is one bit shorter) is allocated to one of the pair; then,
  157940. * skipping the BITS entry for that prefix length, a code word from the next
  157941. * shortest nonzero BITS entry is converted into a prefix for two code words
  157942. * one bit longer.
  157943. */
  157944. for (i = MAX_CLEN; i > 16; i--) {
  157945. while (bits[i] > 0) {
  157946. j = i - 2; /* find length of new prefix to be used */
  157947. while (bits[j] == 0)
  157948. j--;
  157949. bits[i] -= 2; /* remove two symbols */
  157950. bits[i-1]++; /* one goes in this length */
  157951. bits[j+1] += 2; /* two new symbols in this length */
  157952. bits[j]--; /* symbol of this length is now a prefix */
  157953. }
  157954. }
  157955. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  157956. while (bits[i] == 0) /* find largest codelength still in use */
  157957. i--;
  157958. bits[i]--;
  157959. /* Return final symbol counts (only for lengths 0..16) */
  157960. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  157961. /* Return a list of the symbols sorted by code length */
  157962. /* It's not real clear to me why we don't need to consider the codelength
  157963. * changes made above, but the JPEG spec seems to think this works.
  157964. */
  157965. p = 0;
  157966. for (i = 1; i <= MAX_CLEN; i++) {
  157967. for (j = 0; j <= 255; j++) {
  157968. if (codesize[j] == i) {
  157969. htbl->huffval[p] = (UINT8) j;
  157970. p++;
  157971. }
  157972. }
  157973. }
  157974. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  157975. htbl->sent_table = FALSE;
  157976. }
  157977. /*
  157978. * Finish up a statistics-gathering pass and create the new Huffman tables.
  157979. */
  157980. METHODDEF(void)
  157981. finish_pass_gather (j_compress_ptr cinfo)
  157982. {
  157983. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157984. int ci, dctbl, actbl;
  157985. jpeg_component_info * compptr;
  157986. JHUFF_TBL **htblptr;
  157987. boolean did_dc[NUM_HUFF_TBLS];
  157988. boolean did_ac[NUM_HUFF_TBLS];
  157989. /* It's important not to apply jpeg_gen_optimal_table more than once
  157990. * per table, because it clobbers the input frequency counts!
  157991. */
  157992. MEMZERO(did_dc, SIZEOF(did_dc));
  157993. MEMZERO(did_ac, SIZEOF(did_ac));
  157994. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157995. compptr = cinfo->cur_comp_info[ci];
  157996. dctbl = compptr->dc_tbl_no;
  157997. actbl = compptr->ac_tbl_no;
  157998. if (! did_dc[dctbl]) {
  157999. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  158000. if (*htblptr == NULL)
  158001. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  158002. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  158003. did_dc[dctbl] = TRUE;
  158004. }
  158005. if (! did_ac[actbl]) {
  158006. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  158007. if (*htblptr == NULL)
  158008. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  158009. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  158010. did_ac[actbl] = TRUE;
  158011. }
  158012. }
  158013. }
  158014. #endif /* ENTROPY_OPT_SUPPORTED */
  158015. /*
  158016. * Module initialization routine for Huffman entropy encoding.
  158017. */
  158018. GLOBAL(void)
  158019. jinit_huff_encoder (j_compress_ptr cinfo)
  158020. {
  158021. huff_entropy_ptr entropy;
  158022. int i;
  158023. entropy = (huff_entropy_ptr)
  158024. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158025. SIZEOF(huff_entropy_encoder));
  158026. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  158027. entropy->pub.start_pass = start_pass_huff;
  158028. /* Mark tables unallocated */
  158029. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  158030. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  158031. #ifdef ENTROPY_OPT_SUPPORTED
  158032. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  158033. #endif
  158034. }
  158035. }
  158036. /********* End of inlined file: jchuff.c *********/
  158037. #undef emit_byte
  158038. /********* Start of inlined file: jcinit.c *********/
  158039. #define JPEG_INTERNALS
  158040. /*
  158041. * Master selection of compression modules.
  158042. * This is done once at the start of processing an image. We determine
  158043. * which modules will be used and give them appropriate initialization calls.
  158044. */
  158045. GLOBAL(void)
  158046. jinit_compress_master (j_compress_ptr cinfo)
  158047. {
  158048. /* Initialize master control (includes parameter checking/processing) */
  158049. jinit_c_master_control(cinfo, FALSE /* full compression */);
  158050. /* Preprocessing */
  158051. if (! cinfo->raw_data_in) {
  158052. jinit_color_converter(cinfo);
  158053. jinit_downsampler(cinfo);
  158054. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  158055. }
  158056. /* Forward DCT */
  158057. jinit_forward_dct(cinfo);
  158058. /* Entropy encoding: either Huffman or arithmetic coding. */
  158059. if (cinfo->arith_code) {
  158060. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  158061. } else {
  158062. if (cinfo->progressive_mode) {
  158063. #ifdef C_PROGRESSIVE_SUPPORTED
  158064. jinit_phuff_encoder(cinfo);
  158065. #else
  158066. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158067. #endif
  158068. } else
  158069. jinit_huff_encoder(cinfo);
  158070. }
  158071. /* Need a full-image coefficient buffer in any multi-pass mode. */
  158072. jinit_c_coef_controller(cinfo,
  158073. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  158074. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  158075. jinit_marker_writer(cinfo);
  158076. /* We can now tell the memory manager to allocate virtual arrays. */
  158077. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  158078. /* Write the datastream header (SOI) immediately.
  158079. * Frame and scan headers are postponed till later.
  158080. * This lets application insert special markers after the SOI.
  158081. */
  158082. (*cinfo->marker->write_file_header) (cinfo);
  158083. }
  158084. /********* End of inlined file: jcinit.c *********/
  158085. /********* Start of inlined file: jcmainct.c *********/
  158086. #define JPEG_INTERNALS
  158087. /* Note: currently, there is no operating mode in which a full-image buffer
  158088. * is needed at this step. If there were, that mode could not be used with
  158089. * "raw data" input, since this module is bypassed in that case. However,
  158090. * we've left the code here for possible use in special applications.
  158091. */
  158092. #undef FULL_MAIN_BUFFER_SUPPORTED
  158093. /* Private buffer controller object */
  158094. typedef struct {
  158095. struct jpeg_c_main_controller pub; /* public fields */
  158096. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  158097. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  158098. boolean suspended; /* remember if we suspended output */
  158099. J_BUF_MODE pass_mode; /* current operating mode */
  158100. /* If using just a strip buffer, this points to the entire set of buffers
  158101. * (we allocate one for each component). In the full-image case, this
  158102. * points to the currently accessible strips of the virtual arrays.
  158103. */
  158104. JSAMPARRAY buffer[MAX_COMPONENTS];
  158105. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158106. /* If using full-image storage, this array holds pointers to virtual-array
  158107. * control blocks for each component. Unused if not full-image storage.
  158108. */
  158109. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  158110. #endif
  158111. } my_main_controller;
  158112. typedef my_main_controller * my_main_ptr;
  158113. /* Forward declarations */
  158114. METHODDEF(void) process_data_simple_main
  158115. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  158116. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  158117. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158118. METHODDEF(void) process_data_buffer_main
  158119. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  158120. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  158121. #endif
  158122. /*
  158123. * Initialize for a processing pass.
  158124. */
  158125. METHODDEF(void)
  158126. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  158127. {
  158128. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  158129. /* Do nothing in raw-data mode. */
  158130. if (cinfo->raw_data_in)
  158131. return;
  158132. main_->cur_iMCU_row = 0; /* initialize counters */
  158133. main_->rowgroup_ctr = 0;
  158134. main_->suspended = FALSE;
  158135. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  158136. switch (pass_mode) {
  158137. case JBUF_PASS_THRU:
  158138. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158139. if (main_->whole_image[0] != NULL)
  158140. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158141. #endif
  158142. main_->pub.process_data = process_data_simple_main;
  158143. break;
  158144. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158145. case JBUF_SAVE_SOURCE:
  158146. case JBUF_CRANK_DEST:
  158147. case JBUF_SAVE_AND_PASS:
  158148. if (main_->whole_image[0] == NULL)
  158149. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158150. main_->pub.process_data = process_data_buffer_main;
  158151. break;
  158152. #endif
  158153. default:
  158154. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158155. break;
  158156. }
  158157. }
  158158. /*
  158159. * Process some data.
  158160. * This routine handles the simple pass-through mode,
  158161. * where we have only a strip buffer.
  158162. */
  158163. METHODDEF(void)
  158164. process_data_simple_main (j_compress_ptr cinfo,
  158165. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  158166. JDIMENSION in_rows_avail)
  158167. {
  158168. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  158169. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  158170. /* Read input data if we haven't filled the main buffer yet */
  158171. if (main_->rowgroup_ctr < DCTSIZE)
  158172. (*cinfo->prep->pre_process_data) (cinfo,
  158173. input_buf, in_row_ctr, in_rows_avail,
  158174. main_->buffer, &main_->rowgroup_ctr,
  158175. (JDIMENSION) DCTSIZE);
  158176. /* If we don't have a full iMCU row buffered, return to application for
  158177. * more data. Note that preprocessor will always pad to fill the iMCU row
  158178. * at the bottom of the image.
  158179. */
  158180. if (main_->rowgroup_ctr != DCTSIZE)
  158181. return;
  158182. /* Send the completed row to the compressor */
  158183. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  158184. /* If compressor did not consume the whole row, then we must need to
  158185. * suspend processing and return to the application. In this situation
  158186. * we pretend we didn't yet consume the last input row; otherwise, if
  158187. * it happened to be the last row of the image, the application would
  158188. * think we were done.
  158189. */
  158190. if (! main_->suspended) {
  158191. (*in_row_ctr)--;
  158192. main_->suspended = TRUE;
  158193. }
  158194. return;
  158195. }
  158196. /* We did finish the row. Undo our little suspension hack if a previous
  158197. * call suspended; then mark the main buffer empty.
  158198. */
  158199. if (main_->suspended) {
  158200. (*in_row_ctr)++;
  158201. main_->suspended = FALSE;
  158202. }
  158203. main_->rowgroup_ctr = 0;
  158204. main_->cur_iMCU_row++;
  158205. }
  158206. }
  158207. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158208. /*
  158209. * Process some data.
  158210. * This routine handles all of the modes that use a full-size buffer.
  158211. */
  158212. METHODDEF(void)
  158213. process_data_buffer_main (j_compress_ptr cinfo,
  158214. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  158215. JDIMENSION in_rows_avail)
  158216. {
  158217. my_main_ptr main = (my_main_ptr) cinfo->main;
  158218. int ci;
  158219. jpeg_component_info *compptr;
  158220. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  158221. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  158222. /* Realign the virtual buffers if at the start of an iMCU row. */
  158223. if (main->rowgroup_ctr == 0) {
  158224. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158225. ci++, compptr++) {
  158226. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  158227. ((j_common_ptr) cinfo, main->whole_image[ci],
  158228. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  158229. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  158230. }
  158231. /* In a read pass, pretend we just read some source data. */
  158232. if (! writing) {
  158233. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  158234. main->rowgroup_ctr = DCTSIZE;
  158235. }
  158236. }
  158237. /* If a write pass, read input data until the current iMCU row is full. */
  158238. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  158239. if (writing) {
  158240. (*cinfo->prep->pre_process_data) (cinfo,
  158241. input_buf, in_row_ctr, in_rows_avail,
  158242. main->buffer, &main->rowgroup_ctr,
  158243. (JDIMENSION) DCTSIZE);
  158244. /* Return to application if we need more data to fill the iMCU row. */
  158245. if (main->rowgroup_ctr < DCTSIZE)
  158246. return;
  158247. }
  158248. /* Emit data, unless this is a sink-only pass. */
  158249. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  158250. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  158251. /* If compressor did not consume the whole row, then we must need to
  158252. * suspend processing and return to the application. In this situation
  158253. * we pretend we didn't yet consume the last input row; otherwise, if
  158254. * it happened to be the last row of the image, the application would
  158255. * think we were done.
  158256. */
  158257. if (! main->suspended) {
  158258. (*in_row_ctr)--;
  158259. main->suspended = TRUE;
  158260. }
  158261. return;
  158262. }
  158263. /* We did finish the row. Undo our little suspension hack if a previous
  158264. * call suspended; then mark the main buffer empty.
  158265. */
  158266. if (main->suspended) {
  158267. (*in_row_ctr)++;
  158268. main->suspended = FALSE;
  158269. }
  158270. }
  158271. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  158272. main->rowgroup_ctr = 0;
  158273. main->cur_iMCU_row++;
  158274. }
  158275. }
  158276. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  158277. /*
  158278. * Initialize main buffer controller.
  158279. */
  158280. GLOBAL(void)
  158281. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  158282. {
  158283. my_main_ptr main_;
  158284. int ci;
  158285. jpeg_component_info *compptr;
  158286. main_ = (my_main_ptr)
  158287. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158288. SIZEOF(my_main_controller));
  158289. cinfo->main = (struct jpeg_c_main_controller *) main_;
  158290. main_->pub.start_pass = start_pass_main;
  158291. /* We don't need to create a buffer in raw-data mode. */
  158292. if (cinfo->raw_data_in)
  158293. return;
  158294. /* Create the buffer. It holds downsampled data, so each component
  158295. * may be of a different size.
  158296. */
  158297. if (need_full_buffer) {
  158298. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158299. /* Allocate a full-image virtual array for each component */
  158300. /* Note we pad the bottom to a multiple of the iMCU height */
  158301. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158302. ci++, compptr++) {
  158303. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  158304. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  158305. compptr->width_in_blocks * DCTSIZE,
  158306. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  158307. (long) compptr->v_samp_factor) * DCTSIZE,
  158308. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  158309. }
  158310. #else
  158311. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  158312. #endif
  158313. } else {
  158314. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  158315. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  158316. #endif
  158317. /* Allocate a strip buffer for each component */
  158318. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158319. ci++, compptr++) {
  158320. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  158321. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158322. compptr->width_in_blocks * DCTSIZE,
  158323. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  158324. }
  158325. }
  158326. }
  158327. /********* End of inlined file: jcmainct.c *********/
  158328. /********* Start of inlined file: jcmarker.c *********/
  158329. #define JPEG_INTERNALS
  158330. /* Private state */
  158331. typedef struct {
  158332. struct jpeg_marker_writer pub; /* public fields */
  158333. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  158334. } my_marker_writer;
  158335. typedef my_marker_writer * my_marker_ptr;
  158336. /*
  158337. * Basic output routines.
  158338. *
  158339. * Note that we do not support suspension while writing a marker.
  158340. * Therefore, an application using suspension must ensure that there is
  158341. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  158342. * calling jpeg_start_compress, and enough space to write the trailing EOI
  158343. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  158344. * modes are not supported at all with suspension, so those two are the only
  158345. * points where markers will be written.
  158346. */
  158347. LOCAL(void)
  158348. emit_byte (j_compress_ptr cinfo, int val)
  158349. /* Emit a byte */
  158350. {
  158351. struct jpeg_destination_mgr * dest = cinfo->dest;
  158352. *(dest->next_output_byte)++ = (JOCTET) val;
  158353. if (--dest->free_in_buffer == 0) {
  158354. if (! (*dest->empty_output_buffer) (cinfo))
  158355. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  158356. }
  158357. }
  158358. LOCAL(void)
  158359. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  158360. /* Emit a marker code */
  158361. {
  158362. emit_byte(cinfo, 0xFF);
  158363. emit_byte(cinfo, (int) mark);
  158364. }
  158365. LOCAL(void)
  158366. emit_2bytes (j_compress_ptr cinfo, int value)
  158367. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  158368. {
  158369. emit_byte(cinfo, (value >> 8) & 0xFF);
  158370. emit_byte(cinfo, value & 0xFF);
  158371. }
  158372. /*
  158373. * Routines to write specific marker types.
  158374. */
  158375. LOCAL(int)
  158376. emit_dqt (j_compress_ptr cinfo, int index)
  158377. /* Emit a DQT marker */
  158378. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  158379. {
  158380. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  158381. int prec;
  158382. int i;
  158383. if (qtbl == NULL)
  158384. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  158385. prec = 0;
  158386. for (i = 0; i < DCTSIZE2; i++) {
  158387. if (qtbl->quantval[i] > 255)
  158388. prec = 1;
  158389. }
  158390. if (! qtbl->sent_table) {
  158391. emit_marker(cinfo, M_DQT);
  158392. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  158393. emit_byte(cinfo, index + (prec<<4));
  158394. for (i = 0; i < DCTSIZE2; i++) {
  158395. /* The table entries must be emitted in zigzag order. */
  158396. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  158397. if (prec)
  158398. emit_byte(cinfo, (int) (qval >> 8));
  158399. emit_byte(cinfo, (int) (qval & 0xFF));
  158400. }
  158401. qtbl->sent_table = TRUE;
  158402. }
  158403. return prec;
  158404. }
  158405. LOCAL(void)
  158406. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  158407. /* Emit a DHT marker */
  158408. {
  158409. JHUFF_TBL * htbl;
  158410. int length, i;
  158411. if (is_ac) {
  158412. htbl = cinfo->ac_huff_tbl_ptrs[index];
  158413. index += 0x10; /* output index has AC bit set */
  158414. } else {
  158415. htbl = cinfo->dc_huff_tbl_ptrs[index];
  158416. }
  158417. if (htbl == NULL)
  158418. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  158419. if (! htbl->sent_table) {
  158420. emit_marker(cinfo, M_DHT);
  158421. length = 0;
  158422. for (i = 1; i <= 16; i++)
  158423. length += htbl->bits[i];
  158424. emit_2bytes(cinfo, length + 2 + 1 + 16);
  158425. emit_byte(cinfo, index);
  158426. for (i = 1; i <= 16; i++)
  158427. emit_byte(cinfo, htbl->bits[i]);
  158428. for (i = 0; i < length; i++)
  158429. emit_byte(cinfo, htbl->huffval[i]);
  158430. htbl->sent_table = TRUE;
  158431. }
  158432. }
  158433. LOCAL(void)
  158434. emit_dac (j_compress_ptr cinfo)
  158435. /* Emit a DAC marker */
  158436. /* Since the useful info is so small, we want to emit all the tables in */
  158437. /* one DAC marker. Therefore this routine does its own scan of the table. */
  158438. {
  158439. #ifdef C_ARITH_CODING_SUPPORTED
  158440. char dc_in_use[NUM_ARITH_TBLS];
  158441. char ac_in_use[NUM_ARITH_TBLS];
  158442. int length, i;
  158443. jpeg_component_info *compptr;
  158444. for (i = 0; i < NUM_ARITH_TBLS; i++)
  158445. dc_in_use[i] = ac_in_use[i] = 0;
  158446. for (i = 0; i < cinfo->comps_in_scan; i++) {
  158447. compptr = cinfo->cur_comp_info[i];
  158448. dc_in_use[compptr->dc_tbl_no] = 1;
  158449. ac_in_use[compptr->ac_tbl_no] = 1;
  158450. }
  158451. length = 0;
  158452. for (i = 0; i < NUM_ARITH_TBLS; i++)
  158453. length += dc_in_use[i] + ac_in_use[i];
  158454. emit_marker(cinfo, M_DAC);
  158455. emit_2bytes(cinfo, length*2 + 2);
  158456. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  158457. if (dc_in_use[i]) {
  158458. emit_byte(cinfo, i);
  158459. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  158460. }
  158461. if (ac_in_use[i]) {
  158462. emit_byte(cinfo, i + 0x10);
  158463. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  158464. }
  158465. }
  158466. #endif /* C_ARITH_CODING_SUPPORTED */
  158467. }
  158468. LOCAL(void)
  158469. emit_dri (j_compress_ptr cinfo)
  158470. /* Emit a DRI marker */
  158471. {
  158472. emit_marker(cinfo, M_DRI);
  158473. emit_2bytes(cinfo, 4); /* fixed length */
  158474. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  158475. }
  158476. LOCAL(void)
  158477. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  158478. /* Emit a SOF marker */
  158479. {
  158480. int ci;
  158481. jpeg_component_info *compptr;
  158482. emit_marker(cinfo, code);
  158483. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  158484. /* Make sure image isn't bigger than SOF field can handle */
  158485. if ((long) cinfo->image_height > 65535L ||
  158486. (long) cinfo->image_width > 65535L)
  158487. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  158488. emit_byte(cinfo, cinfo->data_precision);
  158489. emit_2bytes(cinfo, (int) cinfo->image_height);
  158490. emit_2bytes(cinfo, (int) cinfo->image_width);
  158491. emit_byte(cinfo, cinfo->num_components);
  158492. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158493. ci++, compptr++) {
  158494. emit_byte(cinfo, compptr->component_id);
  158495. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  158496. emit_byte(cinfo, compptr->quant_tbl_no);
  158497. }
  158498. }
  158499. LOCAL(void)
  158500. emit_sos (j_compress_ptr cinfo)
  158501. /* Emit a SOS marker */
  158502. {
  158503. int i, td, ta;
  158504. jpeg_component_info *compptr;
  158505. emit_marker(cinfo, M_SOS);
  158506. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  158507. emit_byte(cinfo, cinfo->comps_in_scan);
  158508. for (i = 0; i < cinfo->comps_in_scan; i++) {
  158509. compptr = cinfo->cur_comp_info[i];
  158510. emit_byte(cinfo, compptr->component_id);
  158511. td = compptr->dc_tbl_no;
  158512. ta = compptr->ac_tbl_no;
  158513. if (cinfo->progressive_mode) {
  158514. /* Progressive mode: only DC or only AC tables are used in one scan;
  158515. * furthermore, Huffman coding of DC refinement uses no table at all.
  158516. * We emit 0 for unused field(s); this is recommended by the P&M text
  158517. * but does not seem to be specified in the standard.
  158518. */
  158519. if (cinfo->Ss == 0) {
  158520. ta = 0; /* DC scan */
  158521. if (cinfo->Ah != 0 && !cinfo->arith_code)
  158522. td = 0; /* no DC table either */
  158523. } else {
  158524. td = 0; /* AC scan */
  158525. }
  158526. }
  158527. emit_byte(cinfo, (td << 4) + ta);
  158528. }
  158529. emit_byte(cinfo, cinfo->Ss);
  158530. emit_byte(cinfo, cinfo->Se);
  158531. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  158532. }
  158533. LOCAL(void)
  158534. emit_jfif_app0 (j_compress_ptr cinfo)
  158535. /* Emit a JFIF-compliant APP0 marker */
  158536. {
  158537. /*
  158538. * Length of APP0 block (2 bytes)
  158539. * Block ID (4 bytes - ASCII "JFIF")
  158540. * Zero byte (1 byte to terminate the ID string)
  158541. * Version Major, Minor (2 bytes - major first)
  158542. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  158543. * Xdpu (2 bytes - dots per unit horizontal)
  158544. * Ydpu (2 bytes - dots per unit vertical)
  158545. * Thumbnail X size (1 byte)
  158546. * Thumbnail Y size (1 byte)
  158547. */
  158548. emit_marker(cinfo, M_APP0);
  158549. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  158550. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  158551. emit_byte(cinfo, 0x46);
  158552. emit_byte(cinfo, 0x49);
  158553. emit_byte(cinfo, 0x46);
  158554. emit_byte(cinfo, 0);
  158555. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  158556. emit_byte(cinfo, cinfo->JFIF_minor_version);
  158557. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  158558. emit_2bytes(cinfo, (int) cinfo->X_density);
  158559. emit_2bytes(cinfo, (int) cinfo->Y_density);
  158560. emit_byte(cinfo, 0); /* No thumbnail image */
  158561. emit_byte(cinfo, 0);
  158562. }
  158563. LOCAL(void)
  158564. emit_adobe_app14 (j_compress_ptr cinfo)
  158565. /* Emit an Adobe APP14 marker */
  158566. {
  158567. /*
  158568. * Length of APP14 block (2 bytes)
  158569. * Block ID (5 bytes - ASCII "Adobe")
  158570. * Version Number (2 bytes - currently 100)
  158571. * Flags0 (2 bytes - currently 0)
  158572. * Flags1 (2 bytes - currently 0)
  158573. * Color transform (1 byte)
  158574. *
  158575. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  158576. * now in circulation seem to use Version = 100, so that's what we write.
  158577. *
  158578. * We write the color transform byte as 1 if the JPEG color space is
  158579. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  158580. * whether the encoder performed a transformation, which is pretty useless.
  158581. */
  158582. emit_marker(cinfo, M_APP14);
  158583. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  158584. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  158585. emit_byte(cinfo, 0x64);
  158586. emit_byte(cinfo, 0x6F);
  158587. emit_byte(cinfo, 0x62);
  158588. emit_byte(cinfo, 0x65);
  158589. emit_2bytes(cinfo, 100); /* Version */
  158590. emit_2bytes(cinfo, 0); /* Flags0 */
  158591. emit_2bytes(cinfo, 0); /* Flags1 */
  158592. switch (cinfo->jpeg_color_space) {
  158593. case JCS_YCbCr:
  158594. emit_byte(cinfo, 1); /* Color transform = 1 */
  158595. break;
  158596. case JCS_YCCK:
  158597. emit_byte(cinfo, 2); /* Color transform = 2 */
  158598. break;
  158599. default:
  158600. emit_byte(cinfo, 0); /* Color transform = 0 */
  158601. break;
  158602. }
  158603. }
  158604. /*
  158605. * These routines allow writing an arbitrary marker with parameters.
  158606. * The only intended use is to emit COM or APPn markers after calling
  158607. * write_file_header and before calling write_frame_header.
  158608. * Other uses are not guaranteed to produce desirable results.
  158609. * Counting the parameter bytes properly is the caller's responsibility.
  158610. */
  158611. METHODDEF(void)
  158612. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  158613. /* Emit an arbitrary marker header */
  158614. {
  158615. if (datalen > (unsigned int) 65533) /* safety check */
  158616. ERREXIT(cinfo, JERR_BAD_LENGTH);
  158617. emit_marker(cinfo, (JPEG_MARKER) marker);
  158618. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  158619. }
  158620. METHODDEF(void)
  158621. write_marker_byte (j_compress_ptr cinfo, int val)
  158622. /* Emit one byte of marker parameters following write_marker_header */
  158623. {
  158624. emit_byte(cinfo, val);
  158625. }
  158626. /*
  158627. * Write datastream header.
  158628. * This consists of an SOI and optional APPn markers.
  158629. * We recommend use of the JFIF marker, but not the Adobe marker,
  158630. * when using YCbCr or grayscale data. The JFIF marker should NOT
  158631. * be used for any other JPEG colorspace. The Adobe marker is helpful
  158632. * to distinguish RGB, CMYK, and YCCK colorspaces.
  158633. * Note that an application can write additional header markers after
  158634. * jpeg_start_compress returns.
  158635. */
  158636. METHODDEF(void)
  158637. write_file_header (j_compress_ptr cinfo)
  158638. {
  158639. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  158640. emit_marker(cinfo, M_SOI); /* first the SOI */
  158641. /* SOI is defined to reset restart interval to 0 */
  158642. marker->last_restart_interval = 0;
  158643. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  158644. emit_jfif_app0(cinfo);
  158645. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  158646. emit_adobe_app14(cinfo);
  158647. }
  158648. /*
  158649. * Write frame header.
  158650. * This consists of DQT and SOFn markers.
  158651. * Note that we do not emit the SOF until we have emitted the DQT(s).
  158652. * This avoids compatibility problems with incorrect implementations that
  158653. * try to error-check the quant table numbers as soon as they see the SOF.
  158654. */
  158655. METHODDEF(void)
  158656. write_frame_header (j_compress_ptr cinfo)
  158657. {
  158658. int ci, prec;
  158659. boolean is_baseline;
  158660. jpeg_component_info *compptr;
  158661. /* Emit DQT for each quantization table.
  158662. * Note that emit_dqt() suppresses any duplicate tables.
  158663. */
  158664. prec = 0;
  158665. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158666. ci++, compptr++) {
  158667. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  158668. }
  158669. /* now prec is nonzero iff there are any 16-bit quant tables. */
  158670. /* Check for a non-baseline specification.
  158671. * Note we assume that Huffman table numbers won't be changed later.
  158672. */
  158673. if (cinfo->arith_code || cinfo->progressive_mode ||
  158674. cinfo->data_precision != 8) {
  158675. is_baseline = FALSE;
  158676. } else {
  158677. is_baseline = TRUE;
  158678. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158679. ci++, compptr++) {
  158680. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  158681. is_baseline = FALSE;
  158682. }
  158683. if (prec && is_baseline) {
  158684. is_baseline = FALSE;
  158685. /* If it's baseline except for quantizer size, warn the user */
  158686. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  158687. }
  158688. }
  158689. /* Emit the proper SOF marker */
  158690. if (cinfo->arith_code) {
  158691. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  158692. } else {
  158693. if (cinfo->progressive_mode)
  158694. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  158695. else if (is_baseline)
  158696. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  158697. else
  158698. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  158699. }
  158700. }
  158701. /*
  158702. * Write scan header.
  158703. * This consists of DHT or DAC markers, optional DRI, and SOS.
  158704. * Compressed data will be written following the SOS.
  158705. */
  158706. METHODDEF(void)
  158707. write_scan_header (j_compress_ptr cinfo)
  158708. {
  158709. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  158710. int i;
  158711. jpeg_component_info *compptr;
  158712. if (cinfo->arith_code) {
  158713. /* Emit arith conditioning info. We may have some duplication
  158714. * if the file has multiple scans, but it's so small it's hardly
  158715. * worth worrying about.
  158716. */
  158717. emit_dac(cinfo);
  158718. } else {
  158719. /* Emit Huffman tables.
  158720. * Note that emit_dht() suppresses any duplicate tables.
  158721. */
  158722. for (i = 0; i < cinfo->comps_in_scan; i++) {
  158723. compptr = cinfo->cur_comp_info[i];
  158724. if (cinfo->progressive_mode) {
  158725. /* Progressive mode: only DC or only AC tables are used in one scan */
  158726. if (cinfo->Ss == 0) {
  158727. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  158728. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  158729. } else {
  158730. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  158731. }
  158732. } else {
  158733. /* Sequential mode: need both DC and AC tables */
  158734. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  158735. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  158736. }
  158737. }
  158738. }
  158739. /* Emit DRI if required --- note that DRI value could change for each scan.
  158740. * We avoid wasting space with unnecessary DRIs, however.
  158741. */
  158742. if (cinfo->restart_interval != marker->last_restart_interval) {
  158743. emit_dri(cinfo);
  158744. marker->last_restart_interval = cinfo->restart_interval;
  158745. }
  158746. emit_sos(cinfo);
  158747. }
  158748. /*
  158749. * Write datastream trailer.
  158750. */
  158751. METHODDEF(void)
  158752. write_file_trailer (j_compress_ptr cinfo)
  158753. {
  158754. emit_marker(cinfo, M_EOI);
  158755. }
  158756. /*
  158757. * Write an abbreviated table-specification datastream.
  158758. * This consists of SOI, DQT and DHT tables, and EOI.
  158759. * Any table that is defined and not marked sent_table = TRUE will be
  158760. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  158761. */
  158762. METHODDEF(void)
  158763. write_tables_only (j_compress_ptr cinfo)
  158764. {
  158765. int i;
  158766. emit_marker(cinfo, M_SOI);
  158767. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  158768. if (cinfo->quant_tbl_ptrs[i] != NULL)
  158769. (void) emit_dqt(cinfo, i);
  158770. }
  158771. if (! cinfo->arith_code) {
  158772. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  158773. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  158774. emit_dht(cinfo, i, FALSE);
  158775. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  158776. emit_dht(cinfo, i, TRUE);
  158777. }
  158778. }
  158779. emit_marker(cinfo, M_EOI);
  158780. }
  158781. /*
  158782. * Initialize the marker writer module.
  158783. */
  158784. GLOBAL(void)
  158785. jinit_marker_writer (j_compress_ptr cinfo)
  158786. {
  158787. my_marker_ptr marker;
  158788. /* Create the subobject */
  158789. marker = (my_marker_ptr)
  158790. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158791. SIZEOF(my_marker_writer));
  158792. cinfo->marker = (struct jpeg_marker_writer *) marker;
  158793. /* Initialize method pointers */
  158794. marker->pub.write_file_header = write_file_header;
  158795. marker->pub.write_frame_header = write_frame_header;
  158796. marker->pub.write_scan_header = write_scan_header;
  158797. marker->pub.write_file_trailer = write_file_trailer;
  158798. marker->pub.write_tables_only = write_tables_only;
  158799. marker->pub.write_marker_header = write_marker_header;
  158800. marker->pub.write_marker_byte = write_marker_byte;
  158801. /* Initialize private state */
  158802. marker->last_restart_interval = 0;
  158803. }
  158804. /********* End of inlined file: jcmarker.c *********/
  158805. /********* Start of inlined file: jcmaster.c *********/
  158806. #define JPEG_INTERNALS
  158807. /* Private state */
  158808. typedef enum {
  158809. main_pass, /* input data, also do first output step */
  158810. huff_opt_pass, /* Huffman code optimization pass */
  158811. output_pass /* data output pass */
  158812. } c_pass_type;
  158813. typedef struct {
  158814. struct jpeg_comp_master pub; /* public fields */
  158815. c_pass_type pass_type; /* the type of the current pass */
  158816. int pass_number; /* # of passes completed */
  158817. int total_passes; /* total # of passes needed */
  158818. int scan_number; /* current index in scan_info[] */
  158819. } my_comp_master;
  158820. typedef my_comp_master * my_master_ptr;
  158821. /*
  158822. * Support routines that do various essential calculations.
  158823. */
  158824. LOCAL(void)
  158825. initial_setup (j_compress_ptr cinfo)
  158826. /* Do computations that are needed before master selection phase */
  158827. {
  158828. int ci;
  158829. jpeg_component_info *compptr;
  158830. long samplesperrow;
  158831. JDIMENSION jd_samplesperrow;
  158832. /* Sanity check on image dimensions */
  158833. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  158834. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  158835. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  158836. /* Make sure image isn't bigger than I can handle */
  158837. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  158838. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  158839. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  158840. /* Width of an input scanline must be representable as JDIMENSION. */
  158841. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  158842. jd_samplesperrow = (JDIMENSION) samplesperrow;
  158843. if ((long) jd_samplesperrow != samplesperrow)
  158844. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  158845. /* For now, precision must match compiled-in value... */
  158846. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  158847. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  158848. /* Check that number of components won't exceed internal array sizes */
  158849. if (cinfo->num_components > MAX_COMPONENTS)
  158850. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  158851. MAX_COMPONENTS);
  158852. /* Compute maximum sampling factors; check factor validity */
  158853. cinfo->max_h_samp_factor = 1;
  158854. cinfo->max_v_samp_factor = 1;
  158855. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158856. ci++, compptr++) {
  158857. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  158858. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  158859. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  158860. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  158861. compptr->h_samp_factor);
  158862. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  158863. compptr->v_samp_factor);
  158864. }
  158865. /* Compute dimensions of components */
  158866. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158867. ci++, compptr++) {
  158868. /* Fill in the correct component_index value; don't rely on application */
  158869. compptr->component_index = ci;
  158870. /* For compression, we never do DCT scaling. */
  158871. compptr->DCT_scaled_size = DCTSIZE;
  158872. /* Size in DCT blocks */
  158873. compptr->width_in_blocks = (JDIMENSION)
  158874. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  158875. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  158876. compptr->height_in_blocks = (JDIMENSION)
  158877. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  158878. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  158879. /* Size in samples */
  158880. compptr->downsampled_width = (JDIMENSION)
  158881. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  158882. (long) cinfo->max_h_samp_factor);
  158883. compptr->downsampled_height = (JDIMENSION)
  158884. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  158885. (long) cinfo->max_v_samp_factor);
  158886. /* Mark component needed (this flag isn't actually used for compression) */
  158887. compptr->component_needed = TRUE;
  158888. }
  158889. /* Compute number of fully interleaved MCU rows (number of times that
  158890. * main controller will call coefficient controller).
  158891. */
  158892. cinfo->total_iMCU_rows = (JDIMENSION)
  158893. jdiv_round_up((long) cinfo->image_height,
  158894. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  158895. }
  158896. #ifdef C_MULTISCAN_FILES_SUPPORTED
  158897. LOCAL(void)
  158898. validate_script (j_compress_ptr cinfo)
  158899. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  158900. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  158901. */
  158902. {
  158903. const jpeg_scan_info * scanptr;
  158904. int scanno, ncomps, ci, coefi, thisi;
  158905. int Ss, Se, Ah, Al;
  158906. boolean component_sent[MAX_COMPONENTS];
  158907. #ifdef C_PROGRESSIVE_SUPPORTED
  158908. int * last_bitpos_ptr;
  158909. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  158910. /* -1 until that coefficient has been seen; then last Al for it */
  158911. #endif
  158912. if (cinfo->num_scans <= 0)
  158913. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  158914. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  158915. * for progressive JPEG, no scan can have this.
  158916. */
  158917. scanptr = cinfo->scan_info;
  158918. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  158919. #ifdef C_PROGRESSIVE_SUPPORTED
  158920. cinfo->progressive_mode = TRUE;
  158921. last_bitpos_ptr = & last_bitpos[0][0];
  158922. for (ci = 0; ci < cinfo->num_components; ci++)
  158923. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  158924. *last_bitpos_ptr++ = -1;
  158925. #else
  158926. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158927. #endif
  158928. } else {
  158929. cinfo->progressive_mode = FALSE;
  158930. for (ci = 0; ci < cinfo->num_components; ci++)
  158931. component_sent[ci] = FALSE;
  158932. }
  158933. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  158934. /* Validate component indexes */
  158935. ncomps = scanptr->comps_in_scan;
  158936. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  158937. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  158938. for (ci = 0; ci < ncomps; ci++) {
  158939. thisi = scanptr->component_index[ci];
  158940. if (thisi < 0 || thisi >= cinfo->num_components)
  158941. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  158942. /* Components must appear in SOF order within each scan */
  158943. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  158944. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  158945. }
  158946. /* Validate progression parameters */
  158947. Ss = scanptr->Ss;
  158948. Se = scanptr->Se;
  158949. Ah = scanptr->Ah;
  158950. Al = scanptr->Al;
  158951. if (cinfo->progressive_mode) {
  158952. #ifdef C_PROGRESSIVE_SUPPORTED
  158953. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  158954. * seems wrong: the upper bound ought to depend on data precision.
  158955. * Perhaps they really meant 0..N+1 for N-bit precision.
  158956. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  158957. * out-of-range reconstructed DC values during the first DC scan,
  158958. * which might cause problems for some decoders.
  158959. */
  158960. #if BITS_IN_JSAMPLE == 8
  158961. #define MAX_AH_AL 10
  158962. #else
  158963. #define MAX_AH_AL 13
  158964. #endif
  158965. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  158966. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  158967. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158968. if (Ss == 0) {
  158969. if (Se != 0) /* DC and AC together not OK */
  158970. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158971. } else {
  158972. if (ncomps != 1) /* AC scans must be for only one component */
  158973. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158974. }
  158975. for (ci = 0; ci < ncomps; ci++) {
  158976. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  158977. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  158978. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158979. for (coefi = Ss; coefi <= Se; coefi++) {
  158980. if (last_bitpos_ptr[coefi] < 0) {
  158981. /* first scan of this coefficient */
  158982. if (Ah != 0)
  158983. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158984. } else {
  158985. /* not first scan */
  158986. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  158987. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158988. }
  158989. last_bitpos_ptr[coefi] = Al;
  158990. }
  158991. }
  158992. #endif
  158993. } else {
  158994. /* For sequential JPEG, all progression parameters must be these: */
  158995. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  158996. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158997. /* Make sure components are not sent twice */
  158998. for (ci = 0; ci < ncomps; ci++) {
  158999. thisi = scanptr->component_index[ci];
  159000. if (component_sent[thisi])
  159001. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  159002. component_sent[thisi] = TRUE;
  159003. }
  159004. }
  159005. }
  159006. /* Now verify that everything got sent. */
  159007. if (cinfo->progressive_mode) {
  159008. #ifdef C_PROGRESSIVE_SUPPORTED
  159009. /* For progressive mode, we only check that at least some DC data
  159010. * got sent for each component; the spec does not require that all bits
  159011. * of all coefficients be transmitted. Would it be wiser to enforce
  159012. * transmission of all coefficient bits??
  159013. */
  159014. for (ci = 0; ci < cinfo->num_components; ci++) {
  159015. if (last_bitpos[ci][0] < 0)
  159016. ERREXIT(cinfo, JERR_MISSING_DATA);
  159017. }
  159018. #endif
  159019. } else {
  159020. for (ci = 0; ci < cinfo->num_components; ci++) {
  159021. if (! component_sent[ci])
  159022. ERREXIT(cinfo, JERR_MISSING_DATA);
  159023. }
  159024. }
  159025. }
  159026. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  159027. LOCAL(void)
  159028. select_scan_parameters (j_compress_ptr cinfo)
  159029. /* Set up the scan parameters for the current scan */
  159030. {
  159031. int ci;
  159032. #ifdef C_MULTISCAN_FILES_SUPPORTED
  159033. if (cinfo->scan_info != NULL) {
  159034. /* Prepare for current scan --- the script is already validated */
  159035. my_master_ptr master = (my_master_ptr) cinfo->master;
  159036. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  159037. cinfo->comps_in_scan = scanptr->comps_in_scan;
  159038. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  159039. cinfo->cur_comp_info[ci] =
  159040. &cinfo->comp_info[scanptr->component_index[ci]];
  159041. }
  159042. cinfo->Ss = scanptr->Ss;
  159043. cinfo->Se = scanptr->Se;
  159044. cinfo->Ah = scanptr->Ah;
  159045. cinfo->Al = scanptr->Al;
  159046. }
  159047. else
  159048. #endif
  159049. {
  159050. /* Prepare for single sequential-JPEG scan containing all components */
  159051. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  159052. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  159053. MAX_COMPS_IN_SCAN);
  159054. cinfo->comps_in_scan = cinfo->num_components;
  159055. for (ci = 0; ci < cinfo->num_components; ci++) {
  159056. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  159057. }
  159058. cinfo->Ss = 0;
  159059. cinfo->Se = DCTSIZE2-1;
  159060. cinfo->Ah = 0;
  159061. cinfo->Al = 0;
  159062. }
  159063. }
  159064. LOCAL(void)
  159065. per_scan_setup (j_compress_ptr cinfo)
  159066. /* Do computations that are needed before processing a JPEG scan */
  159067. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  159068. {
  159069. int ci, mcublks, tmp;
  159070. jpeg_component_info *compptr;
  159071. if (cinfo->comps_in_scan == 1) {
  159072. /* Noninterleaved (single-component) scan */
  159073. compptr = cinfo->cur_comp_info[0];
  159074. /* Overall image size in MCUs */
  159075. cinfo->MCUs_per_row = compptr->width_in_blocks;
  159076. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  159077. /* For noninterleaved scan, always one block per MCU */
  159078. compptr->MCU_width = 1;
  159079. compptr->MCU_height = 1;
  159080. compptr->MCU_blocks = 1;
  159081. compptr->MCU_sample_width = DCTSIZE;
  159082. compptr->last_col_width = 1;
  159083. /* For noninterleaved scans, it is convenient to define last_row_height
  159084. * as the number of block rows present in the last iMCU row.
  159085. */
  159086. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  159087. if (tmp == 0) tmp = compptr->v_samp_factor;
  159088. compptr->last_row_height = tmp;
  159089. /* Prepare array describing MCU composition */
  159090. cinfo->blocks_in_MCU = 1;
  159091. cinfo->MCU_membership[0] = 0;
  159092. } else {
  159093. /* Interleaved (multi-component) scan */
  159094. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  159095. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  159096. MAX_COMPS_IN_SCAN);
  159097. /* Overall image size in MCUs */
  159098. cinfo->MCUs_per_row = (JDIMENSION)
  159099. jdiv_round_up((long) cinfo->image_width,
  159100. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  159101. cinfo->MCU_rows_in_scan = (JDIMENSION)
  159102. jdiv_round_up((long) cinfo->image_height,
  159103. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  159104. cinfo->blocks_in_MCU = 0;
  159105. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159106. compptr = cinfo->cur_comp_info[ci];
  159107. /* Sampling factors give # of blocks of component in each MCU */
  159108. compptr->MCU_width = compptr->h_samp_factor;
  159109. compptr->MCU_height = compptr->v_samp_factor;
  159110. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  159111. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  159112. /* Figure number of non-dummy blocks in last MCU column & row */
  159113. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  159114. if (tmp == 0) tmp = compptr->MCU_width;
  159115. compptr->last_col_width = tmp;
  159116. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  159117. if (tmp == 0) tmp = compptr->MCU_height;
  159118. compptr->last_row_height = tmp;
  159119. /* Prepare array describing MCU composition */
  159120. mcublks = compptr->MCU_blocks;
  159121. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  159122. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  159123. while (mcublks-- > 0) {
  159124. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  159125. }
  159126. }
  159127. }
  159128. /* Convert restart specified in rows to actual MCU count. */
  159129. /* Note that count must fit in 16 bits, so we provide limiting. */
  159130. if (cinfo->restart_in_rows > 0) {
  159131. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  159132. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  159133. }
  159134. }
  159135. /*
  159136. * Per-pass setup.
  159137. * This is called at the beginning of each pass. We determine which modules
  159138. * will be active during this pass and give them appropriate start_pass calls.
  159139. * We also set is_last_pass to indicate whether any more passes will be
  159140. * required.
  159141. */
  159142. METHODDEF(void)
  159143. prepare_for_pass (j_compress_ptr cinfo)
  159144. {
  159145. my_master_ptr master = (my_master_ptr) cinfo->master;
  159146. switch (master->pass_type) {
  159147. case main_pass:
  159148. /* Initial pass: will collect input data, and do either Huffman
  159149. * optimization or data output for the first scan.
  159150. */
  159151. select_scan_parameters(cinfo);
  159152. per_scan_setup(cinfo);
  159153. if (! cinfo->raw_data_in) {
  159154. (*cinfo->cconvert->start_pass) (cinfo);
  159155. (*cinfo->downsample->start_pass) (cinfo);
  159156. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  159157. }
  159158. (*cinfo->fdct->start_pass) (cinfo);
  159159. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  159160. (*cinfo->coef->start_pass) (cinfo,
  159161. (master->total_passes > 1 ?
  159162. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  159163. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  159164. if (cinfo->optimize_coding) {
  159165. /* No immediate data output; postpone writing frame/scan headers */
  159166. master->pub.call_pass_startup = FALSE;
  159167. } else {
  159168. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  159169. master->pub.call_pass_startup = TRUE;
  159170. }
  159171. break;
  159172. #ifdef ENTROPY_OPT_SUPPORTED
  159173. case huff_opt_pass:
  159174. /* Do Huffman optimization for a scan after the first one. */
  159175. select_scan_parameters(cinfo);
  159176. per_scan_setup(cinfo);
  159177. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  159178. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  159179. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  159180. master->pub.call_pass_startup = FALSE;
  159181. break;
  159182. }
  159183. /* Special case: Huffman DC refinement scans need no Huffman table
  159184. * and therefore we can skip the optimization pass for them.
  159185. */
  159186. master->pass_type = output_pass;
  159187. master->pass_number++;
  159188. /*FALLTHROUGH*/
  159189. #endif
  159190. case output_pass:
  159191. /* Do a data-output pass. */
  159192. /* We need not repeat per-scan setup if prior optimization pass did it. */
  159193. if (! cinfo->optimize_coding) {
  159194. select_scan_parameters(cinfo);
  159195. per_scan_setup(cinfo);
  159196. }
  159197. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  159198. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  159199. /* We emit frame/scan headers now */
  159200. if (master->scan_number == 0)
  159201. (*cinfo->marker->write_frame_header) (cinfo);
  159202. (*cinfo->marker->write_scan_header) (cinfo);
  159203. master->pub.call_pass_startup = FALSE;
  159204. break;
  159205. default:
  159206. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159207. }
  159208. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  159209. /* Set up progress monitor's pass info if present */
  159210. if (cinfo->progress != NULL) {
  159211. cinfo->progress->completed_passes = master->pass_number;
  159212. cinfo->progress->total_passes = master->total_passes;
  159213. }
  159214. }
  159215. /*
  159216. * Special start-of-pass hook.
  159217. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  159218. * In single-pass processing, we need this hook because we don't want to
  159219. * write frame/scan headers during jpeg_start_compress; we want to let the
  159220. * application write COM markers etc. between jpeg_start_compress and the
  159221. * jpeg_write_scanlines loop.
  159222. * In multi-pass processing, this routine is not used.
  159223. */
  159224. METHODDEF(void)
  159225. pass_startup (j_compress_ptr cinfo)
  159226. {
  159227. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  159228. (*cinfo->marker->write_frame_header) (cinfo);
  159229. (*cinfo->marker->write_scan_header) (cinfo);
  159230. }
  159231. /*
  159232. * Finish up at end of pass.
  159233. */
  159234. METHODDEF(void)
  159235. finish_pass_master (j_compress_ptr cinfo)
  159236. {
  159237. my_master_ptr master = (my_master_ptr) cinfo->master;
  159238. /* The entropy coder always needs an end-of-pass call,
  159239. * either to analyze statistics or to flush its output buffer.
  159240. */
  159241. (*cinfo->entropy->finish_pass) (cinfo);
  159242. /* Update state for next pass */
  159243. switch (master->pass_type) {
  159244. case main_pass:
  159245. /* next pass is either output of scan 0 (after optimization)
  159246. * or output of scan 1 (if no optimization).
  159247. */
  159248. master->pass_type = output_pass;
  159249. if (! cinfo->optimize_coding)
  159250. master->scan_number++;
  159251. break;
  159252. case huff_opt_pass:
  159253. /* next pass is always output of current scan */
  159254. master->pass_type = output_pass;
  159255. break;
  159256. case output_pass:
  159257. /* next pass is either optimization or output of next scan */
  159258. if (cinfo->optimize_coding)
  159259. master->pass_type = huff_opt_pass;
  159260. master->scan_number++;
  159261. break;
  159262. }
  159263. master->pass_number++;
  159264. }
  159265. /*
  159266. * Initialize master compression control.
  159267. */
  159268. GLOBAL(void)
  159269. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  159270. {
  159271. my_master_ptr master;
  159272. master = (my_master_ptr)
  159273. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159274. SIZEOF(my_comp_master));
  159275. cinfo->master = (struct jpeg_comp_master *) master;
  159276. master->pub.prepare_for_pass = prepare_for_pass;
  159277. master->pub.pass_startup = pass_startup;
  159278. master->pub.finish_pass = finish_pass_master;
  159279. master->pub.is_last_pass = FALSE;
  159280. /* Validate parameters, determine derived values */
  159281. initial_setup(cinfo);
  159282. if (cinfo->scan_info != NULL) {
  159283. #ifdef C_MULTISCAN_FILES_SUPPORTED
  159284. validate_script(cinfo);
  159285. #else
  159286. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159287. #endif
  159288. } else {
  159289. cinfo->progressive_mode = FALSE;
  159290. cinfo->num_scans = 1;
  159291. }
  159292. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  159293. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  159294. /* Initialize my private state */
  159295. if (transcode_only) {
  159296. /* no main pass in transcoding */
  159297. if (cinfo->optimize_coding)
  159298. master->pass_type = huff_opt_pass;
  159299. else
  159300. master->pass_type = output_pass;
  159301. } else {
  159302. /* for normal compression, first pass is always this type: */
  159303. master->pass_type = main_pass;
  159304. }
  159305. master->scan_number = 0;
  159306. master->pass_number = 0;
  159307. if (cinfo->optimize_coding)
  159308. master->total_passes = cinfo->num_scans * 2;
  159309. else
  159310. master->total_passes = cinfo->num_scans;
  159311. }
  159312. /********* End of inlined file: jcmaster.c *********/
  159313. /********* Start of inlined file: jcomapi.c *********/
  159314. #define JPEG_INTERNALS
  159315. /*
  159316. * Abort processing of a JPEG compression or decompression operation,
  159317. * but don't destroy the object itself.
  159318. *
  159319. * For this, we merely clean up all the nonpermanent memory pools.
  159320. * Note that temp files (virtual arrays) are not allowed to belong to
  159321. * the permanent pool, so we will be able to close all temp files here.
  159322. * Closing a data source or destination, if necessary, is the application's
  159323. * responsibility.
  159324. */
  159325. GLOBAL(void)
  159326. jpeg_abort (j_common_ptr cinfo)
  159327. {
  159328. int pool;
  159329. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  159330. if (cinfo->mem == NULL)
  159331. return;
  159332. /* Releasing pools in reverse order might help avoid fragmentation
  159333. * with some (brain-damaged) malloc libraries.
  159334. */
  159335. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  159336. (*cinfo->mem->free_pool) (cinfo, pool);
  159337. }
  159338. /* Reset overall state for possible reuse of object */
  159339. if (cinfo->is_decompressor) {
  159340. cinfo->global_state = DSTATE_START;
  159341. /* Try to keep application from accessing now-deleted marker list.
  159342. * A bit kludgy to do it here, but this is the most central place.
  159343. */
  159344. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  159345. } else {
  159346. cinfo->global_state = CSTATE_START;
  159347. }
  159348. }
  159349. /*
  159350. * Destruction of a JPEG object.
  159351. *
  159352. * Everything gets deallocated except the master jpeg_compress_struct itself
  159353. * and the error manager struct. Both of these are supplied by the application
  159354. * and must be freed, if necessary, by the application. (Often they are on
  159355. * the stack and so don't need to be freed anyway.)
  159356. * Closing a data source or destination, if necessary, is the application's
  159357. * responsibility.
  159358. */
  159359. GLOBAL(void)
  159360. jpeg_destroy (j_common_ptr cinfo)
  159361. {
  159362. /* We need only tell the memory manager to release everything. */
  159363. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  159364. if (cinfo->mem != NULL)
  159365. (*cinfo->mem->self_destruct) (cinfo);
  159366. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  159367. cinfo->global_state = 0; /* mark it destroyed */
  159368. }
  159369. /*
  159370. * Convenience routines for allocating quantization and Huffman tables.
  159371. * (Would jutils.c be a more reasonable place to put these?)
  159372. */
  159373. GLOBAL(JQUANT_TBL *)
  159374. jpeg_alloc_quant_table (j_common_ptr cinfo)
  159375. {
  159376. JQUANT_TBL *tbl;
  159377. tbl = (JQUANT_TBL *)
  159378. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  159379. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  159380. return tbl;
  159381. }
  159382. GLOBAL(JHUFF_TBL *)
  159383. jpeg_alloc_huff_table (j_common_ptr cinfo)
  159384. {
  159385. JHUFF_TBL *tbl;
  159386. tbl = (JHUFF_TBL *)
  159387. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  159388. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  159389. return tbl;
  159390. }
  159391. /********* End of inlined file: jcomapi.c *********/
  159392. /********* Start of inlined file: jcparam.c *********/
  159393. #define JPEG_INTERNALS
  159394. /*
  159395. * Quantization table setup routines
  159396. */
  159397. GLOBAL(void)
  159398. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  159399. const unsigned int *basic_table,
  159400. int scale_factor, boolean force_baseline)
  159401. /* Define a quantization table equal to the basic_table times
  159402. * a scale factor (given as a percentage).
  159403. * If force_baseline is TRUE, the computed quantization table entries
  159404. * are limited to 1..255 for JPEG baseline compatibility.
  159405. */
  159406. {
  159407. JQUANT_TBL ** qtblptr;
  159408. int i;
  159409. long temp;
  159410. /* Safety check to ensure start_compress not called yet. */
  159411. if (cinfo->global_state != CSTATE_START)
  159412. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  159413. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  159414. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  159415. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  159416. if (*qtblptr == NULL)
  159417. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  159418. for (i = 0; i < DCTSIZE2; i++) {
  159419. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  159420. /* limit the values to the valid range */
  159421. if (temp <= 0L) temp = 1L;
  159422. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  159423. if (force_baseline && temp > 255L)
  159424. temp = 255L; /* limit to baseline range if requested */
  159425. (*qtblptr)->quantval[i] = (UINT16) temp;
  159426. }
  159427. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  159428. (*qtblptr)->sent_table = FALSE;
  159429. }
  159430. GLOBAL(void)
  159431. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  159432. boolean force_baseline)
  159433. /* Set or change the 'quality' (quantization) setting, using default tables
  159434. * and a straight percentage-scaling quality scale. In most cases it's better
  159435. * to use jpeg_set_quality (below); this entry point is provided for
  159436. * applications that insist on a linear percentage scaling.
  159437. */
  159438. {
  159439. /* These are the sample quantization tables given in JPEG spec section K.1.
  159440. * The spec says that the values given produce "good" quality, and
  159441. * when divided by 2, "very good" quality.
  159442. */
  159443. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  159444. 16, 11, 10, 16, 24, 40, 51, 61,
  159445. 12, 12, 14, 19, 26, 58, 60, 55,
  159446. 14, 13, 16, 24, 40, 57, 69, 56,
  159447. 14, 17, 22, 29, 51, 87, 80, 62,
  159448. 18, 22, 37, 56, 68, 109, 103, 77,
  159449. 24, 35, 55, 64, 81, 104, 113, 92,
  159450. 49, 64, 78, 87, 103, 121, 120, 101,
  159451. 72, 92, 95, 98, 112, 100, 103, 99
  159452. };
  159453. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  159454. 17, 18, 24, 47, 99, 99, 99, 99,
  159455. 18, 21, 26, 66, 99, 99, 99, 99,
  159456. 24, 26, 56, 99, 99, 99, 99, 99,
  159457. 47, 66, 99, 99, 99, 99, 99, 99,
  159458. 99, 99, 99, 99, 99, 99, 99, 99,
  159459. 99, 99, 99, 99, 99, 99, 99, 99,
  159460. 99, 99, 99, 99, 99, 99, 99, 99,
  159461. 99, 99, 99, 99, 99, 99, 99, 99
  159462. };
  159463. /* Set up two quantization tables using the specified scaling */
  159464. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  159465. scale_factor, force_baseline);
  159466. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  159467. scale_factor, force_baseline);
  159468. }
  159469. GLOBAL(int)
  159470. jpeg_quality_scaling (int quality)
  159471. /* Convert a user-specified quality rating to a percentage scaling factor
  159472. * for an underlying quantization table, using our recommended scaling curve.
  159473. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  159474. */
  159475. {
  159476. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  159477. if (quality <= 0) quality = 1;
  159478. if (quality > 100) quality = 100;
  159479. /* The basic table is used as-is (scaling 100) for a quality of 50.
  159480. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  159481. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  159482. * to make all the table entries 1 (hence, minimum quantization loss).
  159483. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  159484. */
  159485. if (quality < 50)
  159486. quality = 5000 / quality;
  159487. else
  159488. quality = 200 - quality*2;
  159489. return quality;
  159490. }
  159491. GLOBAL(void)
  159492. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  159493. /* Set or change the 'quality' (quantization) setting, using default tables.
  159494. * This is the standard quality-adjusting entry point for typical user
  159495. * interfaces; only those who want detailed control over quantization tables
  159496. * would use the preceding three routines directly.
  159497. */
  159498. {
  159499. /* Convert user 0-100 rating to percentage scaling */
  159500. quality = jpeg_quality_scaling(quality);
  159501. /* Set up standard quality tables */
  159502. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  159503. }
  159504. /*
  159505. * Huffman table setup routines
  159506. */
  159507. LOCAL(void)
  159508. add_huff_table (j_compress_ptr cinfo,
  159509. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  159510. /* Define a Huffman table */
  159511. {
  159512. int nsymbols, len;
  159513. if (*htblptr == NULL)
  159514. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  159515. /* Copy the number-of-symbols-of-each-code-length counts */
  159516. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  159517. /* Validate the counts. We do this here mainly so we can copy the right
  159518. * number of symbols from the val[] array, without risking marching off
  159519. * the end of memory. jchuff.c will do a more thorough test later.
  159520. */
  159521. nsymbols = 0;
  159522. for (len = 1; len <= 16; len++)
  159523. nsymbols += bits[len];
  159524. if (nsymbols < 1 || nsymbols > 256)
  159525. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  159526. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  159527. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  159528. (*htblptr)->sent_table = FALSE;
  159529. }
  159530. LOCAL(void)
  159531. std_huff_tables (j_compress_ptr cinfo)
  159532. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  159533. /* IMPORTANT: these are only valid for 8-bit data precision! */
  159534. {
  159535. static const UINT8 bits_dc_luminance[17] =
  159536. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  159537. static const UINT8 val_dc_luminance[] =
  159538. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  159539. static const UINT8 bits_dc_chrominance[17] =
  159540. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  159541. static const UINT8 val_dc_chrominance[] =
  159542. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  159543. static const UINT8 bits_ac_luminance[17] =
  159544. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  159545. static const UINT8 val_ac_luminance[] =
  159546. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  159547. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  159548. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  159549. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  159550. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  159551. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  159552. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  159553. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  159554. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  159555. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  159556. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  159557. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  159558. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  159559. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  159560. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  159561. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  159562. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  159563. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  159564. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  159565. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  159566. 0xf9, 0xfa };
  159567. static const UINT8 bits_ac_chrominance[17] =
  159568. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  159569. static const UINT8 val_ac_chrominance[] =
  159570. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  159571. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  159572. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  159573. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  159574. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  159575. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  159576. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  159577. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  159578. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  159579. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  159580. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  159581. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  159582. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  159583. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  159584. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  159585. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  159586. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  159587. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  159588. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  159589. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  159590. 0xf9, 0xfa };
  159591. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  159592. bits_dc_luminance, val_dc_luminance);
  159593. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  159594. bits_ac_luminance, val_ac_luminance);
  159595. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  159596. bits_dc_chrominance, val_dc_chrominance);
  159597. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  159598. bits_ac_chrominance, val_ac_chrominance);
  159599. }
  159600. /*
  159601. * Default parameter setup for compression.
  159602. *
  159603. * Applications that don't choose to use this routine must do their
  159604. * own setup of all these parameters. Alternately, you can call this
  159605. * to establish defaults and then alter parameters selectively. This
  159606. * is the recommended approach since, if we add any new parameters,
  159607. * your code will still work (they'll be set to reasonable defaults).
  159608. */
  159609. GLOBAL(void)
  159610. jpeg_set_defaults (j_compress_ptr cinfo)
  159611. {
  159612. int i;
  159613. /* Safety check to ensure start_compress not called yet. */
  159614. if (cinfo->global_state != CSTATE_START)
  159615. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  159616. /* Allocate comp_info array large enough for maximum component count.
  159617. * Array is made permanent in case application wants to compress
  159618. * multiple images at same param settings.
  159619. */
  159620. if (cinfo->comp_info == NULL)
  159621. cinfo->comp_info = (jpeg_component_info *)
  159622. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  159623. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  159624. /* Initialize everything not dependent on the color space */
  159625. cinfo->data_precision = BITS_IN_JSAMPLE;
  159626. /* Set up two quantization tables using default quality of 75 */
  159627. jpeg_set_quality(cinfo, 75, TRUE);
  159628. /* Set up two Huffman tables */
  159629. std_huff_tables(cinfo);
  159630. /* Initialize default arithmetic coding conditioning */
  159631. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  159632. cinfo->arith_dc_L[i] = 0;
  159633. cinfo->arith_dc_U[i] = 1;
  159634. cinfo->arith_ac_K[i] = 5;
  159635. }
  159636. /* Default is no multiple-scan output */
  159637. cinfo->scan_info = NULL;
  159638. cinfo->num_scans = 0;
  159639. /* Expect normal source image, not raw downsampled data */
  159640. cinfo->raw_data_in = FALSE;
  159641. /* Use Huffman coding, not arithmetic coding, by default */
  159642. cinfo->arith_code = FALSE;
  159643. /* By default, don't do extra passes to optimize entropy coding */
  159644. cinfo->optimize_coding = FALSE;
  159645. /* The standard Huffman tables are only valid for 8-bit data precision.
  159646. * If the precision is higher, force optimization on so that usable
  159647. * tables will be computed. This test can be removed if default tables
  159648. * are supplied that are valid for the desired precision.
  159649. */
  159650. if (cinfo->data_precision > 8)
  159651. cinfo->optimize_coding = TRUE;
  159652. /* By default, use the simpler non-cosited sampling alignment */
  159653. cinfo->CCIR601_sampling = FALSE;
  159654. /* No input smoothing */
  159655. cinfo->smoothing_factor = 0;
  159656. /* DCT algorithm preference */
  159657. cinfo->dct_method = JDCT_DEFAULT;
  159658. /* No restart markers */
  159659. cinfo->restart_interval = 0;
  159660. cinfo->restart_in_rows = 0;
  159661. /* Fill in default JFIF marker parameters. Note that whether the marker
  159662. * will actually be written is determined by jpeg_set_colorspace.
  159663. *
  159664. * By default, the library emits JFIF version code 1.01.
  159665. * An application that wants to emit JFIF 1.02 extension markers should set
  159666. * JFIF_minor_version to 2. We could probably get away with just defaulting
  159667. * to 1.02, but there may still be some decoders in use that will complain
  159668. * about that; saying 1.01 should minimize compatibility problems.
  159669. */
  159670. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  159671. cinfo->JFIF_minor_version = 1;
  159672. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  159673. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  159674. cinfo->Y_density = 1;
  159675. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  159676. jpeg_default_colorspace(cinfo);
  159677. }
  159678. /*
  159679. * Select an appropriate JPEG colorspace for in_color_space.
  159680. */
  159681. GLOBAL(void)
  159682. jpeg_default_colorspace (j_compress_ptr cinfo)
  159683. {
  159684. switch (cinfo->in_color_space) {
  159685. case JCS_GRAYSCALE:
  159686. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  159687. break;
  159688. case JCS_RGB:
  159689. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  159690. break;
  159691. case JCS_YCbCr:
  159692. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  159693. break;
  159694. case JCS_CMYK:
  159695. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  159696. break;
  159697. case JCS_YCCK:
  159698. jpeg_set_colorspace(cinfo, JCS_YCCK);
  159699. break;
  159700. case JCS_UNKNOWN:
  159701. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  159702. break;
  159703. default:
  159704. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  159705. }
  159706. }
  159707. /*
  159708. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  159709. */
  159710. GLOBAL(void)
  159711. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  159712. {
  159713. jpeg_component_info * compptr;
  159714. int ci;
  159715. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  159716. (compptr = &cinfo->comp_info[index], \
  159717. compptr->component_id = (id), \
  159718. compptr->h_samp_factor = (hsamp), \
  159719. compptr->v_samp_factor = (vsamp), \
  159720. compptr->quant_tbl_no = (quant), \
  159721. compptr->dc_tbl_no = (dctbl), \
  159722. compptr->ac_tbl_no = (actbl) )
  159723. /* Safety check to ensure start_compress not called yet. */
  159724. if (cinfo->global_state != CSTATE_START)
  159725. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  159726. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  159727. * tables 1 for chrominance components.
  159728. */
  159729. cinfo->jpeg_color_space = colorspace;
  159730. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  159731. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  159732. switch (colorspace) {
  159733. case JCS_GRAYSCALE:
  159734. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  159735. cinfo->num_components = 1;
  159736. /* JFIF specifies component ID 1 */
  159737. SET_COMP(0, 1, 1,1, 0, 0,0);
  159738. break;
  159739. case JCS_RGB:
  159740. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  159741. cinfo->num_components = 3;
  159742. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  159743. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  159744. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  159745. break;
  159746. case JCS_YCbCr:
  159747. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  159748. cinfo->num_components = 3;
  159749. /* JFIF specifies component IDs 1,2,3 */
  159750. /* We default to 2x2 subsamples of chrominance */
  159751. SET_COMP(0, 1, 2,2, 0, 0,0);
  159752. SET_COMP(1, 2, 1,1, 1, 1,1);
  159753. SET_COMP(2, 3, 1,1, 1, 1,1);
  159754. break;
  159755. case JCS_CMYK:
  159756. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  159757. cinfo->num_components = 4;
  159758. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  159759. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  159760. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  159761. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  159762. break;
  159763. case JCS_YCCK:
  159764. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  159765. cinfo->num_components = 4;
  159766. SET_COMP(0, 1, 2,2, 0, 0,0);
  159767. SET_COMP(1, 2, 1,1, 1, 1,1);
  159768. SET_COMP(2, 3, 1,1, 1, 1,1);
  159769. SET_COMP(3, 4, 2,2, 0, 0,0);
  159770. break;
  159771. case JCS_UNKNOWN:
  159772. cinfo->num_components = cinfo->input_components;
  159773. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  159774. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  159775. MAX_COMPONENTS);
  159776. for (ci = 0; ci < cinfo->num_components; ci++) {
  159777. SET_COMP(ci, ci, 1,1, 0, 0,0);
  159778. }
  159779. break;
  159780. default:
  159781. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  159782. }
  159783. }
  159784. #ifdef C_PROGRESSIVE_SUPPORTED
  159785. LOCAL(jpeg_scan_info *)
  159786. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  159787. int Ss, int Se, int Ah, int Al)
  159788. /* Support routine: generate one scan for specified component */
  159789. {
  159790. scanptr->comps_in_scan = 1;
  159791. scanptr->component_index[0] = ci;
  159792. scanptr->Ss = Ss;
  159793. scanptr->Se = Se;
  159794. scanptr->Ah = Ah;
  159795. scanptr->Al = Al;
  159796. scanptr++;
  159797. return scanptr;
  159798. }
  159799. LOCAL(jpeg_scan_info *)
  159800. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  159801. int Ss, int Se, int Ah, int Al)
  159802. /* Support routine: generate one scan for each component */
  159803. {
  159804. int ci;
  159805. for (ci = 0; ci < ncomps; ci++) {
  159806. scanptr->comps_in_scan = 1;
  159807. scanptr->component_index[0] = ci;
  159808. scanptr->Ss = Ss;
  159809. scanptr->Se = Se;
  159810. scanptr->Ah = Ah;
  159811. scanptr->Al = Al;
  159812. scanptr++;
  159813. }
  159814. return scanptr;
  159815. }
  159816. LOCAL(jpeg_scan_info *)
  159817. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  159818. /* Support routine: generate interleaved DC scan if possible, else N scans */
  159819. {
  159820. int ci;
  159821. if (ncomps <= MAX_COMPS_IN_SCAN) {
  159822. /* Single interleaved DC scan */
  159823. scanptr->comps_in_scan = ncomps;
  159824. for (ci = 0; ci < ncomps; ci++)
  159825. scanptr->component_index[ci] = ci;
  159826. scanptr->Ss = scanptr->Se = 0;
  159827. scanptr->Ah = Ah;
  159828. scanptr->Al = Al;
  159829. scanptr++;
  159830. } else {
  159831. /* Noninterleaved DC scan for each component */
  159832. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  159833. }
  159834. return scanptr;
  159835. }
  159836. /*
  159837. * Create a recommended progressive-JPEG script.
  159838. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  159839. */
  159840. GLOBAL(void)
  159841. jpeg_simple_progression (j_compress_ptr cinfo)
  159842. {
  159843. int ncomps = cinfo->num_components;
  159844. int nscans;
  159845. jpeg_scan_info * scanptr;
  159846. /* Safety check to ensure start_compress not called yet. */
  159847. if (cinfo->global_state != CSTATE_START)
  159848. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  159849. /* Figure space needed for script. Calculation must match code below! */
  159850. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  159851. /* Custom script for YCbCr color images. */
  159852. nscans = 10;
  159853. } else {
  159854. /* All-purpose script for other color spaces. */
  159855. if (ncomps > MAX_COMPS_IN_SCAN)
  159856. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  159857. else
  159858. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  159859. }
  159860. /* Allocate space for script.
  159861. * We need to put it in the permanent pool in case the application performs
  159862. * multiple compressions without changing the settings. To avoid a memory
  159863. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  159864. * object, we try to re-use previously allocated space, and we allocate
  159865. * enough space to handle YCbCr even if initially asked for grayscale.
  159866. */
  159867. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  159868. cinfo->script_space_size = MAX(nscans, 10);
  159869. cinfo->script_space = (jpeg_scan_info *)
  159870. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  159871. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  159872. }
  159873. scanptr = cinfo->script_space;
  159874. cinfo->scan_info = scanptr;
  159875. cinfo->num_scans = nscans;
  159876. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  159877. /* Custom script for YCbCr color images. */
  159878. /* Initial DC scan */
  159879. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  159880. /* Initial AC scan: get some luma data out in a hurry */
  159881. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  159882. /* Chroma data is too small to be worth expending many scans on */
  159883. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  159884. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  159885. /* Complete spectral selection for luma AC */
  159886. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  159887. /* Refine next bit of luma AC */
  159888. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  159889. /* Finish DC successive approximation */
  159890. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  159891. /* Finish AC successive approximation */
  159892. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  159893. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  159894. /* Luma bottom bit comes last since it's usually largest scan */
  159895. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  159896. } else {
  159897. /* All-purpose script for other color spaces. */
  159898. /* Successive approximation first pass */
  159899. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  159900. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  159901. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  159902. /* Successive approximation second pass */
  159903. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  159904. /* Successive approximation final pass */
  159905. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  159906. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  159907. }
  159908. }
  159909. #endif /* C_PROGRESSIVE_SUPPORTED */
  159910. /********* End of inlined file: jcparam.c *********/
  159911. /********* Start of inlined file: jcphuff.c *********/
  159912. #define JPEG_INTERNALS
  159913. #ifdef C_PROGRESSIVE_SUPPORTED
  159914. /* Expanded entropy encoder object for progressive Huffman encoding. */
  159915. typedef struct {
  159916. struct jpeg_entropy_encoder pub; /* public fields */
  159917. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  159918. boolean gather_statistics;
  159919. /* Bit-level coding status.
  159920. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  159921. */
  159922. JOCTET * next_output_byte; /* => next byte to write in buffer */
  159923. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  159924. INT32 put_buffer; /* current bit-accumulation buffer */
  159925. int put_bits; /* # of bits now in it */
  159926. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  159927. /* Coding status for DC components */
  159928. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  159929. /* Coding status for AC components */
  159930. int ac_tbl_no; /* the table number of the single component */
  159931. unsigned int EOBRUN; /* run length of EOBs */
  159932. unsigned int BE; /* # of buffered correction bits before MCU */
  159933. char * bit_buffer; /* buffer for correction bits (1 per char) */
  159934. /* packing correction bits tightly would save some space but cost time... */
  159935. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  159936. int next_restart_num; /* next restart number to write (0-7) */
  159937. /* Pointers to derived tables (these workspaces have image lifespan).
  159938. * Since any one scan codes only DC or only AC, we only need one set
  159939. * of tables, not one for DC and one for AC.
  159940. */
  159941. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  159942. /* Statistics tables for optimization; again, one set is enough */
  159943. long * count_ptrs[NUM_HUFF_TBLS];
  159944. } phuff_entropy_encoder;
  159945. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  159946. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  159947. * buffer can hold. Larger sizes may slightly improve compression, but
  159948. * 1000 is already well into the realm of overkill.
  159949. * The minimum safe size is 64 bits.
  159950. */
  159951. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  159952. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  159953. * We assume that int right shift is unsigned if INT32 right shift is,
  159954. * which should be safe.
  159955. */
  159956. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  159957. #define ISHIFT_TEMPS int ishift_temp;
  159958. #define IRIGHT_SHIFT(x,shft) \
  159959. ((ishift_temp = (x)) < 0 ? \
  159960. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  159961. (ishift_temp >> (shft)))
  159962. #else
  159963. #define ISHIFT_TEMPS
  159964. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  159965. #endif
  159966. /* Forward declarations */
  159967. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  159968. JBLOCKROW *MCU_data));
  159969. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  159970. JBLOCKROW *MCU_data));
  159971. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  159972. JBLOCKROW *MCU_data));
  159973. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  159974. JBLOCKROW *MCU_data));
  159975. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  159976. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  159977. /*
  159978. * Initialize for a Huffman-compressed scan using progressive JPEG.
  159979. */
  159980. METHODDEF(void)
  159981. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  159982. {
  159983. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159984. boolean is_DC_band;
  159985. int ci, tbl;
  159986. jpeg_component_info * compptr;
  159987. entropy->cinfo = cinfo;
  159988. entropy->gather_statistics = gather_statistics;
  159989. is_DC_band = (cinfo->Ss == 0);
  159990. /* We assume jcmaster.c already validated the scan parameters. */
  159991. /* Select execution routines */
  159992. if (cinfo->Ah == 0) {
  159993. if (is_DC_band)
  159994. entropy->pub.encode_mcu = encode_mcu_DC_first;
  159995. else
  159996. entropy->pub.encode_mcu = encode_mcu_AC_first;
  159997. } else {
  159998. if (is_DC_band)
  159999. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  160000. else {
  160001. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  160002. /* AC refinement needs a correction bit buffer */
  160003. if (entropy->bit_buffer == NULL)
  160004. entropy->bit_buffer = (char *)
  160005. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160006. MAX_CORR_BITS * SIZEOF(char));
  160007. }
  160008. }
  160009. if (gather_statistics)
  160010. entropy->pub.finish_pass = finish_pass_gather_phuff;
  160011. else
  160012. entropy->pub.finish_pass = finish_pass_phuff;
  160013. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  160014. * for AC coefficients.
  160015. */
  160016. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160017. compptr = cinfo->cur_comp_info[ci];
  160018. /* Initialize DC predictions to 0 */
  160019. entropy->last_dc_val[ci] = 0;
  160020. /* Get table index */
  160021. if (is_DC_band) {
  160022. if (cinfo->Ah != 0) /* DC refinement needs no table */
  160023. continue;
  160024. tbl = compptr->dc_tbl_no;
  160025. } else {
  160026. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  160027. }
  160028. if (gather_statistics) {
  160029. /* Check for invalid table index */
  160030. /* (make_c_derived_tbl does this in the other path) */
  160031. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  160032. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  160033. /* Allocate and zero the statistics tables */
  160034. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  160035. if (entropy->count_ptrs[tbl] == NULL)
  160036. entropy->count_ptrs[tbl] = (long *)
  160037. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160038. 257 * SIZEOF(long));
  160039. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  160040. } else {
  160041. /* Compute derived values for Huffman table */
  160042. /* We may do this more than once for a table, but it's not expensive */
  160043. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  160044. & entropy->derived_tbls[tbl]);
  160045. }
  160046. }
  160047. /* Initialize AC stuff */
  160048. entropy->EOBRUN = 0;
  160049. entropy->BE = 0;
  160050. /* Initialize bit buffer to empty */
  160051. entropy->put_buffer = 0;
  160052. entropy->put_bits = 0;
  160053. /* Initialize restart stuff */
  160054. entropy->restarts_to_go = cinfo->restart_interval;
  160055. entropy->next_restart_num = 0;
  160056. }
  160057. /* Outputting bytes to the file.
  160058. * NB: these must be called only when actually outputting,
  160059. * that is, entropy->gather_statistics == FALSE.
  160060. */
  160061. /* Emit a byte */
  160062. #define emit_byte(entropy,val) \
  160063. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  160064. if (--(entropy)->free_in_buffer == 0) \
  160065. dump_buffer_p(entropy); }
  160066. LOCAL(void)
  160067. dump_buffer_p (phuff_entropy_ptr entropy)
  160068. /* Empty the output buffer; we do not support suspension in this module. */
  160069. {
  160070. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  160071. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  160072. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  160073. /* After a successful buffer dump, must reset buffer pointers */
  160074. entropy->next_output_byte = dest->next_output_byte;
  160075. entropy->free_in_buffer = dest->free_in_buffer;
  160076. }
  160077. /* Outputting bits to the file */
  160078. /* Only the right 24 bits of put_buffer are used; the valid bits are
  160079. * left-justified in this part. At most 16 bits can be passed to emit_bits
  160080. * in one call, and we never retain more than 7 bits in put_buffer
  160081. * between calls, so 24 bits are sufficient.
  160082. */
  160083. INLINE
  160084. LOCAL(void)
  160085. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  160086. /* Emit some bits, unless we are in gather mode */
  160087. {
  160088. /* This routine is heavily used, so it's worth coding tightly. */
  160089. register INT32 put_buffer = (INT32) code;
  160090. register int put_bits = entropy->put_bits;
  160091. /* if size is 0, caller used an invalid Huffman table entry */
  160092. if (size == 0)
  160093. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  160094. if (entropy->gather_statistics)
  160095. return; /* do nothing if we're only getting stats */
  160096. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  160097. put_bits += size; /* new number of bits in buffer */
  160098. put_buffer <<= 24 - put_bits; /* align incoming bits */
  160099. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  160100. while (put_bits >= 8) {
  160101. int c = (int) ((put_buffer >> 16) & 0xFF);
  160102. emit_byte(entropy, c);
  160103. if (c == 0xFF) { /* need to stuff a zero byte? */
  160104. emit_byte(entropy, 0);
  160105. }
  160106. put_buffer <<= 8;
  160107. put_bits -= 8;
  160108. }
  160109. entropy->put_buffer = put_buffer; /* update variables */
  160110. entropy->put_bits = put_bits;
  160111. }
  160112. LOCAL(void)
  160113. flush_bits_p (phuff_entropy_ptr entropy)
  160114. {
  160115. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  160116. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  160117. entropy->put_bits = 0;
  160118. }
  160119. /*
  160120. * Emit (or just count) a Huffman symbol.
  160121. */
  160122. INLINE
  160123. LOCAL(void)
  160124. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  160125. {
  160126. if (entropy->gather_statistics)
  160127. entropy->count_ptrs[tbl_no][symbol]++;
  160128. else {
  160129. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  160130. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  160131. }
  160132. }
  160133. /*
  160134. * Emit bits from a correction bit buffer.
  160135. */
  160136. LOCAL(void)
  160137. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  160138. unsigned int nbits)
  160139. {
  160140. if (entropy->gather_statistics)
  160141. return; /* no real work */
  160142. while (nbits > 0) {
  160143. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  160144. bufstart++;
  160145. nbits--;
  160146. }
  160147. }
  160148. /*
  160149. * Emit any pending EOBRUN symbol.
  160150. */
  160151. LOCAL(void)
  160152. emit_eobrun (phuff_entropy_ptr entropy)
  160153. {
  160154. register int temp, nbits;
  160155. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  160156. temp = entropy->EOBRUN;
  160157. nbits = 0;
  160158. while ((temp >>= 1))
  160159. nbits++;
  160160. /* safety check: shouldn't happen given limited correction-bit buffer */
  160161. if (nbits > 14)
  160162. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  160163. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  160164. if (nbits)
  160165. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  160166. entropy->EOBRUN = 0;
  160167. /* Emit any buffered correction bits */
  160168. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  160169. entropy->BE = 0;
  160170. }
  160171. }
  160172. /*
  160173. * Emit a restart marker & resynchronize predictions.
  160174. */
  160175. LOCAL(void)
  160176. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  160177. {
  160178. int ci;
  160179. emit_eobrun(entropy);
  160180. if (! entropy->gather_statistics) {
  160181. flush_bits_p(entropy);
  160182. emit_byte(entropy, 0xFF);
  160183. emit_byte(entropy, JPEG_RST0 + restart_num);
  160184. }
  160185. if (entropy->cinfo->Ss == 0) {
  160186. /* Re-initialize DC predictions to 0 */
  160187. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  160188. entropy->last_dc_val[ci] = 0;
  160189. } else {
  160190. /* Re-initialize all AC-related fields to 0 */
  160191. entropy->EOBRUN = 0;
  160192. entropy->BE = 0;
  160193. }
  160194. }
  160195. /*
  160196. * MCU encoding for DC initial scan (either spectral selection,
  160197. * or first pass of successive approximation).
  160198. */
  160199. METHODDEF(boolean)
  160200. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160201. {
  160202. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160203. register int temp, temp2;
  160204. register int nbits;
  160205. int blkn, ci;
  160206. int Al = cinfo->Al;
  160207. JBLOCKROW block;
  160208. jpeg_component_info * compptr;
  160209. ISHIFT_TEMPS
  160210. entropy->next_output_byte = cinfo->dest->next_output_byte;
  160211. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  160212. /* Emit restart marker if needed */
  160213. if (cinfo->restart_interval)
  160214. if (entropy->restarts_to_go == 0)
  160215. emit_restart_p(entropy, entropy->next_restart_num);
  160216. /* Encode the MCU data blocks */
  160217. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  160218. block = MCU_data[blkn];
  160219. ci = cinfo->MCU_membership[blkn];
  160220. compptr = cinfo->cur_comp_info[ci];
  160221. /* Compute the DC value after the required point transform by Al.
  160222. * This is simply an arithmetic right shift.
  160223. */
  160224. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  160225. /* DC differences are figured on the point-transformed values. */
  160226. temp = temp2 - entropy->last_dc_val[ci];
  160227. entropy->last_dc_val[ci] = temp2;
  160228. /* Encode the DC coefficient difference per section G.1.2.1 */
  160229. temp2 = temp;
  160230. if (temp < 0) {
  160231. temp = -temp; /* temp is abs value of input */
  160232. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  160233. /* This code assumes we are on a two's complement machine */
  160234. temp2--;
  160235. }
  160236. /* Find the number of bits needed for the magnitude of the coefficient */
  160237. nbits = 0;
  160238. while (temp) {
  160239. nbits++;
  160240. temp >>= 1;
  160241. }
  160242. /* Check for out-of-range coefficient values.
  160243. * Since we're encoding a difference, the range limit is twice as much.
  160244. */
  160245. if (nbits > MAX_COEF_BITS+1)
  160246. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  160247. /* Count/emit the Huffman-coded symbol for the number of bits */
  160248. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  160249. /* Emit that number of bits of the value, if positive, */
  160250. /* or the complement of its magnitude, if negative. */
  160251. if (nbits) /* emit_bits rejects calls with size 0 */
  160252. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  160253. }
  160254. cinfo->dest->next_output_byte = entropy->next_output_byte;
  160255. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  160256. /* Update restart-interval state too */
  160257. if (cinfo->restart_interval) {
  160258. if (entropy->restarts_to_go == 0) {
  160259. entropy->restarts_to_go = cinfo->restart_interval;
  160260. entropy->next_restart_num++;
  160261. entropy->next_restart_num &= 7;
  160262. }
  160263. entropy->restarts_to_go--;
  160264. }
  160265. return TRUE;
  160266. }
  160267. /*
  160268. * MCU encoding for AC initial scan (either spectral selection,
  160269. * or first pass of successive approximation).
  160270. */
  160271. METHODDEF(boolean)
  160272. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160273. {
  160274. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160275. register int temp, temp2;
  160276. register int nbits;
  160277. register int r, k;
  160278. int Se = cinfo->Se;
  160279. int Al = cinfo->Al;
  160280. JBLOCKROW block;
  160281. entropy->next_output_byte = cinfo->dest->next_output_byte;
  160282. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  160283. /* Emit restart marker if needed */
  160284. if (cinfo->restart_interval)
  160285. if (entropy->restarts_to_go == 0)
  160286. emit_restart_p(entropy, entropy->next_restart_num);
  160287. /* Encode the MCU data block */
  160288. block = MCU_data[0];
  160289. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  160290. r = 0; /* r = run length of zeros */
  160291. for (k = cinfo->Ss; k <= Se; k++) {
  160292. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  160293. r++;
  160294. continue;
  160295. }
  160296. /* We must apply the point transform by Al. For AC coefficients this
  160297. * is an integer division with rounding towards 0. To do this portably
  160298. * in C, we shift after obtaining the absolute value; so the code is
  160299. * interwoven with finding the abs value (temp) and output bits (temp2).
  160300. */
  160301. if (temp < 0) {
  160302. temp = -temp; /* temp is abs value of input */
  160303. temp >>= Al; /* apply the point transform */
  160304. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  160305. temp2 = ~temp;
  160306. } else {
  160307. temp >>= Al; /* apply the point transform */
  160308. temp2 = temp;
  160309. }
  160310. /* Watch out for case that nonzero coef is zero after point transform */
  160311. if (temp == 0) {
  160312. r++;
  160313. continue;
  160314. }
  160315. /* Emit any pending EOBRUN */
  160316. if (entropy->EOBRUN > 0)
  160317. emit_eobrun(entropy);
  160318. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  160319. while (r > 15) {
  160320. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  160321. r -= 16;
  160322. }
  160323. /* Find the number of bits needed for the magnitude of the coefficient */
  160324. nbits = 1; /* there must be at least one 1 bit */
  160325. while ((temp >>= 1))
  160326. nbits++;
  160327. /* Check for out-of-range coefficient values */
  160328. if (nbits > MAX_COEF_BITS)
  160329. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  160330. /* Count/emit Huffman symbol for run length / number of bits */
  160331. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  160332. /* Emit that number of bits of the value, if positive, */
  160333. /* or the complement of its magnitude, if negative. */
  160334. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  160335. r = 0; /* reset zero run length */
  160336. }
  160337. if (r > 0) { /* If there are trailing zeroes, */
  160338. entropy->EOBRUN++; /* count an EOB */
  160339. if (entropy->EOBRUN == 0x7FFF)
  160340. emit_eobrun(entropy); /* force it out to avoid overflow */
  160341. }
  160342. cinfo->dest->next_output_byte = entropy->next_output_byte;
  160343. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  160344. /* Update restart-interval state too */
  160345. if (cinfo->restart_interval) {
  160346. if (entropy->restarts_to_go == 0) {
  160347. entropy->restarts_to_go = cinfo->restart_interval;
  160348. entropy->next_restart_num++;
  160349. entropy->next_restart_num &= 7;
  160350. }
  160351. entropy->restarts_to_go--;
  160352. }
  160353. return TRUE;
  160354. }
  160355. /*
  160356. * MCU encoding for DC successive approximation refinement scan.
  160357. * Note: we assume such scans can be multi-component, although the spec
  160358. * is not very clear on the point.
  160359. */
  160360. METHODDEF(boolean)
  160361. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160362. {
  160363. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160364. register int temp;
  160365. int blkn;
  160366. int Al = cinfo->Al;
  160367. JBLOCKROW block;
  160368. entropy->next_output_byte = cinfo->dest->next_output_byte;
  160369. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  160370. /* Emit restart marker if needed */
  160371. if (cinfo->restart_interval)
  160372. if (entropy->restarts_to_go == 0)
  160373. emit_restart_p(entropy, entropy->next_restart_num);
  160374. /* Encode the MCU data blocks */
  160375. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  160376. block = MCU_data[blkn];
  160377. /* We simply emit the Al'th bit of the DC coefficient value. */
  160378. temp = (*block)[0];
  160379. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  160380. }
  160381. cinfo->dest->next_output_byte = entropy->next_output_byte;
  160382. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  160383. /* Update restart-interval state too */
  160384. if (cinfo->restart_interval) {
  160385. if (entropy->restarts_to_go == 0) {
  160386. entropy->restarts_to_go = cinfo->restart_interval;
  160387. entropy->next_restart_num++;
  160388. entropy->next_restart_num &= 7;
  160389. }
  160390. entropy->restarts_to_go--;
  160391. }
  160392. return TRUE;
  160393. }
  160394. /*
  160395. * MCU encoding for AC successive approximation refinement scan.
  160396. */
  160397. METHODDEF(boolean)
  160398. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  160399. {
  160400. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160401. register int temp;
  160402. register int r, k;
  160403. int EOB;
  160404. char *BR_buffer;
  160405. unsigned int BR;
  160406. int Se = cinfo->Se;
  160407. int Al = cinfo->Al;
  160408. JBLOCKROW block;
  160409. int absvalues[DCTSIZE2];
  160410. entropy->next_output_byte = cinfo->dest->next_output_byte;
  160411. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  160412. /* Emit restart marker if needed */
  160413. if (cinfo->restart_interval)
  160414. if (entropy->restarts_to_go == 0)
  160415. emit_restart_p(entropy, entropy->next_restart_num);
  160416. /* Encode the MCU data block */
  160417. block = MCU_data[0];
  160418. /* It is convenient to make a pre-pass to determine the transformed
  160419. * coefficients' absolute values and the EOB position.
  160420. */
  160421. EOB = 0;
  160422. for (k = cinfo->Ss; k <= Se; k++) {
  160423. temp = (*block)[jpeg_natural_order[k]];
  160424. /* We must apply the point transform by Al. For AC coefficients this
  160425. * is an integer division with rounding towards 0. To do this portably
  160426. * in C, we shift after obtaining the absolute value.
  160427. */
  160428. if (temp < 0)
  160429. temp = -temp; /* temp is abs value of input */
  160430. temp >>= Al; /* apply the point transform */
  160431. absvalues[k] = temp; /* save abs value for main pass */
  160432. if (temp == 1)
  160433. EOB = k; /* EOB = index of last newly-nonzero coef */
  160434. }
  160435. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  160436. r = 0; /* r = run length of zeros */
  160437. BR = 0; /* BR = count of buffered bits added now */
  160438. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  160439. for (k = cinfo->Ss; k <= Se; k++) {
  160440. if ((temp = absvalues[k]) == 0) {
  160441. r++;
  160442. continue;
  160443. }
  160444. /* Emit any required ZRLs, but not if they can be folded into EOB */
  160445. while (r > 15 && k <= EOB) {
  160446. /* emit any pending EOBRUN and the BE correction bits */
  160447. emit_eobrun(entropy);
  160448. /* Emit ZRL */
  160449. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  160450. r -= 16;
  160451. /* Emit buffered correction bits that must be associated with ZRL */
  160452. emit_buffered_bits(entropy, BR_buffer, BR);
  160453. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  160454. BR = 0;
  160455. }
  160456. /* If the coef was previously nonzero, it only needs a correction bit.
  160457. * NOTE: a straight translation of the spec's figure G.7 would suggest
  160458. * that we also need to test r > 15. But if r > 15, we can only get here
  160459. * if k > EOB, which implies that this coefficient is not 1.
  160460. */
  160461. if (temp > 1) {
  160462. /* The correction bit is the next bit of the absolute value. */
  160463. BR_buffer[BR++] = (char) (temp & 1);
  160464. continue;
  160465. }
  160466. /* Emit any pending EOBRUN and the BE correction bits */
  160467. emit_eobrun(entropy);
  160468. /* Count/emit Huffman symbol for run length / number of bits */
  160469. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  160470. /* Emit output bit for newly-nonzero coef */
  160471. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  160472. emit_bits_p(entropy, (unsigned int) temp, 1);
  160473. /* Emit buffered correction bits that must be associated with this code */
  160474. emit_buffered_bits(entropy, BR_buffer, BR);
  160475. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  160476. BR = 0;
  160477. r = 0; /* reset zero run length */
  160478. }
  160479. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  160480. entropy->EOBRUN++; /* count an EOB */
  160481. entropy->BE += BR; /* concat my correction bits to older ones */
  160482. /* We force out the EOB if we risk either:
  160483. * 1. overflow of the EOB counter;
  160484. * 2. overflow of the correction bit buffer during the next MCU.
  160485. */
  160486. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  160487. emit_eobrun(entropy);
  160488. }
  160489. cinfo->dest->next_output_byte = entropy->next_output_byte;
  160490. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  160491. /* Update restart-interval state too */
  160492. if (cinfo->restart_interval) {
  160493. if (entropy->restarts_to_go == 0) {
  160494. entropy->restarts_to_go = cinfo->restart_interval;
  160495. entropy->next_restart_num++;
  160496. entropy->next_restart_num &= 7;
  160497. }
  160498. entropy->restarts_to_go--;
  160499. }
  160500. return TRUE;
  160501. }
  160502. /*
  160503. * Finish up at the end of a Huffman-compressed progressive scan.
  160504. */
  160505. METHODDEF(void)
  160506. finish_pass_phuff (j_compress_ptr cinfo)
  160507. {
  160508. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160509. entropy->next_output_byte = cinfo->dest->next_output_byte;
  160510. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  160511. /* Flush out any buffered data */
  160512. emit_eobrun(entropy);
  160513. flush_bits_p(entropy);
  160514. cinfo->dest->next_output_byte = entropy->next_output_byte;
  160515. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  160516. }
  160517. /*
  160518. * Finish up a statistics-gathering pass and create the new Huffman tables.
  160519. */
  160520. METHODDEF(void)
  160521. finish_pass_gather_phuff (j_compress_ptr cinfo)
  160522. {
  160523. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  160524. boolean is_DC_band;
  160525. int ci, tbl;
  160526. jpeg_component_info * compptr;
  160527. JHUFF_TBL **htblptr;
  160528. boolean did[NUM_HUFF_TBLS];
  160529. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  160530. emit_eobrun(entropy);
  160531. is_DC_band = (cinfo->Ss == 0);
  160532. /* It's important not to apply jpeg_gen_optimal_table more than once
  160533. * per table, because it clobbers the input frequency counts!
  160534. */
  160535. MEMZERO(did, SIZEOF(did));
  160536. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160537. compptr = cinfo->cur_comp_info[ci];
  160538. if (is_DC_band) {
  160539. if (cinfo->Ah != 0) /* DC refinement needs no table */
  160540. continue;
  160541. tbl = compptr->dc_tbl_no;
  160542. } else {
  160543. tbl = compptr->ac_tbl_no;
  160544. }
  160545. if (! did[tbl]) {
  160546. if (is_DC_band)
  160547. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  160548. else
  160549. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  160550. if (*htblptr == NULL)
  160551. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  160552. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  160553. did[tbl] = TRUE;
  160554. }
  160555. }
  160556. }
  160557. /*
  160558. * Module initialization routine for progressive Huffman entropy encoding.
  160559. */
  160560. GLOBAL(void)
  160561. jinit_phuff_encoder (j_compress_ptr cinfo)
  160562. {
  160563. phuff_entropy_ptr entropy;
  160564. int i;
  160565. entropy = (phuff_entropy_ptr)
  160566. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160567. SIZEOF(phuff_entropy_encoder));
  160568. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  160569. entropy->pub.start_pass = start_pass_phuff;
  160570. /* Mark tables unallocated */
  160571. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160572. entropy->derived_tbls[i] = NULL;
  160573. entropy->count_ptrs[i] = NULL;
  160574. }
  160575. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  160576. }
  160577. #endif /* C_PROGRESSIVE_SUPPORTED */
  160578. /********* End of inlined file: jcphuff.c *********/
  160579. /********* Start of inlined file: jcprepct.c *********/
  160580. #define JPEG_INTERNALS
  160581. /* At present, jcsample.c can request context rows only for smoothing.
  160582. * In the future, we might also need context rows for CCIR601 sampling
  160583. * or other more-complex downsampling procedures. The code to support
  160584. * context rows should be compiled only if needed.
  160585. */
  160586. #ifdef INPUT_SMOOTHING_SUPPORTED
  160587. #define CONTEXT_ROWS_SUPPORTED
  160588. #endif
  160589. /*
  160590. * For the simple (no-context-row) case, we just need to buffer one
  160591. * row group's worth of pixels for the downsampling step. At the bottom of
  160592. * the image, we pad to a full row group by replicating the last pixel row.
  160593. * The downsampler's last output row is then replicated if needed to pad
  160594. * out to a full iMCU row.
  160595. *
  160596. * When providing context rows, we must buffer three row groups' worth of
  160597. * pixels. Three row groups are physically allocated, but the row pointer
  160598. * arrays are made five row groups high, with the extra pointers above and
  160599. * below "wrapping around" to point to the last and first real row groups.
  160600. * This allows the downsampler to access the proper context rows.
  160601. * At the top and bottom of the image, we create dummy context rows by
  160602. * copying the first or last real pixel row. This copying could be avoided
  160603. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  160604. * trouble on the compression side.
  160605. */
  160606. /* Private buffer controller object */
  160607. typedef struct {
  160608. struct jpeg_c_prep_controller pub; /* public fields */
  160609. /* Downsampling input buffer. This buffer holds color-converted data
  160610. * until we have enough to do a downsample step.
  160611. */
  160612. JSAMPARRAY color_buf[MAX_COMPONENTS];
  160613. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  160614. int next_buf_row; /* index of next row to store in color_buf */
  160615. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  160616. int this_row_group; /* starting row index of group to process */
  160617. int next_buf_stop; /* downsample when we reach this index */
  160618. #endif
  160619. } my_prep_controller;
  160620. typedef my_prep_controller * my_prep_ptr;
  160621. /*
  160622. * Initialize for a processing pass.
  160623. */
  160624. METHODDEF(void)
  160625. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  160626. {
  160627. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  160628. if (pass_mode != JBUF_PASS_THRU)
  160629. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160630. /* Initialize total-height counter for detecting bottom of image */
  160631. prep->rows_to_go = cinfo->image_height;
  160632. /* Mark the conversion buffer empty */
  160633. prep->next_buf_row = 0;
  160634. #ifdef CONTEXT_ROWS_SUPPORTED
  160635. /* Preset additional state variables for context mode.
  160636. * These aren't used in non-context mode, so we needn't test which mode.
  160637. */
  160638. prep->this_row_group = 0;
  160639. /* Set next_buf_stop to stop after two row groups have been read in. */
  160640. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  160641. #endif
  160642. }
  160643. /*
  160644. * Expand an image vertically from height input_rows to height output_rows,
  160645. * by duplicating the bottom row.
  160646. */
  160647. LOCAL(void)
  160648. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  160649. int input_rows, int output_rows)
  160650. {
  160651. register int row;
  160652. for (row = input_rows; row < output_rows; row++) {
  160653. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  160654. 1, num_cols);
  160655. }
  160656. }
  160657. /*
  160658. * Process some data in the simple no-context case.
  160659. *
  160660. * Preprocessor output data is counted in "row groups". A row group
  160661. * is defined to be v_samp_factor sample rows of each component.
  160662. * Downsampling will produce this much data from each max_v_samp_factor
  160663. * input rows.
  160664. */
  160665. METHODDEF(void)
  160666. pre_process_data (j_compress_ptr cinfo,
  160667. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160668. JDIMENSION in_rows_avail,
  160669. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  160670. JDIMENSION out_row_groups_avail)
  160671. {
  160672. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  160673. int numrows, ci;
  160674. JDIMENSION inrows;
  160675. jpeg_component_info * compptr;
  160676. while (*in_row_ctr < in_rows_avail &&
  160677. *out_row_group_ctr < out_row_groups_avail) {
  160678. /* Do color conversion to fill the conversion buffer. */
  160679. inrows = in_rows_avail - *in_row_ctr;
  160680. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  160681. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  160682. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  160683. prep->color_buf,
  160684. (JDIMENSION) prep->next_buf_row,
  160685. numrows);
  160686. *in_row_ctr += numrows;
  160687. prep->next_buf_row += numrows;
  160688. prep->rows_to_go -= numrows;
  160689. /* If at bottom of image, pad to fill the conversion buffer. */
  160690. if (prep->rows_to_go == 0 &&
  160691. prep->next_buf_row < cinfo->max_v_samp_factor) {
  160692. for (ci = 0; ci < cinfo->num_components; ci++) {
  160693. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  160694. prep->next_buf_row, cinfo->max_v_samp_factor);
  160695. }
  160696. prep->next_buf_row = cinfo->max_v_samp_factor;
  160697. }
  160698. /* If we've filled the conversion buffer, empty it. */
  160699. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  160700. (*cinfo->downsample->downsample) (cinfo,
  160701. prep->color_buf, (JDIMENSION) 0,
  160702. output_buf, *out_row_group_ctr);
  160703. prep->next_buf_row = 0;
  160704. (*out_row_group_ctr)++;
  160705. }
  160706. /* If at bottom of image, pad the output to a full iMCU height.
  160707. * Note we assume the caller is providing a one-iMCU-height output buffer!
  160708. */
  160709. if (prep->rows_to_go == 0 &&
  160710. *out_row_group_ctr < out_row_groups_avail) {
  160711. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160712. ci++, compptr++) {
  160713. expand_bottom_edge(output_buf[ci],
  160714. compptr->width_in_blocks * DCTSIZE,
  160715. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  160716. (int) (out_row_groups_avail * compptr->v_samp_factor));
  160717. }
  160718. *out_row_group_ctr = out_row_groups_avail;
  160719. break; /* can exit outer loop without test */
  160720. }
  160721. }
  160722. }
  160723. #ifdef CONTEXT_ROWS_SUPPORTED
  160724. /*
  160725. * Process some data in the context case.
  160726. */
  160727. METHODDEF(void)
  160728. pre_process_context (j_compress_ptr cinfo,
  160729. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160730. JDIMENSION in_rows_avail,
  160731. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  160732. JDIMENSION out_row_groups_avail)
  160733. {
  160734. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  160735. int numrows, ci;
  160736. int buf_height = cinfo->max_v_samp_factor * 3;
  160737. JDIMENSION inrows;
  160738. while (*out_row_group_ctr < out_row_groups_avail) {
  160739. if (*in_row_ctr < in_rows_avail) {
  160740. /* Do color conversion to fill the conversion buffer. */
  160741. inrows = in_rows_avail - *in_row_ctr;
  160742. numrows = prep->next_buf_stop - prep->next_buf_row;
  160743. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  160744. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  160745. prep->color_buf,
  160746. (JDIMENSION) prep->next_buf_row,
  160747. numrows);
  160748. /* Pad at top of image, if first time through */
  160749. if (prep->rows_to_go == cinfo->image_height) {
  160750. for (ci = 0; ci < cinfo->num_components; ci++) {
  160751. int row;
  160752. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  160753. jcopy_sample_rows(prep->color_buf[ci], 0,
  160754. prep->color_buf[ci], -row,
  160755. 1, cinfo->image_width);
  160756. }
  160757. }
  160758. }
  160759. *in_row_ctr += numrows;
  160760. prep->next_buf_row += numrows;
  160761. prep->rows_to_go -= numrows;
  160762. } else {
  160763. /* Return for more data, unless we are at the bottom of the image. */
  160764. if (prep->rows_to_go != 0)
  160765. break;
  160766. /* When at bottom of image, pad to fill the conversion buffer. */
  160767. if (prep->next_buf_row < prep->next_buf_stop) {
  160768. for (ci = 0; ci < cinfo->num_components; ci++) {
  160769. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  160770. prep->next_buf_row, prep->next_buf_stop);
  160771. }
  160772. prep->next_buf_row = prep->next_buf_stop;
  160773. }
  160774. }
  160775. /* If we've gotten enough data, downsample a row group. */
  160776. if (prep->next_buf_row == prep->next_buf_stop) {
  160777. (*cinfo->downsample->downsample) (cinfo,
  160778. prep->color_buf,
  160779. (JDIMENSION) prep->this_row_group,
  160780. output_buf, *out_row_group_ctr);
  160781. (*out_row_group_ctr)++;
  160782. /* Advance pointers with wraparound as necessary. */
  160783. prep->this_row_group += cinfo->max_v_samp_factor;
  160784. if (prep->this_row_group >= buf_height)
  160785. prep->this_row_group = 0;
  160786. if (prep->next_buf_row >= buf_height)
  160787. prep->next_buf_row = 0;
  160788. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  160789. }
  160790. }
  160791. }
  160792. /*
  160793. * Create the wrapped-around downsampling input buffer needed for context mode.
  160794. */
  160795. LOCAL(void)
  160796. create_context_buffer (j_compress_ptr cinfo)
  160797. {
  160798. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  160799. int rgroup_height = cinfo->max_v_samp_factor;
  160800. int ci, i;
  160801. jpeg_component_info * compptr;
  160802. JSAMPARRAY true_buffer, fake_buffer;
  160803. /* Grab enough space for fake row pointers for all the components;
  160804. * we need five row groups' worth of pointers for each component.
  160805. */
  160806. fake_buffer = (JSAMPARRAY)
  160807. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160808. (cinfo->num_components * 5 * rgroup_height) *
  160809. SIZEOF(JSAMPROW));
  160810. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160811. ci++, compptr++) {
  160812. /* Allocate the actual buffer space (3 row groups) for this component.
  160813. * We make the buffer wide enough to allow the downsampler to edge-expand
  160814. * horizontally within the buffer, if it so chooses.
  160815. */
  160816. true_buffer = (*cinfo->mem->alloc_sarray)
  160817. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160818. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  160819. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  160820. (JDIMENSION) (3 * rgroup_height));
  160821. /* Copy true buffer row pointers into the middle of the fake row array */
  160822. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  160823. 3 * rgroup_height * SIZEOF(JSAMPROW));
  160824. /* Fill in the above and below wraparound pointers */
  160825. for (i = 0; i < rgroup_height; i++) {
  160826. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  160827. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  160828. }
  160829. prep->color_buf[ci] = fake_buffer + rgroup_height;
  160830. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  160831. }
  160832. }
  160833. #endif /* CONTEXT_ROWS_SUPPORTED */
  160834. /*
  160835. * Initialize preprocessing controller.
  160836. */
  160837. GLOBAL(void)
  160838. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  160839. {
  160840. my_prep_ptr prep;
  160841. int ci;
  160842. jpeg_component_info * compptr;
  160843. if (need_full_buffer) /* safety check */
  160844. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160845. prep = (my_prep_ptr)
  160846. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160847. SIZEOF(my_prep_controller));
  160848. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  160849. prep->pub.start_pass = start_pass_prep;
  160850. /* Allocate the color conversion buffer.
  160851. * We make the buffer wide enough to allow the downsampler to edge-expand
  160852. * horizontally within the buffer, if it so chooses.
  160853. */
  160854. if (cinfo->downsample->need_context_rows) {
  160855. /* Set up to provide context rows */
  160856. #ifdef CONTEXT_ROWS_SUPPORTED
  160857. prep->pub.pre_process_data = pre_process_context;
  160858. create_context_buffer(cinfo);
  160859. #else
  160860. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160861. #endif
  160862. } else {
  160863. /* No context, just make it tall enough for one row group */
  160864. prep->pub.pre_process_data = pre_process_data;
  160865. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160866. ci++, compptr++) {
  160867. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  160868. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160869. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  160870. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  160871. (JDIMENSION) cinfo->max_v_samp_factor);
  160872. }
  160873. }
  160874. }
  160875. /********* End of inlined file: jcprepct.c *********/
  160876. /********* Start of inlined file: jcsample.c *********/
  160877. #define JPEG_INTERNALS
  160878. /* Pointer to routine to downsample a single component */
  160879. typedef JMETHOD(void, downsample1_ptr,
  160880. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160881. JSAMPARRAY input_data, JSAMPARRAY output_data));
  160882. /* Private subobject */
  160883. typedef struct {
  160884. struct jpeg_downsampler pub; /* public fields */
  160885. /* Downsampling method pointers, one per component */
  160886. downsample1_ptr methods[MAX_COMPONENTS];
  160887. } my_downsampler;
  160888. typedef my_downsampler * my_downsample_ptr;
  160889. /*
  160890. * Initialize for a downsampling pass.
  160891. */
  160892. METHODDEF(void)
  160893. start_pass_downsample (j_compress_ptr cinfo)
  160894. {
  160895. /* no work for now */
  160896. }
  160897. /*
  160898. * Expand a component horizontally from width input_cols to width output_cols,
  160899. * by duplicating the rightmost samples.
  160900. */
  160901. LOCAL(void)
  160902. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  160903. JDIMENSION input_cols, JDIMENSION output_cols)
  160904. {
  160905. register JSAMPROW ptr;
  160906. register JSAMPLE pixval;
  160907. register int count;
  160908. int row;
  160909. int numcols = (int) (output_cols - input_cols);
  160910. if (numcols > 0) {
  160911. for (row = 0; row < num_rows; row++) {
  160912. ptr = image_data[row] + input_cols;
  160913. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  160914. for (count = numcols; count > 0; count--)
  160915. *ptr++ = pixval;
  160916. }
  160917. }
  160918. }
  160919. /*
  160920. * Do downsampling for a whole row group (all components).
  160921. *
  160922. * In this version we simply downsample each component independently.
  160923. */
  160924. METHODDEF(void)
  160925. sep_downsample (j_compress_ptr cinfo,
  160926. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160927. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  160928. {
  160929. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  160930. int ci;
  160931. jpeg_component_info * compptr;
  160932. JSAMPARRAY in_ptr, out_ptr;
  160933. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160934. ci++, compptr++) {
  160935. in_ptr = input_buf[ci] + in_row_index;
  160936. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  160937. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  160938. }
  160939. }
  160940. /*
  160941. * Downsample pixel values of a single component.
  160942. * One row group is processed per call.
  160943. * This version handles arbitrary integral sampling ratios, without smoothing.
  160944. * Note that this version is not actually used for customary sampling ratios.
  160945. */
  160946. METHODDEF(void)
  160947. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160948. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160949. {
  160950. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  160951. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  160952. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160953. JSAMPROW inptr, outptr;
  160954. INT32 outvalue;
  160955. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  160956. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  160957. numpix = h_expand * v_expand;
  160958. numpix2 = numpix/2;
  160959. /* Expand input data enough to let all the output samples be generated
  160960. * by the standard loop. Special-casing padded output would be more
  160961. * efficient.
  160962. */
  160963. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  160964. cinfo->image_width, output_cols * h_expand);
  160965. inrow = 0;
  160966. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160967. outptr = output_data[outrow];
  160968. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  160969. outcol++, outcol_h += h_expand) {
  160970. outvalue = 0;
  160971. for (v = 0; v < v_expand; v++) {
  160972. inptr = input_data[inrow+v] + outcol_h;
  160973. for (h = 0; h < h_expand; h++) {
  160974. outvalue += (INT32) GETJSAMPLE(*inptr++);
  160975. }
  160976. }
  160977. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  160978. }
  160979. inrow += v_expand;
  160980. }
  160981. }
  160982. /*
  160983. * Downsample pixel values of a single component.
  160984. * This version handles the special case of a full-size component,
  160985. * without smoothing.
  160986. */
  160987. METHODDEF(void)
  160988. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160989. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160990. {
  160991. /* Copy the data */
  160992. jcopy_sample_rows(input_data, 0, output_data, 0,
  160993. cinfo->max_v_samp_factor, cinfo->image_width);
  160994. /* Edge-expand */
  160995. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  160996. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  160997. }
  160998. /*
  160999. * Downsample pixel values of a single component.
  161000. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  161001. * without smoothing.
  161002. *
  161003. * A note about the "bias" calculations: when rounding fractional values to
  161004. * integer, we do not want to always round 0.5 up to the next integer.
  161005. * If we did that, we'd introduce a noticeable bias towards larger values.
  161006. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  161007. * alternate pixel locations (a simple ordered dither pattern).
  161008. */
  161009. METHODDEF(void)
  161010. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161011. JSAMPARRAY input_data, JSAMPARRAY output_data)
  161012. {
  161013. int outrow;
  161014. JDIMENSION outcol;
  161015. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  161016. register JSAMPROW inptr, outptr;
  161017. register int bias;
  161018. /* Expand input data enough to let all the output samples be generated
  161019. * by the standard loop. Special-casing padded output would be more
  161020. * efficient.
  161021. */
  161022. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  161023. cinfo->image_width, output_cols * 2);
  161024. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  161025. outptr = output_data[outrow];
  161026. inptr = input_data[outrow];
  161027. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  161028. for (outcol = 0; outcol < output_cols; outcol++) {
  161029. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  161030. + bias) >> 1);
  161031. bias ^= 1; /* 0=>1, 1=>0 */
  161032. inptr += 2;
  161033. }
  161034. }
  161035. }
  161036. /*
  161037. * Downsample pixel values of a single component.
  161038. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  161039. * without smoothing.
  161040. */
  161041. METHODDEF(void)
  161042. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161043. JSAMPARRAY input_data, JSAMPARRAY output_data)
  161044. {
  161045. int inrow, outrow;
  161046. JDIMENSION outcol;
  161047. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  161048. register JSAMPROW inptr0, inptr1, outptr;
  161049. register int bias;
  161050. /* Expand input data enough to let all the output samples be generated
  161051. * by the standard loop. Special-casing padded output would be more
  161052. * efficient.
  161053. */
  161054. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  161055. cinfo->image_width, output_cols * 2);
  161056. inrow = 0;
  161057. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  161058. outptr = output_data[outrow];
  161059. inptr0 = input_data[inrow];
  161060. inptr1 = input_data[inrow+1];
  161061. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  161062. for (outcol = 0; outcol < output_cols; outcol++) {
  161063. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  161064. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  161065. + bias) >> 2);
  161066. bias ^= 3; /* 1=>2, 2=>1 */
  161067. inptr0 += 2; inptr1 += 2;
  161068. }
  161069. inrow += 2;
  161070. }
  161071. }
  161072. #ifdef INPUT_SMOOTHING_SUPPORTED
  161073. /*
  161074. * Downsample pixel values of a single component.
  161075. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  161076. * with smoothing. One row of context is required.
  161077. */
  161078. METHODDEF(void)
  161079. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161080. JSAMPARRAY input_data, JSAMPARRAY output_data)
  161081. {
  161082. int inrow, outrow;
  161083. JDIMENSION colctr;
  161084. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  161085. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  161086. INT32 membersum, neighsum, memberscale, neighscale;
  161087. /* Expand input data enough to let all the output samples be generated
  161088. * by the standard loop. Special-casing padded output would be more
  161089. * efficient.
  161090. */
  161091. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  161092. cinfo->image_width, output_cols * 2);
  161093. /* We don't bother to form the individual "smoothed" input pixel values;
  161094. * we can directly compute the output which is the average of the four
  161095. * smoothed values. Each of the four member pixels contributes a fraction
  161096. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  161097. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  161098. * output. The four corner-adjacent neighbor pixels contribute a fraction
  161099. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  161100. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  161101. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  161102. * factors are scaled by 2^16 = 65536.
  161103. * Also recall that SF = smoothing_factor / 1024.
  161104. */
  161105. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  161106. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  161107. inrow = 0;
  161108. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  161109. outptr = output_data[outrow];
  161110. inptr0 = input_data[inrow];
  161111. inptr1 = input_data[inrow+1];
  161112. above_ptr = input_data[inrow-1];
  161113. below_ptr = input_data[inrow+2];
  161114. /* Special case for first column: pretend column -1 is same as column 0 */
  161115. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  161116. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  161117. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  161118. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  161119. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  161120. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  161121. neighsum += neighsum;
  161122. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  161123. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  161124. membersum = membersum * memberscale + neighsum * neighscale;
  161125. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  161126. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  161127. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  161128. /* sum of pixels directly mapped to this output element */
  161129. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  161130. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  161131. /* sum of edge-neighbor pixels */
  161132. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  161133. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  161134. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  161135. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  161136. /* The edge-neighbors count twice as much as corner-neighbors */
  161137. neighsum += neighsum;
  161138. /* Add in the corner-neighbors */
  161139. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  161140. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  161141. /* form final output scaled up by 2^16 */
  161142. membersum = membersum * memberscale + neighsum * neighscale;
  161143. /* round, descale and output it */
  161144. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  161145. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  161146. }
  161147. /* Special case for last column */
  161148. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  161149. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  161150. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  161151. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  161152. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  161153. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  161154. neighsum += neighsum;
  161155. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  161156. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  161157. membersum = membersum * memberscale + neighsum * neighscale;
  161158. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  161159. inrow += 2;
  161160. }
  161161. }
  161162. /*
  161163. * Downsample pixel values of a single component.
  161164. * This version handles the special case of a full-size component,
  161165. * with smoothing. One row of context is required.
  161166. */
  161167. METHODDEF(void)
  161168. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  161169. JSAMPARRAY input_data, JSAMPARRAY output_data)
  161170. {
  161171. int outrow;
  161172. JDIMENSION colctr;
  161173. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  161174. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  161175. INT32 membersum, neighsum, memberscale, neighscale;
  161176. int colsum, lastcolsum, nextcolsum;
  161177. /* Expand input data enough to let all the output samples be generated
  161178. * by the standard loop. Special-casing padded output would be more
  161179. * efficient.
  161180. */
  161181. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  161182. cinfo->image_width, output_cols);
  161183. /* Each of the eight neighbor pixels contributes a fraction SF to the
  161184. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  161185. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  161186. * Also recall that SF = smoothing_factor / 1024.
  161187. */
  161188. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  161189. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  161190. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  161191. outptr = output_data[outrow];
  161192. inptr = input_data[outrow];
  161193. above_ptr = input_data[outrow-1];
  161194. below_ptr = input_data[outrow+1];
  161195. /* Special case for first column */
  161196. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  161197. GETJSAMPLE(*inptr);
  161198. membersum = GETJSAMPLE(*inptr++);
  161199. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  161200. GETJSAMPLE(*inptr);
  161201. neighsum = colsum + (colsum - membersum) + nextcolsum;
  161202. membersum = membersum * memberscale + neighsum * neighscale;
  161203. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  161204. lastcolsum = colsum; colsum = nextcolsum;
  161205. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  161206. membersum = GETJSAMPLE(*inptr++);
  161207. above_ptr++; below_ptr++;
  161208. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  161209. GETJSAMPLE(*inptr);
  161210. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  161211. membersum = membersum * memberscale + neighsum * neighscale;
  161212. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  161213. lastcolsum = colsum; colsum = nextcolsum;
  161214. }
  161215. /* Special case for last column */
  161216. membersum = GETJSAMPLE(*inptr);
  161217. neighsum = lastcolsum + (colsum - membersum) + colsum;
  161218. membersum = membersum * memberscale + neighsum * neighscale;
  161219. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  161220. }
  161221. }
  161222. #endif /* INPUT_SMOOTHING_SUPPORTED */
  161223. /*
  161224. * Module initialization routine for downsampling.
  161225. * Note that we must select a routine for each component.
  161226. */
  161227. GLOBAL(void)
  161228. jinit_downsampler (j_compress_ptr cinfo)
  161229. {
  161230. my_downsample_ptr downsample;
  161231. int ci;
  161232. jpeg_component_info * compptr;
  161233. boolean smoothok = TRUE;
  161234. downsample = (my_downsample_ptr)
  161235. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161236. SIZEOF(my_downsampler));
  161237. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  161238. downsample->pub.start_pass = start_pass_downsample;
  161239. downsample->pub.downsample = sep_downsample;
  161240. downsample->pub.need_context_rows = FALSE;
  161241. if (cinfo->CCIR601_sampling)
  161242. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  161243. /* Verify we can handle the sampling factors, and set up method pointers */
  161244. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161245. ci++, compptr++) {
  161246. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  161247. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  161248. #ifdef INPUT_SMOOTHING_SUPPORTED
  161249. if (cinfo->smoothing_factor) {
  161250. downsample->methods[ci] = fullsize_smooth_downsample;
  161251. downsample->pub.need_context_rows = TRUE;
  161252. } else
  161253. #endif
  161254. downsample->methods[ci] = fullsize_downsample;
  161255. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  161256. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  161257. smoothok = FALSE;
  161258. downsample->methods[ci] = h2v1_downsample;
  161259. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  161260. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  161261. #ifdef INPUT_SMOOTHING_SUPPORTED
  161262. if (cinfo->smoothing_factor) {
  161263. downsample->methods[ci] = h2v2_smooth_downsample;
  161264. downsample->pub.need_context_rows = TRUE;
  161265. } else
  161266. #endif
  161267. downsample->methods[ci] = h2v2_downsample;
  161268. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  161269. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  161270. smoothok = FALSE;
  161271. downsample->methods[ci] = int_downsample;
  161272. } else
  161273. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  161274. }
  161275. #ifdef INPUT_SMOOTHING_SUPPORTED
  161276. if (cinfo->smoothing_factor && !smoothok)
  161277. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  161278. #endif
  161279. }
  161280. /********* End of inlined file: jcsample.c *********/
  161281. /********* Start of inlined file: jctrans.c *********/
  161282. #define JPEG_INTERNALS
  161283. /* Forward declarations */
  161284. LOCAL(void) transencode_master_selection
  161285. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  161286. LOCAL(void) transencode_coef_controller
  161287. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  161288. /*
  161289. * Compression initialization for writing raw-coefficient data.
  161290. * Before calling this, all parameters and a data destination must be set up.
  161291. * Call jpeg_finish_compress() to actually write the data.
  161292. *
  161293. * The number of passed virtual arrays must match cinfo->num_components.
  161294. * Note that the virtual arrays need not be filled or even realized at
  161295. * the time write_coefficients is called; indeed, if the virtual arrays
  161296. * were requested from this compression object's memory manager, they
  161297. * typically will be realized during this routine and filled afterwards.
  161298. */
  161299. GLOBAL(void)
  161300. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  161301. {
  161302. if (cinfo->global_state != CSTATE_START)
  161303. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161304. /* Mark all tables to be written */
  161305. jpeg_suppress_tables(cinfo, FALSE);
  161306. /* (Re)initialize error mgr and destination modules */
  161307. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161308. (*cinfo->dest->init_destination) (cinfo);
  161309. /* Perform master selection of active modules */
  161310. transencode_master_selection(cinfo, coef_arrays);
  161311. /* Wait for jpeg_finish_compress() call */
  161312. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  161313. cinfo->global_state = CSTATE_WRCOEFS;
  161314. }
  161315. /*
  161316. * Initialize the compression object with default parameters,
  161317. * then copy from the source object all parameters needed for lossless
  161318. * transcoding. Parameters that can be varied without loss (such as
  161319. * scan script and Huffman optimization) are left in their default states.
  161320. */
  161321. GLOBAL(void)
  161322. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  161323. j_compress_ptr dstinfo)
  161324. {
  161325. JQUANT_TBL ** qtblptr;
  161326. jpeg_component_info *incomp, *outcomp;
  161327. JQUANT_TBL *c_quant, *slot_quant;
  161328. int tblno, ci, coefi;
  161329. /* Safety check to ensure start_compress not called yet. */
  161330. if (dstinfo->global_state != CSTATE_START)
  161331. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  161332. /* Copy fundamental image dimensions */
  161333. dstinfo->image_width = srcinfo->image_width;
  161334. dstinfo->image_height = srcinfo->image_height;
  161335. dstinfo->input_components = srcinfo->num_components;
  161336. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  161337. /* Initialize all parameters to default values */
  161338. jpeg_set_defaults(dstinfo);
  161339. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  161340. * Fix it to get the right header markers for the image colorspace.
  161341. */
  161342. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  161343. dstinfo->data_precision = srcinfo->data_precision;
  161344. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  161345. /* Copy the source's quantization tables. */
  161346. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  161347. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  161348. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  161349. if (*qtblptr == NULL)
  161350. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  161351. MEMCOPY((*qtblptr)->quantval,
  161352. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  161353. SIZEOF((*qtblptr)->quantval));
  161354. (*qtblptr)->sent_table = FALSE;
  161355. }
  161356. }
  161357. /* Copy the source's per-component info.
  161358. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  161359. */
  161360. dstinfo->num_components = srcinfo->num_components;
  161361. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  161362. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  161363. MAX_COMPONENTS);
  161364. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  161365. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  161366. outcomp->component_id = incomp->component_id;
  161367. outcomp->h_samp_factor = incomp->h_samp_factor;
  161368. outcomp->v_samp_factor = incomp->v_samp_factor;
  161369. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  161370. /* Make sure saved quantization table for component matches the qtable
  161371. * slot. If not, the input file re-used this qtable slot.
  161372. * IJG encoder currently cannot duplicate this.
  161373. */
  161374. tblno = outcomp->quant_tbl_no;
  161375. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  161376. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  161377. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  161378. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  161379. c_quant = incomp->quant_table;
  161380. if (c_quant != NULL) {
  161381. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  161382. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  161383. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  161384. }
  161385. }
  161386. /* Note: we do not copy the source's Huffman table assignments;
  161387. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  161388. */
  161389. }
  161390. /* Also copy JFIF version and resolution information, if available.
  161391. * Strictly speaking this isn't "critical" info, but it's nearly
  161392. * always appropriate to copy it if available. In particular,
  161393. * if the application chooses to copy JFIF 1.02 extension markers from
  161394. * the source file, we need to copy the version to make sure we don't
  161395. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  161396. * We will *not*, however, copy version info from mislabeled "2.01" files.
  161397. */
  161398. if (srcinfo->saw_JFIF_marker) {
  161399. if (srcinfo->JFIF_major_version == 1) {
  161400. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  161401. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  161402. }
  161403. dstinfo->density_unit = srcinfo->density_unit;
  161404. dstinfo->X_density = srcinfo->X_density;
  161405. dstinfo->Y_density = srcinfo->Y_density;
  161406. }
  161407. }
  161408. /*
  161409. * Master selection of compression modules for transcoding.
  161410. * This substitutes for jcinit.c's initialization of the full compressor.
  161411. */
  161412. LOCAL(void)
  161413. transencode_master_selection (j_compress_ptr cinfo,
  161414. jvirt_barray_ptr * coef_arrays)
  161415. {
  161416. /* Although we don't actually use input_components for transcoding,
  161417. * jcmaster.c's initial_setup will complain if input_components is 0.
  161418. */
  161419. cinfo->input_components = 1;
  161420. /* Initialize master control (includes parameter checking/processing) */
  161421. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  161422. /* Entropy encoding: either Huffman or arithmetic coding. */
  161423. if (cinfo->arith_code) {
  161424. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  161425. } else {
  161426. if (cinfo->progressive_mode) {
  161427. #ifdef C_PROGRESSIVE_SUPPORTED
  161428. jinit_phuff_encoder(cinfo);
  161429. #else
  161430. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161431. #endif
  161432. } else
  161433. jinit_huff_encoder(cinfo);
  161434. }
  161435. /* We need a special coefficient buffer controller. */
  161436. transencode_coef_controller(cinfo, coef_arrays);
  161437. jinit_marker_writer(cinfo);
  161438. /* We can now tell the memory manager to allocate virtual arrays. */
  161439. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  161440. /* Write the datastream header (SOI, JFIF) immediately.
  161441. * Frame and scan headers are postponed till later.
  161442. * This lets application insert special markers after the SOI.
  161443. */
  161444. (*cinfo->marker->write_file_header) (cinfo);
  161445. }
  161446. /*
  161447. * The rest of this file is a special implementation of the coefficient
  161448. * buffer controller. This is similar to jccoefct.c, but it handles only
  161449. * output from presupplied virtual arrays. Furthermore, we generate any
  161450. * dummy padding blocks on-the-fly rather than expecting them to be present
  161451. * in the arrays.
  161452. */
  161453. /* Private buffer controller object */
  161454. typedef struct {
  161455. struct jpeg_c_coef_controller pub; /* public fields */
  161456. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161457. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161458. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161459. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161460. /* Virtual block array for each component. */
  161461. jvirt_barray_ptr * whole_image;
  161462. /* Workspace for constructing dummy blocks at right/bottom edges. */
  161463. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  161464. } my_coef_controller2;
  161465. typedef my_coef_controller2 * my_coef_ptr2;
  161466. LOCAL(void)
  161467. start_iMCU_row2 (j_compress_ptr cinfo)
  161468. /* Reset within-iMCU-row counters for a new row */
  161469. {
  161470. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  161471. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161472. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161473. * But at the bottom of the image, process only what's left.
  161474. */
  161475. if (cinfo->comps_in_scan > 1) {
  161476. coef->MCU_rows_per_iMCU_row = 1;
  161477. } else {
  161478. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161479. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161480. else
  161481. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161482. }
  161483. coef->mcu_ctr = 0;
  161484. coef->MCU_vert_offset = 0;
  161485. }
  161486. /*
  161487. * Initialize for a processing pass.
  161488. */
  161489. METHODDEF(void)
  161490. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161491. {
  161492. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  161493. if (pass_mode != JBUF_CRANK_DEST)
  161494. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161495. coef->iMCU_row_num = 0;
  161496. start_iMCU_row2(cinfo);
  161497. }
  161498. /*
  161499. * Process some data.
  161500. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161501. * per call, ie, v_samp_factor block rows for each component in the scan.
  161502. * The data is obtained from the virtual arrays and fed to the entropy coder.
  161503. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161504. *
  161505. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  161506. */
  161507. METHODDEF(boolean)
  161508. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161509. {
  161510. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  161511. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161512. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161513. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161514. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  161515. JDIMENSION start_col;
  161516. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161517. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161518. JBLOCKROW buffer_ptr;
  161519. jpeg_component_info *compptr;
  161520. /* Align the virtual buffers for the components used in this scan. */
  161521. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161522. compptr = cinfo->cur_comp_info[ci];
  161523. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161524. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161525. coef->iMCU_row_num * compptr->v_samp_factor,
  161526. (JDIMENSION) compptr->v_samp_factor, FALSE);
  161527. }
  161528. /* Loop to process one whole iMCU row */
  161529. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161530. yoffset++) {
  161531. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  161532. MCU_col_num++) {
  161533. /* Construct list of pointers to DCT blocks belonging to this MCU */
  161534. blkn = 0; /* index of current DCT block within MCU */
  161535. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161536. compptr = cinfo->cur_comp_info[ci];
  161537. start_col = MCU_col_num * compptr->MCU_width;
  161538. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161539. : compptr->last_col_width;
  161540. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161541. if (coef->iMCU_row_num < last_iMCU_row ||
  161542. yindex+yoffset < compptr->last_row_height) {
  161543. /* Fill in pointers to real blocks in this row */
  161544. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  161545. for (xindex = 0; xindex < blockcnt; xindex++)
  161546. MCU_buffer[blkn++] = buffer_ptr++;
  161547. } else {
  161548. /* At bottom of image, need a whole row of dummy blocks */
  161549. xindex = 0;
  161550. }
  161551. /* Fill in any dummy blocks needed in this row.
  161552. * Dummy blocks are filled in the same way as in jccoefct.c:
  161553. * all zeroes in the AC entries, DC entries equal to previous
  161554. * block's DC value. The init routine has already zeroed the
  161555. * AC entries, so we need only set the DC entries correctly.
  161556. */
  161557. for (; xindex < compptr->MCU_width; xindex++) {
  161558. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  161559. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  161560. blkn++;
  161561. }
  161562. }
  161563. }
  161564. /* Try to write the MCU. */
  161565. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  161566. /* Suspension forced; update state counters and exit */
  161567. coef->MCU_vert_offset = yoffset;
  161568. coef->mcu_ctr = MCU_col_num;
  161569. return FALSE;
  161570. }
  161571. }
  161572. /* Completed an MCU row, but perhaps not an iMCU row */
  161573. coef->mcu_ctr = 0;
  161574. }
  161575. /* Completed the iMCU row, advance counters for next one */
  161576. coef->iMCU_row_num++;
  161577. start_iMCU_row2(cinfo);
  161578. return TRUE;
  161579. }
  161580. /*
  161581. * Initialize coefficient buffer controller.
  161582. *
  161583. * Each passed coefficient array must be the right size for that
  161584. * coefficient: width_in_blocks wide and height_in_blocks high,
  161585. * with unitheight at least v_samp_factor.
  161586. */
  161587. LOCAL(void)
  161588. transencode_coef_controller (j_compress_ptr cinfo,
  161589. jvirt_barray_ptr * coef_arrays)
  161590. {
  161591. my_coef_ptr2 coef;
  161592. JBLOCKROW buffer;
  161593. int i;
  161594. coef = (my_coef_ptr2)
  161595. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161596. SIZEOF(my_coef_controller2));
  161597. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  161598. coef->pub.start_pass = start_pass_coef2;
  161599. coef->pub.compress_data = compress_output2;
  161600. /* Save pointer to virtual arrays */
  161601. coef->whole_image = coef_arrays;
  161602. /* Allocate and pre-zero space for dummy DCT blocks. */
  161603. buffer = (JBLOCKROW)
  161604. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161605. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161606. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161607. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  161608. coef->dummy_buffer[i] = buffer + i;
  161609. }
  161610. }
  161611. /********* End of inlined file: jctrans.c *********/
  161612. /********* Start of inlined file: jdapistd.c *********/
  161613. #define JPEG_INTERNALS
  161614. /* Forward declarations */
  161615. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  161616. /*
  161617. * Decompression initialization.
  161618. * jpeg_read_header must be completed before calling this.
  161619. *
  161620. * If a multipass operating mode was selected, this will do all but the
  161621. * last pass, and thus may take a great deal of time.
  161622. *
  161623. * Returns FALSE if suspended. The return value need be inspected only if
  161624. * a suspending data source is used.
  161625. */
  161626. GLOBAL(boolean)
  161627. jpeg_start_decompress (j_decompress_ptr cinfo)
  161628. {
  161629. if (cinfo->global_state == DSTATE_READY) {
  161630. /* First call: initialize master control, select active modules */
  161631. jinit_master_decompress(cinfo);
  161632. if (cinfo->buffered_image) {
  161633. /* No more work here; expecting jpeg_start_output next */
  161634. cinfo->global_state = DSTATE_BUFIMAGE;
  161635. return TRUE;
  161636. }
  161637. cinfo->global_state = DSTATE_PRELOAD;
  161638. }
  161639. if (cinfo->global_state == DSTATE_PRELOAD) {
  161640. /* If file has multiple scans, absorb them all into the coef buffer */
  161641. if (cinfo->inputctl->has_multiple_scans) {
  161642. #ifdef D_MULTISCAN_FILES_SUPPORTED
  161643. for (;;) {
  161644. int retcode;
  161645. /* Call progress monitor hook if present */
  161646. if (cinfo->progress != NULL)
  161647. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161648. /* Absorb some more input */
  161649. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  161650. if (retcode == JPEG_SUSPENDED)
  161651. return FALSE;
  161652. if (retcode == JPEG_REACHED_EOI)
  161653. break;
  161654. /* Advance progress counter if appropriate */
  161655. if (cinfo->progress != NULL &&
  161656. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  161657. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  161658. /* jdmaster underestimated number of scans; ratchet up one scan */
  161659. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  161660. }
  161661. }
  161662. }
  161663. #else
  161664. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161665. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  161666. }
  161667. cinfo->output_scan_number = cinfo->input_scan_number;
  161668. } else if (cinfo->global_state != DSTATE_PRESCAN)
  161669. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161670. /* Perform any dummy output passes, and set up for the final pass */
  161671. return output_pass_setup(cinfo);
  161672. }
  161673. /*
  161674. * Set up for an output pass, and perform any dummy pass(es) needed.
  161675. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  161676. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  161677. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  161678. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  161679. */
  161680. LOCAL(boolean)
  161681. output_pass_setup (j_decompress_ptr cinfo)
  161682. {
  161683. if (cinfo->global_state != DSTATE_PRESCAN) {
  161684. /* First call: do pass setup */
  161685. (*cinfo->master->prepare_for_output_pass) (cinfo);
  161686. cinfo->output_scanline = 0;
  161687. cinfo->global_state = DSTATE_PRESCAN;
  161688. }
  161689. /* Loop over any required dummy passes */
  161690. while (cinfo->master->is_dummy_pass) {
  161691. #ifdef QUANT_2PASS_SUPPORTED
  161692. /* Crank through the dummy pass */
  161693. while (cinfo->output_scanline < cinfo->output_height) {
  161694. JDIMENSION last_scanline;
  161695. /* Call progress monitor hook if present */
  161696. if (cinfo->progress != NULL) {
  161697. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  161698. cinfo->progress->pass_limit = (long) cinfo->output_height;
  161699. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161700. }
  161701. /* Process some data */
  161702. last_scanline = cinfo->output_scanline;
  161703. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  161704. &cinfo->output_scanline, (JDIMENSION) 0);
  161705. if (cinfo->output_scanline == last_scanline)
  161706. return FALSE; /* No progress made, must suspend */
  161707. }
  161708. /* Finish up dummy pass, and set up for another one */
  161709. (*cinfo->master->finish_output_pass) (cinfo);
  161710. (*cinfo->master->prepare_for_output_pass) (cinfo);
  161711. cinfo->output_scanline = 0;
  161712. #else
  161713. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161714. #endif /* QUANT_2PASS_SUPPORTED */
  161715. }
  161716. /* Ready for application to drive output pass through
  161717. * jpeg_read_scanlines or jpeg_read_raw_data.
  161718. */
  161719. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  161720. return TRUE;
  161721. }
  161722. /*
  161723. * Read some scanlines of data from the JPEG decompressor.
  161724. *
  161725. * The return value will be the number of lines actually read.
  161726. * This may be less than the number requested in several cases,
  161727. * including bottom of image, data source suspension, and operating
  161728. * modes that emit multiple scanlines at a time.
  161729. *
  161730. * Note: we warn about excess calls to jpeg_read_scanlines() since
  161731. * this likely signals an application programmer error. However,
  161732. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  161733. */
  161734. GLOBAL(JDIMENSION)
  161735. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  161736. JDIMENSION max_lines)
  161737. {
  161738. JDIMENSION row_ctr;
  161739. if (cinfo->global_state != DSTATE_SCANNING)
  161740. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161741. if (cinfo->output_scanline >= cinfo->output_height) {
  161742. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161743. return 0;
  161744. }
  161745. /* Call progress monitor hook if present */
  161746. if (cinfo->progress != NULL) {
  161747. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  161748. cinfo->progress->pass_limit = (long) cinfo->output_height;
  161749. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161750. }
  161751. /* Process some data */
  161752. row_ctr = 0;
  161753. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  161754. cinfo->output_scanline += row_ctr;
  161755. return row_ctr;
  161756. }
  161757. /*
  161758. * Alternate entry point to read raw data.
  161759. * Processes exactly one iMCU row per call, unless suspended.
  161760. */
  161761. GLOBAL(JDIMENSION)
  161762. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  161763. JDIMENSION max_lines)
  161764. {
  161765. JDIMENSION lines_per_iMCU_row;
  161766. if (cinfo->global_state != DSTATE_RAW_OK)
  161767. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161768. if (cinfo->output_scanline >= cinfo->output_height) {
  161769. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161770. return 0;
  161771. }
  161772. /* Call progress monitor hook if present */
  161773. if (cinfo->progress != NULL) {
  161774. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  161775. cinfo->progress->pass_limit = (long) cinfo->output_height;
  161776. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161777. }
  161778. /* Verify that at least one iMCU row can be returned. */
  161779. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  161780. if (max_lines < lines_per_iMCU_row)
  161781. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161782. /* Decompress directly into user's buffer. */
  161783. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  161784. return 0; /* suspension forced, can do nothing more */
  161785. /* OK, we processed one iMCU row. */
  161786. cinfo->output_scanline += lines_per_iMCU_row;
  161787. return lines_per_iMCU_row;
  161788. }
  161789. /* Additional entry points for buffered-image mode. */
  161790. #ifdef D_MULTISCAN_FILES_SUPPORTED
  161791. /*
  161792. * Initialize for an output pass in buffered-image mode.
  161793. */
  161794. GLOBAL(boolean)
  161795. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  161796. {
  161797. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  161798. cinfo->global_state != DSTATE_PRESCAN)
  161799. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161800. /* Limit scan number to valid range */
  161801. if (scan_number <= 0)
  161802. scan_number = 1;
  161803. if (cinfo->inputctl->eoi_reached &&
  161804. scan_number > cinfo->input_scan_number)
  161805. scan_number = cinfo->input_scan_number;
  161806. cinfo->output_scan_number = scan_number;
  161807. /* Perform any dummy output passes, and set up for the real pass */
  161808. return output_pass_setup(cinfo);
  161809. }
  161810. /*
  161811. * Finish up after an output pass in buffered-image mode.
  161812. *
  161813. * Returns FALSE if suspended. The return value need be inspected only if
  161814. * a suspending data source is used.
  161815. */
  161816. GLOBAL(boolean)
  161817. jpeg_finish_output (j_decompress_ptr cinfo)
  161818. {
  161819. if ((cinfo->global_state == DSTATE_SCANNING ||
  161820. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  161821. /* Terminate this pass. */
  161822. /* We do not require the whole pass to have been completed. */
  161823. (*cinfo->master->finish_output_pass) (cinfo);
  161824. cinfo->global_state = DSTATE_BUFPOST;
  161825. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  161826. /* BUFPOST = repeat call after a suspension, anything else is error */
  161827. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161828. }
  161829. /* Read markers looking for SOS or EOI */
  161830. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  161831. ! cinfo->inputctl->eoi_reached) {
  161832. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  161833. return FALSE; /* Suspend, come back later */
  161834. }
  161835. cinfo->global_state = DSTATE_BUFIMAGE;
  161836. return TRUE;
  161837. }
  161838. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  161839. /********* End of inlined file: jdapistd.c *********/
  161840. /********* Start of inlined file: jdapimin.c *********/
  161841. #define JPEG_INTERNALS
  161842. /*
  161843. * Initialization of a JPEG decompression object.
  161844. * The error manager must already be set up (in case memory manager fails).
  161845. */
  161846. GLOBAL(void)
  161847. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  161848. {
  161849. int i;
  161850. /* Guard against version mismatches between library and caller. */
  161851. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161852. if (version != JPEG_LIB_VERSION)
  161853. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161854. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  161855. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161856. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  161857. /* For debugging purposes, we zero the whole master structure.
  161858. * But the application has already set the err pointer, and may have set
  161859. * client_data, so we have to save and restore those fields.
  161860. * Note: if application hasn't set client_data, tools like Purify may
  161861. * complain here.
  161862. */
  161863. {
  161864. struct jpeg_error_mgr * err = cinfo->err;
  161865. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161866. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  161867. cinfo->err = err;
  161868. cinfo->client_data = client_data;
  161869. }
  161870. cinfo->is_decompressor = TRUE;
  161871. /* Initialize a memory manager instance for this object */
  161872. jinit_memory_mgr((j_common_ptr) cinfo);
  161873. /* Zero out pointers to permanent structures. */
  161874. cinfo->progress = NULL;
  161875. cinfo->src = NULL;
  161876. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161877. cinfo->quant_tbl_ptrs[i] = NULL;
  161878. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161879. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161880. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161881. }
  161882. /* Initialize marker processor so application can override methods
  161883. * for COM, APPn markers before calling jpeg_read_header.
  161884. */
  161885. cinfo->marker_list = NULL;
  161886. jinit_marker_reader(cinfo);
  161887. /* And initialize the overall input controller. */
  161888. jinit_input_controller(cinfo);
  161889. /* OK, I'm ready */
  161890. cinfo->global_state = DSTATE_START;
  161891. }
  161892. /*
  161893. * Destruction of a JPEG decompression object
  161894. */
  161895. GLOBAL(void)
  161896. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  161897. {
  161898. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161899. }
  161900. /*
  161901. * Abort processing of a JPEG decompression operation,
  161902. * but don't destroy the object itself.
  161903. */
  161904. GLOBAL(void)
  161905. jpeg_abort_decompress (j_decompress_ptr cinfo)
  161906. {
  161907. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161908. }
  161909. /*
  161910. * Set default decompression parameters.
  161911. */
  161912. LOCAL(void)
  161913. default_decompress_parms (j_decompress_ptr cinfo)
  161914. {
  161915. /* Guess the input colorspace, and set output colorspace accordingly. */
  161916. /* (Wish JPEG committee had provided a real way to specify this...) */
  161917. /* Note application may override our guesses. */
  161918. switch (cinfo->num_components) {
  161919. case 1:
  161920. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  161921. cinfo->out_color_space = JCS_GRAYSCALE;
  161922. break;
  161923. case 3:
  161924. if (cinfo->saw_JFIF_marker) {
  161925. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  161926. } else if (cinfo->saw_Adobe_marker) {
  161927. switch (cinfo->Adobe_transform) {
  161928. case 0:
  161929. cinfo->jpeg_color_space = JCS_RGB;
  161930. break;
  161931. case 1:
  161932. cinfo->jpeg_color_space = JCS_YCbCr;
  161933. break;
  161934. default:
  161935. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  161936. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  161937. break;
  161938. }
  161939. } else {
  161940. /* Saw no special markers, try to guess from the component IDs */
  161941. int cid0 = cinfo->comp_info[0].component_id;
  161942. int cid1 = cinfo->comp_info[1].component_id;
  161943. int cid2 = cinfo->comp_info[2].component_id;
  161944. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  161945. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  161946. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  161947. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  161948. else {
  161949. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  161950. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  161951. }
  161952. }
  161953. /* Always guess RGB is proper output colorspace. */
  161954. cinfo->out_color_space = JCS_RGB;
  161955. break;
  161956. case 4:
  161957. if (cinfo->saw_Adobe_marker) {
  161958. switch (cinfo->Adobe_transform) {
  161959. case 0:
  161960. cinfo->jpeg_color_space = JCS_CMYK;
  161961. break;
  161962. case 2:
  161963. cinfo->jpeg_color_space = JCS_YCCK;
  161964. break;
  161965. default:
  161966. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  161967. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  161968. break;
  161969. }
  161970. } else {
  161971. /* No special markers, assume straight CMYK. */
  161972. cinfo->jpeg_color_space = JCS_CMYK;
  161973. }
  161974. cinfo->out_color_space = JCS_CMYK;
  161975. break;
  161976. default:
  161977. cinfo->jpeg_color_space = JCS_UNKNOWN;
  161978. cinfo->out_color_space = JCS_UNKNOWN;
  161979. break;
  161980. }
  161981. /* Set defaults for other decompression parameters. */
  161982. cinfo->scale_num = 1; /* 1:1 scaling */
  161983. cinfo->scale_denom = 1;
  161984. cinfo->output_gamma = 1.0;
  161985. cinfo->buffered_image = FALSE;
  161986. cinfo->raw_data_out = FALSE;
  161987. cinfo->dct_method = JDCT_DEFAULT;
  161988. cinfo->do_fancy_upsampling = TRUE;
  161989. cinfo->do_block_smoothing = TRUE;
  161990. cinfo->quantize_colors = FALSE;
  161991. /* We set these in case application only sets quantize_colors. */
  161992. cinfo->dither_mode = JDITHER_FS;
  161993. #ifdef QUANT_2PASS_SUPPORTED
  161994. cinfo->two_pass_quantize = TRUE;
  161995. #else
  161996. cinfo->two_pass_quantize = FALSE;
  161997. #endif
  161998. cinfo->desired_number_of_colors = 256;
  161999. cinfo->colormap = NULL;
  162000. /* Initialize for no mode change in buffered-image mode. */
  162001. cinfo->enable_1pass_quant = FALSE;
  162002. cinfo->enable_external_quant = FALSE;
  162003. cinfo->enable_2pass_quant = FALSE;
  162004. }
  162005. /*
  162006. * Decompression startup: read start of JPEG datastream to see what's there.
  162007. * Need only initialize JPEG object and supply a data source before calling.
  162008. *
  162009. * This routine will read as far as the first SOS marker (ie, actual start of
  162010. * compressed data), and will save all tables and parameters in the JPEG
  162011. * object. It will also initialize the decompression parameters to default
  162012. * values, and finally return JPEG_HEADER_OK. On return, the application may
  162013. * adjust the decompression parameters and then call jpeg_start_decompress.
  162014. * (Or, if the application only wanted to determine the image parameters,
  162015. * the data need not be decompressed. In that case, call jpeg_abort or
  162016. * jpeg_destroy to release any temporary space.)
  162017. * If an abbreviated (tables only) datastream is presented, the routine will
  162018. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  162019. * re-use the JPEG object to read the abbreviated image datastream(s).
  162020. * It is unnecessary (but OK) to call jpeg_abort in this case.
  162021. * The JPEG_SUSPENDED return code only occurs if the data source module
  162022. * requests suspension of the decompressor. In this case the application
  162023. * should load more source data and then re-call jpeg_read_header to resume
  162024. * processing.
  162025. * If a non-suspending data source is used and require_image is TRUE, then the
  162026. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  162027. *
  162028. * This routine is now just a front end to jpeg_consume_input, with some
  162029. * extra error checking.
  162030. */
  162031. GLOBAL(int)
  162032. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  162033. {
  162034. int retcode;
  162035. if (cinfo->global_state != DSTATE_START &&
  162036. cinfo->global_state != DSTATE_INHEADER)
  162037. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162038. retcode = jpeg_consume_input(cinfo);
  162039. switch (retcode) {
  162040. case JPEG_REACHED_SOS:
  162041. retcode = JPEG_HEADER_OK;
  162042. break;
  162043. case JPEG_REACHED_EOI:
  162044. if (require_image) /* Complain if application wanted an image */
  162045. ERREXIT(cinfo, JERR_NO_IMAGE);
  162046. /* Reset to start state; it would be safer to require the application to
  162047. * call jpeg_abort, but we can't change it now for compatibility reasons.
  162048. * A side effect is to free any temporary memory (there shouldn't be any).
  162049. */
  162050. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  162051. retcode = JPEG_HEADER_TABLES_ONLY;
  162052. break;
  162053. case JPEG_SUSPENDED:
  162054. /* no work */
  162055. break;
  162056. }
  162057. return retcode;
  162058. }
  162059. /*
  162060. * Consume data in advance of what the decompressor requires.
  162061. * This can be called at any time once the decompressor object has
  162062. * been created and a data source has been set up.
  162063. *
  162064. * This routine is essentially a state machine that handles a couple
  162065. * of critical state-transition actions, namely initial setup and
  162066. * transition from header scanning to ready-for-start_decompress.
  162067. * All the actual input is done via the input controller's consume_input
  162068. * method.
  162069. */
  162070. GLOBAL(int)
  162071. jpeg_consume_input (j_decompress_ptr cinfo)
  162072. {
  162073. int retcode = JPEG_SUSPENDED;
  162074. /* NB: every possible DSTATE value should be listed in this switch */
  162075. switch (cinfo->global_state) {
  162076. case DSTATE_START:
  162077. /* Start-of-datastream actions: reset appropriate modules */
  162078. (*cinfo->inputctl->reset_input_controller) (cinfo);
  162079. /* Initialize application's data source module */
  162080. (*cinfo->src->init_source) (cinfo);
  162081. cinfo->global_state = DSTATE_INHEADER;
  162082. /*FALLTHROUGH*/
  162083. case DSTATE_INHEADER:
  162084. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  162085. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  162086. /* Set up default parameters based on header data */
  162087. default_decompress_parms(cinfo);
  162088. /* Set global state: ready for start_decompress */
  162089. cinfo->global_state = DSTATE_READY;
  162090. }
  162091. break;
  162092. case DSTATE_READY:
  162093. /* Can't advance past first SOS until start_decompress is called */
  162094. retcode = JPEG_REACHED_SOS;
  162095. break;
  162096. case DSTATE_PRELOAD:
  162097. case DSTATE_PRESCAN:
  162098. case DSTATE_SCANNING:
  162099. case DSTATE_RAW_OK:
  162100. case DSTATE_BUFIMAGE:
  162101. case DSTATE_BUFPOST:
  162102. case DSTATE_STOPPING:
  162103. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  162104. break;
  162105. default:
  162106. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162107. }
  162108. return retcode;
  162109. }
  162110. /*
  162111. * Have we finished reading the input file?
  162112. */
  162113. GLOBAL(boolean)
  162114. jpeg_input_complete (j_decompress_ptr cinfo)
  162115. {
  162116. /* Check for valid jpeg object */
  162117. if (cinfo->global_state < DSTATE_START ||
  162118. cinfo->global_state > DSTATE_STOPPING)
  162119. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162120. return cinfo->inputctl->eoi_reached;
  162121. }
  162122. /*
  162123. * Is there more than one scan?
  162124. */
  162125. GLOBAL(boolean)
  162126. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  162127. {
  162128. /* Only valid after jpeg_read_header completes */
  162129. if (cinfo->global_state < DSTATE_READY ||
  162130. cinfo->global_state > DSTATE_STOPPING)
  162131. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162132. return cinfo->inputctl->has_multiple_scans;
  162133. }
  162134. /*
  162135. * Finish JPEG decompression.
  162136. *
  162137. * This will normally just verify the file trailer and release temp storage.
  162138. *
  162139. * Returns FALSE if suspended. The return value need be inspected only if
  162140. * a suspending data source is used.
  162141. */
  162142. GLOBAL(boolean)
  162143. jpeg_finish_decompress (j_decompress_ptr cinfo)
  162144. {
  162145. if ((cinfo->global_state == DSTATE_SCANNING ||
  162146. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  162147. /* Terminate final pass of non-buffered mode */
  162148. if (cinfo->output_scanline < cinfo->output_height)
  162149. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  162150. (*cinfo->master->finish_output_pass) (cinfo);
  162151. cinfo->global_state = DSTATE_STOPPING;
  162152. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  162153. /* Finishing after a buffered-image operation */
  162154. cinfo->global_state = DSTATE_STOPPING;
  162155. } else if (cinfo->global_state != DSTATE_STOPPING) {
  162156. /* STOPPING = repeat call after a suspension, anything else is error */
  162157. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162158. }
  162159. /* Read until EOI */
  162160. while (! cinfo->inputctl->eoi_reached) {
  162161. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  162162. return FALSE; /* Suspend, come back later */
  162163. }
  162164. /* Do final cleanup */
  162165. (*cinfo->src->term_source) (cinfo);
  162166. /* We can use jpeg_abort to release memory and reset global_state */
  162167. jpeg_abort((j_common_ptr) cinfo);
  162168. return TRUE;
  162169. }
  162170. /********* End of inlined file: jdapimin.c *********/
  162171. /********* Start of inlined file: jdatasrc.c *********/
  162172. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  162173. /********* Start of inlined file: jerror.h *********/
  162174. /*
  162175. * To define the enum list of message codes, include this file without
  162176. * defining macro JMESSAGE. To create a message string table, include it
  162177. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  162178. */
  162179. #ifndef JMESSAGE
  162180. #ifndef JERROR_H
  162181. /* First time through, define the enum list */
  162182. #define JMAKE_ENUM_LIST
  162183. #else
  162184. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  162185. #define JMESSAGE(code,string)
  162186. #endif /* JERROR_H */
  162187. #endif /* JMESSAGE */
  162188. #ifdef JMAKE_ENUM_LIST
  162189. typedef enum {
  162190. #define JMESSAGE(code,string) code ,
  162191. #endif /* JMAKE_ENUM_LIST */
  162192. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  162193. /* For maintenance convenience, list is alphabetical by message code name */
  162194. JMESSAGE(JERR_ARITH_NOTIMPL,
  162195. "Sorry, there are legal restrictions on arithmetic coding")
  162196. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  162197. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  162198. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  162199. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  162200. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  162201. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  162202. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  162203. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  162204. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  162205. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  162206. JMESSAGE(JERR_BAD_LIB_VERSION,
  162207. "Wrong JPEG library version: library is %d, caller expects %d")
  162208. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  162209. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  162210. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  162211. JMESSAGE(JERR_BAD_PROGRESSION,
  162212. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  162213. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  162214. "Invalid progressive parameters at scan script entry %d")
  162215. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  162216. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  162217. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  162218. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  162219. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  162220. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  162221. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  162222. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  162223. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  162224. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  162225. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  162226. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  162227. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  162228. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  162229. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  162230. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  162231. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  162232. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  162233. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  162234. JMESSAGE(JERR_FILE_READ, "Input file read error")
  162235. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  162236. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  162237. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  162238. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  162239. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  162240. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  162241. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  162242. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  162243. "Cannot transcode due to multiple use of quantization table %d")
  162244. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  162245. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  162246. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  162247. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  162248. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  162249. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  162250. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  162251. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  162252. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  162253. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  162254. JMESSAGE(JERR_QUANT_COMPONENTS,
  162255. "Cannot quantize more than %d color components")
  162256. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  162257. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  162258. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  162259. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  162260. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  162261. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  162262. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  162263. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  162264. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  162265. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  162266. JMESSAGE(JERR_TFILE_WRITE,
  162267. "Write failed on temporary file --- out of disk space?")
  162268. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  162269. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  162270. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  162271. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  162272. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  162273. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  162274. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  162275. JMESSAGE(JMSG_VERSION, JVERSION)
  162276. JMESSAGE(JTRC_16BIT_TABLES,
  162277. "Caution: quantization tables are too coarse for baseline JPEG")
  162278. JMESSAGE(JTRC_ADOBE,
  162279. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  162280. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  162281. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  162282. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  162283. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  162284. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  162285. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  162286. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  162287. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  162288. JMESSAGE(JTRC_EOI, "End Of Image")
  162289. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  162290. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  162291. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  162292. "Warning: thumbnail image size does not match data length %u")
  162293. JMESSAGE(JTRC_JFIF_EXTENSION,
  162294. "JFIF extension marker: type 0x%02x, length %u")
  162295. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  162296. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  162297. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  162298. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  162299. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  162300. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  162301. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  162302. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  162303. JMESSAGE(JTRC_RST, "RST%d")
  162304. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  162305. "Smoothing not supported with nonstandard sampling ratios")
  162306. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  162307. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  162308. JMESSAGE(JTRC_SOI, "Start of Image")
  162309. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  162310. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  162311. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  162312. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  162313. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  162314. JMESSAGE(JTRC_THUMB_JPEG,
  162315. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  162316. JMESSAGE(JTRC_THUMB_PALETTE,
  162317. "JFIF extension marker: palette thumbnail image, length %u")
  162318. JMESSAGE(JTRC_THUMB_RGB,
  162319. "JFIF extension marker: RGB thumbnail image, length %u")
  162320. JMESSAGE(JTRC_UNKNOWN_IDS,
  162321. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  162322. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  162323. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  162324. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  162325. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  162326. "Inconsistent progression sequence for component %d coefficient %d")
  162327. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  162328. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  162329. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  162330. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  162331. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  162332. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  162333. JMESSAGE(JWRN_MUST_RESYNC,
  162334. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  162335. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  162336. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  162337. #ifdef JMAKE_ENUM_LIST
  162338. JMSG_LASTMSGCODE
  162339. } J_MESSAGE_CODE;
  162340. #undef JMAKE_ENUM_LIST
  162341. #endif /* JMAKE_ENUM_LIST */
  162342. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  162343. #undef JMESSAGE
  162344. #ifndef JERROR_H
  162345. #define JERROR_H
  162346. /* Macros to simplify using the error and trace message stuff */
  162347. /* The first parameter is either type of cinfo pointer */
  162348. /* Fatal errors (print message and exit) */
  162349. #define ERREXIT(cinfo,code) \
  162350. ((cinfo)->err->msg_code = (code), \
  162351. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162352. #define ERREXIT1(cinfo,code,p1) \
  162353. ((cinfo)->err->msg_code = (code), \
  162354. (cinfo)->err->msg_parm.i[0] = (p1), \
  162355. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162356. #define ERREXIT2(cinfo,code,p1,p2) \
  162357. ((cinfo)->err->msg_code = (code), \
  162358. (cinfo)->err->msg_parm.i[0] = (p1), \
  162359. (cinfo)->err->msg_parm.i[1] = (p2), \
  162360. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162361. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  162362. ((cinfo)->err->msg_code = (code), \
  162363. (cinfo)->err->msg_parm.i[0] = (p1), \
  162364. (cinfo)->err->msg_parm.i[1] = (p2), \
  162365. (cinfo)->err->msg_parm.i[2] = (p3), \
  162366. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162367. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  162368. ((cinfo)->err->msg_code = (code), \
  162369. (cinfo)->err->msg_parm.i[0] = (p1), \
  162370. (cinfo)->err->msg_parm.i[1] = (p2), \
  162371. (cinfo)->err->msg_parm.i[2] = (p3), \
  162372. (cinfo)->err->msg_parm.i[3] = (p4), \
  162373. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162374. #define ERREXITS(cinfo,code,str) \
  162375. ((cinfo)->err->msg_code = (code), \
  162376. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  162377. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162378. #define MAKESTMT(stuff) do { stuff } while (0)
  162379. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  162380. #define WARNMS(cinfo,code) \
  162381. ((cinfo)->err->msg_code = (code), \
  162382. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  162383. #define WARNMS1(cinfo,code,p1) \
  162384. ((cinfo)->err->msg_code = (code), \
  162385. (cinfo)->err->msg_parm.i[0] = (p1), \
  162386. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  162387. #define WARNMS2(cinfo,code,p1,p2) \
  162388. ((cinfo)->err->msg_code = (code), \
  162389. (cinfo)->err->msg_parm.i[0] = (p1), \
  162390. (cinfo)->err->msg_parm.i[1] = (p2), \
  162391. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  162392. /* Informational/debugging messages */
  162393. #define TRACEMS(cinfo,lvl,code) \
  162394. ((cinfo)->err->msg_code = (code), \
  162395. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  162396. #define TRACEMS1(cinfo,lvl,code,p1) \
  162397. ((cinfo)->err->msg_code = (code), \
  162398. (cinfo)->err->msg_parm.i[0] = (p1), \
  162399. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  162400. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  162401. ((cinfo)->err->msg_code = (code), \
  162402. (cinfo)->err->msg_parm.i[0] = (p1), \
  162403. (cinfo)->err->msg_parm.i[1] = (p2), \
  162404. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  162405. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  162406. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  162407. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  162408. (cinfo)->err->msg_code = (code); \
  162409. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  162410. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  162411. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  162412. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  162413. (cinfo)->err->msg_code = (code); \
  162414. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  162415. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  162416. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  162417. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  162418. _mp[4] = (p5); \
  162419. (cinfo)->err->msg_code = (code); \
  162420. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  162421. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  162422. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  162423. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  162424. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  162425. (cinfo)->err->msg_code = (code); \
  162426. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  162427. #define TRACEMSS(cinfo,lvl,code,str) \
  162428. ((cinfo)->err->msg_code = (code), \
  162429. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  162430. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  162431. #endif /* JERROR_H */
  162432. /********* End of inlined file: jerror.h *********/
  162433. /* Expanded data source object for stdio input */
  162434. typedef struct {
  162435. struct jpeg_source_mgr pub; /* public fields */
  162436. FILE * infile; /* source stream */
  162437. JOCTET * buffer; /* start of buffer */
  162438. boolean start_of_file; /* have we gotten any data yet? */
  162439. } my_source_mgr;
  162440. typedef my_source_mgr * my_src_ptr;
  162441. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  162442. /*
  162443. * Initialize source --- called by jpeg_read_header
  162444. * before any data is actually read.
  162445. */
  162446. METHODDEF(void)
  162447. init_source (j_decompress_ptr cinfo)
  162448. {
  162449. my_src_ptr src = (my_src_ptr) cinfo->src;
  162450. /* We reset the empty-input-file flag for each image,
  162451. * but we don't clear the input buffer.
  162452. * This is correct behavior for reading a series of images from one source.
  162453. */
  162454. src->start_of_file = TRUE;
  162455. }
  162456. /*
  162457. * Fill the input buffer --- called whenever buffer is emptied.
  162458. *
  162459. * In typical applications, this should read fresh data into the buffer
  162460. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  162461. * reset the pointer & count to the start of the buffer, and return TRUE
  162462. * indicating that the buffer has been reloaded. It is not necessary to
  162463. * fill the buffer entirely, only to obtain at least one more byte.
  162464. *
  162465. * There is no such thing as an EOF return. If the end of the file has been
  162466. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  162467. * the buffer. In most cases, generating a warning message and inserting a
  162468. * fake EOI marker is the best course of action --- this will allow the
  162469. * decompressor to output however much of the image is there. However,
  162470. * the resulting error message is misleading if the real problem is an empty
  162471. * input file, so we handle that case specially.
  162472. *
  162473. * In applications that need to be able to suspend compression due to input
  162474. * not being available yet, a FALSE return indicates that no more data can be
  162475. * obtained right now, but more may be forthcoming later. In this situation,
  162476. * the decompressor will return to its caller (with an indication of the
  162477. * number of scanlines it has read, if any). The application should resume
  162478. * decompression after it has loaded more data into the input buffer. Note
  162479. * that there are substantial restrictions on the use of suspension --- see
  162480. * the documentation.
  162481. *
  162482. * When suspending, the decompressor will back up to a convenient restart point
  162483. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  162484. * indicate where the restart point will be if the current call returns FALSE.
  162485. * Data beyond this point must be rescanned after resumption, so move it to
  162486. * the front of the buffer rather than discarding it.
  162487. */
  162488. METHODDEF(boolean)
  162489. fill_input_buffer (j_decompress_ptr cinfo)
  162490. {
  162491. my_src_ptr src = (my_src_ptr) cinfo->src;
  162492. size_t nbytes;
  162493. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  162494. if (nbytes <= 0) {
  162495. if (src->start_of_file) /* Treat empty input file as fatal error */
  162496. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  162497. WARNMS(cinfo, JWRN_JPEG_EOF);
  162498. /* Insert a fake EOI marker */
  162499. src->buffer[0] = (JOCTET) 0xFF;
  162500. src->buffer[1] = (JOCTET) JPEG_EOI;
  162501. nbytes = 2;
  162502. }
  162503. src->pub.next_input_byte = src->buffer;
  162504. src->pub.bytes_in_buffer = nbytes;
  162505. src->start_of_file = FALSE;
  162506. return TRUE;
  162507. }
  162508. /*
  162509. * Skip data --- used to skip over a potentially large amount of
  162510. * uninteresting data (such as an APPn marker).
  162511. *
  162512. * Writers of suspendable-input applications must note that skip_input_data
  162513. * is not granted the right to give a suspension return. If the skip extends
  162514. * beyond the data currently in the buffer, the buffer can be marked empty so
  162515. * that the next read will cause a fill_input_buffer call that can suspend.
  162516. * Arranging for additional bytes to be discarded before reloading the input
  162517. * buffer is the application writer's problem.
  162518. */
  162519. METHODDEF(void)
  162520. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  162521. {
  162522. my_src_ptr src = (my_src_ptr) cinfo->src;
  162523. /* Just a dumb implementation for now. Could use fseek() except
  162524. * it doesn't work on pipes. Not clear that being smart is worth
  162525. * any trouble anyway --- large skips are infrequent.
  162526. */
  162527. if (num_bytes > 0) {
  162528. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  162529. num_bytes -= (long) src->pub.bytes_in_buffer;
  162530. (void) fill_input_buffer(cinfo);
  162531. /* note we assume that fill_input_buffer will never return FALSE,
  162532. * so suspension need not be handled.
  162533. */
  162534. }
  162535. src->pub.next_input_byte += (size_t) num_bytes;
  162536. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  162537. }
  162538. }
  162539. /*
  162540. * An additional method that can be provided by data source modules is the
  162541. * resync_to_restart method for error recovery in the presence of RST markers.
  162542. * For the moment, this source module just uses the default resync method
  162543. * provided by the JPEG library. That method assumes that no backtracking
  162544. * is possible.
  162545. */
  162546. /*
  162547. * Terminate source --- called by jpeg_finish_decompress
  162548. * after all data has been read. Often a no-op.
  162549. *
  162550. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  162551. * application must deal with any cleanup that should happen even
  162552. * for error exit.
  162553. */
  162554. METHODDEF(void)
  162555. term_source (j_decompress_ptr cinfo)
  162556. {
  162557. /* no work necessary here */
  162558. }
  162559. /*
  162560. * Prepare for input from a stdio stream.
  162561. * The caller must have already opened the stream, and is responsible
  162562. * for closing it after finishing decompression.
  162563. */
  162564. GLOBAL(void)
  162565. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  162566. {
  162567. my_src_ptr src;
  162568. /* The source object and input buffer are made permanent so that a series
  162569. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  162570. * only before the first one. (If we discarded the buffer at the end of
  162571. * one image, we'd likely lose the start of the next one.)
  162572. * This makes it unsafe to use this manager and a different source
  162573. * manager serially with the same JPEG object. Caveat programmer.
  162574. */
  162575. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  162576. cinfo->src = (struct jpeg_source_mgr *)
  162577. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  162578. SIZEOF(my_source_mgr));
  162579. src = (my_src_ptr) cinfo->src;
  162580. src->buffer = (JOCTET *)
  162581. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  162582. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  162583. }
  162584. src = (my_src_ptr) cinfo->src;
  162585. src->pub.init_source = init_source;
  162586. src->pub.fill_input_buffer = fill_input_buffer;
  162587. src->pub.skip_input_data = skip_input_data;
  162588. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  162589. src->pub.term_source = term_source;
  162590. src->infile = infile;
  162591. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  162592. src->pub.next_input_byte = NULL; /* until buffer loaded */
  162593. }
  162594. /********* End of inlined file: jdatasrc.c *********/
  162595. /********* Start of inlined file: jdcoefct.c *********/
  162596. #define JPEG_INTERNALS
  162597. /* Block smoothing is only applicable for progressive JPEG, so: */
  162598. #ifndef D_PROGRESSIVE_SUPPORTED
  162599. #undef BLOCK_SMOOTHING_SUPPORTED
  162600. #endif
  162601. /* Private buffer controller object */
  162602. typedef struct {
  162603. struct jpeg_d_coef_controller pub; /* public fields */
  162604. /* These variables keep track of the current location of the input side. */
  162605. /* cinfo->input_iMCU_row is also used for this. */
  162606. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  162607. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  162608. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  162609. /* The output side's location is represented by cinfo->output_iMCU_row. */
  162610. /* In single-pass modes, it's sufficient to buffer just one MCU.
  162611. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  162612. * and let the entropy decoder write into that workspace each time.
  162613. * (On 80x86, the workspace is FAR even though it's not really very big;
  162614. * this is to keep the module interfaces unchanged when a large coefficient
  162615. * buffer is necessary.)
  162616. * In multi-pass modes, this array points to the current MCU's blocks
  162617. * within the virtual arrays; it is used only by the input side.
  162618. */
  162619. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  162620. #ifdef D_MULTISCAN_FILES_SUPPORTED
  162621. /* In multi-pass modes, we need a virtual block array for each component. */
  162622. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  162623. #endif
  162624. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162625. /* When doing block smoothing, we latch coefficient Al values here */
  162626. int * coef_bits_latch;
  162627. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  162628. #endif
  162629. } my_coef_controller3;
  162630. typedef my_coef_controller3 * my_coef_ptr3;
  162631. /* Forward declarations */
  162632. METHODDEF(int) decompress_onepass
  162633. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  162634. #ifdef D_MULTISCAN_FILES_SUPPORTED
  162635. METHODDEF(int) decompress_data
  162636. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  162637. #endif
  162638. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162639. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  162640. METHODDEF(int) decompress_smooth_data
  162641. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  162642. #endif
  162643. LOCAL(void)
  162644. start_iMCU_row3 (j_decompress_ptr cinfo)
  162645. /* Reset within-iMCU-row counters for a new row (input side) */
  162646. {
  162647. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162648. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162649. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162650. * But at the bottom of the image, process only what's left.
  162651. */
  162652. if (cinfo->comps_in_scan > 1) {
  162653. coef->MCU_rows_per_iMCU_row = 1;
  162654. } else {
  162655. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  162656. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162657. else
  162658. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162659. }
  162660. coef->MCU_ctr = 0;
  162661. coef->MCU_vert_offset = 0;
  162662. }
  162663. /*
  162664. * Initialize for an input processing pass.
  162665. */
  162666. METHODDEF(void)
  162667. start_input_pass (j_decompress_ptr cinfo)
  162668. {
  162669. cinfo->input_iMCU_row = 0;
  162670. start_iMCU_row3(cinfo);
  162671. }
  162672. /*
  162673. * Initialize for an output processing pass.
  162674. */
  162675. METHODDEF(void)
  162676. start_output_pass (j_decompress_ptr cinfo)
  162677. {
  162678. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162679. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162680. /* If multipass, check to see whether to use block smoothing on this pass */
  162681. if (coef->pub.coef_arrays != NULL) {
  162682. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  162683. coef->pub.decompress_data = decompress_smooth_data;
  162684. else
  162685. coef->pub.decompress_data = decompress_data;
  162686. }
  162687. #endif
  162688. cinfo->output_iMCU_row = 0;
  162689. }
  162690. /*
  162691. * Decompress and return some data in the single-pass case.
  162692. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  162693. * Input and output must run in lockstep since we have only a one-MCU buffer.
  162694. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  162695. *
  162696. * NB: output_buf contains a plane for each component in image,
  162697. * which we index according to the component's SOF position.
  162698. */
  162699. METHODDEF(int)
  162700. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  162701. {
  162702. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162703. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162704. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162705. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162706. int blkn, ci, xindex, yindex, yoffset, useful_width;
  162707. JSAMPARRAY output_ptr;
  162708. JDIMENSION start_col, output_col;
  162709. jpeg_component_info *compptr;
  162710. inverse_DCT_method_ptr inverse_DCT;
  162711. /* Loop to process as much as one whole iMCU row */
  162712. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162713. yoffset++) {
  162714. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  162715. MCU_col_num++) {
  162716. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  162717. jzero_far((void FAR *) coef->MCU_buffer[0],
  162718. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  162719. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  162720. /* Suspension forced; update state counters and exit */
  162721. coef->MCU_vert_offset = yoffset;
  162722. coef->MCU_ctr = MCU_col_num;
  162723. return JPEG_SUSPENDED;
  162724. }
  162725. /* Determine where data should go in output_buf and do the IDCT thing.
  162726. * We skip dummy blocks at the right and bottom edges (but blkn gets
  162727. * incremented past them!). Note the inner loop relies on having
  162728. * allocated the MCU_buffer[] blocks sequentially.
  162729. */
  162730. blkn = 0; /* index of current DCT block within MCU */
  162731. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162732. compptr = cinfo->cur_comp_info[ci];
  162733. /* Don't bother to IDCT an uninteresting component. */
  162734. if (! compptr->component_needed) {
  162735. blkn += compptr->MCU_blocks;
  162736. continue;
  162737. }
  162738. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  162739. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162740. : compptr->last_col_width;
  162741. output_ptr = output_buf[compptr->component_index] +
  162742. yoffset * compptr->DCT_scaled_size;
  162743. start_col = MCU_col_num * compptr->MCU_sample_width;
  162744. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162745. if (cinfo->input_iMCU_row < last_iMCU_row ||
  162746. yoffset+yindex < compptr->last_row_height) {
  162747. output_col = start_col;
  162748. for (xindex = 0; xindex < useful_width; xindex++) {
  162749. (*inverse_DCT) (cinfo, compptr,
  162750. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  162751. output_ptr, output_col);
  162752. output_col += compptr->DCT_scaled_size;
  162753. }
  162754. }
  162755. blkn += compptr->MCU_width;
  162756. output_ptr += compptr->DCT_scaled_size;
  162757. }
  162758. }
  162759. }
  162760. /* Completed an MCU row, but perhaps not an iMCU row */
  162761. coef->MCU_ctr = 0;
  162762. }
  162763. /* Completed the iMCU row, advance counters for next one */
  162764. cinfo->output_iMCU_row++;
  162765. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  162766. start_iMCU_row3(cinfo);
  162767. return JPEG_ROW_COMPLETED;
  162768. }
  162769. /* Completed the scan */
  162770. (*cinfo->inputctl->finish_input_pass) (cinfo);
  162771. return JPEG_SCAN_COMPLETED;
  162772. }
  162773. /*
  162774. * Dummy consume-input routine for single-pass operation.
  162775. */
  162776. METHODDEF(int)
  162777. dummy_consume_data (j_decompress_ptr cinfo)
  162778. {
  162779. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  162780. }
  162781. #ifdef D_MULTISCAN_FILES_SUPPORTED
  162782. /*
  162783. * Consume input data and store it in the full-image coefficient buffer.
  162784. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  162785. * ie, v_samp_factor block rows for each component in the scan.
  162786. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  162787. */
  162788. METHODDEF(int)
  162789. consume_data (j_decompress_ptr cinfo)
  162790. {
  162791. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162792. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162793. int blkn, ci, xindex, yindex, yoffset;
  162794. JDIMENSION start_col;
  162795. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162796. JBLOCKROW buffer_ptr;
  162797. jpeg_component_info *compptr;
  162798. /* Align the virtual buffers for the components used in this scan. */
  162799. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162800. compptr = cinfo->cur_comp_info[ci];
  162801. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162802. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162803. cinfo->input_iMCU_row * compptr->v_samp_factor,
  162804. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162805. /* Note: entropy decoder expects buffer to be zeroed,
  162806. * but this is handled automatically by the memory manager
  162807. * because we requested a pre-zeroed array.
  162808. */
  162809. }
  162810. /* Loop to process one whole iMCU row */
  162811. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162812. yoffset++) {
  162813. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162814. MCU_col_num++) {
  162815. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162816. blkn = 0; /* index of current DCT block within MCU */
  162817. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162818. compptr = cinfo->cur_comp_info[ci];
  162819. start_col = MCU_col_num * compptr->MCU_width;
  162820. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162821. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162822. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162823. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162824. }
  162825. }
  162826. }
  162827. /* Try to fetch the MCU. */
  162828. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  162829. /* Suspension forced; update state counters and exit */
  162830. coef->MCU_vert_offset = yoffset;
  162831. coef->MCU_ctr = MCU_col_num;
  162832. return JPEG_SUSPENDED;
  162833. }
  162834. }
  162835. /* Completed an MCU row, but perhaps not an iMCU row */
  162836. coef->MCU_ctr = 0;
  162837. }
  162838. /* Completed the iMCU row, advance counters for next one */
  162839. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  162840. start_iMCU_row3(cinfo);
  162841. return JPEG_ROW_COMPLETED;
  162842. }
  162843. /* Completed the scan */
  162844. (*cinfo->inputctl->finish_input_pass) (cinfo);
  162845. return JPEG_SCAN_COMPLETED;
  162846. }
  162847. /*
  162848. * Decompress and return some data in the multi-pass case.
  162849. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  162850. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  162851. *
  162852. * NB: output_buf contains a plane for each component in image.
  162853. */
  162854. METHODDEF(int)
  162855. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  162856. {
  162857. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162858. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162859. JDIMENSION block_num;
  162860. int ci, block_row, block_rows;
  162861. JBLOCKARRAY buffer;
  162862. JBLOCKROW buffer_ptr;
  162863. JSAMPARRAY output_ptr;
  162864. JDIMENSION output_col;
  162865. jpeg_component_info *compptr;
  162866. inverse_DCT_method_ptr inverse_DCT;
  162867. /* Force some input to be done if we are getting ahead of the input. */
  162868. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  162869. (cinfo->input_scan_number == cinfo->output_scan_number &&
  162870. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  162871. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  162872. return JPEG_SUSPENDED;
  162873. }
  162874. /* OK, output from the virtual arrays. */
  162875. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162876. ci++, compptr++) {
  162877. /* Don't bother to IDCT an uninteresting component. */
  162878. if (! compptr->component_needed)
  162879. continue;
  162880. /* Align the virtual buffer for this component. */
  162881. buffer = (*cinfo->mem->access_virt_barray)
  162882. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162883. cinfo->output_iMCU_row * compptr->v_samp_factor,
  162884. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162885. /* Count non-dummy DCT block rows in this iMCU row. */
  162886. if (cinfo->output_iMCU_row < last_iMCU_row)
  162887. block_rows = compptr->v_samp_factor;
  162888. else {
  162889. /* NB: can't use last_row_height here; it is input-side-dependent! */
  162890. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162891. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162892. }
  162893. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  162894. output_ptr = output_buf[ci];
  162895. /* Loop over all DCT blocks to be processed. */
  162896. for (block_row = 0; block_row < block_rows; block_row++) {
  162897. buffer_ptr = buffer[block_row];
  162898. output_col = 0;
  162899. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  162900. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  162901. output_ptr, output_col);
  162902. buffer_ptr++;
  162903. output_col += compptr->DCT_scaled_size;
  162904. }
  162905. output_ptr += compptr->DCT_scaled_size;
  162906. }
  162907. }
  162908. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  162909. return JPEG_ROW_COMPLETED;
  162910. return JPEG_SCAN_COMPLETED;
  162911. }
  162912. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  162913. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162914. /*
  162915. * This code applies interblock smoothing as described by section K.8
  162916. * of the JPEG standard: the first 5 AC coefficients are estimated from
  162917. * the DC values of a DCT block and its 8 neighboring blocks.
  162918. * We apply smoothing only for progressive JPEG decoding, and only if
  162919. * the coefficients it can estimate are not yet known to full precision.
  162920. */
  162921. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  162922. #define Q01_POS 1
  162923. #define Q10_POS 8
  162924. #define Q20_POS 16
  162925. #define Q11_POS 9
  162926. #define Q02_POS 2
  162927. /*
  162928. * Determine whether block smoothing is applicable and safe.
  162929. * We also latch the current states of the coef_bits[] entries for the
  162930. * AC coefficients; otherwise, if the input side of the decompressor
  162931. * advances into a new scan, we might think the coefficients are known
  162932. * more accurately than they really are.
  162933. */
  162934. LOCAL(boolean)
  162935. smoothing_ok (j_decompress_ptr cinfo)
  162936. {
  162937. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162938. boolean smoothing_useful = FALSE;
  162939. int ci, coefi;
  162940. jpeg_component_info *compptr;
  162941. JQUANT_TBL * qtable;
  162942. int * coef_bits;
  162943. int * coef_bits_latch;
  162944. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  162945. return FALSE;
  162946. /* Allocate latch area if not already done */
  162947. if (coef->coef_bits_latch == NULL)
  162948. coef->coef_bits_latch = (int *)
  162949. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162950. cinfo->num_components *
  162951. (SAVED_COEFS * SIZEOF(int)));
  162952. coef_bits_latch = coef->coef_bits_latch;
  162953. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162954. ci++, compptr++) {
  162955. /* All components' quantization values must already be latched. */
  162956. if ((qtable = compptr->quant_table) == NULL)
  162957. return FALSE;
  162958. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  162959. if (qtable->quantval[0] == 0 ||
  162960. qtable->quantval[Q01_POS] == 0 ||
  162961. qtable->quantval[Q10_POS] == 0 ||
  162962. qtable->quantval[Q20_POS] == 0 ||
  162963. qtable->quantval[Q11_POS] == 0 ||
  162964. qtable->quantval[Q02_POS] == 0)
  162965. return FALSE;
  162966. /* DC values must be at least partly known for all components. */
  162967. coef_bits = cinfo->coef_bits[ci];
  162968. if (coef_bits[0] < 0)
  162969. return FALSE;
  162970. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  162971. for (coefi = 1; coefi <= 5; coefi++) {
  162972. coef_bits_latch[coefi] = coef_bits[coefi];
  162973. if (coef_bits[coefi] != 0)
  162974. smoothing_useful = TRUE;
  162975. }
  162976. coef_bits_latch += SAVED_COEFS;
  162977. }
  162978. return smoothing_useful;
  162979. }
  162980. /*
  162981. * Variant of decompress_data for use when doing block smoothing.
  162982. */
  162983. METHODDEF(int)
  162984. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  162985. {
  162986. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162987. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162988. JDIMENSION block_num, last_block_column;
  162989. int ci, block_row, block_rows, access_rows;
  162990. JBLOCKARRAY buffer;
  162991. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  162992. JSAMPARRAY output_ptr;
  162993. JDIMENSION output_col;
  162994. jpeg_component_info *compptr;
  162995. inverse_DCT_method_ptr inverse_DCT;
  162996. boolean first_row, last_row;
  162997. JBLOCK workspace;
  162998. int *coef_bits;
  162999. JQUANT_TBL *quanttbl;
  163000. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  163001. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  163002. int Al, pred;
  163003. /* Force some input to be done if we are getting ahead of the input. */
  163004. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  163005. ! cinfo->inputctl->eoi_reached) {
  163006. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  163007. /* If input is working on current scan, we ordinarily want it to
  163008. * have completed the current row. But if input scan is DC,
  163009. * we want it to keep one row ahead so that next block row's DC
  163010. * values are up to date.
  163011. */
  163012. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  163013. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  163014. break;
  163015. }
  163016. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  163017. return JPEG_SUSPENDED;
  163018. }
  163019. /* OK, output from the virtual arrays. */
  163020. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163021. ci++, compptr++) {
  163022. /* Don't bother to IDCT an uninteresting component. */
  163023. if (! compptr->component_needed)
  163024. continue;
  163025. /* Count non-dummy DCT block rows in this iMCU row. */
  163026. if (cinfo->output_iMCU_row < last_iMCU_row) {
  163027. block_rows = compptr->v_samp_factor;
  163028. access_rows = block_rows * 2; /* this and next iMCU row */
  163029. last_row = FALSE;
  163030. } else {
  163031. /* NB: can't use last_row_height here; it is input-side-dependent! */
  163032. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  163033. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  163034. access_rows = block_rows; /* this iMCU row only */
  163035. last_row = TRUE;
  163036. }
  163037. /* Align the virtual buffer for this component. */
  163038. if (cinfo->output_iMCU_row > 0) {
  163039. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  163040. buffer = (*cinfo->mem->access_virt_barray)
  163041. ((j_common_ptr) cinfo, coef->whole_image[ci],
  163042. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  163043. (JDIMENSION) access_rows, FALSE);
  163044. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  163045. first_row = FALSE;
  163046. } else {
  163047. buffer = (*cinfo->mem->access_virt_barray)
  163048. ((j_common_ptr) cinfo, coef->whole_image[ci],
  163049. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  163050. first_row = TRUE;
  163051. }
  163052. /* Fetch component-dependent info */
  163053. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  163054. quanttbl = compptr->quant_table;
  163055. Q00 = quanttbl->quantval[0];
  163056. Q01 = quanttbl->quantval[Q01_POS];
  163057. Q10 = quanttbl->quantval[Q10_POS];
  163058. Q20 = quanttbl->quantval[Q20_POS];
  163059. Q11 = quanttbl->quantval[Q11_POS];
  163060. Q02 = quanttbl->quantval[Q02_POS];
  163061. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  163062. output_ptr = output_buf[ci];
  163063. /* Loop over all DCT blocks to be processed. */
  163064. for (block_row = 0; block_row < block_rows; block_row++) {
  163065. buffer_ptr = buffer[block_row];
  163066. if (first_row && block_row == 0)
  163067. prev_block_row = buffer_ptr;
  163068. else
  163069. prev_block_row = buffer[block_row-1];
  163070. if (last_row && block_row == block_rows-1)
  163071. next_block_row = buffer_ptr;
  163072. else
  163073. next_block_row = buffer[block_row+1];
  163074. /* We fetch the surrounding DC values using a sliding-register approach.
  163075. * Initialize all nine here so as to do the right thing on narrow pics.
  163076. */
  163077. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  163078. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  163079. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  163080. output_col = 0;
  163081. last_block_column = compptr->width_in_blocks - 1;
  163082. for (block_num = 0; block_num <= last_block_column; block_num++) {
  163083. /* Fetch current DCT block into workspace so we can modify it. */
  163084. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  163085. /* Update DC values */
  163086. if (block_num < last_block_column) {
  163087. DC3 = (int) prev_block_row[1][0];
  163088. DC6 = (int) buffer_ptr[1][0];
  163089. DC9 = (int) next_block_row[1][0];
  163090. }
  163091. /* Compute coefficient estimates per K.8.
  163092. * An estimate is applied only if coefficient is still zero,
  163093. * and is not known to be fully accurate.
  163094. */
  163095. /* AC01 */
  163096. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  163097. num = 36 * Q00 * (DC4 - DC6);
  163098. if (num >= 0) {
  163099. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  163100. if (Al > 0 && pred >= (1<<Al))
  163101. pred = (1<<Al)-1;
  163102. } else {
  163103. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  163104. if (Al > 0 && pred >= (1<<Al))
  163105. pred = (1<<Al)-1;
  163106. pred = -pred;
  163107. }
  163108. workspace[1] = (JCOEF) pred;
  163109. }
  163110. /* AC10 */
  163111. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  163112. num = 36 * Q00 * (DC2 - DC8);
  163113. if (num >= 0) {
  163114. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  163115. if (Al > 0 && pred >= (1<<Al))
  163116. pred = (1<<Al)-1;
  163117. } else {
  163118. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  163119. if (Al > 0 && pred >= (1<<Al))
  163120. pred = (1<<Al)-1;
  163121. pred = -pred;
  163122. }
  163123. workspace[8] = (JCOEF) pred;
  163124. }
  163125. /* AC20 */
  163126. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  163127. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  163128. if (num >= 0) {
  163129. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  163130. if (Al > 0 && pred >= (1<<Al))
  163131. pred = (1<<Al)-1;
  163132. } else {
  163133. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  163134. if (Al > 0 && pred >= (1<<Al))
  163135. pred = (1<<Al)-1;
  163136. pred = -pred;
  163137. }
  163138. workspace[16] = (JCOEF) pred;
  163139. }
  163140. /* AC11 */
  163141. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  163142. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  163143. if (num >= 0) {
  163144. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  163145. if (Al > 0 && pred >= (1<<Al))
  163146. pred = (1<<Al)-1;
  163147. } else {
  163148. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  163149. if (Al > 0 && pred >= (1<<Al))
  163150. pred = (1<<Al)-1;
  163151. pred = -pred;
  163152. }
  163153. workspace[9] = (JCOEF) pred;
  163154. }
  163155. /* AC02 */
  163156. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  163157. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  163158. if (num >= 0) {
  163159. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  163160. if (Al > 0 && pred >= (1<<Al))
  163161. pred = (1<<Al)-1;
  163162. } else {
  163163. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  163164. if (Al > 0 && pred >= (1<<Al))
  163165. pred = (1<<Al)-1;
  163166. pred = -pred;
  163167. }
  163168. workspace[2] = (JCOEF) pred;
  163169. }
  163170. /* OK, do the IDCT */
  163171. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  163172. output_ptr, output_col);
  163173. /* Advance for next column */
  163174. DC1 = DC2; DC2 = DC3;
  163175. DC4 = DC5; DC5 = DC6;
  163176. DC7 = DC8; DC8 = DC9;
  163177. buffer_ptr++, prev_block_row++, next_block_row++;
  163178. output_col += compptr->DCT_scaled_size;
  163179. }
  163180. output_ptr += compptr->DCT_scaled_size;
  163181. }
  163182. }
  163183. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  163184. return JPEG_ROW_COMPLETED;
  163185. return JPEG_SCAN_COMPLETED;
  163186. }
  163187. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  163188. /*
  163189. * Initialize coefficient buffer controller.
  163190. */
  163191. GLOBAL(void)
  163192. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  163193. {
  163194. my_coef_ptr3 coef;
  163195. coef = (my_coef_ptr3)
  163196. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163197. SIZEOF(my_coef_controller3));
  163198. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  163199. coef->pub.start_input_pass = start_input_pass;
  163200. coef->pub.start_output_pass = start_output_pass;
  163201. #ifdef BLOCK_SMOOTHING_SUPPORTED
  163202. coef->coef_bits_latch = NULL;
  163203. #endif
  163204. /* Create the coefficient buffer. */
  163205. if (need_full_buffer) {
  163206. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163207. /* Allocate a full-image virtual array for each component, */
  163208. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  163209. /* Note we ask for a pre-zeroed array. */
  163210. int ci, access_rows;
  163211. jpeg_component_info *compptr;
  163212. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163213. ci++, compptr++) {
  163214. access_rows = compptr->v_samp_factor;
  163215. #ifdef BLOCK_SMOOTHING_SUPPORTED
  163216. /* If block smoothing could be used, need a bigger window */
  163217. if (cinfo->progressive_mode)
  163218. access_rows *= 3;
  163219. #endif
  163220. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  163221. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  163222. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  163223. (long) compptr->h_samp_factor),
  163224. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163225. (long) compptr->v_samp_factor),
  163226. (JDIMENSION) access_rows);
  163227. }
  163228. coef->pub.consume_data = consume_data;
  163229. coef->pub.decompress_data = decompress_data;
  163230. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  163231. #else
  163232. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163233. #endif
  163234. } else {
  163235. /* We only need a single-MCU buffer. */
  163236. JBLOCKROW buffer;
  163237. int i;
  163238. buffer = (JBLOCKROW)
  163239. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163240. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163241. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  163242. coef->MCU_buffer[i] = buffer + i;
  163243. }
  163244. coef->pub.consume_data = dummy_consume_data;
  163245. coef->pub.decompress_data = decompress_onepass;
  163246. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  163247. }
  163248. }
  163249. /********* End of inlined file: jdcoefct.c *********/
  163250. #undef FIX
  163251. /********* Start of inlined file: jdcolor.c *********/
  163252. #define JPEG_INTERNALS
  163253. /* Private subobject */
  163254. typedef struct {
  163255. struct jpeg_color_deconverter pub; /* public fields */
  163256. /* Private state for YCC->RGB conversion */
  163257. int * Cr_r_tab; /* => table for Cr to R conversion */
  163258. int * Cb_b_tab; /* => table for Cb to B conversion */
  163259. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  163260. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  163261. } my_color_deconverter2;
  163262. typedef my_color_deconverter2 * my_cconvert_ptr2;
  163263. /**************** YCbCr -> RGB conversion: most common case **************/
  163264. /*
  163265. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  163266. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  163267. * The conversion equations to be implemented are therefore
  163268. * R = Y + 1.40200 * Cr
  163269. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  163270. * B = Y + 1.77200 * Cb
  163271. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  163272. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  163273. *
  163274. * To avoid floating-point arithmetic, we represent the fractional constants
  163275. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  163276. * the products by 2^16, with appropriate rounding, to get the correct answer.
  163277. * Notice that Y, being an integral input, does not contribute any fraction
  163278. * so it need not participate in the rounding.
  163279. *
  163280. * For even more speed, we avoid doing any multiplications in the inner loop
  163281. * by precalculating the constants times Cb and Cr for all possible values.
  163282. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  163283. * for 12-bit samples it is still acceptable. It's not very reasonable for
  163284. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  163285. * colorspace anyway.
  163286. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  163287. * values for the G calculation are left scaled up, since we must add them
  163288. * together before rounding.
  163289. */
  163290. #define SCALEBITS 16 /* speediest right-shift on some machines */
  163291. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  163292. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  163293. /*
  163294. * Initialize tables for YCC->RGB colorspace conversion.
  163295. */
  163296. LOCAL(void)
  163297. build_ycc_rgb_table (j_decompress_ptr cinfo)
  163298. {
  163299. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  163300. int i;
  163301. INT32 x;
  163302. SHIFT_TEMPS
  163303. cconvert->Cr_r_tab = (int *)
  163304. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163305. (MAXJSAMPLE+1) * SIZEOF(int));
  163306. cconvert->Cb_b_tab = (int *)
  163307. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163308. (MAXJSAMPLE+1) * SIZEOF(int));
  163309. cconvert->Cr_g_tab = (INT32 *)
  163310. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163311. (MAXJSAMPLE+1) * SIZEOF(INT32));
  163312. cconvert->Cb_g_tab = (INT32 *)
  163313. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163314. (MAXJSAMPLE+1) * SIZEOF(INT32));
  163315. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  163316. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  163317. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  163318. /* Cr=>R value is nearest int to 1.40200 * x */
  163319. cconvert->Cr_r_tab[i] = (int)
  163320. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  163321. /* Cb=>B value is nearest int to 1.77200 * x */
  163322. cconvert->Cb_b_tab[i] = (int)
  163323. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  163324. /* Cr=>G value is scaled-up -0.71414 * x */
  163325. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  163326. /* Cb=>G value is scaled-up -0.34414 * x */
  163327. /* We also add in ONE_HALF so that need not do it in inner loop */
  163328. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  163329. }
  163330. }
  163331. /*
  163332. * Convert some rows of samples to the output colorspace.
  163333. *
  163334. * Note that we change from noninterleaved, one-plane-per-component format
  163335. * to interleaved-pixel format. The output buffer is therefore three times
  163336. * as wide as the input buffer.
  163337. * A starting row offset is provided only for the input buffer. The caller
  163338. * can easily adjust the passed output_buf value to accommodate any row
  163339. * offset required on that side.
  163340. */
  163341. METHODDEF(void)
  163342. ycc_rgb_convert (j_decompress_ptr cinfo,
  163343. JSAMPIMAGE input_buf, JDIMENSION input_row,
  163344. JSAMPARRAY output_buf, int num_rows)
  163345. {
  163346. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  163347. register int y, cb, cr;
  163348. register JSAMPROW outptr;
  163349. register JSAMPROW inptr0, inptr1, inptr2;
  163350. register JDIMENSION col;
  163351. JDIMENSION num_cols = cinfo->output_width;
  163352. /* copy these pointers into registers if possible */
  163353. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  163354. register int * Crrtab = cconvert->Cr_r_tab;
  163355. register int * Cbbtab = cconvert->Cb_b_tab;
  163356. register INT32 * Crgtab = cconvert->Cr_g_tab;
  163357. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  163358. SHIFT_TEMPS
  163359. while (--num_rows >= 0) {
  163360. inptr0 = input_buf[0][input_row];
  163361. inptr1 = input_buf[1][input_row];
  163362. inptr2 = input_buf[2][input_row];
  163363. input_row++;
  163364. outptr = *output_buf++;
  163365. for (col = 0; col < num_cols; col++) {
  163366. y = GETJSAMPLE(inptr0[col]);
  163367. cb = GETJSAMPLE(inptr1[col]);
  163368. cr = GETJSAMPLE(inptr2[col]);
  163369. /* Range-limiting is essential due to noise introduced by DCT losses. */
  163370. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  163371. outptr[RGB_GREEN] = range_limit[y +
  163372. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  163373. SCALEBITS))];
  163374. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  163375. outptr += RGB_PIXELSIZE;
  163376. }
  163377. }
  163378. }
  163379. /**************** Cases other than YCbCr -> RGB **************/
  163380. /*
  163381. * Color conversion for no colorspace change: just copy the data,
  163382. * converting from separate-planes to interleaved representation.
  163383. */
  163384. METHODDEF(void)
  163385. null_convert2 (j_decompress_ptr cinfo,
  163386. JSAMPIMAGE input_buf, JDIMENSION input_row,
  163387. JSAMPARRAY output_buf, int num_rows)
  163388. {
  163389. register JSAMPROW inptr, outptr;
  163390. register JDIMENSION count;
  163391. register int num_components = cinfo->num_components;
  163392. JDIMENSION num_cols = cinfo->output_width;
  163393. int ci;
  163394. while (--num_rows >= 0) {
  163395. for (ci = 0; ci < num_components; ci++) {
  163396. inptr = input_buf[ci][input_row];
  163397. outptr = output_buf[0] + ci;
  163398. for (count = num_cols; count > 0; count--) {
  163399. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  163400. outptr += num_components;
  163401. }
  163402. }
  163403. input_row++;
  163404. output_buf++;
  163405. }
  163406. }
  163407. /*
  163408. * Color conversion for grayscale: just copy the data.
  163409. * This also works for YCbCr -> grayscale conversion, in which
  163410. * we just copy the Y (luminance) component and ignore chrominance.
  163411. */
  163412. METHODDEF(void)
  163413. grayscale_convert2 (j_decompress_ptr cinfo,
  163414. JSAMPIMAGE input_buf, JDIMENSION input_row,
  163415. JSAMPARRAY output_buf, int num_rows)
  163416. {
  163417. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  163418. num_rows, cinfo->output_width);
  163419. }
  163420. /*
  163421. * Convert grayscale to RGB: just duplicate the graylevel three times.
  163422. * This is provided to support applications that don't want to cope
  163423. * with grayscale as a separate case.
  163424. */
  163425. METHODDEF(void)
  163426. gray_rgb_convert (j_decompress_ptr cinfo,
  163427. JSAMPIMAGE input_buf, JDIMENSION input_row,
  163428. JSAMPARRAY output_buf, int num_rows)
  163429. {
  163430. register JSAMPROW inptr, outptr;
  163431. register JDIMENSION col;
  163432. JDIMENSION num_cols = cinfo->output_width;
  163433. while (--num_rows >= 0) {
  163434. inptr = input_buf[0][input_row++];
  163435. outptr = *output_buf++;
  163436. for (col = 0; col < num_cols; col++) {
  163437. /* We can dispense with GETJSAMPLE() here */
  163438. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  163439. outptr += RGB_PIXELSIZE;
  163440. }
  163441. }
  163442. }
  163443. /*
  163444. * Adobe-style YCCK->CMYK conversion.
  163445. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  163446. * conversion as above, while passing K (black) unchanged.
  163447. * We assume build_ycc_rgb_table has been called.
  163448. */
  163449. METHODDEF(void)
  163450. ycck_cmyk_convert (j_decompress_ptr cinfo,
  163451. JSAMPIMAGE input_buf, JDIMENSION input_row,
  163452. JSAMPARRAY output_buf, int num_rows)
  163453. {
  163454. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  163455. register int y, cb, cr;
  163456. register JSAMPROW outptr;
  163457. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  163458. register JDIMENSION col;
  163459. JDIMENSION num_cols = cinfo->output_width;
  163460. /* copy these pointers into registers if possible */
  163461. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  163462. register int * Crrtab = cconvert->Cr_r_tab;
  163463. register int * Cbbtab = cconvert->Cb_b_tab;
  163464. register INT32 * Crgtab = cconvert->Cr_g_tab;
  163465. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  163466. SHIFT_TEMPS
  163467. while (--num_rows >= 0) {
  163468. inptr0 = input_buf[0][input_row];
  163469. inptr1 = input_buf[1][input_row];
  163470. inptr2 = input_buf[2][input_row];
  163471. inptr3 = input_buf[3][input_row];
  163472. input_row++;
  163473. outptr = *output_buf++;
  163474. for (col = 0; col < num_cols; col++) {
  163475. y = GETJSAMPLE(inptr0[col]);
  163476. cb = GETJSAMPLE(inptr1[col]);
  163477. cr = GETJSAMPLE(inptr2[col]);
  163478. /* Range-limiting is essential due to noise introduced by DCT losses. */
  163479. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  163480. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  163481. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  163482. SCALEBITS)))];
  163483. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  163484. /* K passes through unchanged */
  163485. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  163486. outptr += 4;
  163487. }
  163488. }
  163489. }
  163490. /*
  163491. * Empty method for start_pass.
  163492. */
  163493. METHODDEF(void)
  163494. start_pass_dcolor (j_decompress_ptr cinfo)
  163495. {
  163496. /* no work needed */
  163497. }
  163498. /*
  163499. * Module initialization routine for output colorspace conversion.
  163500. */
  163501. GLOBAL(void)
  163502. jinit_color_deconverter (j_decompress_ptr cinfo)
  163503. {
  163504. my_cconvert_ptr2 cconvert;
  163505. int ci;
  163506. cconvert = (my_cconvert_ptr2)
  163507. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163508. SIZEOF(my_color_deconverter2));
  163509. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  163510. cconvert->pub.start_pass = start_pass_dcolor;
  163511. /* Make sure num_components agrees with jpeg_color_space */
  163512. switch (cinfo->jpeg_color_space) {
  163513. case JCS_GRAYSCALE:
  163514. if (cinfo->num_components != 1)
  163515. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163516. break;
  163517. case JCS_RGB:
  163518. case JCS_YCbCr:
  163519. if (cinfo->num_components != 3)
  163520. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163521. break;
  163522. case JCS_CMYK:
  163523. case JCS_YCCK:
  163524. if (cinfo->num_components != 4)
  163525. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163526. break;
  163527. default: /* JCS_UNKNOWN can be anything */
  163528. if (cinfo->num_components < 1)
  163529. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163530. break;
  163531. }
  163532. /* Set out_color_components and conversion method based on requested space.
  163533. * Also clear the component_needed flags for any unused components,
  163534. * so that earlier pipeline stages can avoid useless computation.
  163535. */
  163536. switch (cinfo->out_color_space) {
  163537. case JCS_GRAYSCALE:
  163538. cinfo->out_color_components = 1;
  163539. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  163540. cinfo->jpeg_color_space == JCS_YCbCr) {
  163541. cconvert->pub.color_convert = grayscale_convert2;
  163542. /* For color->grayscale conversion, only the Y (0) component is needed */
  163543. for (ci = 1; ci < cinfo->num_components; ci++)
  163544. cinfo->comp_info[ci].component_needed = FALSE;
  163545. } else
  163546. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163547. break;
  163548. case JCS_RGB:
  163549. cinfo->out_color_components = RGB_PIXELSIZE;
  163550. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  163551. cconvert->pub.color_convert = ycc_rgb_convert;
  163552. build_ycc_rgb_table(cinfo);
  163553. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  163554. cconvert->pub.color_convert = gray_rgb_convert;
  163555. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  163556. cconvert->pub.color_convert = null_convert2;
  163557. } else
  163558. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163559. break;
  163560. case JCS_CMYK:
  163561. cinfo->out_color_components = 4;
  163562. if (cinfo->jpeg_color_space == JCS_YCCK) {
  163563. cconvert->pub.color_convert = ycck_cmyk_convert;
  163564. build_ycc_rgb_table(cinfo);
  163565. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  163566. cconvert->pub.color_convert = null_convert2;
  163567. } else
  163568. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163569. break;
  163570. default:
  163571. /* Permit null conversion to same output space */
  163572. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  163573. cinfo->out_color_components = cinfo->num_components;
  163574. cconvert->pub.color_convert = null_convert2;
  163575. } else /* unsupported non-null conversion */
  163576. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163577. break;
  163578. }
  163579. if (cinfo->quantize_colors)
  163580. cinfo->output_components = 1; /* single colormapped output component */
  163581. else
  163582. cinfo->output_components = cinfo->out_color_components;
  163583. }
  163584. /********* End of inlined file: jdcolor.c *********/
  163585. #undef FIX
  163586. /********* Start of inlined file: jddctmgr.c *********/
  163587. #define JPEG_INTERNALS
  163588. /*
  163589. * The decompressor input side (jdinput.c) saves away the appropriate
  163590. * quantization table for each component at the start of the first scan
  163591. * involving that component. (This is necessary in order to correctly
  163592. * decode files that reuse Q-table slots.)
  163593. * When we are ready to make an output pass, the saved Q-table is converted
  163594. * to a multiplier table that will actually be used by the IDCT routine.
  163595. * The multiplier table contents are IDCT-method-dependent. To support
  163596. * application changes in IDCT method between scans, we can remake the
  163597. * multiplier tables if necessary.
  163598. * In buffered-image mode, the first output pass may occur before any data
  163599. * has been seen for some components, and thus before their Q-tables have
  163600. * been saved away. To handle this case, multiplier tables are preset
  163601. * to zeroes; the result of the IDCT will be a neutral gray level.
  163602. */
  163603. /* Private subobject for this module */
  163604. typedef struct {
  163605. struct jpeg_inverse_dct pub; /* public fields */
  163606. /* This array contains the IDCT method code that each multiplier table
  163607. * is currently set up for, or -1 if it's not yet set up.
  163608. * The actual multiplier tables are pointed to by dct_table in the
  163609. * per-component comp_info structures.
  163610. */
  163611. int cur_method[MAX_COMPONENTS];
  163612. } my_idct_controller;
  163613. typedef my_idct_controller * my_idct_ptr;
  163614. /* Allocated multiplier tables: big enough for any supported variant */
  163615. typedef union {
  163616. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  163617. #ifdef DCT_IFAST_SUPPORTED
  163618. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  163619. #endif
  163620. #ifdef DCT_FLOAT_SUPPORTED
  163621. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  163622. #endif
  163623. } multiplier_table;
  163624. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  163625. * so be sure to compile that code if either ISLOW or SCALING is requested.
  163626. */
  163627. #ifdef DCT_ISLOW_SUPPORTED
  163628. #define PROVIDE_ISLOW_TABLES
  163629. #else
  163630. #ifdef IDCT_SCALING_SUPPORTED
  163631. #define PROVIDE_ISLOW_TABLES
  163632. #endif
  163633. #endif
  163634. /*
  163635. * Prepare for an output pass.
  163636. * Here we select the proper IDCT routine for each component and build
  163637. * a matching multiplier table.
  163638. */
  163639. METHODDEF(void)
  163640. start_pass (j_decompress_ptr cinfo)
  163641. {
  163642. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  163643. int ci, i;
  163644. jpeg_component_info *compptr;
  163645. int method = 0;
  163646. inverse_DCT_method_ptr method_ptr = NULL;
  163647. JQUANT_TBL * qtbl;
  163648. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163649. ci++, compptr++) {
  163650. /* Select the proper IDCT routine for this component's scaling */
  163651. switch (compptr->DCT_scaled_size) {
  163652. #ifdef IDCT_SCALING_SUPPORTED
  163653. case 1:
  163654. method_ptr = jpeg_idct_1x1;
  163655. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  163656. break;
  163657. case 2:
  163658. method_ptr = jpeg_idct_2x2;
  163659. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  163660. break;
  163661. case 4:
  163662. method_ptr = jpeg_idct_4x4;
  163663. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  163664. break;
  163665. #endif
  163666. case DCTSIZE:
  163667. switch (cinfo->dct_method) {
  163668. #ifdef DCT_ISLOW_SUPPORTED
  163669. case JDCT_ISLOW:
  163670. method_ptr = jpeg_idct_islow;
  163671. method = JDCT_ISLOW;
  163672. break;
  163673. #endif
  163674. #ifdef DCT_IFAST_SUPPORTED
  163675. case JDCT_IFAST:
  163676. method_ptr = jpeg_idct_ifast;
  163677. method = JDCT_IFAST;
  163678. break;
  163679. #endif
  163680. #ifdef DCT_FLOAT_SUPPORTED
  163681. case JDCT_FLOAT:
  163682. method_ptr = jpeg_idct_float;
  163683. method = JDCT_FLOAT;
  163684. break;
  163685. #endif
  163686. default:
  163687. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163688. break;
  163689. }
  163690. break;
  163691. default:
  163692. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  163693. break;
  163694. }
  163695. idct->pub.inverse_DCT[ci] = method_ptr;
  163696. /* Create multiplier table from quant table.
  163697. * However, we can skip this if the component is uninteresting
  163698. * or if we already built the table. Also, if no quant table
  163699. * has yet been saved for the component, we leave the
  163700. * multiplier table all-zero; we'll be reading zeroes from the
  163701. * coefficient controller's buffer anyway.
  163702. */
  163703. if (! compptr->component_needed || idct->cur_method[ci] == method)
  163704. continue;
  163705. qtbl = compptr->quant_table;
  163706. if (qtbl == NULL) /* happens if no data yet for component */
  163707. continue;
  163708. idct->cur_method[ci] = method;
  163709. switch (method) {
  163710. #ifdef PROVIDE_ISLOW_TABLES
  163711. case JDCT_ISLOW:
  163712. {
  163713. /* For LL&M IDCT method, multipliers are equal to raw quantization
  163714. * coefficients, but are stored as ints to ensure access efficiency.
  163715. */
  163716. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  163717. for (i = 0; i < DCTSIZE2; i++) {
  163718. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  163719. }
  163720. }
  163721. break;
  163722. #endif
  163723. #ifdef DCT_IFAST_SUPPORTED
  163724. case JDCT_IFAST:
  163725. {
  163726. /* For AA&N IDCT method, multipliers are equal to quantization
  163727. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163728. * scalefactor[0] = 1
  163729. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163730. * For integer operation, the multiplier table is to be scaled by
  163731. * IFAST_SCALE_BITS.
  163732. */
  163733. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  163734. #define CONST_BITS 14
  163735. static const INT16 aanscales[DCTSIZE2] = {
  163736. /* precomputed values scaled up by 14 bits */
  163737. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163738. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  163739. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  163740. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  163741. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163742. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  163743. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  163744. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  163745. };
  163746. SHIFT_TEMPS
  163747. for (i = 0; i < DCTSIZE2; i++) {
  163748. ifmtbl[i] = (IFAST_MULT_TYPE)
  163749. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  163750. (INT32) aanscales[i]),
  163751. CONST_BITS-IFAST_SCALE_BITS);
  163752. }
  163753. }
  163754. break;
  163755. #endif
  163756. #ifdef DCT_FLOAT_SUPPORTED
  163757. case JDCT_FLOAT:
  163758. {
  163759. /* For float AA&N IDCT method, multipliers are equal to quantization
  163760. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163761. * scalefactor[0] = 1
  163762. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163763. */
  163764. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  163765. int row, col;
  163766. static const double aanscalefactor[DCTSIZE] = {
  163767. 1.0, 1.387039845, 1.306562965, 1.175875602,
  163768. 1.0, 0.785694958, 0.541196100, 0.275899379
  163769. };
  163770. i = 0;
  163771. for (row = 0; row < DCTSIZE; row++) {
  163772. for (col = 0; col < DCTSIZE; col++) {
  163773. fmtbl[i] = (FLOAT_MULT_TYPE)
  163774. ((double) qtbl->quantval[i] *
  163775. aanscalefactor[row] * aanscalefactor[col]);
  163776. i++;
  163777. }
  163778. }
  163779. }
  163780. break;
  163781. #endif
  163782. default:
  163783. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163784. break;
  163785. }
  163786. }
  163787. }
  163788. /*
  163789. * Initialize IDCT manager.
  163790. */
  163791. GLOBAL(void)
  163792. jinit_inverse_dct (j_decompress_ptr cinfo)
  163793. {
  163794. my_idct_ptr idct;
  163795. int ci;
  163796. jpeg_component_info *compptr;
  163797. idct = (my_idct_ptr)
  163798. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163799. SIZEOF(my_idct_controller));
  163800. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  163801. idct->pub.start_pass = start_pass;
  163802. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163803. ci++, compptr++) {
  163804. /* Allocate and pre-zero a multiplier table for each component */
  163805. compptr->dct_table =
  163806. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163807. SIZEOF(multiplier_table));
  163808. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  163809. /* Mark multiplier table not yet set up for any method */
  163810. idct->cur_method[ci] = -1;
  163811. }
  163812. }
  163813. /********* End of inlined file: jddctmgr.c *********/
  163814. #undef CONST_BITS
  163815. #undef ASSIGN_STATE
  163816. /********* Start of inlined file: jdhuff.c *********/
  163817. #define JPEG_INTERNALS
  163818. /********* Start of inlined file: jdhuff.h *********/
  163819. /* Short forms of external names for systems with brain-damaged linkers. */
  163820. #ifndef __jdhuff_h__
  163821. #define __jdhuff_h__
  163822. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163823. #define jpeg_make_d_derived_tbl jMkDDerived
  163824. #define jpeg_fill_bit_buffer jFilBitBuf
  163825. #define jpeg_huff_decode jHufDecode
  163826. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163827. /* Derived data constructed for each Huffman table */
  163828. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  163829. typedef struct {
  163830. /* Basic tables: (element [0] of each array is unused) */
  163831. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  163832. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  163833. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  163834. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  163835. * the smallest code of length k; so given a code of length k, the
  163836. * corresponding symbol is huffval[code + valoffset[k]]
  163837. */
  163838. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  163839. JHUFF_TBL *pub;
  163840. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  163841. * the input data stream. If the next Huffman code is no more
  163842. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  163843. * the corresponding symbol directly from these tables.
  163844. */
  163845. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  163846. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  163847. } d_derived_tbl;
  163848. /* Expand a Huffman table definition into the derived format */
  163849. EXTERN(void) jpeg_make_d_derived_tbl
  163850. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  163851. d_derived_tbl ** pdtbl));
  163852. /*
  163853. * Fetching the next N bits from the input stream is a time-critical operation
  163854. * for the Huffman decoders. We implement it with a combination of inline
  163855. * macros and out-of-line subroutines. Note that N (the number of bits
  163856. * demanded at one time) never exceeds 15 for JPEG use.
  163857. *
  163858. * We read source bytes into get_buffer and dole out bits as needed.
  163859. * If get_buffer already contains enough bits, they are fetched in-line
  163860. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  163861. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  163862. * as full as possible (not just to the number of bits needed; this
  163863. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  163864. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  163865. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  163866. * at least the requested number of bits --- dummy zeroes are inserted if
  163867. * necessary.
  163868. */
  163869. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  163870. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  163871. /* If long is > 32 bits on your machine, and shifting/masking longs is
  163872. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  163873. * appropriately should be a win. Unfortunately we can't define the size
  163874. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  163875. * because not all machines measure sizeof in 8-bit bytes.
  163876. */
  163877. typedef struct { /* Bitreading state saved across MCUs */
  163878. bit_buf_type get_buffer; /* current bit-extraction buffer */
  163879. int bits_left; /* # of unused bits in it */
  163880. } bitread_perm_state;
  163881. typedef struct { /* Bitreading working state within an MCU */
  163882. /* Current data source location */
  163883. /* We need a copy, rather than munging the original, in case of suspension */
  163884. const JOCTET * next_input_byte; /* => next byte to read from source */
  163885. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  163886. /* Bit input buffer --- note these values are kept in register variables,
  163887. * not in this struct, inside the inner loops.
  163888. */
  163889. bit_buf_type get_buffer; /* current bit-extraction buffer */
  163890. int bits_left; /* # of unused bits in it */
  163891. /* Pointer needed by jpeg_fill_bit_buffer. */
  163892. j_decompress_ptr cinfo; /* back link to decompress master record */
  163893. } bitread_working_state;
  163894. /* Macros to declare and load/save bitread local variables. */
  163895. #define BITREAD_STATE_VARS \
  163896. register bit_buf_type get_buffer; \
  163897. register int bits_left; \
  163898. bitread_working_state br_state
  163899. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  163900. br_state.cinfo = cinfop; \
  163901. br_state.next_input_byte = cinfop->src->next_input_byte; \
  163902. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  163903. get_buffer = permstate.get_buffer; \
  163904. bits_left = permstate.bits_left;
  163905. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  163906. cinfop->src->next_input_byte = br_state.next_input_byte; \
  163907. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  163908. permstate.get_buffer = get_buffer; \
  163909. permstate.bits_left = bits_left
  163910. /*
  163911. * These macros provide the in-line portion of bit fetching.
  163912. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  163913. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  163914. * The variables get_buffer and bits_left are assumed to be locals,
  163915. * but the state struct might not be (jpeg_huff_decode needs this).
  163916. * CHECK_BIT_BUFFER(state,n,action);
  163917. * Ensure there are N bits in get_buffer; if suspend, take action.
  163918. * val = GET_BITS(n);
  163919. * Fetch next N bits.
  163920. * val = PEEK_BITS(n);
  163921. * Fetch next N bits without removing them from the buffer.
  163922. * DROP_BITS(n);
  163923. * Discard next N bits.
  163924. * The value N should be a simple variable, not an expression, because it
  163925. * is evaluated multiple times.
  163926. */
  163927. #define CHECK_BIT_BUFFER(state,nbits,action) \
  163928. { if (bits_left < (nbits)) { \
  163929. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  163930. { action; } \
  163931. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  163932. #define GET_BITS(nbits) \
  163933. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  163934. #define PEEK_BITS(nbits) \
  163935. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  163936. #define DROP_BITS(nbits) \
  163937. (bits_left -= (nbits))
  163938. /* Load up the bit buffer to a depth of at least nbits */
  163939. EXTERN(boolean) jpeg_fill_bit_buffer
  163940. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  163941. register int bits_left, int nbits));
  163942. /*
  163943. * Code for extracting next Huffman-coded symbol from input bit stream.
  163944. * Again, this is time-critical and we make the main paths be macros.
  163945. *
  163946. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  163947. * without looping. Usually, more than 95% of the Huffman codes will be 8
  163948. * or fewer bits long. The few overlength codes are handled with a loop,
  163949. * which need not be inline code.
  163950. *
  163951. * Notes about the HUFF_DECODE macro:
  163952. * 1. Near the end of the data segment, we may fail to get enough bits
  163953. * for a lookahead. In that case, we do it the hard way.
  163954. * 2. If the lookahead table contains no entry, the next code must be
  163955. * more than HUFF_LOOKAHEAD bits long.
  163956. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  163957. */
  163958. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  163959. { register int nb, look; \
  163960. if (bits_left < HUFF_LOOKAHEAD) { \
  163961. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  163962. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  163963. if (bits_left < HUFF_LOOKAHEAD) { \
  163964. nb = 1; goto slowlabel; \
  163965. } \
  163966. } \
  163967. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  163968. if ((nb = htbl->look_nbits[look]) != 0) { \
  163969. DROP_BITS(nb); \
  163970. result = htbl->look_sym[look]; \
  163971. } else { \
  163972. nb = HUFF_LOOKAHEAD+1; \
  163973. slowlabel: \
  163974. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  163975. { failaction; } \
  163976. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  163977. } \
  163978. }
  163979. /* Out-of-line case for Huffman code fetching */
  163980. EXTERN(int) jpeg_huff_decode
  163981. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  163982. register int bits_left, d_derived_tbl * htbl, int min_bits));
  163983. #endif
  163984. /********* End of inlined file: jdhuff.h *********/
  163985. /* Declarations shared with jdphuff.c */
  163986. /*
  163987. * Expanded entropy decoder object for Huffman decoding.
  163988. *
  163989. * The savable_state subrecord contains fields that change within an MCU,
  163990. * but must not be updated permanently until we complete the MCU.
  163991. */
  163992. typedef struct {
  163993. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163994. } savable_state2;
  163995. /* This macro is to work around compilers with missing or broken
  163996. * structure assignment. You'll need to fix this code if you have
  163997. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163998. */
  163999. #ifndef NO_STRUCT_ASSIGN
  164000. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  164001. #else
  164002. #if MAX_COMPS_IN_SCAN == 4
  164003. #define ASSIGN_STATE(dest,src) \
  164004. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  164005. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  164006. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  164007. (dest).last_dc_val[3] = (src).last_dc_val[3])
  164008. #endif
  164009. #endif
  164010. typedef struct {
  164011. struct jpeg_entropy_decoder pub; /* public fields */
  164012. /* These fields are loaded into local variables at start of each MCU.
  164013. * In case of suspension, we exit WITHOUT updating them.
  164014. */
  164015. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  164016. savable_state2 saved; /* Other state at start of MCU */
  164017. /* These fields are NOT loaded into local working state. */
  164018. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  164019. /* Pointers to derived tables (these workspaces have image lifespan) */
  164020. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  164021. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  164022. /* Precalculated info set up by start_pass for use in decode_mcu: */
  164023. /* Pointers to derived tables to be used for each block within an MCU */
  164024. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  164025. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  164026. /* Whether we care about the DC and AC coefficient values for each block */
  164027. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  164028. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  164029. } huff_entropy_decoder2;
  164030. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  164031. /*
  164032. * Initialize for a Huffman-compressed scan.
  164033. */
  164034. METHODDEF(void)
  164035. start_pass_huff_decoder (j_decompress_ptr cinfo)
  164036. {
  164037. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  164038. int ci, blkn, dctbl, actbl;
  164039. jpeg_component_info * compptr;
  164040. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  164041. * This ought to be an error condition, but we make it a warning because
  164042. * there are some baseline files out there with all zeroes in these bytes.
  164043. */
  164044. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  164045. cinfo->Ah != 0 || cinfo->Al != 0)
  164046. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  164047. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164048. compptr = cinfo->cur_comp_info[ci];
  164049. dctbl = compptr->dc_tbl_no;
  164050. actbl = compptr->ac_tbl_no;
  164051. /* Compute derived values for Huffman tables */
  164052. /* We may do this more than once for a table, but it's not expensive */
  164053. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  164054. & entropy->dc_derived_tbls[dctbl]);
  164055. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  164056. & entropy->ac_derived_tbls[actbl]);
  164057. /* Initialize DC predictions to 0 */
  164058. entropy->saved.last_dc_val[ci] = 0;
  164059. }
  164060. /* Precalculate decoding info for each block in an MCU of this scan */
  164061. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  164062. ci = cinfo->MCU_membership[blkn];
  164063. compptr = cinfo->cur_comp_info[ci];
  164064. /* Precalculate which table to use for each block */
  164065. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  164066. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  164067. /* Decide whether we really care about the coefficient values */
  164068. if (compptr->component_needed) {
  164069. entropy->dc_needed[blkn] = TRUE;
  164070. /* we don't need the ACs if producing a 1/8th-size image */
  164071. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  164072. } else {
  164073. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  164074. }
  164075. }
  164076. /* Initialize bitread state variables */
  164077. entropy->bitstate.bits_left = 0;
  164078. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  164079. entropy->pub.insufficient_data = FALSE;
  164080. /* Initialize restart counter */
  164081. entropy->restarts_to_go = cinfo->restart_interval;
  164082. }
  164083. /*
  164084. * Compute the derived values for a Huffman table.
  164085. * This routine also performs some validation checks on the table.
  164086. *
  164087. * Note this is also used by jdphuff.c.
  164088. */
  164089. GLOBAL(void)
  164090. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  164091. d_derived_tbl ** pdtbl)
  164092. {
  164093. JHUFF_TBL *htbl;
  164094. d_derived_tbl *dtbl;
  164095. int p, i, l, si, numsymbols;
  164096. int lookbits, ctr;
  164097. char huffsize[257];
  164098. unsigned int huffcode[257];
  164099. unsigned int code;
  164100. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  164101. * paralleling the order of the symbols themselves in htbl->huffval[].
  164102. */
  164103. /* Find the input Huffman table */
  164104. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  164105. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  164106. htbl =
  164107. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  164108. if (htbl == NULL)
  164109. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  164110. /* Allocate a workspace if we haven't already done so. */
  164111. if (*pdtbl == NULL)
  164112. *pdtbl = (d_derived_tbl *)
  164113. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164114. SIZEOF(d_derived_tbl));
  164115. dtbl = *pdtbl;
  164116. dtbl->pub = htbl; /* fill in back link */
  164117. /* Figure C.1: make table of Huffman code length for each symbol */
  164118. p = 0;
  164119. for (l = 1; l <= 16; l++) {
  164120. i = (int) htbl->bits[l];
  164121. if (i < 0 || p + i > 256) /* protect against table overrun */
  164122. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164123. while (i--)
  164124. huffsize[p++] = (char) l;
  164125. }
  164126. huffsize[p] = 0;
  164127. numsymbols = p;
  164128. /* Figure C.2: generate the codes themselves */
  164129. /* We also validate that the counts represent a legal Huffman code tree. */
  164130. code = 0;
  164131. si = huffsize[0];
  164132. p = 0;
  164133. while (huffsize[p]) {
  164134. while (((int) huffsize[p]) == si) {
  164135. huffcode[p++] = code;
  164136. code++;
  164137. }
  164138. /* code is now 1 more than the last code used for codelength si; but
  164139. * it must still fit in si bits, since no code is allowed to be all ones.
  164140. */
  164141. if (((INT32) code) >= (((INT32) 1) << si))
  164142. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164143. code <<= 1;
  164144. si++;
  164145. }
  164146. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  164147. p = 0;
  164148. for (l = 1; l <= 16; l++) {
  164149. if (htbl->bits[l]) {
  164150. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  164151. * minus the minimum code of length l
  164152. */
  164153. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  164154. p += htbl->bits[l];
  164155. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  164156. } else {
  164157. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  164158. }
  164159. }
  164160. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  164161. /* Compute lookahead tables to speed up decoding.
  164162. * First we set all the table entries to 0, indicating "too long";
  164163. * then we iterate through the Huffman codes that are short enough and
  164164. * fill in all the entries that correspond to bit sequences starting
  164165. * with that code.
  164166. */
  164167. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  164168. p = 0;
  164169. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  164170. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  164171. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  164172. /* Generate left-justified code followed by all possible bit sequences */
  164173. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  164174. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  164175. dtbl->look_nbits[lookbits] = l;
  164176. dtbl->look_sym[lookbits] = htbl->huffval[p];
  164177. lookbits++;
  164178. }
  164179. }
  164180. }
  164181. /* Validate symbols as being reasonable.
  164182. * For AC tables, we make no check, but accept all byte values 0..255.
  164183. * For DC tables, we require the symbols to be in range 0..15.
  164184. * (Tighter bounds could be applied depending on the data depth and mode,
  164185. * but this is sufficient to ensure safe decoding.)
  164186. */
  164187. if (isDC) {
  164188. for (i = 0; i < numsymbols; i++) {
  164189. int sym = htbl->huffval[i];
  164190. if (sym < 0 || sym > 15)
  164191. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164192. }
  164193. }
  164194. }
  164195. /*
  164196. * Out-of-line code for bit fetching (shared with jdphuff.c).
  164197. * See jdhuff.h for info about usage.
  164198. * Note: current values of get_buffer and bits_left are passed as parameters,
  164199. * but are returned in the corresponding fields of the state struct.
  164200. *
  164201. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  164202. * of get_buffer to be used. (On machines with wider words, an even larger
  164203. * buffer could be used.) However, on some machines 32-bit shifts are
  164204. * quite slow and take time proportional to the number of places shifted.
  164205. * (This is true with most PC compilers, for instance.) In this case it may
  164206. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  164207. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  164208. */
  164209. #ifdef SLOW_SHIFT_32
  164210. #define MIN_GET_BITS 15 /* minimum allowable value */
  164211. #else
  164212. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  164213. #endif
  164214. GLOBAL(boolean)
  164215. jpeg_fill_bit_buffer (bitread_working_state * state,
  164216. register bit_buf_type get_buffer, register int bits_left,
  164217. int nbits)
  164218. /* Load up the bit buffer to a depth of at least nbits */
  164219. {
  164220. /* Copy heavily used state fields into locals (hopefully registers) */
  164221. register const JOCTET * next_input_byte = state->next_input_byte;
  164222. register size_t bytes_in_buffer = state->bytes_in_buffer;
  164223. j_decompress_ptr cinfo = state->cinfo;
  164224. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  164225. /* (It is assumed that no request will be for more than that many bits.) */
  164226. /* We fail to do so only if we hit a marker or are forced to suspend. */
  164227. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  164228. while (bits_left < MIN_GET_BITS) {
  164229. register int c;
  164230. /* Attempt to read a byte */
  164231. if (bytes_in_buffer == 0) {
  164232. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  164233. return FALSE;
  164234. next_input_byte = cinfo->src->next_input_byte;
  164235. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  164236. }
  164237. bytes_in_buffer--;
  164238. c = GETJOCTET(*next_input_byte++);
  164239. /* If it's 0xFF, check and discard stuffed zero byte */
  164240. if (c == 0xFF) {
  164241. /* Loop here to discard any padding FF's on terminating marker,
  164242. * so that we can save a valid unread_marker value. NOTE: we will
  164243. * accept multiple FF's followed by a 0 as meaning a single FF data
  164244. * byte. This data pattern is not valid according to the standard.
  164245. */
  164246. do {
  164247. if (bytes_in_buffer == 0) {
  164248. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  164249. return FALSE;
  164250. next_input_byte = cinfo->src->next_input_byte;
  164251. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  164252. }
  164253. bytes_in_buffer--;
  164254. c = GETJOCTET(*next_input_byte++);
  164255. } while (c == 0xFF);
  164256. if (c == 0) {
  164257. /* Found FF/00, which represents an FF data byte */
  164258. c = 0xFF;
  164259. } else {
  164260. /* Oops, it's actually a marker indicating end of compressed data.
  164261. * Save the marker code for later use.
  164262. * Fine point: it might appear that we should save the marker into
  164263. * bitread working state, not straight into permanent state. But
  164264. * once we have hit a marker, we cannot need to suspend within the
  164265. * current MCU, because we will read no more bytes from the data
  164266. * source. So it is OK to update permanent state right away.
  164267. */
  164268. cinfo->unread_marker = c;
  164269. /* See if we need to insert some fake zero bits. */
  164270. goto no_more_bytes;
  164271. }
  164272. }
  164273. /* OK, load c into get_buffer */
  164274. get_buffer = (get_buffer << 8) | c;
  164275. bits_left += 8;
  164276. } /* end while */
  164277. } else {
  164278. no_more_bytes:
  164279. /* We get here if we've read the marker that terminates the compressed
  164280. * data segment. There should be enough bits in the buffer register
  164281. * to satisfy the request; if so, no problem.
  164282. */
  164283. if (nbits > bits_left) {
  164284. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  164285. * the data stream, so that we can produce some kind of image.
  164286. * We use a nonvolatile flag to ensure that only one warning message
  164287. * appears per data segment.
  164288. */
  164289. if (! cinfo->entropy->insufficient_data) {
  164290. WARNMS(cinfo, JWRN_HIT_MARKER);
  164291. cinfo->entropy->insufficient_data = TRUE;
  164292. }
  164293. /* Fill the buffer with zero bits */
  164294. get_buffer <<= MIN_GET_BITS - bits_left;
  164295. bits_left = MIN_GET_BITS;
  164296. }
  164297. }
  164298. /* Unload the local registers */
  164299. state->next_input_byte = next_input_byte;
  164300. state->bytes_in_buffer = bytes_in_buffer;
  164301. state->get_buffer = get_buffer;
  164302. state->bits_left = bits_left;
  164303. return TRUE;
  164304. }
  164305. /*
  164306. * Out-of-line code for Huffman code decoding.
  164307. * See jdhuff.h for info about usage.
  164308. */
  164309. GLOBAL(int)
  164310. jpeg_huff_decode (bitread_working_state * state,
  164311. register bit_buf_type get_buffer, register int bits_left,
  164312. d_derived_tbl * htbl, int min_bits)
  164313. {
  164314. register int l = min_bits;
  164315. register INT32 code;
  164316. /* HUFF_DECODE has determined that the code is at least min_bits */
  164317. /* bits long, so fetch that many bits in one swoop. */
  164318. CHECK_BIT_BUFFER(*state, l, return -1);
  164319. code = GET_BITS(l);
  164320. /* Collect the rest of the Huffman code one bit at a time. */
  164321. /* This is per Figure F.16 in the JPEG spec. */
  164322. while (code > htbl->maxcode[l]) {
  164323. code <<= 1;
  164324. CHECK_BIT_BUFFER(*state, 1, return -1);
  164325. code |= GET_BITS(1);
  164326. l++;
  164327. }
  164328. /* Unload the local registers */
  164329. state->get_buffer = get_buffer;
  164330. state->bits_left = bits_left;
  164331. /* With garbage input we may reach the sentinel value l = 17. */
  164332. if (l > 16) {
  164333. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  164334. return 0; /* fake a zero as the safest result */
  164335. }
  164336. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  164337. }
  164338. /*
  164339. * Check for a restart marker & resynchronize decoder.
  164340. * Returns FALSE if must suspend.
  164341. */
  164342. LOCAL(boolean)
  164343. process_restart (j_decompress_ptr cinfo)
  164344. {
  164345. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  164346. int ci;
  164347. /* Throw away any unused bits remaining in bit buffer; */
  164348. /* include any full bytes in next_marker's count of discarded bytes */
  164349. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  164350. entropy->bitstate.bits_left = 0;
  164351. /* Advance past the RSTn marker */
  164352. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  164353. return FALSE;
  164354. /* Re-initialize DC predictions to 0 */
  164355. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  164356. entropy->saved.last_dc_val[ci] = 0;
  164357. /* Reset restart counter */
  164358. entropy->restarts_to_go = cinfo->restart_interval;
  164359. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  164360. * against a marker. In that case we will end up treating the next data
  164361. * segment as empty, and we can avoid producing bogus output pixels by
  164362. * leaving the flag set.
  164363. */
  164364. if (cinfo->unread_marker == 0)
  164365. entropy->pub.insufficient_data = FALSE;
  164366. return TRUE;
  164367. }
  164368. /*
  164369. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  164370. * The coefficients are reordered from zigzag order into natural array order,
  164371. * but are not dequantized.
  164372. *
  164373. * The i'th block of the MCU is stored into the block pointed to by
  164374. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  164375. * (Wholesale zeroing is usually a little faster than retail...)
  164376. *
  164377. * Returns FALSE if data source requested suspension. In that case no
  164378. * changes have been made to permanent state. (Exception: some output
  164379. * coefficients may already have been assigned. This is harmless for
  164380. * this module, since we'll just re-assign them on the next call.)
  164381. */
  164382. METHODDEF(boolean)
  164383. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  164384. {
  164385. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  164386. int blkn;
  164387. BITREAD_STATE_VARS;
  164388. savable_state2 state;
  164389. /* Process restart marker if needed; may have to suspend */
  164390. if (cinfo->restart_interval) {
  164391. if (entropy->restarts_to_go == 0)
  164392. if (! process_restart(cinfo))
  164393. return FALSE;
  164394. }
  164395. /* If we've run out of data, just leave the MCU set to zeroes.
  164396. * This way, we return uniform gray for the remainder of the segment.
  164397. */
  164398. if (! entropy->pub.insufficient_data) {
  164399. /* Load up working state */
  164400. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  164401. ASSIGN_STATE(state, entropy->saved);
  164402. /* Outer loop handles each block in the MCU */
  164403. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  164404. JBLOCKROW block = MCU_data[blkn];
  164405. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  164406. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  164407. register int s, k, r;
  164408. /* Decode a single block's worth of coefficients */
  164409. /* Section F.2.2.1: decode the DC coefficient difference */
  164410. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  164411. if (s) {
  164412. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  164413. r = GET_BITS(s);
  164414. s = HUFF_EXTEND(r, s);
  164415. }
  164416. if (entropy->dc_needed[blkn]) {
  164417. /* Convert DC difference to actual value, update last_dc_val */
  164418. int ci = cinfo->MCU_membership[blkn];
  164419. s += state.last_dc_val[ci];
  164420. state.last_dc_val[ci] = s;
  164421. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  164422. (*block)[0] = (JCOEF) s;
  164423. }
  164424. if (entropy->ac_needed[blkn]) {
  164425. /* Section F.2.2.2: decode the AC coefficients */
  164426. /* Since zeroes are skipped, output area must be cleared beforehand */
  164427. for (k = 1; k < DCTSIZE2; k++) {
  164428. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  164429. r = s >> 4;
  164430. s &= 15;
  164431. if (s) {
  164432. k += r;
  164433. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  164434. r = GET_BITS(s);
  164435. s = HUFF_EXTEND(r, s);
  164436. /* Output coefficient in natural (dezigzagged) order.
  164437. * Note: the extra entries in jpeg_natural_order[] will save us
  164438. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  164439. */
  164440. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  164441. } else {
  164442. if (r != 15)
  164443. break;
  164444. k += 15;
  164445. }
  164446. }
  164447. } else {
  164448. /* Section F.2.2.2: decode the AC coefficients */
  164449. /* In this path we just discard the values */
  164450. for (k = 1; k < DCTSIZE2; k++) {
  164451. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  164452. r = s >> 4;
  164453. s &= 15;
  164454. if (s) {
  164455. k += r;
  164456. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  164457. DROP_BITS(s);
  164458. } else {
  164459. if (r != 15)
  164460. break;
  164461. k += 15;
  164462. }
  164463. }
  164464. }
  164465. }
  164466. /* Completed MCU, so update state */
  164467. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  164468. ASSIGN_STATE(entropy->saved, state);
  164469. }
  164470. /* Account for restart interval (no-op if not using restarts) */
  164471. entropy->restarts_to_go--;
  164472. return TRUE;
  164473. }
  164474. /*
  164475. * Module initialization routine for Huffman entropy decoding.
  164476. */
  164477. GLOBAL(void)
  164478. jinit_huff_decoder (j_decompress_ptr cinfo)
  164479. {
  164480. huff_entropy_ptr2 entropy;
  164481. int i;
  164482. entropy = (huff_entropy_ptr2)
  164483. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164484. SIZEOF(huff_entropy_decoder2));
  164485. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  164486. entropy->pub.start_pass = start_pass_huff_decoder;
  164487. entropy->pub.decode_mcu = decode_mcu;
  164488. /* Mark tables unallocated */
  164489. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164490. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  164491. }
  164492. }
  164493. /********* End of inlined file: jdhuff.c *********/
  164494. /********* Start of inlined file: jdinput.c *********/
  164495. #define JPEG_INTERNALS
  164496. /* Private state */
  164497. typedef struct {
  164498. struct jpeg_input_controller pub; /* public fields */
  164499. boolean inheaders; /* TRUE until first SOS is reached */
  164500. } my_input_controller;
  164501. typedef my_input_controller * my_inputctl_ptr;
  164502. /* Forward declarations */
  164503. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  164504. /*
  164505. * Routines to calculate various quantities related to the size of the image.
  164506. */
  164507. LOCAL(void)
  164508. initial_setup2 (j_decompress_ptr cinfo)
  164509. /* Called once, when first SOS marker is reached */
  164510. {
  164511. int ci;
  164512. jpeg_component_info *compptr;
  164513. /* Make sure image isn't bigger than I can handle */
  164514. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164515. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164516. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164517. /* For now, precision must match compiled-in value... */
  164518. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164519. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164520. /* Check that number of components won't exceed internal array sizes */
  164521. if (cinfo->num_components > MAX_COMPONENTS)
  164522. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164523. MAX_COMPONENTS);
  164524. /* Compute maximum sampling factors; check factor validity */
  164525. cinfo->max_h_samp_factor = 1;
  164526. cinfo->max_v_samp_factor = 1;
  164527. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164528. ci++, compptr++) {
  164529. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164530. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164531. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164532. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164533. compptr->h_samp_factor);
  164534. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164535. compptr->v_samp_factor);
  164536. }
  164537. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  164538. * In the full decompressor, this will be overridden by jdmaster.c;
  164539. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  164540. */
  164541. cinfo->min_DCT_scaled_size = DCTSIZE;
  164542. /* Compute dimensions of components */
  164543. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164544. ci++, compptr++) {
  164545. compptr->DCT_scaled_size = DCTSIZE;
  164546. /* Size in DCT blocks */
  164547. compptr->width_in_blocks = (JDIMENSION)
  164548. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164549. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164550. compptr->height_in_blocks = (JDIMENSION)
  164551. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164552. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164553. /* downsampled_width and downsampled_height will also be overridden by
  164554. * jdmaster.c if we are doing full decompression. The transcoder library
  164555. * doesn't use these values, but the calling application might.
  164556. */
  164557. /* Size in samples */
  164558. compptr->downsampled_width = (JDIMENSION)
  164559. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164560. (long) cinfo->max_h_samp_factor);
  164561. compptr->downsampled_height = (JDIMENSION)
  164562. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164563. (long) cinfo->max_v_samp_factor);
  164564. /* Mark component needed, until color conversion says otherwise */
  164565. compptr->component_needed = TRUE;
  164566. /* Mark no quantization table yet saved for component */
  164567. compptr->quant_table = NULL;
  164568. }
  164569. /* Compute number of fully interleaved MCU rows. */
  164570. cinfo->total_iMCU_rows = (JDIMENSION)
  164571. jdiv_round_up((long) cinfo->image_height,
  164572. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164573. /* Decide whether file contains multiple scans */
  164574. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  164575. cinfo->inputctl->has_multiple_scans = TRUE;
  164576. else
  164577. cinfo->inputctl->has_multiple_scans = FALSE;
  164578. }
  164579. LOCAL(void)
  164580. per_scan_setup2 (j_decompress_ptr cinfo)
  164581. /* Do computations that are needed before processing a JPEG scan */
  164582. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  164583. {
  164584. int ci, mcublks, tmp;
  164585. jpeg_component_info *compptr;
  164586. if (cinfo->comps_in_scan == 1) {
  164587. /* Noninterleaved (single-component) scan */
  164588. compptr = cinfo->cur_comp_info[0];
  164589. /* Overall image size in MCUs */
  164590. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164591. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164592. /* For noninterleaved scan, always one block per MCU */
  164593. compptr->MCU_width = 1;
  164594. compptr->MCU_height = 1;
  164595. compptr->MCU_blocks = 1;
  164596. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  164597. compptr->last_col_width = 1;
  164598. /* For noninterleaved scans, it is convenient to define last_row_height
  164599. * as the number of block rows present in the last iMCU row.
  164600. */
  164601. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164602. if (tmp == 0) tmp = compptr->v_samp_factor;
  164603. compptr->last_row_height = tmp;
  164604. /* Prepare array describing MCU composition */
  164605. cinfo->blocks_in_MCU = 1;
  164606. cinfo->MCU_membership[0] = 0;
  164607. } else {
  164608. /* Interleaved (multi-component) scan */
  164609. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164610. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164611. MAX_COMPS_IN_SCAN);
  164612. /* Overall image size in MCUs */
  164613. cinfo->MCUs_per_row = (JDIMENSION)
  164614. jdiv_round_up((long) cinfo->image_width,
  164615. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164616. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164617. jdiv_round_up((long) cinfo->image_height,
  164618. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164619. cinfo->blocks_in_MCU = 0;
  164620. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164621. compptr = cinfo->cur_comp_info[ci];
  164622. /* Sampling factors give # of blocks of component in each MCU */
  164623. compptr->MCU_width = compptr->h_samp_factor;
  164624. compptr->MCU_height = compptr->v_samp_factor;
  164625. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164626. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  164627. /* Figure number of non-dummy blocks in last MCU column & row */
  164628. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164629. if (tmp == 0) tmp = compptr->MCU_width;
  164630. compptr->last_col_width = tmp;
  164631. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164632. if (tmp == 0) tmp = compptr->MCU_height;
  164633. compptr->last_row_height = tmp;
  164634. /* Prepare array describing MCU composition */
  164635. mcublks = compptr->MCU_blocks;
  164636. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  164637. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164638. while (mcublks-- > 0) {
  164639. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164640. }
  164641. }
  164642. }
  164643. }
  164644. /*
  164645. * Save away a copy of the Q-table referenced by each component present
  164646. * in the current scan, unless already saved during a prior scan.
  164647. *
  164648. * In a multiple-scan JPEG file, the encoder could assign different components
  164649. * the same Q-table slot number, but change table definitions between scans
  164650. * so that each component uses a different Q-table. (The IJG encoder is not
  164651. * currently capable of doing this, but other encoders might.) Since we want
  164652. * to be able to dequantize all the components at the end of the file, this
  164653. * means that we have to save away the table actually used for each component.
  164654. * We do this by copying the table at the start of the first scan containing
  164655. * the component.
  164656. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  164657. * slot between scans of a component using that slot. If the encoder does so
  164658. * anyway, this decoder will simply use the Q-table values that were current
  164659. * at the start of the first scan for the component.
  164660. *
  164661. * The decompressor output side looks only at the saved quant tables,
  164662. * not at the current Q-table slots.
  164663. */
  164664. LOCAL(void)
  164665. latch_quant_tables (j_decompress_ptr cinfo)
  164666. {
  164667. int ci, qtblno;
  164668. jpeg_component_info *compptr;
  164669. JQUANT_TBL * qtbl;
  164670. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164671. compptr = cinfo->cur_comp_info[ci];
  164672. /* No work if we already saved Q-table for this component */
  164673. if (compptr->quant_table != NULL)
  164674. continue;
  164675. /* Make sure specified quantization table is present */
  164676. qtblno = compptr->quant_tbl_no;
  164677. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  164678. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  164679. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  164680. /* OK, save away the quantization table */
  164681. qtbl = (JQUANT_TBL *)
  164682. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164683. SIZEOF(JQUANT_TBL));
  164684. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  164685. compptr->quant_table = qtbl;
  164686. }
  164687. }
  164688. /*
  164689. * Initialize the input modules to read a scan of compressed data.
  164690. * The first call to this is done by jdmaster.c after initializing
  164691. * the entire decompressor (during jpeg_start_decompress).
  164692. * Subsequent calls come from consume_markers, below.
  164693. */
  164694. METHODDEF(void)
  164695. start_input_pass2 (j_decompress_ptr cinfo)
  164696. {
  164697. per_scan_setup2(cinfo);
  164698. latch_quant_tables(cinfo);
  164699. (*cinfo->entropy->start_pass) (cinfo);
  164700. (*cinfo->coef->start_input_pass) (cinfo);
  164701. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  164702. }
  164703. /*
  164704. * Finish up after inputting a compressed-data scan.
  164705. * This is called by the coefficient controller after it's read all
  164706. * the expected data of the scan.
  164707. */
  164708. METHODDEF(void)
  164709. finish_input_pass (j_decompress_ptr cinfo)
  164710. {
  164711. cinfo->inputctl->consume_input = consume_markers;
  164712. }
  164713. /*
  164714. * Read JPEG markers before, between, or after compressed-data scans.
  164715. * Change state as necessary when a new scan is reached.
  164716. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  164717. *
  164718. * The consume_input method pointer points either here or to the
  164719. * coefficient controller's consume_data routine, depending on whether
  164720. * we are reading a compressed data segment or inter-segment markers.
  164721. */
  164722. METHODDEF(int)
  164723. consume_markers (j_decompress_ptr cinfo)
  164724. {
  164725. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  164726. int val;
  164727. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  164728. return JPEG_REACHED_EOI;
  164729. val = (*cinfo->marker->read_markers) (cinfo);
  164730. switch (val) {
  164731. case JPEG_REACHED_SOS: /* Found SOS */
  164732. if (inputctl->inheaders) { /* 1st SOS */
  164733. initial_setup2(cinfo);
  164734. inputctl->inheaders = FALSE;
  164735. /* Note: start_input_pass must be called by jdmaster.c
  164736. * before any more input can be consumed. jdapimin.c is
  164737. * responsible for enforcing this sequencing.
  164738. */
  164739. } else { /* 2nd or later SOS marker */
  164740. if (! inputctl->pub.has_multiple_scans)
  164741. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  164742. start_input_pass2(cinfo);
  164743. }
  164744. break;
  164745. case JPEG_REACHED_EOI: /* Found EOI */
  164746. inputctl->pub.eoi_reached = TRUE;
  164747. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  164748. if (cinfo->marker->saw_SOF)
  164749. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  164750. } else {
  164751. /* Prevent infinite loop in coef ctlr's decompress_data routine
  164752. * if user set output_scan_number larger than number of scans.
  164753. */
  164754. if (cinfo->output_scan_number > cinfo->input_scan_number)
  164755. cinfo->output_scan_number = cinfo->input_scan_number;
  164756. }
  164757. break;
  164758. case JPEG_SUSPENDED:
  164759. break;
  164760. }
  164761. return val;
  164762. }
  164763. /*
  164764. * Reset state to begin a fresh datastream.
  164765. */
  164766. METHODDEF(void)
  164767. reset_input_controller (j_decompress_ptr cinfo)
  164768. {
  164769. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  164770. inputctl->pub.consume_input = consume_markers;
  164771. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  164772. inputctl->pub.eoi_reached = FALSE;
  164773. inputctl->inheaders = TRUE;
  164774. /* Reset other modules */
  164775. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  164776. (*cinfo->marker->reset_marker_reader) (cinfo);
  164777. /* Reset progression state -- would be cleaner if entropy decoder did this */
  164778. cinfo->coef_bits = NULL;
  164779. }
  164780. /*
  164781. * Initialize the input controller module.
  164782. * This is called only once, when the decompression object is created.
  164783. */
  164784. GLOBAL(void)
  164785. jinit_input_controller (j_decompress_ptr cinfo)
  164786. {
  164787. my_inputctl_ptr inputctl;
  164788. /* Create subobject in permanent pool */
  164789. inputctl = (my_inputctl_ptr)
  164790. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164791. SIZEOF(my_input_controller));
  164792. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  164793. /* Initialize method pointers */
  164794. inputctl->pub.consume_input = consume_markers;
  164795. inputctl->pub.reset_input_controller = reset_input_controller;
  164796. inputctl->pub.start_input_pass = start_input_pass2;
  164797. inputctl->pub.finish_input_pass = finish_input_pass;
  164798. /* Initialize state: can't use reset_input_controller since we don't
  164799. * want to try to reset other modules yet.
  164800. */
  164801. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  164802. inputctl->pub.eoi_reached = FALSE;
  164803. inputctl->inheaders = TRUE;
  164804. }
  164805. /********* End of inlined file: jdinput.c *********/
  164806. /********* Start of inlined file: jdmainct.c *********/
  164807. #define JPEG_INTERNALS
  164808. /*
  164809. * In the current system design, the main buffer need never be a full-image
  164810. * buffer; any full-height buffers will be found inside the coefficient or
  164811. * postprocessing controllers. Nonetheless, the main controller is not
  164812. * trivial. Its responsibility is to provide context rows for upsampling/
  164813. * rescaling, and doing this in an efficient fashion is a bit tricky.
  164814. *
  164815. * Postprocessor input data is counted in "row groups". A row group
  164816. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  164817. * sample rows of each component. (We require DCT_scaled_size values to be
  164818. * chosen such that these numbers are integers. In practice DCT_scaled_size
  164819. * values will likely be powers of two, so we actually have the stronger
  164820. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  164821. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  164822. * row group (times any additional scale factor that the upsampler is
  164823. * applying).
  164824. *
  164825. * The coefficient controller will deliver data to us one iMCU row at a time;
  164826. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  164827. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  164828. * to one row of MCUs when the image is fully interleaved.) Note that the
  164829. * number of sample rows varies across components, but the number of row
  164830. * groups does not. Some garbage sample rows may be included in the last iMCU
  164831. * row at the bottom of the image.
  164832. *
  164833. * Depending on the vertical scaling algorithm used, the upsampler may need
  164834. * access to the sample row(s) above and below its current input row group.
  164835. * The upsampler is required to set need_context_rows TRUE at global selection
  164836. * time if so. When need_context_rows is FALSE, this controller can simply
  164837. * obtain one iMCU row at a time from the coefficient controller and dole it
  164838. * out as row groups to the postprocessor.
  164839. *
  164840. * When need_context_rows is TRUE, this controller guarantees that the buffer
  164841. * passed to postprocessing contains at least one row group's worth of samples
  164842. * above and below the row group(s) being processed. Note that the context
  164843. * rows "above" the first passed row group appear at negative row offsets in
  164844. * the passed buffer. At the top and bottom of the image, the required
  164845. * context rows are manufactured by duplicating the first or last real sample
  164846. * row; this avoids having special cases in the upsampling inner loops.
  164847. *
  164848. * The amount of context is fixed at one row group just because that's a
  164849. * convenient number for this controller to work with. The existing
  164850. * upsamplers really only need one sample row of context. An upsampler
  164851. * supporting arbitrary output rescaling might wish for more than one row
  164852. * group of context when shrinking the image; tough, we don't handle that.
  164853. * (This is justified by the assumption that downsizing will be handled mostly
  164854. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  164855. * the upsample step needn't be much less than one.)
  164856. *
  164857. * To provide the desired context, we have to retain the last two row groups
  164858. * of one iMCU row while reading in the next iMCU row. (The last row group
  164859. * can't be processed until we have another row group for its below-context,
  164860. * and so we have to save the next-to-last group too for its above-context.)
  164861. * We could do this most simply by copying data around in our buffer, but
  164862. * that'd be very slow. We can avoid copying any data by creating a rather
  164863. * strange pointer structure. Here's how it works. We allocate a workspace
  164864. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  164865. * of row groups per iMCU row). We create two sets of redundant pointers to
  164866. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  164867. * pointer lists look like this:
  164868. * M+1 M-1
  164869. * master pointer --> 0 master pointer --> 0
  164870. * 1 1
  164871. * ... ...
  164872. * M-3 M-3
  164873. * M-2 M
  164874. * M-1 M+1
  164875. * M M-2
  164876. * M+1 M-1
  164877. * 0 0
  164878. * We read alternate iMCU rows using each master pointer; thus the last two
  164879. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  164880. * The pointer lists are set up so that the required context rows appear to
  164881. * be adjacent to the proper places when we pass the pointer lists to the
  164882. * upsampler.
  164883. *
  164884. * The above pictures describe the normal state of the pointer lists.
  164885. * At top and bottom of the image, we diddle the pointer lists to duplicate
  164886. * the first or last sample row as necessary (this is cheaper than copying
  164887. * sample rows around).
  164888. *
  164889. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  164890. * situation each iMCU row provides only one row group so the buffering logic
  164891. * must be different (eg, we must read two iMCU rows before we can emit the
  164892. * first row group). For now, we simply do not support providing context
  164893. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  164894. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  164895. * want it quick and dirty, so a context-free upsampler is sufficient.
  164896. */
  164897. /* Private buffer controller object */
  164898. typedef struct {
  164899. struct jpeg_d_main_controller pub; /* public fields */
  164900. /* Pointer to allocated workspace (M or M+2 row groups). */
  164901. JSAMPARRAY buffer[MAX_COMPONENTS];
  164902. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  164903. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  164904. /* Remaining fields are only used in the context case. */
  164905. /* These are the master pointers to the funny-order pointer lists. */
  164906. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  164907. int whichptr; /* indicates which pointer set is now in use */
  164908. int context_state; /* process_data state machine status */
  164909. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  164910. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  164911. } my_main_controller4;
  164912. typedef my_main_controller4 * my_main_ptr4;
  164913. /* context_state values: */
  164914. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  164915. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  164916. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  164917. /* Forward declarations */
  164918. METHODDEF(void) process_data_simple_main2
  164919. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  164920. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  164921. METHODDEF(void) process_data_context_main
  164922. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  164923. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  164924. #ifdef QUANT_2PASS_SUPPORTED
  164925. METHODDEF(void) process_data_crank_post
  164926. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  164927. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  164928. #endif
  164929. LOCAL(void)
  164930. alloc_funny_pointers (j_decompress_ptr cinfo)
  164931. /* Allocate space for the funny pointer lists.
  164932. * This is done only once, not once per pass.
  164933. */
  164934. {
  164935. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164936. int ci, rgroup;
  164937. int M = cinfo->min_DCT_scaled_size;
  164938. jpeg_component_info *compptr;
  164939. JSAMPARRAY xbuf;
  164940. /* Get top-level space for component array pointers.
  164941. * We alloc both arrays with one call to save a few cycles.
  164942. */
  164943. main_->xbuffer[0] = (JSAMPIMAGE)
  164944. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164945. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  164946. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  164947. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164948. ci++, compptr++) {
  164949. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  164950. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  164951. /* Get space for pointer lists --- M+4 row groups in each list.
  164952. * We alloc both pointer lists with one call to save a few cycles.
  164953. */
  164954. xbuf = (JSAMPARRAY)
  164955. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164956. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  164957. xbuf += rgroup; /* want one row group at negative offsets */
  164958. main_->xbuffer[0][ci] = xbuf;
  164959. xbuf += rgroup * (M + 4);
  164960. main_->xbuffer[1][ci] = xbuf;
  164961. }
  164962. }
  164963. LOCAL(void)
  164964. make_funny_pointers (j_decompress_ptr cinfo)
  164965. /* Create the funny pointer lists discussed in the comments above.
  164966. * The actual workspace is already allocated (in main->buffer),
  164967. * and the space for the pointer lists is allocated too.
  164968. * This routine just fills in the curiously ordered lists.
  164969. * This will be repeated at the beginning of each pass.
  164970. */
  164971. {
  164972. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164973. int ci, i, rgroup;
  164974. int M = cinfo->min_DCT_scaled_size;
  164975. jpeg_component_info *compptr;
  164976. JSAMPARRAY buf, xbuf0, xbuf1;
  164977. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164978. ci++, compptr++) {
  164979. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  164980. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  164981. xbuf0 = main_->xbuffer[0][ci];
  164982. xbuf1 = main_->xbuffer[1][ci];
  164983. /* First copy the workspace pointers as-is */
  164984. buf = main_->buffer[ci];
  164985. for (i = 0; i < rgroup * (M + 2); i++) {
  164986. xbuf0[i] = xbuf1[i] = buf[i];
  164987. }
  164988. /* In the second list, put the last four row groups in swapped order */
  164989. for (i = 0; i < rgroup * 2; i++) {
  164990. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  164991. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  164992. }
  164993. /* The wraparound pointers at top and bottom will be filled later
  164994. * (see set_wraparound_pointers, below). Initially we want the "above"
  164995. * pointers to duplicate the first actual data line. This only needs
  164996. * to happen in xbuffer[0].
  164997. */
  164998. for (i = 0; i < rgroup; i++) {
  164999. xbuf0[i - rgroup] = xbuf0[0];
  165000. }
  165001. }
  165002. }
  165003. LOCAL(void)
  165004. set_wraparound_pointers (j_decompress_ptr cinfo)
  165005. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  165006. * This changes the pointer list state from top-of-image to the normal state.
  165007. */
  165008. {
  165009. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165010. int ci, i, rgroup;
  165011. int M = cinfo->min_DCT_scaled_size;
  165012. jpeg_component_info *compptr;
  165013. JSAMPARRAY xbuf0, xbuf1;
  165014. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165015. ci++, compptr++) {
  165016. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  165017. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  165018. xbuf0 = main_->xbuffer[0][ci];
  165019. xbuf1 = main_->xbuffer[1][ci];
  165020. for (i = 0; i < rgroup; i++) {
  165021. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  165022. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  165023. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  165024. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  165025. }
  165026. }
  165027. }
  165028. LOCAL(void)
  165029. set_bottom_pointers (j_decompress_ptr cinfo)
  165030. /* Change the pointer lists to duplicate the last sample row at the bottom
  165031. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  165032. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  165033. */
  165034. {
  165035. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165036. int ci, i, rgroup, iMCUheight, rows_left;
  165037. jpeg_component_info *compptr;
  165038. JSAMPARRAY xbuf;
  165039. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165040. ci++, compptr++) {
  165041. /* Count sample rows in one iMCU row and in one row group */
  165042. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  165043. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  165044. /* Count nondummy sample rows remaining for this component */
  165045. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  165046. if (rows_left == 0) rows_left = iMCUheight;
  165047. /* Count nondummy row groups. Should get same answer for each component,
  165048. * so we need only do it once.
  165049. */
  165050. if (ci == 0) {
  165051. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  165052. }
  165053. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  165054. * last partial rowgroup and ensures at least one full rowgroup of context.
  165055. */
  165056. xbuf = main_->xbuffer[main_->whichptr][ci];
  165057. for (i = 0; i < rgroup * 2; i++) {
  165058. xbuf[rows_left + i] = xbuf[rows_left-1];
  165059. }
  165060. }
  165061. }
  165062. /*
  165063. * Initialize for a processing pass.
  165064. */
  165065. METHODDEF(void)
  165066. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  165067. {
  165068. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165069. switch (pass_mode) {
  165070. case JBUF_PASS_THRU:
  165071. if (cinfo->upsample->need_context_rows) {
  165072. main_->pub.process_data = process_data_context_main;
  165073. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  165074. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  165075. main_->context_state = CTX_PREPARE_FOR_IMCU;
  165076. main_->iMCU_row_ctr = 0;
  165077. } else {
  165078. /* Simple case with no context needed */
  165079. main_->pub.process_data = process_data_simple_main2;
  165080. }
  165081. main_->buffer_full = FALSE; /* Mark buffer empty */
  165082. main_->rowgroup_ctr = 0;
  165083. break;
  165084. #ifdef QUANT_2PASS_SUPPORTED
  165085. case JBUF_CRANK_DEST:
  165086. /* For last pass of 2-pass quantization, just crank the postprocessor */
  165087. main_->pub.process_data = process_data_crank_post;
  165088. break;
  165089. #endif
  165090. default:
  165091. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165092. break;
  165093. }
  165094. }
  165095. /*
  165096. * Process some data.
  165097. * This handles the simple case where no context is required.
  165098. */
  165099. METHODDEF(void)
  165100. process_data_simple_main2 (j_decompress_ptr cinfo,
  165101. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  165102. JDIMENSION out_rows_avail)
  165103. {
  165104. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165105. JDIMENSION rowgroups_avail;
  165106. /* Read input data if we haven't filled the main buffer yet */
  165107. if (! main_->buffer_full) {
  165108. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  165109. return; /* suspension forced, can do nothing more */
  165110. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  165111. }
  165112. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  165113. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  165114. /* Note: at the bottom of the image, we may pass extra garbage row groups
  165115. * to the postprocessor. The postprocessor has to check for bottom
  165116. * of image anyway (at row resolution), so no point in us doing it too.
  165117. */
  165118. /* Feed the postprocessor */
  165119. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  165120. &main_->rowgroup_ctr, rowgroups_avail,
  165121. output_buf, out_row_ctr, out_rows_avail);
  165122. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  165123. if (main_->rowgroup_ctr >= rowgroups_avail) {
  165124. main_->buffer_full = FALSE;
  165125. main_->rowgroup_ctr = 0;
  165126. }
  165127. }
  165128. /*
  165129. * Process some data.
  165130. * This handles the case where context rows must be provided.
  165131. */
  165132. METHODDEF(void)
  165133. process_data_context_main (j_decompress_ptr cinfo,
  165134. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  165135. JDIMENSION out_rows_avail)
  165136. {
  165137. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  165138. /* Read input data if we haven't filled the main buffer yet */
  165139. if (! main_->buffer_full) {
  165140. if (! (*cinfo->coef->decompress_data) (cinfo,
  165141. main_->xbuffer[main_->whichptr]))
  165142. return; /* suspension forced, can do nothing more */
  165143. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  165144. main_->iMCU_row_ctr++; /* count rows received */
  165145. }
  165146. /* Postprocessor typically will not swallow all the input data it is handed
  165147. * in one call (due to filling the output buffer first). Must be prepared
  165148. * to exit and restart. This switch lets us keep track of how far we got.
  165149. * Note that each case falls through to the next on successful completion.
  165150. */
  165151. switch (main_->context_state) {
  165152. case CTX_POSTPONED_ROW:
  165153. /* Call postprocessor using previously set pointers for postponed row */
  165154. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  165155. &main_->rowgroup_ctr, main_->rowgroups_avail,
  165156. output_buf, out_row_ctr, out_rows_avail);
  165157. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  165158. return; /* Need to suspend */
  165159. main_->context_state = CTX_PREPARE_FOR_IMCU;
  165160. if (*out_row_ctr >= out_rows_avail)
  165161. return; /* Postprocessor exactly filled output buf */
  165162. /*FALLTHROUGH*/
  165163. case CTX_PREPARE_FOR_IMCU:
  165164. /* Prepare to process first M-1 row groups of this iMCU row */
  165165. main_->rowgroup_ctr = 0;
  165166. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  165167. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  165168. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  165169. */
  165170. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  165171. set_bottom_pointers(cinfo);
  165172. main_->context_state = CTX_PROCESS_IMCU;
  165173. /*FALLTHROUGH*/
  165174. case CTX_PROCESS_IMCU:
  165175. /* Call postprocessor using previously set pointers */
  165176. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  165177. &main_->rowgroup_ctr, main_->rowgroups_avail,
  165178. output_buf, out_row_ctr, out_rows_avail);
  165179. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  165180. return; /* Need to suspend */
  165181. /* After the first iMCU, change wraparound pointers to normal state */
  165182. if (main_->iMCU_row_ctr == 1)
  165183. set_wraparound_pointers(cinfo);
  165184. /* Prepare to load new iMCU row using other xbuffer list */
  165185. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  165186. main_->buffer_full = FALSE;
  165187. /* Still need to process last row group of this iMCU row, */
  165188. /* which is saved at index M+1 of the other xbuffer */
  165189. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  165190. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  165191. main_->context_state = CTX_POSTPONED_ROW;
  165192. }
  165193. }
  165194. /*
  165195. * Process some data.
  165196. * Final pass of two-pass quantization: just call the postprocessor.
  165197. * Source data will be the postprocessor controller's internal buffer.
  165198. */
  165199. #ifdef QUANT_2PASS_SUPPORTED
  165200. METHODDEF(void)
  165201. process_data_crank_post (j_decompress_ptr cinfo,
  165202. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  165203. JDIMENSION out_rows_avail)
  165204. {
  165205. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  165206. (JDIMENSION *) NULL, (JDIMENSION) 0,
  165207. output_buf, out_row_ctr, out_rows_avail);
  165208. }
  165209. #endif /* QUANT_2PASS_SUPPORTED */
  165210. /*
  165211. * Initialize main buffer controller.
  165212. */
  165213. GLOBAL(void)
  165214. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  165215. {
  165216. my_main_ptr4 main_;
  165217. int ci, rgroup, ngroups;
  165218. jpeg_component_info *compptr;
  165219. main_ = (my_main_ptr4)
  165220. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165221. SIZEOF(my_main_controller4));
  165222. cinfo->main = (struct jpeg_d_main_controller *) main_;
  165223. main_->pub.start_pass = start_pass_main2;
  165224. if (need_full_buffer) /* shouldn't happen */
  165225. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165226. /* Allocate the workspace.
  165227. * ngroups is the number of row groups we need.
  165228. */
  165229. if (cinfo->upsample->need_context_rows) {
  165230. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  165231. ERREXIT(cinfo, JERR_NOTIMPL);
  165232. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  165233. ngroups = cinfo->min_DCT_scaled_size + 2;
  165234. } else {
  165235. ngroups = cinfo->min_DCT_scaled_size;
  165236. }
  165237. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165238. ci++, compptr++) {
  165239. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  165240. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  165241. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  165242. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165243. compptr->width_in_blocks * compptr->DCT_scaled_size,
  165244. (JDIMENSION) (rgroup * ngroups));
  165245. }
  165246. }
  165247. /********* End of inlined file: jdmainct.c *********/
  165248. /********* Start of inlined file: jdmarker.c *********/
  165249. #define JPEG_INTERNALS
  165250. /* Private state */
  165251. typedef struct {
  165252. struct jpeg_marker_reader pub; /* public fields */
  165253. /* Application-overridable marker processing methods */
  165254. jpeg_marker_parser_method process_COM;
  165255. jpeg_marker_parser_method process_APPn[16];
  165256. /* Limit on marker data length to save for each marker type */
  165257. unsigned int length_limit_COM;
  165258. unsigned int length_limit_APPn[16];
  165259. /* Status of COM/APPn marker saving */
  165260. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  165261. unsigned int bytes_read; /* data bytes read so far in marker */
  165262. /* Note: cur_marker is not linked into marker_list until it's all read. */
  165263. } my_marker_reader;
  165264. typedef my_marker_reader * my_marker_ptr2;
  165265. /*
  165266. * Macros for fetching data from the data source module.
  165267. *
  165268. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  165269. * the current restart point; we update them only when we have reached a
  165270. * suitable place to restart if a suspension occurs.
  165271. */
  165272. /* Declare and initialize local copies of input pointer/count */
  165273. #define INPUT_VARS(cinfo) \
  165274. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  165275. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  165276. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  165277. /* Unload the local copies --- do this only at a restart boundary */
  165278. #define INPUT_SYNC(cinfo) \
  165279. ( datasrc->next_input_byte = next_input_byte, \
  165280. datasrc->bytes_in_buffer = bytes_in_buffer )
  165281. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  165282. #define INPUT_RELOAD(cinfo) \
  165283. ( next_input_byte = datasrc->next_input_byte, \
  165284. bytes_in_buffer = datasrc->bytes_in_buffer )
  165285. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  165286. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  165287. * but we must reload the local copies after a successful fill.
  165288. */
  165289. #define MAKE_BYTE_AVAIL(cinfo,action) \
  165290. if (bytes_in_buffer == 0) { \
  165291. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  165292. { action; } \
  165293. INPUT_RELOAD(cinfo); \
  165294. }
  165295. /* Read a byte into variable V.
  165296. * If must suspend, take the specified action (typically "return FALSE").
  165297. */
  165298. #define INPUT_BYTE(cinfo,V,action) \
  165299. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  165300. bytes_in_buffer--; \
  165301. V = GETJOCTET(*next_input_byte++); )
  165302. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  165303. * V should be declared unsigned int or perhaps INT32.
  165304. */
  165305. #define INPUT_2BYTES(cinfo,V,action) \
  165306. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  165307. bytes_in_buffer--; \
  165308. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  165309. MAKE_BYTE_AVAIL(cinfo,action); \
  165310. bytes_in_buffer--; \
  165311. V += GETJOCTET(*next_input_byte++); )
  165312. /*
  165313. * Routines to process JPEG markers.
  165314. *
  165315. * Entry condition: JPEG marker itself has been read and its code saved
  165316. * in cinfo->unread_marker; input restart point is just after the marker.
  165317. *
  165318. * Exit: if return TRUE, have read and processed any parameters, and have
  165319. * updated the restart point to point after the parameters.
  165320. * If return FALSE, was forced to suspend before reaching end of
  165321. * marker parameters; restart point has not been moved. Same routine
  165322. * will be called again after application supplies more input data.
  165323. *
  165324. * This approach to suspension assumes that all of a marker's parameters
  165325. * can fit into a single input bufferload. This should hold for "normal"
  165326. * markers. Some COM/APPn markers might have large parameter segments
  165327. * that might not fit. If we are simply dropping such a marker, we use
  165328. * skip_input_data to get past it, and thereby put the problem on the
  165329. * source manager's shoulders. If we are saving the marker's contents
  165330. * into memory, we use a slightly different convention: when forced to
  165331. * suspend, the marker processor updates the restart point to the end of
  165332. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  165333. * On resumption, cinfo->unread_marker still contains the marker code,
  165334. * but the data source will point to the next chunk of marker data.
  165335. * The marker processor must retain internal state to deal with this.
  165336. *
  165337. * Note that we don't bother to avoid duplicate trace messages if a
  165338. * suspension occurs within marker parameters. Other side effects
  165339. * require more care.
  165340. */
  165341. LOCAL(boolean)
  165342. get_soi (j_decompress_ptr cinfo)
  165343. /* Process an SOI marker */
  165344. {
  165345. int i;
  165346. TRACEMS(cinfo, 1, JTRC_SOI);
  165347. if (cinfo->marker->saw_SOI)
  165348. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  165349. /* Reset all parameters that are defined to be reset by SOI */
  165350. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165351. cinfo->arith_dc_L[i] = 0;
  165352. cinfo->arith_dc_U[i] = 1;
  165353. cinfo->arith_ac_K[i] = 5;
  165354. }
  165355. cinfo->restart_interval = 0;
  165356. /* Set initial assumptions for colorspace etc */
  165357. cinfo->jpeg_color_space = JCS_UNKNOWN;
  165358. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  165359. cinfo->saw_JFIF_marker = FALSE;
  165360. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  165361. cinfo->JFIF_minor_version = 1;
  165362. cinfo->density_unit = 0;
  165363. cinfo->X_density = 1;
  165364. cinfo->Y_density = 1;
  165365. cinfo->saw_Adobe_marker = FALSE;
  165366. cinfo->Adobe_transform = 0;
  165367. cinfo->marker->saw_SOI = TRUE;
  165368. return TRUE;
  165369. }
  165370. LOCAL(boolean)
  165371. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  165372. /* Process a SOFn marker */
  165373. {
  165374. INT32 length;
  165375. int c, ci;
  165376. jpeg_component_info * compptr;
  165377. INPUT_VARS(cinfo);
  165378. cinfo->progressive_mode = is_prog;
  165379. cinfo->arith_code = is_arith;
  165380. INPUT_2BYTES(cinfo, length, return FALSE);
  165381. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  165382. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  165383. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  165384. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  165385. length -= 8;
  165386. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  165387. (int) cinfo->image_width, (int) cinfo->image_height,
  165388. cinfo->num_components);
  165389. if (cinfo->marker->saw_SOF)
  165390. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  165391. /* We don't support files in which the image height is initially specified */
  165392. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  165393. /* might as well have a general sanity check. */
  165394. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  165395. || cinfo->num_components <= 0)
  165396. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  165397. if (length != (cinfo->num_components * 3))
  165398. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165399. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  165400. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  165401. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165402. cinfo->num_components * SIZEOF(jpeg_component_info));
  165403. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165404. ci++, compptr++) {
  165405. compptr->component_index = ci;
  165406. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  165407. INPUT_BYTE(cinfo, c, return FALSE);
  165408. compptr->h_samp_factor = (c >> 4) & 15;
  165409. compptr->v_samp_factor = (c ) & 15;
  165410. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  165411. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  165412. compptr->component_id, compptr->h_samp_factor,
  165413. compptr->v_samp_factor, compptr->quant_tbl_no);
  165414. }
  165415. cinfo->marker->saw_SOF = TRUE;
  165416. INPUT_SYNC(cinfo);
  165417. return TRUE;
  165418. }
  165419. LOCAL(boolean)
  165420. get_sos (j_decompress_ptr cinfo)
  165421. /* Process a SOS marker */
  165422. {
  165423. INT32 length;
  165424. int i, ci, n, c, cc;
  165425. jpeg_component_info * compptr;
  165426. INPUT_VARS(cinfo);
  165427. if (! cinfo->marker->saw_SOF)
  165428. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  165429. INPUT_2BYTES(cinfo, length, return FALSE);
  165430. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  165431. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  165432. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  165433. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165434. cinfo->comps_in_scan = n;
  165435. /* Collect the component-spec parameters */
  165436. for (i = 0; i < n; i++) {
  165437. INPUT_BYTE(cinfo, cc, return FALSE);
  165438. INPUT_BYTE(cinfo, c, return FALSE);
  165439. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165440. ci++, compptr++) {
  165441. if (cc == compptr->component_id)
  165442. goto id_found;
  165443. }
  165444. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  165445. id_found:
  165446. cinfo->cur_comp_info[i] = compptr;
  165447. compptr->dc_tbl_no = (c >> 4) & 15;
  165448. compptr->ac_tbl_no = (c ) & 15;
  165449. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  165450. compptr->dc_tbl_no, compptr->ac_tbl_no);
  165451. }
  165452. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  165453. INPUT_BYTE(cinfo, c, return FALSE);
  165454. cinfo->Ss = c;
  165455. INPUT_BYTE(cinfo, c, return FALSE);
  165456. cinfo->Se = c;
  165457. INPUT_BYTE(cinfo, c, return FALSE);
  165458. cinfo->Ah = (c >> 4) & 15;
  165459. cinfo->Al = (c ) & 15;
  165460. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  165461. cinfo->Ah, cinfo->Al);
  165462. /* Prepare to scan data & restart markers */
  165463. cinfo->marker->next_restart_num = 0;
  165464. /* Count another SOS marker */
  165465. cinfo->input_scan_number++;
  165466. INPUT_SYNC(cinfo);
  165467. return TRUE;
  165468. }
  165469. #ifdef D_ARITH_CODING_SUPPORTED
  165470. LOCAL(boolean)
  165471. get_dac (j_decompress_ptr cinfo)
  165472. /* Process a DAC marker */
  165473. {
  165474. INT32 length;
  165475. int index, val;
  165476. INPUT_VARS(cinfo);
  165477. INPUT_2BYTES(cinfo, length, return FALSE);
  165478. length -= 2;
  165479. while (length > 0) {
  165480. INPUT_BYTE(cinfo, index, return FALSE);
  165481. INPUT_BYTE(cinfo, val, return FALSE);
  165482. length -= 2;
  165483. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  165484. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  165485. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  165486. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  165487. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  165488. } else { /* define DC table */
  165489. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  165490. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  165491. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  165492. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  165493. }
  165494. }
  165495. if (length != 0)
  165496. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165497. INPUT_SYNC(cinfo);
  165498. return TRUE;
  165499. }
  165500. #else /* ! D_ARITH_CODING_SUPPORTED */
  165501. #define get_dac(cinfo) skip_variable(cinfo)
  165502. #endif /* D_ARITH_CODING_SUPPORTED */
  165503. LOCAL(boolean)
  165504. get_dht (j_decompress_ptr cinfo)
  165505. /* Process a DHT marker */
  165506. {
  165507. INT32 length;
  165508. UINT8 bits[17];
  165509. UINT8 huffval[256];
  165510. int i, index, count;
  165511. JHUFF_TBL **htblptr;
  165512. INPUT_VARS(cinfo);
  165513. INPUT_2BYTES(cinfo, length, return FALSE);
  165514. length -= 2;
  165515. while (length > 16) {
  165516. INPUT_BYTE(cinfo, index, return FALSE);
  165517. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  165518. bits[0] = 0;
  165519. count = 0;
  165520. for (i = 1; i <= 16; i++) {
  165521. INPUT_BYTE(cinfo, bits[i], return FALSE);
  165522. count += bits[i];
  165523. }
  165524. length -= 1 + 16;
  165525. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  165526. bits[1], bits[2], bits[3], bits[4],
  165527. bits[5], bits[6], bits[7], bits[8]);
  165528. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  165529. bits[9], bits[10], bits[11], bits[12],
  165530. bits[13], bits[14], bits[15], bits[16]);
  165531. /* Here we just do minimal validation of the counts to avoid walking
  165532. * off the end of our table space. jdhuff.c will check more carefully.
  165533. */
  165534. if (count > 256 || ((INT32) count) > length)
  165535. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165536. for (i = 0; i < count; i++)
  165537. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  165538. length -= count;
  165539. if (index & 0x10) { /* AC table definition */
  165540. index -= 0x10;
  165541. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  165542. } else { /* DC table definition */
  165543. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  165544. }
  165545. if (index < 0 || index >= NUM_HUFF_TBLS)
  165546. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  165547. if (*htblptr == NULL)
  165548. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165549. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165550. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  165551. }
  165552. if (length != 0)
  165553. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165554. INPUT_SYNC(cinfo);
  165555. return TRUE;
  165556. }
  165557. LOCAL(boolean)
  165558. get_dqt (j_decompress_ptr cinfo)
  165559. /* Process a DQT marker */
  165560. {
  165561. INT32 length;
  165562. int n, i, prec;
  165563. unsigned int tmp;
  165564. JQUANT_TBL *quant_ptr;
  165565. INPUT_VARS(cinfo);
  165566. INPUT_2BYTES(cinfo, length, return FALSE);
  165567. length -= 2;
  165568. while (length > 0) {
  165569. INPUT_BYTE(cinfo, n, return FALSE);
  165570. prec = n >> 4;
  165571. n &= 0x0F;
  165572. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  165573. if (n >= NUM_QUANT_TBLS)
  165574. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  165575. if (cinfo->quant_tbl_ptrs[n] == NULL)
  165576. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165577. quant_ptr = cinfo->quant_tbl_ptrs[n];
  165578. for (i = 0; i < DCTSIZE2; i++) {
  165579. if (prec)
  165580. INPUT_2BYTES(cinfo, tmp, return FALSE);
  165581. else
  165582. INPUT_BYTE(cinfo, tmp, return FALSE);
  165583. /* We convert the zigzag-order table to natural array order. */
  165584. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  165585. }
  165586. if (cinfo->err->trace_level >= 2) {
  165587. for (i = 0; i < DCTSIZE2; i += 8) {
  165588. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  165589. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  165590. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  165591. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  165592. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  165593. }
  165594. }
  165595. length -= DCTSIZE2+1;
  165596. if (prec) length -= DCTSIZE2;
  165597. }
  165598. if (length != 0)
  165599. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165600. INPUT_SYNC(cinfo);
  165601. return TRUE;
  165602. }
  165603. LOCAL(boolean)
  165604. get_dri (j_decompress_ptr cinfo)
  165605. /* Process a DRI marker */
  165606. {
  165607. INT32 length;
  165608. unsigned int tmp;
  165609. INPUT_VARS(cinfo);
  165610. INPUT_2BYTES(cinfo, length, return FALSE);
  165611. if (length != 4)
  165612. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165613. INPUT_2BYTES(cinfo, tmp, return FALSE);
  165614. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  165615. cinfo->restart_interval = tmp;
  165616. INPUT_SYNC(cinfo);
  165617. return TRUE;
  165618. }
  165619. /*
  165620. * Routines for processing APPn and COM markers.
  165621. * These are either saved in memory or discarded, per application request.
  165622. * APP0 and APP14 are specially checked to see if they are
  165623. * JFIF and Adobe markers, respectively.
  165624. */
  165625. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  165626. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  165627. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  165628. LOCAL(void)
  165629. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  165630. unsigned int datalen, INT32 remaining)
  165631. /* Examine first few bytes from an APP0.
  165632. * Take appropriate action if it is a JFIF marker.
  165633. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  165634. */
  165635. {
  165636. INT32 totallen = (INT32) datalen + remaining;
  165637. if (datalen >= APP0_DATA_LEN &&
  165638. GETJOCTET(data[0]) == 0x4A &&
  165639. GETJOCTET(data[1]) == 0x46 &&
  165640. GETJOCTET(data[2]) == 0x49 &&
  165641. GETJOCTET(data[3]) == 0x46 &&
  165642. GETJOCTET(data[4]) == 0) {
  165643. /* Found JFIF APP0 marker: save info */
  165644. cinfo->saw_JFIF_marker = TRUE;
  165645. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  165646. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  165647. cinfo->density_unit = GETJOCTET(data[7]);
  165648. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  165649. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  165650. /* Check version.
  165651. * Major version must be 1, anything else signals an incompatible change.
  165652. * (We used to treat this as an error, but now it's a nonfatal warning,
  165653. * because some bozo at Hijaak couldn't read the spec.)
  165654. * Minor version should be 0..2, but process anyway if newer.
  165655. */
  165656. if (cinfo->JFIF_major_version != 1)
  165657. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  165658. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  165659. /* Generate trace messages */
  165660. TRACEMS5(cinfo, 1, JTRC_JFIF,
  165661. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  165662. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  165663. /* Validate thumbnail dimensions and issue appropriate messages */
  165664. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  165665. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  165666. GETJOCTET(data[12]), GETJOCTET(data[13]));
  165667. totallen -= APP0_DATA_LEN;
  165668. if (totallen !=
  165669. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  165670. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  165671. } else if (datalen >= 6 &&
  165672. GETJOCTET(data[0]) == 0x4A &&
  165673. GETJOCTET(data[1]) == 0x46 &&
  165674. GETJOCTET(data[2]) == 0x58 &&
  165675. GETJOCTET(data[3]) == 0x58 &&
  165676. GETJOCTET(data[4]) == 0) {
  165677. /* Found JFIF "JFXX" extension APP0 marker */
  165678. /* The library doesn't actually do anything with these,
  165679. * but we try to produce a helpful trace message.
  165680. */
  165681. switch (GETJOCTET(data[5])) {
  165682. case 0x10:
  165683. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  165684. break;
  165685. case 0x11:
  165686. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  165687. break;
  165688. case 0x13:
  165689. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  165690. break;
  165691. default:
  165692. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  165693. GETJOCTET(data[5]), (int) totallen);
  165694. break;
  165695. }
  165696. } else {
  165697. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  165698. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  165699. }
  165700. }
  165701. LOCAL(void)
  165702. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  165703. unsigned int datalen, INT32 remaining)
  165704. /* Examine first few bytes from an APP14.
  165705. * Take appropriate action if it is an Adobe marker.
  165706. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  165707. */
  165708. {
  165709. unsigned int version, flags0, flags1, transform;
  165710. if (datalen >= APP14_DATA_LEN &&
  165711. GETJOCTET(data[0]) == 0x41 &&
  165712. GETJOCTET(data[1]) == 0x64 &&
  165713. GETJOCTET(data[2]) == 0x6F &&
  165714. GETJOCTET(data[3]) == 0x62 &&
  165715. GETJOCTET(data[4]) == 0x65) {
  165716. /* Found Adobe APP14 marker */
  165717. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  165718. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  165719. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  165720. transform = GETJOCTET(data[11]);
  165721. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  165722. cinfo->saw_Adobe_marker = TRUE;
  165723. cinfo->Adobe_transform = (UINT8) transform;
  165724. } else {
  165725. /* Start of APP14 does not match "Adobe", or too short */
  165726. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  165727. }
  165728. }
  165729. METHODDEF(boolean)
  165730. get_interesting_appn (j_decompress_ptr cinfo)
  165731. /* Process an APP0 or APP14 marker without saving it */
  165732. {
  165733. INT32 length;
  165734. JOCTET b[APPN_DATA_LEN];
  165735. unsigned int i, numtoread;
  165736. INPUT_VARS(cinfo);
  165737. INPUT_2BYTES(cinfo, length, return FALSE);
  165738. length -= 2;
  165739. /* get the interesting part of the marker data */
  165740. if (length >= APPN_DATA_LEN)
  165741. numtoread = APPN_DATA_LEN;
  165742. else if (length > 0)
  165743. numtoread = (unsigned int) length;
  165744. else
  165745. numtoread = 0;
  165746. for (i = 0; i < numtoread; i++)
  165747. INPUT_BYTE(cinfo, b[i], return FALSE);
  165748. length -= numtoread;
  165749. /* process it */
  165750. switch (cinfo->unread_marker) {
  165751. case M_APP0:
  165752. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  165753. break;
  165754. case M_APP14:
  165755. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  165756. break;
  165757. default:
  165758. /* can't get here unless jpeg_save_markers chooses wrong processor */
  165759. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  165760. break;
  165761. }
  165762. /* skip any remaining data -- could be lots */
  165763. INPUT_SYNC(cinfo);
  165764. if (length > 0)
  165765. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  165766. return TRUE;
  165767. }
  165768. #ifdef SAVE_MARKERS_SUPPORTED
  165769. METHODDEF(boolean)
  165770. save_marker (j_decompress_ptr cinfo)
  165771. /* Save an APPn or COM marker into the marker list */
  165772. {
  165773. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  165774. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  165775. unsigned int bytes_read, data_length;
  165776. JOCTET FAR * data;
  165777. INT32 length = 0;
  165778. INPUT_VARS(cinfo);
  165779. if (cur_marker == NULL) {
  165780. /* begin reading a marker */
  165781. INPUT_2BYTES(cinfo, length, return FALSE);
  165782. length -= 2;
  165783. if (length >= 0) { /* watch out for bogus length word */
  165784. /* figure out how much we want to save */
  165785. unsigned int limit;
  165786. if (cinfo->unread_marker == (int) M_COM)
  165787. limit = marker->length_limit_COM;
  165788. else
  165789. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  165790. if ((unsigned int) length < limit)
  165791. limit = (unsigned int) length;
  165792. /* allocate and initialize the marker item */
  165793. cur_marker = (jpeg_saved_marker_ptr)
  165794. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165795. SIZEOF(struct jpeg_marker_struct) + limit);
  165796. cur_marker->next = NULL;
  165797. cur_marker->marker = (UINT8) cinfo->unread_marker;
  165798. cur_marker->original_length = (unsigned int) length;
  165799. cur_marker->data_length = limit;
  165800. /* data area is just beyond the jpeg_marker_struct */
  165801. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  165802. marker->cur_marker = cur_marker;
  165803. marker->bytes_read = 0;
  165804. bytes_read = 0;
  165805. data_length = limit;
  165806. } else {
  165807. /* deal with bogus length word */
  165808. bytes_read = data_length = 0;
  165809. data = NULL;
  165810. }
  165811. } else {
  165812. /* resume reading a marker */
  165813. bytes_read = marker->bytes_read;
  165814. data_length = cur_marker->data_length;
  165815. data = cur_marker->data + bytes_read;
  165816. }
  165817. while (bytes_read < data_length) {
  165818. INPUT_SYNC(cinfo); /* move the restart point to here */
  165819. marker->bytes_read = bytes_read;
  165820. /* If there's not at least one byte in buffer, suspend */
  165821. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  165822. /* Copy bytes with reasonable rapidity */
  165823. while (bytes_read < data_length && bytes_in_buffer > 0) {
  165824. *data++ = *next_input_byte++;
  165825. bytes_in_buffer--;
  165826. bytes_read++;
  165827. }
  165828. }
  165829. /* Done reading what we want to read */
  165830. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  165831. /* Add new marker to end of list */
  165832. if (cinfo->marker_list == NULL) {
  165833. cinfo->marker_list = cur_marker;
  165834. } else {
  165835. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  165836. while (prev->next != NULL)
  165837. prev = prev->next;
  165838. prev->next = cur_marker;
  165839. }
  165840. /* Reset pointer & calc remaining data length */
  165841. data = cur_marker->data;
  165842. length = cur_marker->original_length - data_length;
  165843. }
  165844. /* Reset to initial state for next marker */
  165845. marker->cur_marker = NULL;
  165846. /* Process the marker if interesting; else just make a generic trace msg */
  165847. switch (cinfo->unread_marker) {
  165848. case M_APP0:
  165849. examine_app0(cinfo, data, data_length, length);
  165850. break;
  165851. case M_APP14:
  165852. examine_app14(cinfo, data, data_length, length);
  165853. break;
  165854. default:
  165855. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  165856. (int) (data_length + length));
  165857. break;
  165858. }
  165859. /* skip any remaining data -- could be lots */
  165860. INPUT_SYNC(cinfo); /* do before skip_input_data */
  165861. if (length > 0)
  165862. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  165863. return TRUE;
  165864. }
  165865. #endif /* SAVE_MARKERS_SUPPORTED */
  165866. METHODDEF(boolean)
  165867. skip_variable (j_decompress_ptr cinfo)
  165868. /* Skip over an unknown or uninteresting variable-length marker */
  165869. {
  165870. INT32 length;
  165871. INPUT_VARS(cinfo);
  165872. INPUT_2BYTES(cinfo, length, return FALSE);
  165873. length -= 2;
  165874. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  165875. INPUT_SYNC(cinfo); /* do before skip_input_data */
  165876. if (length > 0)
  165877. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  165878. return TRUE;
  165879. }
  165880. /*
  165881. * Find the next JPEG marker, save it in cinfo->unread_marker.
  165882. * Returns FALSE if had to suspend before reaching a marker;
  165883. * in that case cinfo->unread_marker is unchanged.
  165884. *
  165885. * Note that the result might not be a valid marker code,
  165886. * but it will never be 0 or FF.
  165887. */
  165888. LOCAL(boolean)
  165889. next_marker (j_decompress_ptr cinfo)
  165890. {
  165891. int c;
  165892. INPUT_VARS(cinfo);
  165893. for (;;) {
  165894. INPUT_BYTE(cinfo, c, return FALSE);
  165895. /* Skip any non-FF bytes.
  165896. * This may look a bit inefficient, but it will not occur in a valid file.
  165897. * We sync after each discarded byte so that a suspending data source
  165898. * can discard the byte from its buffer.
  165899. */
  165900. while (c != 0xFF) {
  165901. cinfo->marker->discarded_bytes++;
  165902. INPUT_SYNC(cinfo);
  165903. INPUT_BYTE(cinfo, c, return FALSE);
  165904. }
  165905. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  165906. * pad bytes, so don't count them in discarded_bytes. We assume there
  165907. * will not be so many consecutive FF bytes as to overflow a suspending
  165908. * data source's input buffer.
  165909. */
  165910. do {
  165911. INPUT_BYTE(cinfo, c, return FALSE);
  165912. } while (c == 0xFF);
  165913. if (c != 0)
  165914. break; /* found a valid marker, exit loop */
  165915. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  165916. * Discard it and loop back to try again.
  165917. */
  165918. cinfo->marker->discarded_bytes += 2;
  165919. INPUT_SYNC(cinfo);
  165920. }
  165921. if (cinfo->marker->discarded_bytes != 0) {
  165922. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  165923. cinfo->marker->discarded_bytes = 0;
  165924. }
  165925. cinfo->unread_marker = c;
  165926. INPUT_SYNC(cinfo);
  165927. return TRUE;
  165928. }
  165929. LOCAL(boolean)
  165930. first_marker (j_decompress_ptr cinfo)
  165931. /* Like next_marker, but used to obtain the initial SOI marker. */
  165932. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  165933. * we might well scan an entire input file before realizing it ain't JPEG.
  165934. * If an application wants to process non-JFIF files, it must seek to the
  165935. * SOI before calling the JPEG library.
  165936. */
  165937. {
  165938. int c, c2;
  165939. INPUT_VARS(cinfo);
  165940. INPUT_BYTE(cinfo, c, return FALSE);
  165941. INPUT_BYTE(cinfo, c2, return FALSE);
  165942. if (c != 0xFF || c2 != (int) M_SOI)
  165943. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  165944. cinfo->unread_marker = c2;
  165945. INPUT_SYNC(cinfo);
  165946. return TRUE;
  165947. }
  165948. /*
  165949. * Read markers until SOS or EOI.
  165950. *
  165951. * Returns same codes as are defined for jpeg_consume_input:
  165952. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  165953. */
  165954. METHODDEF(int)
  165955. read_markers (j_decompress_ptr cinfo)
  165956. {
  165957. /* Outer loop repeats once for each marker. */
  165958. for (;;) {
  165959. /* Collect the marker proper, unless we already did. */
  165960. /* NB: first_marker() enforces the requirement that SOI appear first. */
  165961. if (cinfo->unread_marker == 0) {
  165962. if (! cinfo->marker->saw_SOI) {
  165963. if (! first_marker(cinfo))
  165964. return JPEG_SUSPENDED;
  165965. } else {
  165966. if (! next_marker(cinfo))
  165967. return JPEG_SUSPENDED;
  165968. }
  165969. }
  165970. /* At this point cinfo->unread_marker contains the marker code and the
  165971. * input point is just past the marker proper, but before any parameters.
  165972. * A suspension will cause us to return with this state still true.
  165973. */
  165974. switch (cinfo->unread_marker) {
  165975. case M_SOI:
  165976. if (! get_soi(cinfo))
  165977. return JPEG_SUSPENDED;
  165978. break;
  165979. case M_SOF0: /* Baseline */
  165980. case M_SOF1: /* Extended sequential, Huffman */
  165981. if (! get_sof(cinfo, FALSE, FALSE))
  165982. return JPEG_SUSPENDED;
  165983. break;
  165984. case M_SOF2: /* Progressive, Huffman */
  165985. if (! get_sof(cinfo, TRUE, FALSE))
  165986. return JPEG_SUSPENDED;
  165987. break;
  165988. case M_SOF9: /* Extended sequential, arithmetic */
  165989. if (! get_sof(cinfo, FALSE, TRUE))
  165990. return JPEG_SUSPENDED;
  165991. break;
  165992. case M_SOF10: /* Progressive, arithmetic */
  165993. if (! get_sof(cinfo, TRUE, TRUE))
  165994. return JPEG_SUSPENDED;
  165995. break;
  165996. /* Currently unsupported SOFn types */
  165997. case M_SOF3: /* Lossless, Huffman */
  165998. case M_SOF5: /* Differential sequential, Huffman */
  165999. case M_SOF6: /* Differential progressive, Huffman */
  166000. case M_SOF7: /* Differential lossless, Huffman */
  166001. case M_JPG: /* Reserved for JPEG extensions */
  166002. case M_SOF11: /* Lossless, arithmetic */
  166003. case M_SOF13: /* Differential sequential, arithmetic */
  166004. case M_SOF14: /* Differential progressive, arithmetic */
  166005. case M_SOF15: /* Differential lossless, arithmetic */
  166006. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  166007. break;
  166008. case M_SOS:
  166009. if (! get_sos(cinfo))
  166010. return JPEG_SUSPENDED;
  166011. cinfo->unread_marker = 0; /* processed the marker */
  166012. return JPEG_REACHED_SOS;
  166013. case M_EOI:
  166014. TRACEMS(cinfo, 1, JTRC_EOI);
  166015. cinfo->unread_marker = 0; /* processed the marker */
  166016. return JPEG_REACHED_EOI;
  166017. case M_DAC:
  166018. if (! get_dac(cinfo))
  166019. return JPEG_SUSPENDED;
  166020. break;
  166021. case M_DHT:
  166022. if (! get_dht(cinfo))
  166023. return JPEG_SUSPENDED;
  166024. break;
  166025. case M_DQT:
  166026. if (! get_dqt(cinfo))
  166027. return JPEG_SUSPENDED;
  166028. break;
  166029. case M_DRI:
  166030. if (! get_dri(cinfo))
  166031. return JPEG_SUSPENDED;
  166032. break;
  166033. case M_APP0:
  166034. case M_APP1:
  166035. case M_APP2:
  166036. case M_APP3:
  166037. case M_APP4:
  166038. case M_APP5:
  166039. case M_APP6:
  166040. case M_APP7:
  166041. case M_APP8:
  166042. case M_APP9:
  166043. case M_APP10:
  166044. case M_APP11:
  166045. case M_APP12:
  166046. case M_APP13:
  166047. case M_APP14:
  166048. case M_APP15:
  166049. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  166050. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  166051. return JPEG_SUSPENDED;
  166052. break;
  166053. case M_COM:
  166054. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  166055. return JPEG_SUSPENDED;
  166056. break;
  166057. case M_RST0: /* these are all parameterless */
  166058. case M_RST1:
  166059. case M_RST2:
  166060. case M_RST3:
  166061. case M_RST4:
  166062. case M_RST5:
  166063. case M_RST6:
  166064. case M_RST7:
  166065. case M_TEM:
  166066. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  166067. break;
  166068. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  166069. if (! skip_variable(cinfo))
  166070. return JPEG_SUSPENDED;
  166071. break;
  166072. default: /* must be DHP, EXP, JPGn, or RESn */
  166073. /* For now, we treat the reserved markers as fatal errors since they are
  166074. * likely to be used to signal incompatible JPEG Part 3 extensions.
  166075. * Once the JPEG 3 version-number marker is well defined, this code
  166076. * ought to change!
  166077. */
  166078. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  166079. break;
  166080. }
  166081. /* Successfully processed marker, so reset state variable */
  166082. cinfo->unread_marker = 0;
  166083. } /* end loop */
  166084. }
  166085. /*
  166086. * Read a restart marker, which is expected to appear next in the datastream;
  166087. * if the marker is not there, take appropriate recovery action.
  166088. * Returns FALSE if suspension is required.
  166089. *
  166090. * This is called by the entropy decoder after it has read an appropriate
  166091. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  166092. * has already read a marker from the data source. Under normal conditions
  166093. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  166094. * it holds a marker which the decoder will be unable to read past.
  166095. */
  166096. METHODDEF(boolean)
  166097. read_restart_marker (j_decompress_ptr cinfo)
  166098. {
  166099. /* Obtain a marker unless we already did. */
  166100. /* Note that next_marker will complain if it skips any data. */
  166101. if (cinfo->unread_marker == 0) {
  166102. if (! next_marker(cinfo))
  166103. return FALSE;
  166104. }
  166105. if (cinfo->unread_marker ==
  166106. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  166107. /* Normal case --- swallow the marker and let entropy decoder continue */
  166108. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  166109. cinfo->unread_marker = 0;
  166110. } else {
  166111. /* Uh-oh, the restart markers have been messed up. */
  166112. /* Let the data source manager determine how to resync. */
  166113. if (! (*cinfo->src->resync_to_restart) (cinfo,
  166114. cinfo->marker->next_restart_num))
  166115. return FALSE;
  166116. }
  166117. /* Update next-restart state */
  166118. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  166119. return TRUE;
  166120. }
  166121. /*
  166122. * This is the default resync_to_restart method for data source managers
  166123. * to use if they don't have any better approach. Some data source managers
  166124. * may be able to back up, or may have additional knowledge about the data
  166125. * which permits a more intelligent recovery strategy; such managers would
  166126. * presumably supply their own resync method.
  166127. *
  166128. * read_restart_marker calls resync_to_restart if it finds a marker other than
  166129. * the restart marker it was expecting. (This code is *not* used unless
  166130. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  166131. * the marker code actually found (might be anything, except 0 or FF).
  166132. * The desired restart marker number (0..7) is passed as a parameter.
  166133. * This routine is supposed to apply whatever error recovery strategy seems
  166134. * appropriate in order to position the input stream to the next data segment.
  166135. * Note that cinfo->unread_marker is treated as a marker appearing before
  166136. * the current data-source input point; usually it should be reset to zero
  166137. * before returning.
  166138. * Returns FALSE if suspension is required.
  166139. *
  166140. * This implementation is substantially constrained by wanting to treat the
  166141. * input as a data stream; this means we can't back up. Therefore, we have
  166142. * only the following actions to work with:
  166143. * 1. Simply discard the marker and let the entropy decoder resume at next
  166144. * byte of file.
  166145. * 2. Read forward until we find another marker, discarding intervening
  166146. * data. (In theory we could look ahead within the current bufferload,
  166147. * without having to discard data if we don't find the desired marker.
  166148. * This idea is not implemented here, in part because it makes behavior
  166149. * dependent on buffer size and chance buffer-boundary positions.)
  166150. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  166151. * This will cause the entropy decoder to process an empty data segment,
  166152. * inserting dummy zeroes, and then we will reprocess the marker.
  166153. *
  166154. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  166155. * appropriate if the found marker is a future restart marker (indicating
  166156. * that we have missed the desired restart marker, probably because it got
  166157. * corrupted).
  166158. * We apply #2 or #3 if the found marker is a restart marker no more than
  166159. * two counts behind or ahead of the expected one. We also apply #2 if the
  166160. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  166161. * If the found marker is a restart marker more than 2 counts away, we do #1
  166162. * (too much risk that the marker is erroneous; with luck we will be able to
  166163. * resync at some future point).
  166164. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  166165. * overrunning the end of a scan. An implementation limited to single-scan
  166166. * files might find it better to apply #2 for markers other than EOI, since
  166167. * any other marker would have to be bogus data in that case.
  166168. */
  166169. GLOBAL(boolean)
  166170. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  166171. {
  166172. int marker = cinfo->unread_marker;
  166173. int action = 1;
  166174. /* Always put up a warning. */
  166175. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  166176. /* Outer loop handles repeated decision after scanning forward. */
  166177. for (;;) {
  166178. if (marker < (int) M_SOF0)
  166179. action = 2; /* invalid marker */
  166180. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  166181. action = 3; /* valid non-restart marker */
  166182. else {
  166183. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  166184. marker == ((int) M_RST0 + ((desired+2) & 7)))
  166185. action = 3; /* one of the next two expected restarts */
  166186. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  166187. marker == ((int) M_RST0 + ((desired-2) & 7)))
  166188. action = 2; /* a prior restart, so advance */
  166189. else
  166190. action = 1; /* desired restart or too far away */
  166191. }
  166192. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  166193. switch (action) {
  166194. case 1:
  166195. /* Discard marker and let entropy decoder resume processing. */
  166196. cinfo->unread_marker = 0;
  166197. return TRUE;
  166198. case 2:
  166199. /* Scan to the next marker, and repeat the decision loop. */
  166200. if (! next_marker(cinfo))
  166201. return FALSE;
  166202. marker = cinfo->unread_marker;
  166203. break;
  166204. case 3:
  166205. /* Return without advancing past this marker. */
  166206. /* Entropy decoder will be forced to process an empty segment. */
  166207. return TRUE;
  166208. }
  166209. } /* end loop */
  166210. }
  166211. /*
  166212. * Reset marker processing state to begin a fresh datastream.
  166213. */
  166214. METHODDEF(void)
  166215. reset_marker_reader (j_decompress_ptr cinfo)
  166216. {
  166217. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  166218. cinfo->comp_info = NULL; /* until allocated by get_sof */
  166219. cinfo->input_scan_number = 0; /* no SOS seen yet */
  166220. cinfo->unread_marker = 0; /* no pending marker */
  166221. marker->pub.saw_SOI = FALSE; /* set internal state too */
  166222. marker->pub.saw_SOF = FALSE;
  166223. marker->pub.discarded_bytes = 0;
  166224. marker->cur_marker = NULL;
  166225. }
  166226. /*
  166227. * Initialize the marker reader module.
  166228. * This is called only once, when the decompression object is created.
  166229. */
  166230. GLOBAL(void)
  166231. jinit_marker_reader (j_decompress_ptr cinfo)
  166232. {
  166233. my_marker_ptr2 marker;
  166234. int i;
  166235. /* Create subobject in permanent pool */
  166236. marker = (my_marker_ptr2)
  166237. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  166238. SIZEOF(my_marker_reader));
  166239. cinfo->marker = (struct jpeg_marker_reader *) marker;
  166240. /* Initialize public method pointers */
  166241. marker->pub.reset_marker_reader = reset_marker_reader;
  166242. marker->pub.read_markers = read_markers;
  166243. marker->pub.read_restart_marker = read_restart_marker;
  166244. /* Initialize COM/APPn processing.
  166245. * By default, we examine and then discard APP0 and APP14,
  166246. * but simply discard COM and all other APPn.
  166247. */
  166248. marker->process_COM = skip_variable;
  166249. marker->length_limit_COM = 0;
  166250. for (i = 0; i < 16; i++) {
  166251. marker->process_APPn[i] = skip_variable;
  166252. marker->length_limit_APPn[i] = 0;
  166253. }
  166254. marker->process_APPn[0] = get_interesting_appn;
  166255. marker->process_APPn[14] = get_interesting_appn;
  166256. /* Reset marker processing state */
  166257. reset_marker_reader(cinfo);
  166258. }
  166259. /*
  166260. * Control saving of COM and APPn markers into marker_list.
  166261. */
  166262. #ifdef SAVE_MARKERS_SUPPORTED
  166263. GLOBAL(void)
  166264. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  166265. unsigned int length_limit)
  166266. {
  166267. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  166268. long maxlength;
  166269. jpeg_marker_parser_method processor;
  166270. /* Length limit mustn't be larger than what we can allocate
  166271. * (should only be a concern in a 16-bit environment).
  166272. */
  166273. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  166274. if (((long) length_limit) > maxlength)
  166275. length_limit = (unsigned int) maxlength;
  166276. /* Choose processor routine to use.
  166277. * APP0/APP14 have special requirements.
  166278. */
  166279. if (length_limit) {
  166280. processor = save_marker;
  166281. /* If saving APP0/APP14, save at least enough for our internal use. */
  166282. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  166283. length_limit = APP0_DATA_LEN;
  166284. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  166285. length_limit = APP14_DATA_LEN;
  166286. } else {
  166287. processor = skip_variable;
  166288. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  166289. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  166290. processor = get_interesting_appn;
  166291. }
  166292. if (marker_code == (int) M_COM) {
  166293. marker->process_COM = processor;
  166294. marker->length_limit_COM = length_limit;
  166295. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  166296. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  166297. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  166298. } else
  166299. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  166300. }
  166301. #endif /* SAVE_MARKERS_SUPPORTED */
  166302. /*
  166303. * Install a special processing method for COM or APPn markers.
  166304. */
  166305. GLOBAL(void)
  166306. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  166307. jpeg_marker_parser_method routine)
  166308. {
  166309. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  166310. if (marker_code == (int) M_COM)
  166311. marker->process_COM = routine;
  166312. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  166313. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  166314. else
  166315. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  166316. }
  166317. /********* End of inlined file: jdmarker.c *********/
  166318. /********* Start of inlined file: jdmaster.c *********/
  166319. #define JPEG_INTERNALS
  166320. /* Private state */
  166321. typedef struct {
  166322. struct jpeg_decomp_master pub; /* public fields */
  166323. int pass_number; /* # of passes completed */
  166324. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  166325. /* Saved references to initialized quantizer modules,
  166326. * in case we need to switch modes.
  166327. */
  166328. struct jpeg_color_quantizer * quantizer_1pass;
  166329. struct jpeg_color_quantizer * quantizer_2pass;
  166330. } my_decomp_master;
  166331. typedef my_decomp_master * my_master_ptr6;
  166332. /*
  166333. * Determine whether merged upsample/color conversion should be used.
  166334. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  166335. */
  166336. LOCAL(boolean)
  166337. use_merged_upsample (j_decompress_ptr cinfo)
  166338. {
  166339. #ifdef UPSAMPLE_MERGING_SUPPORTED
  166340. /* Merging is the equivalent of plain box-filter upsampling */
  166341. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  166342. return FALSE;
  166343. /* jdmerge.c only supports YCC=>RGB color conversion */
  166344. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  166345. cinfo->out_color_space != JCS_RGB ||
  166346. cinfo->out_color_components != RGB_PIXELSIZE)
  166347. return FALSE;
  166348. /* and it only handles 2h1v or 2h2v sampling ratios */
  166349. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  166350. cinfo->comp_info[1].h_samp_factor != 1 ||
  166351. cinfo->comp_info[2].h_samp_factor != 1 ||
  166352. cinfo->comp_info[0].v_samp_factor > 2 ||
  166353. cinfo->comp_info[1].v_samp_factor != 1 ||
  166354. cinfo->comp_info[2].v_samp_factor != 1)
  166355. return FALSE;
  166356. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  166357. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  166358. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  166359. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  166360. return FALSE;
  166361. /* ??? also need to test for upsample-time rescaling, when & if supported */
  166362. return TRUE; /* by golly, it'll work... */
  166363. #else
  166364. return FALSE;
  166365. #endif
  166366. }
  166367. /*
  166368. * Compute output image dimensions and related values.
  166369. * NOTE: this is exported for possible use by application.
  166370. * Hence it mustn't do anything that can't be done twice.
  166371. * Also note that it may be called before the master module is initialized!
  166372. */
  166373. GLOBAL(void)
  166374. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  166375. /* Do computations that are needed before master selection phase */
  166376. {
  166377. #ifdef IDCT_SCALING_SUPPORTED
  166378. int ci;
  166379. jpeg_component_info *compptr;
  166380. #endif
  166381. /* Prevent application from calling me at wrong times */
  166382. if (cinfo->global_state != DSTATE_READY)
  166383. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166384. #ifdef IDCT_SCALING_SUPPORTED
  166385. /* Compute actual output image dimensions and DCT scaling choices. */
  166386. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  166387. /* Provide 1/8 scaling */
  166388. cinfo->output_width = (JDIMENSION)
  166389. jdiv_round_up((long) cinfo->image_width, 8L);
  166390. cinfo->output_height = (JDIMENSION)
  166391. jdiv_round_up((long) cinfo->image_height, 8L);
  166392. cinfo->min_DCT_scaled_size = 1;
  166393. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  166394. /* Provide 1/4 scaling */
  166395. cinfo->output_width = (JDIMENSION)
  166396. jdiv_round_up((long) cinfo->image_width, 4L);
  166397. cinfo->output_height = (JDIMENSION)
  166398. jdiv_round_up((long) cinfo->image_height, 4L);
  166399. cinfo->min_DCT_scaled_size = 2;
  166400. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  166401. /* Provide 1/2 scaling */
  166402. cinfo->output_width = (JDIMENSION)
  166403. jdiv_round_up((long) cinfo->image_width, 2L);
  166404. cinfo->output_height = (JDIMENSION)
  166405. jdiv_round_up((long) cinfo->image_height, 2L);
  166406. cinfo->min_DCT_scaled_size = 4;
  166407. } else {
  166408. /* Provide 1/1 scaling */
  166409. cinfo->output_width = cinfo->image_width;
  166410. cinfo->output_height = cinfo->image_height;
  166411. cinfo->min_DCT_scaled_size = DCTSIZE;
  166412. }
  166413. /* In selecting the actual DCT scaling for each component, we try to
  166414. * scale up the chroma components via IDCT scaling rather than upsampling.
  166415. * This saves time if the upsampler gets to use 1:1 scaling.
  166416. * Note this code assumes that the supported DCT scalings are powers of 2.
  166417. */
  166418. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166419. ci++, compptr++) {
  166420. int ssize = cinfo->min_DCT_scaled_size;
  166421. while (ssize < DCTSIZE &&
  166422. (compptr->h_samp_factor * ssize * 2 <=
  166423. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  166424. (compptr->v_samp_factor * ssize * 2 <=
  166425. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  166426. ssize = ssize * 2;
  166427. }
  166428. compptr->DCT_scaled_size = ssize;
  166429. }
  166430. /* Recompute downsampled dimensions of components;
  166431. * application needs to know these if using raw downsampled data.
  166432. */
  166433. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166434. ci++, compptr++) {
  166435. /* Size in samples, after IDCT scaling */
  166436. compptr->downsampled_width = (JDIMENSION)
  166437. jdiv_round_up((long) cinfo->image_width *
  166438. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  166439. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  166440. compptr->downsampled_height = (JDIMENSION)
  166441. jdiv_round_up((long) cinfo->image_height *
  166442. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  166443. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  166444. }
  166445. #else /* !IDCT_SCALING_SUPPORTED */
  166446. /* Hardwire it to "no scaling" */
  166447. cinfo->output_width = cinfo->image_width;
  166448. cinfo->output_height = cinfo->image_height;
  166449. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  166450. * and has computed unscaled downsampled_width and downsampled_height.
  166451. */
  166452. #endif /* IDCT_SCALING_SUPPORTED */
  166453. /* Report number of components in selected colorspace. */
  166454. /* Probably this should be in the color conversion module... */
  166455. switch (cinfo->out_color_space) {
  166456. case JCS_GRAYSCALE:
  166457. cinfo->out_color_components = 1;
  166458. break;
  166459. case JCS_RGB:
  166460. #if RGB_PIXELSIZE != 3
  166461. cinfo->out_color_components = RGB_PIXELSIZE;
  166462. break;
  166463. #endif /* else share code with YCbCr */
  166464. case JCS_YCbCr:
  166465. cinfo->out_color_components = 3;
  166466. break;
  166467. case JCS_CMYK:
  166468. case JCS_YCCK:
  166469. cinfo->out_color_components = 4;
  166470. break;
  166471. default: /* else must be same colorspace as in file */
  166472. cinfo->out_color_components = cinfo->num_components;
  166473. break;
  166474. }
  166475. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  166476. cinfo->out_color_components);
  166477. /* See if upsampler will want to emit more than one row at a time */
  166478. if (use_merged_upsample(cinfo))
  166479. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  166480. else
  166481. cinfo->rec_outbuf_height = 1;
  166482. }
  166483. /*
  166484. * Several decompression processes need to range-limit values to the range
  166485. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  166486. * due to noise introduced by quantization, roundoff error, etc. These
  166487. * processes are inner loops and need to be as fast as possible. On most
  166488. * machines, particularly CPUs with pipelines or instruction prefetch,
  166489. * a (subscript-check-less) C table lookup
  166490. * x = sample_range_limit[x];
  166491. * is faster than explicit tests
  166492. * if (x < 0) x = 0;
  166493. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  166494. * These processes all use a common table prepared by the routine below.
  166495. *
  166496. * For most steps we can mathematically guarantee that the initial value
  166497. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  166498. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  166499. * limiting step (just after the IDCT), a wildly out-of-range value is
  166500. * possible if the input data is corrupt. To avoid any chance of indexing
  166501. * off the end of memory and getting a bad-pointer trap, we perform the
  166502. * post-IDCT limiting thus:
  166503. * x = range_limit[x & MASK];
  166504. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  166505. * samples. Under normal circumstances this is more than enough range and
  166506. * a correct output will be generated; with bogus input data the mask will
  166507. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  166508. * For the post-IDCT step, we want to convert the data from signed to unsigned
  166509. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  166510. * So the post-IDCT limiting table ends up looking like this:
  166511. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  166512. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  166513. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  166514. * 0,1,...,CENTERJSAMPLE-1
  166515. * Negative inputs select values from the upper half of the table after
  166516. * masking.
  166517. *
  166518. * We can save some space by overlapping the start of the post-IDCT table
  166519. * with the simpler range limiting table. The post-IDCT table begins at
  166520. * sample_range_limit + CENTERJSAMPLE.
  166521. *
  166522. * Note that the table is allocated in near data space on PCs; it's small
  166523. * enough and used often enough to justify this.
  166524. */
  166525. LOCAL(void)
  166526. prepare_range_limit_table (j_decompress_ptr cinfo)
  166527. /* Allocate and fill in the sample_range_limit table */
  166528. {
  166529. JSAMPLE * table;
  166530. int i;
  166531. table = (JSAMPLE *)
  166532. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166533. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  166534. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  166535. cinfo->sample_range_limit = table;
  166536. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  166537. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  166538. /* Main part of "simple" table: limit[x] = x */
  166539. for (i = 0; i <= MAXJSAMPLE; i++)
  166540. table[i] = (JSAMPLE) i;
  166541. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  166542. /* End of simple table, rest of first half of post-IDCT table */
  166543. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  166544. table[i] = MAXJSAMPLE;
  166545. /* Second half of post-IDCT table */
  166546. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  166547. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  166548. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  166549. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  166550. }
  166551. /*
  166552. * Master selection of decompression modules.
  166553. * This is done once at jpeg_start_decompress time. We determine
  166554. * which modules will be used and give them appropriate initialization calls.
  166555. * We also initialize the decompressor input side to begin consuming data.
  166556. *
  166557. * Since jpeg_read_header has finished, we know what is in the SOF
  166558. * and (first) SOS markers. We also have all the application parameter
  166559. * settings.
  166560. */
  166561. LOCAL(void)
  166562. master_selection (j_decompress_ptr cinfo)
  166563. {
  166564. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  166565. boolean use_c_buffer;
  166566. long samplesperrow;
  166567. JDIMENSION jd_samplesperrow;
  166568. /* Initialize dimensions and other stuff */
  166569. jpeg_calc_output_dimensions(cinfo);
  166570. prepare_range_limit_table(cinfo);
  166571. /* Width of an output scanline must be representable as JDIMENSION. */
  166572. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  166573. jd_samplesperrow = (JDIMENSION) samplesperrow;
  166574. if ((long) jd_samplesperrow != samplesperrow)
  166575. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  166576. /* Initialize my private state */
  166577. master->pass_number = 0;
  166578. master->using_merged_upsample = use_merged_upsample(cinfo);
  166579. /* Color quantizer selection */
  166580. master->quantizer_1pass = NULL;
  166581. master->quantizer_2pass = NULL;
  166582. /* No mode changes if not using buffered-image mode. */
  166583. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  166584. cinfo->enable_1pass_quant = FALSE;
  166585. cinfo->enable_external_quant = FALSE;
  166586. cinfo->enable_2pass_quant = FALSE;
  166587. }
  166588. if (cinfo->quantize_colors) {
  166589. if (cinfo->raw_data_out)
  166590. ERREXIT(cinfo, JERR_NOTIMPL);
  166591. /* 2-pass quantizer only works in 3-component color space. */
  166592. if (cinfo->out_color_components != 3) {
  166593. cinfo->enable_1pass_quant = TRUE;
  166594. cinfo->enable_external_quant = FALSE;
  166595. cinfo->enable_2pass_quant = FALSE;
  166596. cinfo->colormap = NULL;
  166597. } else if (cinfo->colormap != NULL) {
  166598. cinfo->enable_external_quant = TRUE;
  166599. } else if (cinfo->two_pass_quantize) {
  166600. cinfo->enable_2pass_quant = TRUE;
  166601. } else {
  166602. cinfo->enable_1pass_quant = TRUE;
  166603. }
  166604. if (cinfo->enable_1pass_quant) {
  166605. #ifdef QUANT_1PASS_SUPPORTED
  166606. jinit_1pass_quantizer(cinfo);
  166607. master->quantizer_1pass = cinfo->cquantize;
  166608. #else
  166609. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166610. #endif
  166611. }
  166612. /* We use the 2-pass code to map to external colormaps. */
  166613. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  166614. #ifdef QUANT_2PASS_SUPPORTED
  166615. jinit_2pass_quantizer(cinfo);
  166616. master->quantizer_2pass = cinfo->cquantize;
  166617. #else
  166618. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166619. #endif
  166620. }
  166621. /* If both quantizers are initialized, the 2-pass one is left active;
  166622. * this is necessary for starting with quantization to an external map.
  166623. */
  166624. }
  166625. /* Post-processing: in particular, color conversion first */
  166626. if (! cinfo->raw_data_out) {
  166627. if (master->using_merged_upsample) {
  166628. #ifdef UPSAMPLE_MERGING_SUPPORTED
  166629. jinit_merged_upsampler(cinfo); /* does color conversion too */
  166630. #else
  166631. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166632. #endif
  166633. } else {
  166634. jinit_color_deconverter(cinfo);
  166635. jinit_upsampler(cinfo);
  166636. }
  166637. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  166638. }
  166639. /* Inverse DCT */
  166640. jinit_inverse_dct(cinfo);
  166641. /* Entropy decoding: either Huffman or arithmetic coding. */
  166642. if (cinfo->arith_code) {
  166643. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  166644. } else {
  166645. if (cinfo->progressive_mode) {
  166646. #ifdef D_PROGRESSIVE_SUPPORTED
  166647. jinit_phuff_decoder(cinfo);
  166648. #else
  166649. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166650. #endif
  166651. } else
  166652. jinit_huff_decoder(cinfo);
  166653. }
  166654. /* Initialize principal buffer controllers. */
  166655. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  166656. jinit_d_coef_controller(cinfo, use_c_buffer);
  166657. if (! cinfo->raw_data_out)
  166658. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  166659. /* We can now tell the memory manager to allocate virtual arrays. */
  166660. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  166661. /* Initialize input side of decompressor to consume first scan. */
  166662. (*cinfo->inputctl->start_input_pass) (cinfo);
  166663. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166664. /* If jpeg_start_decompress will read the whole file, initialize
  166665. * progress monitoring appropriately. The input step is counted
  166666. * as one pass.
  166667. */
  166668. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  166669. cinfo->inputctl->has_multiple_scans) {
  166670. int nscans;
  166671. /* Estimate number of scans to set pass_limit. */
  166672. if (cinfo->progressive_mode) {
  166673. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  166674. nscans = 2 + 3 * cinfo->num_components;
  166675. } else {
  166676. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  166677. nscans = cinfo->num_components;
  166678. }
  166679. cinfo->progress->pass_counter = 0L;
  166680. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  166681. cinfo->progress->completed_passes = 0;
  166682. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  166683. /* Count the input pass as done */
  166684. master->pass_number++;
  166685. }
  166686. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166687. }
  166688. /*
  166689. * Per-pass setup.
  166690. * This is called at the beginning of each output pass. We determine which
  166691. * modules will be active during this pass and give them appropriate
  166692. * start_pass calls. We also set is_dummy_pass to indicate whether this
  166693. * is a "real" output pass or a dummy pass for color quantization.
  166694. * (In the latter case, jdapistd.c will crank the pass to completion.)
  166695. */
  166696. METHODDEF(void)
  166697. prepare_for_output_pass (j_decompress_ptr cinfo)
  166698. {
  166699. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  166700. if (master->pub.is_dummy_pass) {
  166701. #ifdef QUANT_2PASS_SUPPORTED
  166702. /* Final pass of 2-pass quantization */
  166703. master->pub.is_dummy_pass = FALSE;
  166704. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  166705. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  166706. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  166707. #else
  166708. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166709. #endif /* QUANT_2PASS_SUPPORTED */
  166710. } else {
  166711. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  166712. /* Select new quantization method */
  166713. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  166714. cinfo->cquantize = master->quantizer_2pass;
  166715. master->pub.is_dummy_pass = TRUE;
  166716. } else if (cinfo->enable_1pass_quant) {
  166717. cinfo->cquantize = master->quantizer_1pass;
  166718. } else {
  166719. ERREXIT(cinfo, JERR_MODE_CHANGE);
  166720. }
  166721. }
  166722. (*cinfo->idct->start_pass) (cinfo);
  166723. (*cinfo->coef->start_output_pass) (cinfo);
  166724. if (! cinfo->raw_data_out) {
  166725. if (! master->using_merged_upsample)
  166726. (*cinfo->cconvert->start_pass) (cinfo);
  166727. (*cinfo->upsample->start_pass) (cinfo);
  166728. if (cinfo->quantize_colors)
  166729. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  166730. (*cinfo->post->start_pass) (cinfo,
  166731. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  166732. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  166733. }
  166734. }
  166735. /* Set up progress monitor's pass info if present */
  166736. if (cinfo->progress != NULL) {
  166737. cinfo->progress->completed_passes = master->pass_number;
  166738. cinfo->progress->total_passes = master->pass_number +
  166739. (master->pub.is_dummy_pass ? 2 : 1);
  166740. /* In buffered-image mode, we assume one more output pass if EOI not
  166741. * yet reached, but no more passes if EOI has been reached.
  166742. */
  166743. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  166744. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  166745. }
  166746. }
  166747. }
  166748. /*
  166749. * Finish up at end of an output pass.
  166750. */
  166751. METHODDEF(void)
  166752. finish_output_pass (j_decompress_ptr cinfo)
  166753. {
  166754. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  166755. if (cinfo->quantize_colors)
  166756. (*cinfo->cquantize->finish_pass) (cinfo);
  166757. master->pass_number++;
  166758. }
  166759. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166760. /*
  166761. * Switch to a new external colormap between output passes.
  166762. */
  166763. GLOBAL(void)
  166764. jpeg_new_colormap (j_decompress_ptr cinfo)
  166765. {
  166766. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  166767. /* Prevent application from calling me at wrong times */
  166768. if (cinfo->global_state != DSTATE_BUFIMAGE)
  166769. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166770. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  166771. cinfo->colormap != NULL) {
  166772. /* Select 2-pass quantizer for external colormap use */
  166773. cinfo->cquantize = master->quantizer_2pass;
  166774. /* Notify quantizer of colormap change */
  166775. (*cinfo->cquantize->new_color_map) (cinfo);
  166776. master->pub.is_dummy_pass = FALSE; /* just in case */
  166777. } else
  166778. ERREXIT(cinfo, JERR_MODE_CHANGE);
  166779. }
  166780. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166781. /*
  166782. * Initialize master decompression control and select active modules.
  166783. * This is performed at the start of jpeg_start_decompress.
  166784. */
  166785. GLOBAL(void)
  166786. jinit_master_decompress (j_decompress_ptr cinfo)
  166787. {
  166788. my_master_ptr6 master;
  166789. master = (my_master_ptr6)
  166790. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166791. SIZEOF(my_decomp_master));
  166792. cinfo->master = (struct jpeg_decomp_master *) master;
  166793. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  166794. master->pub.finish_output_pass = finish_output_pass;
  166795. master->pub.is_dummy_pass = FALSE;
  166796. master_selection(cinfo);
  166797. }
  166798. /********* End of inlined file: jdmaster.c *********/
  166799. #undef FIX
  166800. /********* Start of inlined file: jdmerge.c *********/
  166801. #define JPEG_INTERNALS
  166802. #ifdef UPSAMPLE_MERGING_SUPPORTED
  166803. /* Private subobject */
  166804. typedef struct {
  166805. struct jpeg_upsampler pub; /* public fields */
  166806. /* Pointer to routine to do actual upsampling/conversion of one row group */
  166807. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  166808. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  166809. JSAMPARRAY output_buf));
  166810. /* Private state for YCC->RGB conversion */
  166811. int * Cr_r_tab; /* => table for Cr to R conversion */
  166812. int * Cb_b_tab; /* => table for Cb to B conversion */
  166813. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  166814. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  166815. /* For 2:1 vertical sampling, we produce two output rows at a time.
  166816. * We need a "spare" row buffer to hold the second output row if the
  166817. * application provides just a one-row buffer; we also use the spare
  166818. * to discard the dummy last row if the image height is odd.
  166819. */
  166820. JSAMPROW spare_row;
  166821. boolean spare_full; /* T if spare buffer is occupied */
  166822. JDIMENSION out_row_width; /* samples per output row */
  166823. JDIMENSION rows_to_go; /* counts rows remaining in image */
  166824. } my_upsampler;
  166825. typedef my_upsampler * my_upsample_ptr;
  166826. #define SCALEBITS 16 /* speediest right-shift on some machines */
  166827. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  166828. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  166829. /*
  166830. * Initialize tables for YCC->RGB colorspace conversion.
  166831. * This is taken directly from jdcolor.c; see that file for more info.
  166832. */
  166833. LOCAL(void)
  166834. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  166835. {
  166836. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166837. int i;
  166838. INT32 x;
  166839. SHIFT_TEMPS
  166840. upsample->Cr_r_tab = (int *)
  166841. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166842. (MAXJSAMPLE+1) * SIZEOF(int));
  166843. upsample->Cb_b_tab = (int *)
  166844. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166845. (MAXJSAMPLE+1) * SIZEOF(int));
  166846. upsample->Cr_g_tab = (INT32 *)
  166847. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166848. (MAXJSAMPLE+1) * SIZEOF(INT32));
  166849. upsample->Cb_g_tab = (INT32 *)
  166850. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166851. (MAXJSAMPLE+1) * SIZEOF(INT32));
  166852. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  166853. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  166854. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  166855. /* Cr=>R value is nearest int to 1.40200 * x */
  166856. upsample->Cr_r_tab[i] = (int)
  166857. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  166858. /* Cb=>B value is nearest int to 1.77200 * x */
  166859. upsample->Cb_b_tab[i] = (int)
  166860. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  166861. /* Cr=>G value is scaled-up -0.71414 * x */
  166862. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  166863. /* Cb=>G value is scaled-up -0.34414 * x */
  166864. /* We also add in ONE_HALF so that need not do it in inner loop */
  166865. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  166866. }
  166867. }
  166868. /*
  166869. * Initialize for an upsampling pass.
  166870. */
  166871. METHODDEF(void)
  166872. start_pass_merged_upsample (j_decompress_ptr cinfo)
  166873. {
  166874. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166875. /* Mark the spare buffer empty */
  166876. upsample->spare_full = FALSE;
  166877. /* Initialize total-height counter for detecting bottom of image */
  166878. upsample->rows_to_go = cinfo->output_height;
  166879. }
  166880. /*
  166881. * Control routine to do upsampling (and color conversion).
  166882. *
  166883. * The control routine just handles the row buffering considerations.
  166884. */
  166885. METHODDEF(void)
  166886. merged_2v_upsample (j_decompress_ptr cinfo,
  166887. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166888. JDIMENSION in_row_groups_avail,
  166889. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166890. JDIMENSION out_rows_avail)
  166891. /* 2:1 vertical sampling case: may need a spare row. */
  166892. {
  166893. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166894. JSAMPROW work_ptrs[2];
  166895. JDIMENSION num_rows; /* number of rows returned to caller */
  166896. if (upsample->spare_full) {
  166897. /* If we have a spare row saved from a previous cycle, just return it. */
  166898. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  166899. 1, upsample->out_row_width);
  166900. num_rows = 1;
  166901. upsample->spare_full = FALSE;
  166902. } else {
  166903. /* Figure number of rows to return to caller. */
  166904. num_rows = 2;
  166905. /* Not more than the distance to the end of the image. */
  166906. if (num_rows > upsample->rows_to_go)
  166907. num_rows = upsample->rows_to_go;
  166908. /* And not more than what the client can accept: */
  166909. out_rows_avail -= *out_row_ctr;
  166910. if (num_rows > out_rows_avail)
  166911. num_rows = out_rows_avail;
  166912. /* Create output pointer array for upsampler. */
  166913. work_ptrs[0] = output_buf[*out_row_ctr];
  166914. if (num_rows > 1) {
  166915. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  166916. } else {
  166917. work_ptrs[1] = upsample->spare_row;
  166918. upsample->spare_full = TRUE;
  166919. }
  166920. /* Now do the upsampling. */
  166921. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  166922. }
  166923. /* Adjust counts */
  166924. *out_row_ctr += num_rows;
  166925. upsample->rows_to_go -= num_rows;
  166926. /* When the buffer is emptied, declare this input row group consumed */
  166927. if (! upsample->spare_full)
  166928. (*in_row_group_ctr)++;
  166929. }
  166930. METHODDEF(void)
  166931. merged_1v_upsample (j_decompress_ptr cinfo,
  166932. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166933. JDIMENSION in_row_groups_avail,
  166934. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166935. JDIMENSION out_rows_avail)
  166936. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  166937. {
  166938. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166939. /* Just do the upsampling. */
  166940. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  166941. output_buf + *out_row_ctr);
  166942. /* Adjust counts */
  166943. (*out_row_ctr)++;
  166944. (*in_row_group_ctr)++;
  166945. }
  166946. /*
  166947. * These are the routines invoked by the control routines to do
  166948. * the actual upsampling/conversion. One row group is processed per call.
  166949. *
  166950. * Note: since we may be writing directly into application-supplied buffers,
  166951. * we have to be honest about the output width; we can't assume the buffer
  166952. * has been rounded up to an even width.
  166953. */
  166954. /*
  166955. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  166956. */
  166957. METHODDEF(void)
  166958. h2v1_merged_upsample (j_decompress_ptr cinfo,
  166959. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  166960. JSAMPARRAY output_buf)
  166961. {
  166962. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166963. register int y, cred, cgreen, cblue;
  166964. int cb, cr;
  166965. register JSAMPROW outptr;
  166966. JSAMPROW inptr0, inptr1, inptr2;
  166967. JDIMENSION col;
  166968. /* copy these pointers into registers if possible */
  166969. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  166970. int * Crrtab = upsample->Cr_r_tab;
  166971. int * Cbbtab = upsample->Cb_b_tab;
  166972. INT32 * Crgtab = upsample->Cr_g_tab;
  166973. INT32 * Cbgtab = upsample->Cb_g_tab;
  166974. SHIFT_TEMPS
  166975. inptr0 = input_buf[0][in_row_group_ctr];
  166976. inptr1 = input_buf[1][in_row_group_ctr];
  166977. inptr2 = input_buf[2][in_row_group_ctr];
  166978. outptr = output_buf[0];
  166979. /* Loop for each pair of output pixels */
  166980. for (col = cinfo->output_width >> 1; col > 0; col--) {
  166981. /* Do the chroma part of the calculation */
  166982. cb = GETJSAMPLE(*inptr1++);
  166983. cr = GETJSAMPLE(*inptr2++);
  166984. cred = Crrtab[cr];
  166985. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166986. cblue = Cbbtab[cb];
  166987. /* Fetch 2 Y values and emit 2 pixels */
  166988. y = GETJSAMPLE(*inptr0++);
  166989. outptr[RGB_RED] = range_limit[y + cred];
  166990. outptr[RGB_GREEN] = range_limit[y + cgreen];
  166991. outptr[RGB_BLUE] = range_limit[y + cblue];
  166992. outptr += RGB_PIXELSIZE;
  166993. y = GETJSAMPLE(*inptr0++);
  166994. outptr[RGB_RED] = range_limit[y + cred];
  166995. outptr[RGB_GREEN] = range_limit[y + cgreen];
  166996. outptr[RGB_BLUE] = range_limit[y + cblue];
  166997. outptr += RGB_PIXELSIZE;
  166998. }
  166999. /* If image width is odd, do the last output column separately */
  167000. if (cinfo->output_width & 1) {
  167001. cb = GETJSAMPLE(*inptr1);
  167002. cr = GETJSAMPLE(*inptr2);
  167003. cred = Crrtab[cr];
  167004. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  167005. cblue = Cbbtab[cb];
  167006. y = GETJSAMPLE(*inptr0);
  167007. outptr[RGB_RED] = range_limit[y + cred];
  167008. outptr[RGB_GREEN] = range_limit[y + cgreen];
  167009. outptr[RGB_BLUE] = range_limit[y + cblue];
  167010. }
  167011. }
  167012. /*
  167013. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  167014. */
  167015. METHODDEF(void)
  167016. h2v2_merged_upsample (j_decompress_ptr cinfo,
  167017. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  167018. JSAMPARRAY output_buf)
  167019. {
  167020. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  167021. register int y, cred, cgreen, cblue;
  167022. int cb, cr;
  167023. register JSAMPROW outptr0, outptr1;
  167024. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  167025. JDIMENSION col;
  167026. /* copy these pointers into registers if possible */
  167027. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  167028. int * Crrtab = upsample->Cr_r_tab;
  167029. int * Cbbtab = upsample->Cb_b_tab;
  167030. INT32 * Crgtab = upsample->Cr_g_tab;
  167031. INT32 * Cbgtab = upsample->Cb_g_tab;
  167032. SHIFT_TEMPS
  167033. inptr00 = input_buf[0][in_row_group_ctr*2];
  167034. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  167035. inptr1 = input_buf[1][in_row_group_ctr];
  167036. inptr2 = input_buf[2][in_row_group_ctr];
  167037. outptr0 = output_buf[0];
  167038. outptr1 = output_buf[1];
  167039. /* Loop for each group of output pixels */
  167040. for (col = cinfo->output_width >> 1; col > 0; col--) {
  167041. /* Do the chroma part of the calculation */
  167042. cb = GETJSAMPLE(*inptr1++);
  167043. cr = GETJSAMPLE(*inptr2++);
  167044. cred = Crrtab[cr];
  167045. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  167046. cblue = Cbbtab[cb];
  167047. /* Fetch 4 Y values and emit 4 pixels */
  167048. y = GETJSAMPLE(*inptr00++);
  167049. outptr0[RGB_RED] = range_limit[y + cred];
  167050. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  167051. outptr0[RGB_BLUE] = range_limit[y + cblue];
  167052. outptr0 += RGB_PIXELSIZE;
  167053. y = GETJSAMPLE(*inptr00++);
  167054. outptr0[RGB_RED] = range_limit[y + cred];
  167055. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  167056. outptr0[RGB_BLUE] = range_limit[y + cblue];
  167057. outptr0 += RGB_PIXELSIZE;
  167058. y = GETJSAMPLE(*inptr01++);
  167059. outptr1[RGB_RED] = range_limit[y + cred];
  167060. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  167061. outptr1[RGB_BLUE] = range_limit[y + cblue];
  167062. outptr1 += RGB_PIXELSIZE;
  167063. y = GETJSAMPLE(*inptr01++);
  167064. outptr1[RGB_RED] = range_limit[y + cred];
  167065. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  167066. outptr1[RGB_BLUE] = range_limit[y + cblue];
  167067. outptr1 += RGB_PIXELSIZE;
  167068. }
  167069. /* If image width is odd, do the last output column separately */
  167070. if (cinfo->output_width & 1) {
  167071. cb = GETJSAMPLE(*inptr1);
  167072. cr = GETJSAMPLE(*inptr2);
  167073. cred = Crrtab[cr];
  167074. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  167075. cblue = Cbbtab[cb];
  167076. y = GETJSAMPLE(*inptr00);
  167077. outptr0[RGB_RED] = range_limit[y + cred];
  167078. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  167079. outptr0[RGB_BLUE] = range_limit[y + cblue];
  167080. y = GETJSAMPLE(*inptr01);
  167081. outptr1[RGB_RED] = range_limit[y + cred];
  167082. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  167083. outptr1[RGB_BLUE] = range_limit[y + cblue];
  167084. }
  167085. }
  167086. /*
  167087. * Module initialization routine for merged upsampling/color conversion.
  167088. *
  167089. * NB: this is called under the conditions determined by use_merged_upsample()
  167090. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  167091. * of this module; no safety checks are made here.
  167092. */
  167093. GLOBAL(void)
  167094. jinit_merged_upsampler (j_decompress_ptr cinfo)
  167095. {
  167096. my_upsample_ptr upsample;
  167097. upsample = (my_upsample_ptr)
  167098. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167099. SIZEOF(my_upsampler));
  167100. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  167101. upsample->pub.start_pass = start_pass_merged_upsample;
  167102. upsample->pub.need_context_rows = FALSE;
  167103. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  167104. if (cinfo->max_v_samp_factor == 2) {
  167105. upsample->pub.upsample = merged_2v_upsample;
  167106. upsample->upmethod = h2v2_merged_upsample;
  167107. /* Allocate a spare row buffer */
  167108. upsample->spare_row = (JSAMPROW)
  167109. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167110. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  167111. } else {
  167112. upsample->pub.upsample = merged_1v_upsample;
  167113. upsample->upmethod = h2v1_merged_upsample;
  167114. /* No spare row needed */
  167115. upsample->spare_row = NULL;
  167116. }
  167117. build_ycc_rgb_table2(cinfo);
  167118. }
  167119. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  167120. /********* End of inlined file: jdmerge.c *********/
  167121. #undef ASSIGN_STATE
  167122. /********* Start of inlined file: jdphuff.c *********/
  167123. #define JPEG_INTERNALS
  167124. #ifdef D_PROGRESSIVE_SUPPORTED
  167125. /*
  167126. * Expanded entropy decoder object for progressive Huffman decoding.
  167127. *
  167128. * The savable_state subrecord contains fields that change within an MCU,
  167129. * but must not be updated permanently until we complete the MCU.
  167130. */
  167131. typedef struct {
  167132. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  167133. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  167134. } savable_state3;
  167135. /* This macro is to work around compilers with missing or broken
  167136. * structure assignment. You'll need to fix this code if you have
  167137. * such a compiler and you change MAX_COMPS_IN_SCAN.
  167138. */
  167139. #ifndef NO_STRUCT_ASSIGN
  167140. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  167141. #else
  167142. #if MAX_COMPS_IN_SCAN == 4
  167143. #define ASSIGN_STATE(dest,src) \
  167144. ((dest).EOBRUN = (src).EOBRUN, \
  167145. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  167146. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  167147. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  167148. (dest).last_dc_val[3] = (src).last_dc_val[3])
  167149. #endif
  167150. #endif
  167151. typedef struct {
  167152. struct jpeg_entropy_decoder pub; /* public fields */
  167153. /* These fields are loaded into local variables at start of each MCU.
  167154. * In case of suspension, we exit WITHOUT updating them.
  167155. */
  167156. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  167157. savable_state3 saved; /* Other state at start of MCU */
  167158. /* These fields are NOT loaded into local working state. */
  167159. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  167160. /* Pointers to derived tables (these workspaces have image lifespan) */
  167161. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  167162. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  167163. } phuff_entropy_decoder;
  167164. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  167165. /* Forward declarations */
  167166. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  167167. JBLOCKROW *MCU_data));
  167168. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  167169. JBLOCKROW *MCU_data));
  167170. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  167171. JBLOCKROW *MCU_data));
  167172. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  167173. JBLOCKROW *MCU_data));
  167174. /*
  167175. * Initialize for a Huffman-compressed scan.
  167176. */
  167177. METHODDEF(void)
  167178. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  167179. {
  167180. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167181. boolean is_DC_band, bad;
  167182. int ci, coefi, tbl;
  167183. int *coef_bit_ptr;
  167184. jpeg_component_info * compptr;
  167185. is_DC_band = (cinfo->Ss == 0);
  167186. /* Validate scan parameters */
  167187. bad = FALSE;
  167188. if (is_DC_band) {
  167189. if (cinfo->Se != 0)
  167190. bad = TRUE;
  167191. } else {
  167192. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  167193. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  167194. bad = TRUE;
  167195. /* AC scans may have only one component */
  167196. if (cinfo->comps_in_scan != 1)
  167197. bad = TRUE;
  167198. }
  167199. if (cinfo->Ah != 0) {
  167200. /* Successive approximation refinement scan: must have Al = Ah-1. */
  167201. if (cinfo->Al != cinfo->Ah-1)
  167202. bad = TRUE;
  167203. }
  167204. if (cinfo->Al > 13) /* need not check for < 0 */
  167205. bad = TRUE;
  167206. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  167207. * but the spec doesn't say so, and we try to be liberal about what we
  167208. * accept. Note: large Al values could result in out-of-range DC
  167209. * coefficients during early scans, leading to bizarre displays due to
  167210. * overflows in the IDCT math. But we won't crash.
  167211. */
  167212. if (bad)
  167213. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  167214. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  167215. /* Update progression status, and verify that scan order is legal.
  167216. * Note that inter-scan inconsistencies are treated as warnings
  167217. * not fatal errors ... not clear if this is right way to behave.
  167218. */
  167219. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167220. int cindex = cinfo->cur_comp_info[ci]->component_index;
  167221. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  167222. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  167223. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  167224. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  167225. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  167226. if (cinfo->Ah != expected)
  167227. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  167228. coef_bit_ptr[coefi] = cinfo->Al;
  167229. }
  167230. }
  167231. /* Select MCU decoding routine */
  167232. if (cinfo->Ah == 0) {
  167233. if (is_DC_band)
  167234. entropy->pub.decode_mcu = decode_mcu_DC_first;
  167235. else
  167236. entropy->pub.decode_mcu = decode_mcu_AC_first;
  167237. } else {
  167238. if (is_DC_band)
  167239. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  167240. else
  167241. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  167242. }
  167243. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167244. compptr = cinfo->cur_comp_info[ci];
  167245. /* Make sure requested tables are present, and compute derived tables.
  167246. * We may build same derived table more than once, but it's not expensive.
  167247. */
  167248. if (is_DC_band) {
  167249. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  167250. tbl = compptr->dc_tbl_no;
  167251. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  167252. & entropy->derived_tbls[tbl]);
  167253. }
  167254. } else {
  167255. tbl = compptr->ac_tbl_no;
  167256. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  167257. & entropy->derived_tbls[tbl]);
  167258. /* remember the single active table */
  167259. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  167260. }
  167261. /* Initialize DC predictions to 0 */
  167262. entropy->saved.last_dc_val[ci] = 0;
  167263. }
  167264. /* Initialize bitread state variables */
  167265. entropy->bitstate.bits_left = 0;
  167266. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  167267. entropy->pub.insufficient_data = FALSE;
  167268. /* Initialize private state variables */
  167269. entropy->saved.EOBRUN = 0;
  167270. /* Initialize restart counter */
  167271. entropy->restarts_to_go = cinfo->restart_interval;
  167272. }
  167273. /*
  167274. * Check for a restart marker & resynchronize decoder.
  167275. * Returns FALSE if must suspend.
  167276. */
  167277. LOCAL(boolean)
  167278. process_restartp (j_decompress_ptr cinfo)
  167279. {
  167280. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167281. int ci;
  167282. /* Throw away any unused bits remaining in bit buffer; */
  167283. /* include any full bytes in next_marker's count of discarded bytes */
  167284. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  167285. entropy->bitstate.bits_left = 0;
  167286. /* Advance past the RSTn marker */
  167287. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  167288. return FALSE;
  167289. /* Re-initialize DC predictions to 0 */
  167290. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  167291. entropy->saved.last_dc_val[ci] = 0;
  167292. /* Re-init EOB run count, too */
  167293. entropy->saved.EOBRUN = 0;
  167294. /* Reset restart counter */
  167295. entropy->restarts_to_go = cinfo->restart_interval;
  167296. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  167297. * against a marker. In that case we will end up treating the next data
  167298. * segment as empty, and we can avoid producing bogus output pixels by
  167299. * leaving the flag set.
  167300. */
  167301. if (cinfo->unread_marker == 0)
  167302. entropy->pub.insufficient_data = FALSE;
  167303. return TRUE;
  167304. }
  167305. /*
  167306. * Huffman MCU decoding.
  167307. * Each of these routines decodes and returns one MCU's worth of
  167308. * Huffman-compressed coefficients.
  167309. * The coefficients are reordered from zigzag order into natural array order,
  167310. * but are not dequantized.
  167311. *
  167312. * The i'th block of the MCU is stored into the block pointed to by
  167313. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  167314. *
  167315. * We return FALSE if data source requested suspension. In that case no
  167316. * changes have been made to permanent state. (Exception: some output
  167317. * coefficients may already have been assigned. This is harmless for
  167318. * spectral selection, since we'll just re-assign them on the next call.
  167319. * Successive approximation AC refinement has to be more careful, however.)
  167320. */
  167321. /*
  167322. * MCU decoding for DC initial scan (either spectral selection,
  167323. * or first pass of successive approximation).
  167324. */
  167325. METHODDEF(boolean)
  167326. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  167327. {
  167328. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167329. int Al = cinfo->Al;
  167330. register int s, r;
  167331. int blkn, ci;
  167332. JBLOCKROW block;
  167333. BITREAD_STATE_VARS;
  167334. savable_state3 state;
  167335. d_derived_tbl * tbl;
  167336. jpeg_component_info * compptr;
  167337. /* Process restart marker if needed; may have to suspend */
  167338. if (cinfo->restart_interval) {
  167339. if (entropy->restarts_to_go == 0)
  167340. if (! process_restartp(cinfo))
  167341. return FALSE;
  167342. }
  167343. /* If we've run out of data, just leave the MCU set to zeroes.
  167344. * This way, we return uniform gray for the remainder of the segment.
  167345. */
  167346. if (! entropy->pub.insufficient_data) {
  167347. /* Load up working state */
  167348. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  167349. ASSIGN_STATE(state, entropy->saved);
  167350. /* Outer loop handles each block in the MCU */
  167351. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  167352. block = MCU_data[blkn];
  167353. ci = cinfo->MCU_membership[blkn];
  167354. compptr = cinfo->cur_comp_info[ci];
  167355. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  167356. /* Decode a single block's worth of coefficients */
  167357. /* Section F.2.2.1: decode the DC coefficient difference */
  167358. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  167359. if (s) {
  167360. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  167361. r = GET_BITS(s);
  167362. s = HUFF_EXTEND(r, s);
  167363. }
  167364. /* Convert DC difference to actual value, update last_dc_val */
  167365. s += state.last_dc_val[ci];
  167366. state.last_dc_val[ci] = s;
  167367. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  167368. (*block)[0] = (JCOEF) (s << Al);
  167369. }
  167370. /* Completed MCU, so update state */
  167371. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  167372. ASSIGN_STATE(entropy->saved, state);
  167373. }
  167374. /* Account for restart interval (no-op if not using restarts) */
  167375. entropy->restarts_to_go--;
  167376. return TRUE;
  167377. }
  167378. /*
  167379. * MCU decoding for AC initial scan (either spectral selection,
  167380. * or first pass of successive approximation).
  167381. */
  167382. METHODDEF(boolean)
  167383. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  167384. {
  167385. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167386. int Se = cinfo->Se;
  167387. int Al = cinfo->Al;
  167388. register int s, k, r;
  167389. unsigned int EOBRUN;
  167390. JBLOCKROW block;
  167391. BITREAD_STATE_VARS;
  167392. d_derived_tbl * tbl;
  167393. /* Process restart marker if needed; may have to suspend */
  167394. if (cinfo->restart_interval) {
  167395. if (entropy->restarts_to_go == 0)
  167396. if (! process_restartp(cinfo))
  167397. return FALSE;
  167398. }
  167399. /* If we've run out of data, just leave the MCU set to zeroes.
  167400. * This way, we return uniform gray for the remainder of the segment.
  167401. */
  167402. if (! entropy->pub.insufficient_data) {
  167403. /* Load up working state.
  167404. * We can avoid loading/saving bitread state if in an EOB run.
  167405. */
  167406. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  167407. /* There is always only one block per MCU */
  167408. if (EOBRUN > 0) /* if it's a band of zeroes... */
  167409. EOBRUN--; /* ...process it now (we do nothing) */
  167410. else {
  167411. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  167412. block = MCU_data[0];
  167413. tbl = entropy->ac_derived_tbl;
  167414. for (k = cinfo->Ss; k <= Se; k++) {
  167415. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  167416. r = s >> 4;
  167417. s &= 15;
  167418. if (s) {
  167419. k += r;
  167420. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  167421. r = GET_BITS(s);
  167422. s = HUFF_EXTEND(r, s);
  167423. /* Scale and output coefficient in natural (dezigzagged) order */
  167424. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  167425. } else {
  167426. if (r == 15) { /* ZRL */
  167427. k += 15; /* skip 15 zeroes in band */
  167428. } else { /* EOBr, run length is 2^r + appended bits */
  167429. EOBRUN = 1 << r;
  167430. if (r) { /* EOBr, r > 0 */
  167431. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  167432. r = GET_BITS(r);
  167433. EOBRUN += r;
  167434. }
  167435. EOBRUN--; /* this band is processed at this moment */
  167436. break; /* force end-of-band */
  167437. }
  167438. }
  167439. }
  167440. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  167441. }
  167442. /* Completed MCU, so update state */
  167443. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  167444. }
  167445. /* Account for restart interval (no-op if not using restarts) */
  167446. entropy->restarts_to_go--;
  167447. return TRUE;
  167448. }
  167449. /*
  167450. * MCU decoding for DC successive approximation refinement scan.
  167451. * Note: we assume such scans can be multi-component, although the spec
  167452. * is not very clear on the point.
  167453. */
  167454. METHODDEF(boolean)
  167455. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  167456. {
  167457. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167458. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  167459. int blkn;
  167460. JBLOCKROW block;
  167461. BITREAD_STATE_VARS;
  167462. /* Process restart marker if needed; may have to suspend */
  167463. if (cinfo->restart_interval) {
  167464. if (entropy->restarts_to_go == 0)
  167465. if (! process_restartp(cinfo))
  167466. return FALSE;
  167467. }
  167468. /* Not worth the cycles to check insufficient_data here,
  167469. * since we will not change the data anyway if we read zeroes.
  167470. */
  167471. /* Load up working state */
  167472. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  167473. /* Outer loop handles each block in the MCU */
  167474. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  167475. block = MCU_data[blkn];
  167476. /* Encoded data is simply the next bit of the two's-complement DC value */
  167477. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  167478. if (GET_BITS(1))
  167479. (*block)[0] |= p1;
  167480. /* Note: since we use |=, repeating the assignment later is safe */
  167481. }
  167482. /* Completed MCU, so update state */
  167483. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  167484. /* Account for restart interval (no-op if not using restarts) */
  167485. entropy->restarts_to_go--;
  167486. return TRUE;
  167487. }
  167488. /*
  167489. * MCU decoding for AC successive approximation refinement scan.
  167490. */
  167491. METHODDEF(boolean)
  167492. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  167493. {
  167494. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  167495. int Se = cinfo->Se;
  167496. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  167497. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  167498. register int s, k, r;
  167499. unsigned int EOBRUN;
  167500. JBLOCKROW block;
  167501. JCOEFPTR thiscoef;
  167502. BITREAD_STATE_VARS;
  167503. d_derived_tbl * tbl;
  167504. int num_newnz;
  167505. int newnz_pos[DCTSIZE2];
  167506. /* Process restart marker if needed; may have to suspend */
  167507. if (cinfo->restart_interval) {
  167508. if (entropy->restarts_to_go == 0)
  167509. if (! process_restartp(cinfo))
  167510. return FALSE;
  167511. }
  167512. /* If we've run out of data, don't modify the MCU.
  167513. */
  167514. if (! entropy->pub.insufficient_data) {
  167515. /* Load up working state */
  167516. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  167517. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  167518. /* There is always only one block per MCU */
  167519. block = MCU_data[0];
  167520. tbl = entropy->ac_derived_tbl;
  167521. /* If we are forced to suspend, we must undo the assignments to any newly
  167522. * nonzero coefficients in the block, because otherwise we'd get confused
  167523. * next time about which coefficients were already nonzero.
  167524. * But we need not undo addition of bits to already-nonzero coefficients;
  167525. * instead, we can test the current bit to see if we already did it.
  167526. */
  167527. num_newnz = 0;
  167528. /* initialize coefficient loop counter to start of band */
  167529. k = cinfo->Ss;
  167530. if (EOBRUN == 0) {
  167531. for (; k <= Se; k++) {
  167532. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  167533. r = s >> 4;
  167534. s &= 15;
  167535. if (s) {
  167536. if (s != 1) /* size of new coef should always be 1 */
  167537. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  167538. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  167539. if (GET_BITS(1))
  167540. s = p1; /* newly nonzero coef is positive */
  167541. else
  167542. s = m1; /* newly nonzero coef is negative */
  167543. } else {
  167544. if (r != 15) {
  167545. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  167546. if (r) {
  167547. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  167548. r = GET_BITS(r);
  167549. EOBRUN += r;
  167550. }
  167551. break; /* rest of block is handled by EOB logic */
  167552. }
  167553. /* note s = 0 for processing ZRL */
  167554. }
  167555. /* Advance over already-nonzero coefs and r still-zero coefs,
  167556. * appending correction bits to the nonzeroes. A correction bit is 1
  167557. * if the absolute value of the coefficient must be increased.
  167558. */
  167559. do {
  167560. thiscoef = *block + jpeg_natural_order[k];
  167561. if (*thiscoef != 0) {
  167562. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  167563. if (GET_BITS(1)) {
  167564. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  167565. if (*thiscoef >= 0)
  167566. *thiscoef += p1;
  167567. else
  167568. *thiscoef += m1;
  167569. }
  167570. }
  167571. } else {
  167572. if (--r < 0)
  167573. break; /* reached target zero coefficient */
  167574. }
  167575. k++;
  167576. } while (k <= Se);
  167577. if (s) {
  167578. int pos = jpeg_natural_order[k];
  167579. /* Output newly nonzero coefficient */
  167580. (*block)[pos] = (JCOEF) s;
  167581. /* Remember its position in case we have to suspend */
  167582. newnz_pos[num_newnz++] = pos;
  167583. }
  167584. }
  167585. }
  167586. if (EOBRUN > 0) {
  167587. /* Scan any remaining coefficient positions after the end-of-band
  167588. * (the last newly nonzero coefficient, if any). Append a correction
  167589. * bit to each already-nonzero coefficient. A correction bit is 1
  167590. * if the absolute value of the coefficient must be increased.
  167591. */
  167592. for (; k <= Se; k++) {
  167593. thiscoef = *block + jpeg_natural_order[k];
  167594. if (*thiscoef != 0) {
  167595. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  167596. if (GET_BITS(1)) {
  167597. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  167598. if (*thiscoef >= 0)
  167599. *thiscoef += p1;
  167600. else
  167601. *thiscoef += m1;
  167602. }
  167603. }
  167604. }
  167605. }
  167606. /* Count one block completed in EOB run */
  167607. EOBRUN--;
  167608. }
  167609. /* Completed MCU, so update state */
  167610. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  167611. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  167612. }
  167613. /* Account for restart interval (no-op if not using restarts) */
  167614. entropy->restarts_to_go--;
  167615. return TRUE;
  167616. undoit:
  167617. /* Re-zero any output coefficients that we made newly nonzero */
  167618. while (num_newnz > 0)
  167619. (*block)[newnz_pos[--num_newnz]] = 0;
  167620. return FALSE;
  167621. }
  167622. /*
  167623. * Module initialization routine for progressive Huffman entropy decoding.
  167624. */
  167625. GLOBAL(void)
  167626. jinit_phuff_decoder (j_decompress_ptr cinfo)
  167627. {
  167628. phuff_entropy_ptr2 entropy;
  167629. int *coef_bit_ptr;
  167630. int ci, i;
  167631. entropy = (phuff_entropy_ptr2)
  167632. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167633. SIZEOF(phuff_entropy_decoder));
  167634. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  167635. entropy->pub.start_pass = start_pass_phuff_decoder;
  167636. /* Mark derived tables unallocated */
  167637. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167638. entropy->derived_tbls[i] = NULL;
  167639. }
  167640. /* Create progression status table */
  167641. cinfo->coef_bits = (int (*)[DCTSIZE2])
  167642. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167643. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  167644. coef_bit_ptr = & cinfo->coef_bits[0][0];
  167645. for (ci = 0; ci < cinfo->num_components; ci++)
  167646. for (i = 0; i < DCTSIZE2; i++)
  167647. *coef_bit_ptr++ = -1;
  167648. }
  167649. #endif /* D_PROGRESSIVE_SUPPORTED */
  167650. /********* End of inlined file: jdphuff.c *********/
  167651. /********* Start of inlined file: jdpostct.c *********/
  167652. #define JPEG_INTERNALS
  167653. /* Private buffer controller object */
  167654. typedef struct {
  167655. struct jpeg_d_post_controller pub; /* public fields */
  167656. /* Color quantization source buffer: this holds output data from
  167657. * the upsample/color conversion step to be passed to the quantizer.
  167658. * For two-pass color quantization, we need a full-image buffer;
  167659. * for one-pass operation, a strip buffer is sufficient.
  167660. */
  167661. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  167662. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  167663. JDIMENSION strip_height; /* buffer size in rows */
  167664. /* for two-pass mode only: */
  167665. JDIMENSION starting_row; /* row # of first row in current strip */
  167666. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  167667. } my_post_controller;
  167668. typedef my_post_controller * my_post_ptr;
  167669. /* Forward declarations */
  167670. METHODDEF(void) post_process_1pass
  167671. JPP((j_decompress_ptr cinfo,
  167672. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167673. JDIMENSION in_row_groups_avail,
  167674. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167675. JDIMENSION out_rows_avail));
  167676. #ifdef QUANT_2PASS_SUPPORTED
  167677. METHODDEF(void) post_process_prepass
  167678. JPP((j_decompress_ptr cinfo,
  167679. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167680. JDIMENSION in_row_groups_avail,
  167681. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167682. JDIMENSION out_rows_avail));
  167683. METHODDEF(void) post_process_2pass
  167684. JPP((j_decompress_ptr cinfo,
  167685. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167686. JDIMENSION in_row_groups_avail,
  167687. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167688. JDIMENSION out_rows_avail));
  167689. #endif
  167690. /*
  167691. * Initialize for a processing pass.
  167692. */
  167693. METHODDEF(void)
  167694. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  167695. {
  167696. my_post_ptr post = (my_post_ptr) cinfo->post;
  167697. switch (pass_mode) {
  167698. case JBUF_PASS_THRU:
  167699. if (cinfo->quantize_colors) {
  167700. /* Single-pass processing with color quantization. */
  167701. post->pub.post_process_data = post_process_1pass;
  167702. /* We could be doing buffered-image output before starting a 2-pass
  167703. * color quantization; in that case, jinit_d_post_controller did not
  167704. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  167705. */
  167706. if (post->buffer == NULL) {
  167707. post->buffer = (*cinfo->mem->access_virt_sarray)
  167708. ((j_common_ptr) cinfo, post->whole_image,
  167709. (JDIMENSION) 0, post->strip_height, TRUE);
  167710. }
  167711. } else {
  167712. /* For single-pass processing without color quantization,
  167713. * I have no work to do; just call the upsampler directly.
  167714. */
  167715. post->pub.post_process_data = cinfo->upsample->upsample;
  167716. }
  167717. break;
  167718. #ifdef QUANT_2PASS_SUPPORTED
  167719. case JBUF_SAVE_AND_PASS:
  167720. /* First pass of 2-pass quantization */
  167721. if (post->whole_image == NULL)
  167722. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167723. post->pub.post_process_data = post_process_prepass;
  167724. break;
  167725. case JBUF_CRANK_DEST:
  167726. /* Second pass of 2-pass quantization */
  167727. if (post->whole_image == NULL)
  167728. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167729. post->pub.post_process_data = post_process_2pass;
  167730. break;
  167731. #endif /* QUANT_2PASS_SUPPORTED */
  167732. default:
  167733. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167734. break;
  167735. }
  167736. post->starting_row = post->next_row = 0;
  167737. }
  167738. /*
  167739. * Process some data in the one-pass (strip buffer) case.
  167740. * This is used for color precision reduction as well as one-pass quantization.
  167741. */
  167742. METHODDEF(void)
  167743. post_process_1pass (j_decompress_ptr cinfo,
  167744. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167745. JDIMENSION in_row_groups_avail,
  167746. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167747. JDIMENSION out_rows_avail)
  167748. {
  167749. my_post_ptr post = (my_post_ptr) cinfo->post;
  167750. JDIMENSION num_rows, max_rows;
  167751. /* Fill the buffer, but not more than what we can dump out in one go. */
  167752. /* Note we rely on the upsampler to detect bottom of image. */
  167753. max_rows = out_rows_avail - *out_row_ctr;
  167754. if (max_rows > post->strip_height)
  167755. max_rows = post->strip_height;
  167756. num_rows = 0;
  167757. (*cinfo->upsample->upsample) (cinfo,
  167758. input_buf, in_row_group_ctr, in_row_groups_avail,
  167759. post->buffer, &num_rows, max_rows);
  167760. /* Quantize and emit data. */
  167761. (*cinfo->cquantize->color_quantize) (cinfo,
  167762. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  167763. *out_row_ctr += num_rows;
  167764. }
  167765. #ifdef QUANT_2PASS_SUPPORTED
  167766. /*
  167767. * Process some data in the first pass of 2-pass quantization.
  167768. */
  167769. METHODDEF(void)
  167770. post_process_prepass (j_decompress_ptr cinfo,
  167771. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167772. JDIMENSION in_row_groups_avail,
  167773. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167774. JDIMENSION out_rows_avail)
  167775. {
  167776. my_post_ptr post = (my_post_ptr) cinfo->post;
  167777. JDIMENSION old_next_row, num_rows;
  167778. /* Reposition virtual buffer if at start of strip. */
  167779. if (post->next_row == 0) {
  167780. post->buffer = (*cinfo->mem->access_virt_sarray)
  167781. ((j_common_ptr) cinfo, post->whole_image,
  167782. post->starting_row, post->strip_height, TRUE);
  167783. }
  167784. /* Upsample some data (up to a strip height's worth). */
  167785. old_next_row = post->next_row;
  167786. (*cinfo->upsample->upsample) (cinfo,
  167787. input_buf, in_row_group_ctr, in_row_groups_avail,
  167788. post->buffer, &post->next_row, post->strip_height);
  167789. /* Allow quantizer to scan new data. No data is emitted, */
  167790. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  167791. if (post->next_row > old_next_row) {
  167792. num_rows = post->next_row - old_next_row;
  167793. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  167794. (JSAMPARRAY) NULL, (int) num_rows);
  167795. *out_row_ctr += num_rows;
  167796. }
  167797. /* Advance if we filled the strip. */
  167798. if (post->next_row >= post->strip_height) {
  167799. post->starting_row += post->strip_height;
  167800. post->next_row = 0;
  167801. }
  167802. }
  167803. /*
  167804. * Process some data in the second pass of 2-pass quantization.
  167805. */
  167806. METHODDEF(void)
  167807. post_process_2pass (j_decompress_ptr cinfo,
  167808. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167809. JDIMENSION in_row_groups_avail,
  167810. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167811. JDIMENSION out_rows_avail)
  167812. {
  167813. my_post_ptr post = (my_post_ptr) cinfo->post;
  167814. JDIMENSION num_rows, max_rows;
  167815. /* Reposition virtual buffer if at start of strip. */
  167816. if (post->next_row == 0) {
  167817. post->buffer = (*cinfo->mem->access_virt_sarray)
  167818. ((j_common_ptr) cinfo, post->whole_image,
  167819. post->starting_row, post->strip_height, FALSE);
  167820. }
  167821. /* Determine number of rows to emit. */
  167822. num_rows = post->strip_height - post->next_row; /* available in strip */
  167823. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  167824. if (num_rows > max_rows)
  167825. num_rows = max_rows;
  167826. /* We have to check bottom of image here, can't depend on upsampler. */
  167827. max_rows = cinfo->output_height - post->starting_row;
  167828. if (num_rows > max_rows)
  167829. num_rows = max_rows;
  167830. /* Quantize and emit data. */
  167831. (*cinfo->cquantize->color_quantize) (cinfo,
  167832. post->buffer + post->next_row, output_buf + *out_row_ctr,
  167833. (int) num_rows);
  167834. *out_row_ctr += num_rows;
  167835. /* Advance if we filled the strip. */
  167836. post->next_row += num_rows;
  167837. if (post->next_row >= post->strip_height) {
  167838. post->starting_row += post->strip_height;
  167839. post->next_row = 0;
  167840. }
  167841. }
  167842. #endif /* QUANT_2PASS_SUPPORTED */
  167843. /*
  167844. * Initialize postprocessing controller.
  167845. */
  167846. GLOBAL(void)
  167847. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  167848. {
  167849. my_post_ptr post;
  167850. post = (my_post_ptr)
  167851. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167852. SIZEOF(my_post_controller));
  167853. cinfo->post = (struct jpeg_d_post_controller *) post;
  167854. post->pub.start_pass = start_pass_dpost;
  167855. post->whole_image = NULL; /* flag for no virtual arrays */
  167856. post->buffer = NULL; /* flag for no strip buffer */
  167857. /* Create the quantization buffer, if needed */
  167858. if (cinfo->quantize_colors) {
  167859. /* The buffer strip height is max_v_samp_factor, which is typically
  167860. * an efficient number of rows for upsampling to return.
  167861. * (In the presence of output rescaling, we might want to be smarter?)
  167862. */
  167863. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  167864. if (need_full_buffer) {
  167865. /* Two-pass color quantization: need full-image storage. */
  167866. /* We round up the number of rows to a multiple of the strip height. */
  167867. #ifdef QUANT_2PASS_SUPPORTED
  167868. post->whole_image = (*cinfo->mem->request_virt_sarray)
  167869. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  167870. cinfo->output_width * cinfo->out_color_components,
  167871. (JDIMENSION) jround_up((long) cinfo->output_height,
  167872. (long) post->strip_height),
  167873. post->strip_height);
  167874. #else
  167875. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167876. #endif /* QUANT_2PASS_SUPPORTED */
  167877. } else {
  167878. /* One-pass color quantization: just make a strip buffer. */
  167879. post->buffer = (*cinfo->mem->alloc_sarray)
  167880. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167881. cinfo->output_width * cinfo->out_color_components,
  167882. post->strip_height);
  167883. }
  167884. }
  167885. }
  167886. /********* End of inlined file: jdpostct.c *********/
  167887. #undef FIX
  167888. /********* Start of inlined file: jdsample.c *********/
  167889. #define JPEG_INTERNALS
  167890. /* Pointer to routine to upsample a single component */
  167891. typedef JMETHOD(void, upsample1_ptr,
  167892. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167893. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  167894. /* Private subobject */
  167895. typedef struct {
  167896. struct jpeg_upsampler pub; /* public fields */
  167897. /* Color conversion buffer. When using separate upsampling and color
  167898. * conversion steps, this buffer holds one upsampled row group until it
  167899. * has been color converted and output.
  167900. * Note: we do not allocate any storage for component(s) which are full-size,
  167901. * ie do not need rescaling. The corresponding entry of color_buf[] is
  167902. * simply set to point to the input data array, thereby avoiding copying.
  167903. */
  167904. JSAMPARRAY color_buf[MAX_COMPONENTS];
  167905. /* Per-component upsampling method pointers */
  167906. upsample1_ptr methods[MAX_COMPONENTS];
  167907. int next_row_out; /* counts rows emitted from color_buf */
  167908. JDIMENSION rows_to_go; /* counts rows remaining in image */
  167909. /* Height of an input row group for each component. */
  167910. int rowgroup_height[MAX_COMPONENTS];
  167911. /* These arrays save pixel expansion factors so that int_expand need not
  167912. * recompute them each time. They are unused for other upsampling methods.
  167913. */
  167914. UINT8 h_expand[MAX_COMPONENTS];
  167915. UINT8 v_expand[MAX_COMPONENTS];
  167916. } my_upsampler2;
  167917. typedef my_upsampler2 * my_upsample_ptr2;
  167918. /*
  167919. * Initialize for an upsampling pass.
  167920. */
  167921. METHODDEF(void)
  167922. start_pass_upsample (j_decompress_ptr cinfo)
  167923. {
  167924. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  167925. /* Mark the conversion buffer empty */
  167926. upsample->next_row_out = cinfo->max_v_samp_factor;
  167927. /* Initialize total-height counter for detecting bottom of image */
  167928. upsample->rows_to_go = cinfo->output_height;
  167929. }
  167930. /*
  167931. * Control routine to do upsampling (and color conversion).
  167932. *
  167933. * In this version we upsample each component independently.
  167934. * We upsample one row group into the conversion buffer, then apply
  167935. * color conversion a row at a time.
  167936. */
  167937. METHODDEF(void)
  167938. sep_upsample (j_decompress_ptr cinfo,
  167939. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167940. JDIMENSION in_row_groups_avail,
  167941. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167942. JDIMENSION out_rows_avail)
  167943. {
  167944. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  167945. int ci;
  167946. jpeg_component_info * compptr;
  167947. JDIMENSION num_rows;
  167948. /* Fill the conversion buffer, if it's empty */
  167949. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  167950. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167951. ci++, compptr++) {
  167952. /* Invoke per-component upsample method. Notice we pass a POINTER
  167953. * to color_buf[ci], so that fullsize_upsample can change it.
  167954. */
  167955. (*upsample->methods[ci]) (cinfo, compptr,
  167956. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  167957. upsample->color_buf + ci);
  167958. }
  167959. upsample->next_row_out = 0;
  167960. }
  167961. /* Color-convert and emit rows */
  167962. /* How many we have in the buffer: */
  167963. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  167964. /* Not more than the distance to the end of the image. Need this test
  167965. * in case the image height is not a multiple of max_v_samp_factor:
  167966. */
  167967. if (num_rows > upsample->rows_to_go)
  167968. num_rows = upsample->rows_to_go;
  167969. /* And not more than what the client can accept: */
  167970. out_rows_avail -= *out_row_ctr;
  167971. if (num_rows > out_rows_avail)
  167972. num_rows = out_rows_avail;
  167973. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  167974. (JDIMENSION) upsample->next_row_out,
  167975. output_buf + *out_row_ctr,
  167976. (int) num_rows);
  167977. /* Adjust counts */
  167978. *out_row_ctr += num_rows;
  167979. upsample->rows_to_go -= num_rows;
  167980. upsample->next_row_out += num_rows;
  167981. /* When the buffer is emptied, declare this input row group consumed */
  167982. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  167983. (*in_row_group_ctr)++;
  167984. }
  167985. /*
  167986. * These are the routines invoked by sep_upsample to upsample pixel values
  167987. * of a single component. One row group is processed per call.
  167988. */
  167989. /*
  167990. * For full-size components, we just make color_buf[ci] point at the
  167991. * input buffer, and thus avoid copying any data. Note that this is
  167992. * safe only because sep_upsample doesn't declare the input row group
  167993. * "consumed" until we are done color converting and emitting it.
  167994. */
  167995. METHODDEF(void)
  167996. fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167997. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167998. {
  167999. *output_data_ptr = input_data;
  168000. }
  168001. /*
  168002. * This is a no-op version used for "uninteresting" components.
  168003. * These components will not be referenced by color conversion.
  168004. */
  168005. METHODDEF(void)
  168006. noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168007. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168008. {
  168009. *output_data_ptr = NULL; /* safety check */
  168010. }
  168011. /*
  168012. * This version handles any integral sampling ratios.
  168013. * This is not used for typical JPEG files, so it need not be fast.
  168014. * Nor, for that matter, is it particularly accurate: the algorithm is
  168015. * simple replication of the input pixel onto the corresponding output
  168016. * pixels. The hi-falutin sampling literature refers to this as a
  168017. * "box filter". A box filter tends to introduce visible artifacts,
  168018. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  168019. * you would be well advised to improve this code.
  168020. */
  168021. METHODDEF(void)
  168022. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168023. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168024. {
  168025. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  168026. JSAMPARRAY output_data = *output_data_ptr;
  168027. register JSAMPROW inptr, outptr;
  168028. register JSAMPLE invalue;
  168029. register int h;
  168030. JSAMPROW outend;
  168031. int h_expand, v_expand;
  168032. int inrow, outrow;
  168033. h_expand = upsample->h_expand[compptr->component_index];
  168034. v_expand = upsample->v_expand[compptr->component_index];
  168035. inrow = outrow = 0;
  168036. while (outrow < cinfo->max_v_samp_factor) {
  168037. /* Generate one output row with proper horizontal expansion */
  168038. inptr = input_data[inrow];
  168039. outptr = output_data[outrow];
  168040. outend = outptr + cinfo->output_width;
  168041. while (outptr < outend) {
  168042. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  168043. for (h = h_expand; h > 0; h--) {
  168044. *outptr++ = invalue;
  168045. }
  168046. }
  168047. /* Generate any additional output rows by duplicating the first one */
  168048. if (v_expand > 1) {
  168049. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  168050. v_expand-1, cinfo->output_width);
  168051. }
  168052. inrow++;
  168053. outrow += v_expand;
  168054. }
  168055. }
  168056. /*
  168057. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  168058. * It's still a box filter.
  168059. */
  168060. METHODDEF(void)
  168061. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168062. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168063. {
  168064. JSAMPARRAY output_data = *output_data_ptr;
  168065. register JSAMPROW inptr, outptr;
  168066. register JSAMPLE invalue;
  168067. JSAMPROW outend;
  168068. int inrow;
  168069. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  168070. inptr = input_data[inrow];
  168071. outptr = output_data[inrow];
  168072. outend = outptr + cinfo->output_width;
  168073. while (outptr < outend) {
  168074. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  168075. *outptr++ = invalue;
  168076. *outptr++ = invalue;
  168077. }
  168078. }
  168079. }
  168080. /*
  168081. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  168082. * It's still a box filter.
  168083. */
  168084. METHODDEF(void)
  168085. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168086. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168087. {
  168088. JSAMPARRAY output_data = *output_data_ptr;
  168089. register JSAMPROW inptr, outptr;
  168090. register JSAMPLE invalue;
  168091. JSAMPROW outend;
  168092. int inrow, outrow;
  168093. inrow = outrow = 0;
  168094. while (outrow < cinfo->max_v_samp_factor) {
  168095. inptr = input_data[inrow];
  168096. outptr = output_data[outrow];
  168097. outend = outptr + cinfo->output_width;
  168098. while (outptr < outend) {
  168099. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  168100. *outptr++ = invalue;
  168101. *outptr++ = invalue;
  168102. }
  168103. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  168104. 1, cinfo->output_width);
  168105. inrow++;
  168106. outrow += 2;
  168107. }
  168108. }
  168109. /*
  168110. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  168111. *
  168112. * The upsampling algorithm is linear interpolation between pixel centers,
  168113. * also known as a "triangle filter". This is a good compromise between
  168114. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  168115. * of the way between input pixel centers.
  168116. *
  168117. * A note about the "bias" calculations: when rounding fractional values to
  168118. * integer, we do not want to always round 0.5 up to the next integer.
  168119. * If we did that, we'd introduce a noticeable bias towards larger values.
  168120. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  168121. * alternate pixel locations (a simple ordered dither pattern).
  168122. */
  168123. METHODDEF(void)
  168124. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168125. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168126. {
  168127. JSAMPARRAY output_data = *output_data_ptr;
  168128. register JSAMPROW inptr, outptr;
  168129. register int invalue;
  168130. register JDIMENSION colctr;
  168131. int inrow;
  168132. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  168133. inptr = input_data[inrow];
  168134. outptr = output_data[inrow];
  168135. /* Special case for first column */
  168136. invalue = GETJSAMPLE(*inptr++);
  168137. *outptr++ = (JSAMPLE) invalue;
  168138. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  168139. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  168140. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  168141. invalue = GETJSAMPLE(*inptr++) * 3;
  168142. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  168143. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  168144. }
  168145. /* Special case for last column */
  168146. invalue = GETJSAMPLE(*inptr);
  168147. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  168148. *outptr++ = (JSAMPLE) invalue;
  168149. }
  168150. }
  168151. /*
  168152. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  168153. * Again a triangle filter; see comments for h2v1 case, above.
  168154. *
  168155. * It is OK for us to reference the adjacent input rows because we demanded
  168156. * context from the main buffer controller (see initialization code).
  168157. */
  168158. METHODDEF(void)
  168159. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168160. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  168161. {
  168162. JSAMPARRAY output_data = *output_data_ptr;
  168163. register JSAMPROW inptr0, inptr1, outptr;
  168164. #if BITS_IN_JSAMPLE == 8
  168165. register int thiscolsum, lastcolsum, nextcolsum;
  168166. #else
  168167. register INT32 thiscolsum, lastcolsum, nextcolsum;
  168168. #endif
  168169. register JDIMENSION colctr;
  168170. int inrow, outrow, v;
  168171. inrow = outrow = 0;
  168172. while (outrow < cinfo->max_v_samp_factor) {
  168173. for (v = 0; v < 2; v++) {
  168174. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  168175. inptr0 = input_data[inrow];
  168176. if (v == 0) /* next nearest is row above */
  168177. inptr1 = input_data[inrow-1];
  168178. else /* next nearest is row below */
  168179. inptr1 = input_data[inrow+1];
  168180. outptr = output_data[outrow++];
  168181. /* Special case for first column */
  168182. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  168183. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  168184. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  168185. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  168186. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  168187. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  168188. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  168189. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  168190. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  168191. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  168192. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  168193. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  168194. }
  168195. /* Special case for last column */
  168196. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  168197. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  168198. }
  168199. inrow++;
  168200. }
  168201. }
  168202. /*
  168203. * Module initialization routine for upsampling.
  168204. */
  168205. GLOBAL(void)
  168206. jinit_upsampler (j_decompress_ptr cinfo)
  168207. {
  168208. my_upsample_ptr2 upsample;
  168209. int ci;
  168210. jpeg_component_info * compptr;
  168211. boolean need_buffer, do_fancy;
  168212. int h_in_group, v_in_group, h_out_group, v_out_group;
  168213. upsample = (my_upsample_ptr2)
  168214. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168215. SIZEOF(my_upsampler2));
  168216. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  168217. upsample->pub.start_pass = start_pass_upsample;
  168218. upsample->pub.upsample = sep_upsample;
  168219. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  168220. if (cinfo->CCIR601_sampling) /* this isn't supported */
  168221. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  168222. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  168223. * so don't ask for it.
  168224. */
  168225. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  168226. /* Verify we can handle the sampling factors, select per-component methods,
  168227. * and create storage as needed.
  168228. */
  168229. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168230. ci++, compptr++) {
  168231. /* Compute size of an "input group" after IDCT scaling. This many samples
  168232. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  168233. */
  168234. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  168235. cinfo->min_DCT_scaled_size;
  168236. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  168237. cinfo->min_DCT_scaled_size;
  168238. h_out_group = cinfo->max_h_samp_factor;
  168239. v_out_group = cinfo->max_v_samp_factor;
  168240. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  168241. need_buffer = TRUE;
  168242. if (! compptr->component_needed) {
  168243. /* Don't bother to upsample an uninteresting component. */
  168244. upsample->methods[ci] = noop_upsample;
  168245. need_buffer = FALSE;
  168246. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  168247. /* Fullsize components can be processed without any work. */
  168248. upsample->methods[ci] = fullsize_upsample;
  168249. need_buffer = FALSE;
  168250. } else if (h_in_group * 2 == h_out_group &&
  168251. v_in_group == v_out_group) {
  168252. /* Special cases for 2h1v upsampling */
  168253. if (do_fancy && compptr->downsampled_width > 2)
  168254. upsample->methods[ci] = h2v1_fancy_upsample;
  168255. else
  168256. upsample->methods[ci] = h2v1_upsample;
  168257. } else if (h_in_group * 2 == h_out_group &&
  168258. v_in_group * 2 == v_out_group) {
  168259. /* Special cases for 2h2v upsampling */
  168260. if (do_fancy && compptr->downsampled_width > 2) {
  168261. upsample->methods[ci] = h2v2_fancy_upsample;
  168262. upsample->pub.need_context_rows = TRUE;
  168263. } else
  168264. upsample->methods[ci] = h2v2_upsample;
  168265. } else if ((h_out_group % h_in_group) == 0 &&
  168266. (v_out_group % v_in_group) == 0) {
  168267. /* Generic integral-factors upsampling method */
  168268. upsample->methods[ci] = int_upsample;
  168269. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  168270. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  168271. } else
  168272. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  168273. if (need_buffer) {
  168274. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  168275. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168276. (JDIMENSION) jround_up((long) cinfo->output_width,
  168277. (long) cinfo->max_h_samp_factor),
  168278. (JDIMENSION) cinfo->max_v_samp_factor);
  168279. }
  168280. }
  168281. }
  168282. /********* End of inlined file: jdsample.c *********/
  168283. /********* Start of inlined file: jdtrans.c *********/
  168284. #define JPEG_INTERNALS
  168285. /* Forward declarations */
  168286. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  168287. /*
  168288. * Read the coefficient arrays from a JPEG file.
  168289. * jpeg_read_header must be completed before calling this.
  168290. *
  168291. * The entire image is read into a set of virtual coefficient-block arrays,
  168292. * one per component. The return value is a pointer to the array of
  168293. * virtual-array descriptors. These can be manipulated directly via the
  168294. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  168295. * To release the memory occupied by the virtual arrays, call
  168296. * jpeg_finish_decompress() when done with the data.
  168297. *
  168298. * An alternative usage is to simply obtain access to the coefficient arrays
  168299. * during a buffered-image-mode decompression operation. This is allowed
  168300. * after any jpeg_finish_output() call. The arrays can be accessed until
  168301. * jpeg_finish_decompress() is called. (Note that any call to the library
  168302. * may reposition the arrays, so don't rely on access_virt_barray() results
  168303. * to stay valid across library calls.)
  168304. *
  168305. * Returns NULL if suspended. This case need be checked only if
  168306. * a suspending data source is used.
  168307. */
  168308. GLOBAL(jvirt_barray_ptr *)
  168309. jpeg_read_coefficients (j_decompress_ptr cinfo)
  168310. {
  168311. if (cinfo->global_state == DSTATE_READY) {
  168312. /* First call: initialize active modules */
  168313. transdecode_master_selection(cinfo);
  168314. cinfo->global_state = DSTATE_RDCOEFS;
  168315. }
  168316. if (cinfo->global_state == DSTATE_RDCOEFS) {
  168317. /* Absorb whole file into the coef buffer */
  168318. for (;;) {
  168319. int retcode;
  168320. /* Call progress monitor hook if present */
  168321. if (cinfo->progress != NULL)
  168322. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  168323. /* Absorb some more input */
  168324. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168325. if (retcode == JPEG_SUSPENDED)
  168326. return NULL;
  168327. if (retcode == JPEG_REACHED_EOI)
  168328. break;
  168329. /* Advance progress counter if appropriate */
  168330. if (cinfo->progress != NULL &&
  168331. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  168332. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  168333. /* startup underestimated number of scans; ratchet up one scan */
  168334. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  168335. }
  168336. }
  168337. }
  168338. /* Set state so that jpeg_finish_decompress does the right thing */
  168339. cinfo->global_state = DSTATE_STOPPING;
  168340. }
  168341. /* At this point we should be in state DSTATE_STOPPING if being used
  168342. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  168343. * to the coefficients during a full buffered-image-mode decompression.
  168344. */
  168345. if ((cinfo->global_state == DSTATE_STOPPING ||
  168346. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  168347. return cinfo->coef->coef_arrays;
  168348. }
  168349. /* Oops, improper usage */
  168350. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168351. return NULL; /* keep compiler happy */
  168352. }
  168353. /*
  168354. * Master selection of decompression modules for transcoding.
  168355. * This substitutes for jdmaster.c's initialization of the full decompressor.
  168356. */
  168357. LOCAL(void)
  168358. transdecode_master_selection (j_decompress_ptr cinfo)
  168359. {
  168360. /* This is effectively a buffered-image operation. */
  168361. cinfo->buffered_image = TRUE;
  168362. /* Entropy decoding: either Huffman or arithmetic coding. */
  168363. if (cinfo->arith_code) {
  168364. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  168365. } else {
  168366. if (cinfo->progressive_mode) {
  168367. #ifdef D_PROGRESSIVE_SUPPORTED
  168368. jinit_phuff_decoder(cinfo);
  168369. #else
  168370. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168371. #endif
  168372. } else
  168373. jinit_huff_decoder(cinfo);
  168374. }
  168375. /* Always get a full-image coefficient buffer. */
  168376. jinit_d_coef_controller(cinfo, TRUE);
  168377. /* We can now tell the memory manager to allocate virtual arrays. */
  168378. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  168379. /* Initialize input side of decompressor to consume first scan. */
  168380. (*cinfo->inputctl->start_input_pass) (cinfo);
  168381. /* Initialize progress monitoring. */
  168382. if (cinfo->progress != NULL) {
  168383. int nscans;
  168384. /* Estimate number of scans to set pass_limit. */
  168385. if (cinfo->progressive_mode) {
  168386. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  168387. nscans = 2 + 3 * cinfo->num_components;
  168388. } else if (cinfo->inputctl->has_multiple_scans) {
  168389. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  168390. nscans = cinfo->num_components;
  168391. } else {
  168392. nscans = 1;
  168393. }
  168394. cinfo->progress->pass_counter = 0L;
  168395. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  168396. cinfo->progress->completed_passes = 0;
  168397. cinfo->progress->total_passes = 1;
  168398. }
  168399. }
  168400. /********* End of inlined file: jdtrans.c *********/
  168401. /********* Start of inlined file: jfdctflt.c *********/
  168402. #define JPEG_INTERNALS
  168403. #ifdef DCT_FLOAT_SUPPORTED
  168404. /*
  168405. * This module is specialized to the case DCTSIZE = 8.
  168406. */
  168407. #if DCTSIZE != 8
  168408. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168409. #endif
  168410. /*
  168411. * Perform the forward DCT on one block of samples.
  168412. */
  168413. GLOBAL(void)
  168414. jpeg_fdct_float (FAST_FLOAT * data)
  168415. {
  168416. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  168417. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  168418. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  168419. FAST_FLOAT *dataptr;
  168420. int ctr;
  168421. /* Pass 1: process rows. */
  168422. dataptr = data;
  168423. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168424. tmp0 = dataptr[0] + dataptr[7];
  168425. tmp7 = dataptr[0] - dataptr[7];
  168426. tmp1 = dataptr[1] + dataptr[6];
  168427. tmp6 = dataptr[1] - dataptr[6];
  168428. tmp2 = dataptr[2] + dataptr[5];
  168429. tmp5 = dataptr[2] - dataptr[5];
  168430. tmp3 = dataptr[3] + dataptr[4];
  168431. tmp4 = dataptr[3] - dataptr[4];
  168432. /* Even part */
  168433. tmp10 = tmp0 + tmp3; /* phase 2 */
  168434. tmp13 = tmp0 - tmp3;
  168435. tmp11 = tmp1 + tmp2;
  168436. tmp12 = tmp1 - tmp2;
  168437. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  168438. dataptr[4] = tmp10 - tmp11;
  168439. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  168440. dataptr[2] = tmp13 + z1; /* phase 5 */
  168441. dataptr[6] = tmp13 - z1;
  168442. /* Odd part */
  168443. tmp10 = tmp4 + tmp5; /* phase 2 */
  168444. tmp11 = tmp5 + tmp6;
  168445. tmp12 = tmp6 + tmp7;
  168446. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  168447. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  168448. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  168449. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  168450. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  168451. z11 = tmp7 + z3; /* phase 5 */
  168452. z13 = tmp7 - z3;
  168453. dataptr[5] = z13 + z2; /* phase 6 */
  168454. dataptr[3] = z13 - z2;
  168455. dataptr[1] = z11 + z4;
  168456. dataptr[7] = z11 - z4;
  168457. dataptr += DCTSIZE; /* advance pointer to next row */
  168458. }
  168459. /* Pass 2: process columns. */
  168460. dataptr = data;
  168461. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168462. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  168463. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  168464. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  168465. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  168466. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  168467. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  168468. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  168469. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  168470. /* Even part */
  168471. tmp10 = tmp0 + tmp3; /* phase 2 */
  168472. tmp13 = tmp0 - tmp3;
  168473. tmp11 = tmp1 + tmp2;
  168474. tmp12 = tmp1 - tmp2;
  168475. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  168476. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  168477. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  168478. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  168479. dataptr[DCTSIZE*6] = tmp13 - z1;
  168480. /* Odd part */
  168481. tmp10 = tmp4 + tmp5; /* phase 2 */
  168482. tmp11 = tmp5 + tmp6;
  168483. tmp12 = tmp6 + tmp7;
  168484. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  168485. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  168486. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  168487. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  168488. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  168489. z11 = tmp7 + z3; /* phase 5 */
  168490. z13 = tmp7 - z3;
  168491. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  168492. dataptr[DCTSIZE*3] = z13 - z2;
  168493. dataptr[DCTSIZE*1] = z11 + z4;
  168494. dataptr[DCTSIZE*7] = z11 - z4;
  168495. dataptr++; /* advance pointer to next column */
  168496. }
  168497. }
  168498. #endif /* DCT_FLOAT_SUPPORTED */
  168499. /********* End of inlined file: jfdctflt.c *********/
  168500. /********* Start of inlined file: jfdctint.c *********/
  168501. #define JPEG_INTERNALS
  168502. #ifdef DCT_ISLOW_SUPPORTED
  168503. /*
  168504. * This module is specialized to the case DCTSIZE = 8.
  168505. */
  168506. #if DCTSIZE != 8
  168507. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168508. #endif
  168509. /*
  168510. * The poop on this scaling stuff is as follows:
  168511. *
  168512. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  168513. * larger than the true DCT outputs. The final outputs are therefore
  168514. * a factor of N larger than desired; since N=8 this can be cured by
  168515. * a simple right shift at the end of the algorithm. The advantage of
  168516. * this arrangement is that we save two multiplications per 1-D DCT,
  168517. * because the y0 and y4 outputs need not be divided by sqrt(N).
  168518. * In the IJG code, this factor of 8 is removed by the quantization step
  168519. * (in jcdctmgr.c), NOT in this module.
  168520. *
  168521. * We have to do addition and subtraction of the integer inputs, which
  168522. * is no problem, and multiplication by fractional constants, which is
  168523. * a problem to do in integer arithmetic. We multiply all the constants
  168524. * by CONST_SCALE and convert them to integer constants (thus retaining
  168525. * CONST_BITS bits of precision in the constants). After doing a
  168526. * multiplication we have to divide the product by CONST_SCALE, with proper
  168527. * rounding, to produce the correct output. This division can be done
  168528. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  168529. * as long as possible so that partial sums can be added together with
  168530. * full fractional precision.
  168531. *
  168532. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  168533. * they are represented to better-than-integral precision. These outputs
  168534. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  168535. * with the recommended scaling. (For 12-bit sample data, the intermediate
  168536. * array is INT32 anyway.)
  168537. *
  168538. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  168539. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  168540. * shows that the values given below are the most effective.
  168541. */
  168542. #if BITS_IN_JSAMPLE == 8
  168543. #define CONST_BITS 13
  168544. #define PASS1_BITS 2
  168545. #else
  168546. #define CONST_BITS 13
  168547. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  168548. #endif
  168549. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  168550. * causing a lot of useless floating-point operations at run time.
  168551. * To get around this we use the following pre-calculated constants.
  168552. * If you change CONST_BITS you may want to add appropriate values.
  168553. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  168554. */
  168555. #if CONST_BITS == 13
  168556. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  168557. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  168558. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  168559. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  168560. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  168561. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  168562. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  168563. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  168564. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  168565. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  168566. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  168567. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  168568. #else
  168569. #define FIX_0_298631336 FIX(0.298631336)
  168570. #define FIX_0_390180644 FIX(0.390180644)
  168571. #define FIX_0_541196100 FIX(0.541196100)
  168572. #define FIX_0_765366865 FIX(0.765366865)
  168573. #define FIX_0_899976223 FIX(0.899976223)
  168574. #define FIX_1_175875602 FIX(1.175875602)
  168575. #define FIX_1_501321110 FIX(1.501321110)
  168576. #define FIX_1_847759065 FIX(1.847759065)
  168577. #define FIX_1_961570560 FIX(1.961570560)
  168578. #define FIX_2_053119869 FIX(2.053119869)
  168579. #define FIX_2_562915447 FIX(2.562915447)
  168580. #define FIX_3_072711026 FIX(3.072711026)
  168581. #endif
  168582. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  168583. * For 8-bit samples with the recommended scaling, all the variable
  168584. * and constant values involved are no more than 16 bits wide, so a
  168585. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  168586. * For 12-bit samples, a full 32-bit multiplication will be needed.
  168587. */
  168588. #if BITS_IN_JSAMPLE == 8
  168589. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  168590. #else
  168591. #define MULTIPLY(var,const) ((var) * (const))
  168592. #endif
  168593. /*
  168594. * Perform the forward DCT on one block of samples.
  168595. */
  168596. GLOBAL(void)
  168597. jpeg_fdct_islow (DCTELEM * data)
  168598. {
  168599. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  168600. INT32 tmp10, tmp11, tmp12, tmp13;
  168601. INT32 z1, z2, z3, z4, z5;
  168602. DCTELEM *dataptr;
  168603. int ctr;
  168604. SHIFT_TEMPS
  168605. /* Pass 1: process rows. */
  168606. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  168607. /* furthermore, we scale the results by 2**PASS1_BITS. */
  168608. dataptr = data;
  168609. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168610. tmp0 = dataptr[0] + dataptr[7];
  168611. tmp7 = dataptr[0] - dataptr[7];
  168612. tmp1 = dataptr[1] + dataptr[6];
  168613. tmp6 = dataptr[1] - dataptr[6];
  168614. tmp2 = dataptr[2] + dataptr[5];
  168615. tmp5 = dataptr[2] - dataptr[5];
  168616. tmp3 = dataptr[3] + dataptr[4];
  168617. tmp4 = dataptr[3] - dataptr[4];
  168618. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  168619. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  168620. */
  168621. tmp10 = tmp0 + tmp3;
  168622. tmp13 = tmp0 - tmp3;
  168623. tmp11 = tmp1 + tmp2;
  168624. tmp12 = tmp1 - tmp2;
  168625. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  168626. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  168627. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  168628. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  168629. CONST_BITS-PASS1_BITS);
  168630. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  168631. CONST_BITS-PASS1_BITS);
  168632. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  168633. * cK represents cos(K*pi/16).
  168634. * i0..i3 in the paper are tmp4..tmp7 here.
  168635. */
  168636. z1 = tmp4 + tmp7;
  168637. z2 = tmp5 + tmp6;
  168638. z3 = tmp4 + tmp6;
  168639. z4 = tmp5 + tmp7;
  168640. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  168641. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  168642. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  168643. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  168644. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  168645. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  168646. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  168647. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  168648. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  168649. z3 += z5;
  168650. z4 += z5;
  168651. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  168652. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  168653. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  168654. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  168655. dataptr += DCTSIZE; /* advance pointer to next row */
  168656. }
  168657. /* Pass 2: process columns.
  168658. * We remove the PASS1_BITS scaling, but leave the results scaled up
  168659. * by an overall factor of 8.
  168660. */
  168661. dataptr = data;
  168662. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168663. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  168664. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  168665. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  168666. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  168667. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  168668. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  168669. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  168670. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  168671. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  168672. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  168673. */
  168674. tmp10 = tmp0 + tmp3;
  168675. tmp13 = tmp0 - tmp3;
  168676. tmp11 = tmp1 + tmp2;
  168677. tmp12 = tmp1 - tmp2;
  168678. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  168679. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  168680. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  168681. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  168682. CONST_BITS+PASS1_BITS);
  168683. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  168684. CONST_BITS+PASS1_BITS);
  168685. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  168686. * cK represents cos(K*pi/16).
  168687. * i0..i3 in the paper are tmp4..tmp7 here.
  168688. */
  168689. z1 = tmp4 + tmp7;
  168690. z2 = tmp5 + tmp6;
  168691. z3 = tmp4 + tmp6;
  168692. z4 = tmp5 + tmp7;
  168693. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  168694. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  168695. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  168696. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  168697. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  168698. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  168699. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  168700. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  168701. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  168702. z3 += z5;
  168703. z4 += z5;
  168704. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  168705. CONST_BITS+PASS1_BITS);
  168706. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  168707. CONST_BITS+PASS1_BITS);
  168708. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  168709. CONST_BITS+PASS1_BITS);
  168710. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  168711. CONST_BITS+PASS1_BITS);
  168712. dataptr++; /* advance pointer to next column */
  168713. }
  168714. }
  168715. #endif /* DCT_ISLOW_SUPPORTED */
  168716. /********* End of inlined file: jfdctint.c *********/
  168717. #undef CONST_BITS
  168718. #undef MULTIPLY
  168719. #undef FIX_0_541196100
  168720. /********* Start of inlined file: jfdctfst.c *********/
  168721. #define JPEG_INTERNALS
  168722. #ifdef DCT_IFAST_SUPPORTED
  168723. /*
  168724. * This module is specialized to the case DCTSIZE = 8.
  168725. */
  168726. #if DCTSIZE != 8
  168727. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168728. #endif
  168729. /* Scaling decisions are generally the same as in the LL&M algorithm;
  168730. * see jfdctint.c for more details. However, we choose to descale
  168731. * (right shift) multiplication products as soon as they are formed,
  168732. * rather than carrying additional fractional bits into subsequent additions.
  168733. * This compromises accuracy slightly, but it lets us save a few shifts.
  168734. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  168735. * everywhere except in the multiplications proper; this saves a good deal
  168736. * of work on 16-bit-int machines.
  168737. *
  168738. * Again to save a few shifts, the intermediate results between pass 1 and
  168739. * pass 2 are not upscaled, but are represented only to integral precision.
  168740. *
  168741. * A final compromise is to represent the multiplicative constants to only
  168742. * 8 fractional bits, rather than 13. This saves some shifting work on some
  168743. * machines, and may also reduce the cost of multiplication (since there
  168744. * are fewer one-bits in the constants).
  168745. */
  168746. #define CONST_BITS 8
  168747. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  168748. * causing a lot of useless floating-point operations at run time.
  168749. * To get around this we use the following pre-calculated constants.
  168750. * If you change CONST_BITS you may want to add appropriate values.
  168751. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  168752. */
  168753. #if CONST_BITS == 8
  168754. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  168755. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  168756. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  168757. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  168758. #else
  168759. #define FIX_0_382683433 FIX(0.382683433)
  168760. #define FIX_0_541196100 FIX(0.541196100)
  168761. #define FIX_0_707106781 FIX(0.707106781)
  168762. #define FIX_1_306562965 FIX(1.306562965)
  168763. #endif
  168764. /* We can gain a little more speed, with a further compromise in accuracy,
  168765. * by omitting the addition in a descaling shift. This yields an incorrectly
  168766. * rounded result half the time...
  168767. */
  168768. #ifndef USE_ACCURATE_ROUNDING
  168769. #undef DESCALE
  168770. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  168771. #endif
  168772. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  168773. * descale to yield a DCTELEM result.
  168774. */
  168775. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  168776. /*
  168777. * Perform the forward DCT on one block of samples.
  168778. */
  168779. GLOBAL(void)
  168780. jpeg_fdct_ifast (DCTELEM * data)
  168781. {
  168782. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  168783. DCTELEM tmp10, tmp11, tmp12, tmp13;
  168784. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  168785. DCTELEM *dataptr;
  168786. int ctr;
  168787. SHIFT_TEMPS
  168788. /* Pass 1: process rows. */
  168789. dataptr = data;
  168790. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168791. tmp0 = dataptr[0] + dataptr[7];
  168792. tmp7 = dataptr[0] - dataptr[7];
  168793. tmp1 = dataptr[1] + dataptr[6];
  168794. tmp6 = dataptr[1] - dataptr[6];
  168795. tmp2 = dataptr[2] + dataptr[5];
  168796. tmp5 = dataptr[2] - dataptr[5];
  168797. tmp3 = dataptr[3] + dataptr[4];
  168798. tmp4 = dataptr[3] - dataptr[4];
  168799. /* Even part */
  168800. tmp10 = tmp0 + tmp3; /* phase 2 */
  168801. tmp13 = tmp0 - tmp3;
  168802. tmp11 = tmp1 + tmp2;
  168803. tmp12 = tmp1 - tmp2;
  168804. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  168805. dataptr[4] = tmp10 - tmp11;
  168806. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  168807. dataptr[2] = tmp13 + z1; /* phase 5 */
  168808. dataptr[6] = tmp13 - z1;
  168809. /* Odd part */
  168810. tmp10 = tmp4 + tmp5; /* phase 2 */
  168811. tmp11 = tmp5 + tmp6;
  168812. tmp12 = tmp6 + tmp7;
  168813. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  168814. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  168815. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  168816. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  168817. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  168818. z11 = tmp7 + z3; /* phase 5 */
  168819. z13 = tmp7 - z3;
  168820. dataptr[5] = z13 + z2; /* phase 6 */
  168821. dataptr[3] = z13 - z2;
  168822. dataptr[1] = z11 + z4;
  168823. dataptr[7] = z11 - z4;
  168824. dataptr += DCTSIZE; /* advance pointer to next row */
  168825. }
  168826. /* Pass 2: process columns. */
  168827. dataptr = data;
  168828. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168829. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  168830. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  168831. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  168832. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  168833. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  168834. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  168835. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  168836. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  168837. /* Even part */
  168838. tmp10 = tmp0 + tmp3; /* phase 2 */
  168839. tmp13 = tmp0 - tmp3;
  168840. tmp11 = tmp1 + tmp2;
  168841. tmp12 = tmp1 - tmp2;
  168842. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  168843. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  168844. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  168845. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  168846. dataptr[DCTSIZE*6] = tmp13 - z1;
  168847. /* Odd part */
  168848. tmp10 = tmp4 + tmp5; /* phase 2 */
  168849. tmp11 = tmp5 + tmp6;
  168850. tmp12 = tmp6 + tmp7;
  168851. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  168852. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  168853. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  168854. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  168855. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  168856. z11 = tmp7 + z3; /* phase 5 */
  168857. z13 = tmp7 - z3;
  168858. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  168859. dataptr[DCTSIZE*3] = z13 - z2;
  168860. dataptr[DCTSIZE*1] = z11 + z4;
  168861. dataptr[DCTSIZE*7] = z11 - z4;
  168862. dataptr++; /* advance pointer to next column */
  168863. }
  168864. }
  168865. #endif /* DCT_IFAST_SUPPORTED */
  168866. /********* End of inlined file: jfdctfst.c *********/
  168867. #undef FIX_0_541196100
  168868. /********* Start of inlined file: jidctflt.c *********/
  168869. #define JPEG_INTERNALS
  168870. #ifdef DCT_FLOAT_SUPPORTED
  168871. /*
  168872. * This module is specialized to the case DCTSIZE = 8.
  168873. */
  168874. #if DCTSIZE != 8
  168875. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168876. #endif
  168877. /* Dequantize a coefficient by multiplying it by the multiplier-table
  168878. * entry; produce a float result.
  168879. */
  168880. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  168881. /*
  168882. * Perform dequantization and inverse DCT on one block of coefficients.
  168883. */
  168884. GLOBAL(void)
  168885. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168886. JCOEFPTR coef_block,
  168887. JSAMPARRAY output_buf, JDIMENSION output_col)
  168888. {
  168889. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  168890. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  168891. FAST_FLOAT z5, z10, z11, z12, z13;
  168892. JCOEFPTR inptr;
  168893. FLOAT_MULT_TYPE * quantptr;
  168894. FAST_FLOAT * wsptr;
  168895. JSAMPROW outptr;
  168896. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  168897. int ctr;
  168898. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  168899. SHIFT_TEMPS
  168900. /* Pass 1: process columns from input, store into work array. */
  168901. inptr = coef_block;
  168902. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  168903. wsptr = workspace;
  168904. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  168905. /* Due to quantization, we will usually find that many of the input
  168906. * coefficients are zero, especially the AC terms. We can exploit this
  168907. * by short-circuiting the IDCT calculation for any column in which all
  168908. * the AC terms are zero. In that case each output is equal to the
  168909. * DC coefficient (with scale factor as needed).
  168910. * With typical images and quantization tables, half or more of the
  168911. * column DCT calculations can be simplified this way.
  168912. */
  168913. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  168914. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  168915. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  168916. inptr[DCTSIZE*7] == 0) {
  168917. /* AC terms all zero */
  168918. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168919. wsptr[DCTSIZE*0] = dcval;
  168920. wsptr[DCTSIZE*1] = dcval;
  168921. wsptr[DCTSIZE*2] = dcval;
  168922. wsptr[DCTSIZE*3] = dcval;
  168923. wsptr[DCTSIZE*4] = dcval;
  168924. wsptr[DCTSIZE*5] = dcval;
  168925. wsptr[DCTSIZE*6] = dcval;
  168926. wsptr[DCTSIZE*7] = dcval;
  168927. inptr++; /* advance pointers to next column */
  168928. quantptr++;
  168929. wsptr++;
  168930. continue;
  168931. }
  168932. /* Even part */
  168933. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168934. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  168935. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  168936. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  168937. tmp10 = tmp0 + tmp2; /* phase 3 */
  168938. tmp11 = tmp0 - tmp2;
  168939. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  168940. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  168941. tmp0 = tmp10 + tmp13; /* phase 2 */
  168942. tmp3 = tmp10 - tmp13;
  168943. tmp1 = tmp11 + tmp12;
  168944. tmp2 = tmp11 - tmp12;
  168945. /* Odd part */
  168946. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  168947. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  168948. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  168949. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  168950. z13 = tmp6 + tmp5; /* phase 6 */
  168951. z10 = tmp6 - tmp5;
  168952. z11 = tmp4 + tmp7;
  168953. z12 = tmp4 - tmp7;
  168954. tmp7 = z11 + z13; /* phase 5 */
  168955. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  168956. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  168957. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  168958. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  168959. tmp6 = tmp12 - tmp7; /* phase 2 */
  168960. tmp5 = tmp11 - tmp6;
  168961. tmp4 = tmp10 + tmp5;
  168962. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  168963. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  168964. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  168965. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  168966. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  168967. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  168968. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  168969. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  168970. inptr++; /* advance pointers to next column */
  168971. quantptr++;
  168972. wsptr++;
  168973. }
  168974. /* Pass 2: process rows from work array, store into output array. */
  168975. /* Note that we must descale the results by a factor of 8 == 2**3. */
  168976. wsptr = workspace;
  168977. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  168978. outptr = output_buf[ctr] + output_col;
  168979. /* Rows of zeroes can be exploited in the same way as we did with columns.
  168980. * However, the column calculation has created many nonzero AC terms, so
  168981. * the simplification applies less often (typically 5% to 10% of the time).
  168982. * And testing floats for zero is relatively expensive, so we don't bother.
  168983. */
  168984. /* Even part */
  168985. tmp10 = wsptr[0] + wsptr[4];
  168986. tmp11 = wsptr[0] - wsptr[4];
  168987. tmp13 = wsptr[2] + wsptr[6];
  168988. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  168989. tmp0 = tmp10 + tmp13;
  168990. tmp3 = tmp10 - tmp13;
  168991. tmp1 = tmp11 + tmp12;
  168992. tmp2 = tmp11 - tmp12;
  168993. /* Odd part */
  168994. z13 = wsptr[5] + wsptr[3];
  168995. z10 = wsptr[5] - wsptr[3];
  168996. z11 = wsptr[1] + wsptr[7];
  168997. z12 = wsptr[1] - wsptr[7];
  168998. tmp7 = z11 + z13;
  168999. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  169000. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  169001. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  169002. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  169003. tmp6 = tmp12 - tmp7;
  169004. tmp5 = tmp11 - tmp6;
  169005. tmp4 = tmp10 + tmp5;
  169006. /* Final output stage: scale down by a factor of 8 and range-limit */
  169007. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  169008. & RANGE_MASK];
  169009. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  169010. & RANGE_MASK];
  169011. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  169012. & RANGE_MASK];
  169013. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  169014. & RANGE_MASK];
  169015. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  169016. & RANGE_MASK];
  169017. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  169018. & RANGE_MASK];
  169019. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  169020. & RANGE_MASK];
  169021. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  169022. & RANGE_MASK];
  169023. wsptr += DCTSIZE; /* advance pointer to next row */
  169024. }
  169025. }
  169026. #endif /* DCT_FLOAT_SUPPORTED */
  169027. /********* End of inlined file: jidctflt.c *********/
  169028. #undef CONST_BITS
  169029. #undef FIX_1_847759065
  169030. #undef MULTIPLY
  169031. #undef DEQUANTIZE
  169032. #undef DESCALE
  169033. /********* Start of inlined file: jidctfst.c *********/
  169034. #define JPEG_INTERNALS
  169035. #ifdef DCT_IFAST_SUPPORTED
  169036. /*
  169037. * This module is specialized to the case DCTSIZE = 8.
  169038. */
  169039. #if DCTSIZE != 8
  169040. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169041. #endif
  169042. /* Scaling decisions are generally the same as in the LL&M algorithm;
  169043. * see jidctint.c for more details. However, we choose to descale
  169044. * (right shift) multiplication products as soon as they are formed,
  169045. * rather than carrying additional fractional bits into subsequent additions.
  169046. * This compromises accuracy slightly, but it lets us save a few shifts.
  169047. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  169048. * everywhere except in the multiplications proper; this saves a good deal
  169049. * of work on 16-bit-int machines.
  169050. *
  169051. * The dequantized coefficients are not integers because the AA&N scaling
  169052. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  169053. * so that the first and second IDCT rounds have the same input scaling.
  169054. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  169055. * avoid a descaling shift; this compromises accuracy rather drastically
  169056. * for small quantization table entries, but it saves a lot of shifts.
  169057. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  169058. * so we use a much larger scaling factor to preserve accuracy.
  169059. *
  169060. * A final compromise is to represent the multiplicative constants to only
  169061. * 8 fractional bits, rather than 13. This saves some shifting work on some
  169062. * machines, and may also reduce the cost of multiplication (since there
  169063. * are fewer one-bits in the constants).
  169064. */
  169065. #if BITS_IN_JSAMPLE == 8
  169066. #define CONST_BITS 8
  169067. #define PASS1_BITS 2
  169068. #else
  169069. #define CONST_BITS 8
  169070. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  169071. #endif
  169072. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  169073. * causing a lot of useless floating-point operations at run time.
  169074. * To get around this we use the following pre-calculated constants.
  169075. * If you change CONST_BITS you may want to add appropriate values.
  169076. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  169077. */
  169078. #if CONST_BITS == 8
  169079. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  169080. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  169081. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  169082. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  169083. #else
  169084. #define FIX_1_082392200 FIX(1.082392200)
  169085. #define FIX_1_414213562 FIX(1.414213562)
  169086. #define FIX_1_847759065 FIX(1.847759065)
  169087. #define FIX_2_613125930 FIX(2.613125930)
  169088. #endif
  169089. /* We can gain a little more speed, with a further compromise in accuracy,
  169090. * by omitting the addition in a descaling shift. This yields an incorrectly
  169091. * rounded result half the time...
  169092. */
  169093. #ifndef USE_ACCURATE_ROUNDING
  169094. #undef DESCALE
  169095. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  169096. #endif
  169097. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  169098. * descale to yield a DCTELEM result.
  169099. */
  169100. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  169101. /* Dequantize a coefficient by multiplying it by the multiplier-table
  169102. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  169103. * multiplication will do. For 12-bit data, the multiplier table is
  169104. * declared INT32, so a 32-bit multiply will be used.
  169105. */
  169106. #if BITS_IN_JSAMPLE == 8
  169107. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  169108. #else
  169109. #define DEQUANTIZE(coef,quantval) \
  169110. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  169111. #endif
  169112. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  169113. * We assume that int right shift is unsigned if INT32 right shift is.
  169114. */
  169115. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  169116. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  169117. #if BITS_IN_JSAMPLE == 8
  169118. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  169119. #else
  169120. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  169121. #endif
  169122. #define IRIGHT_SHIFT(x,shft) \
  169123. ((ishift_temp = (x)) < 0 ? \
  169124. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  169125. (ishift_temp >> (shft)))
  169126. #else
  169127. #define ISHIFT_TEMPS
  169128. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  169129. #endif
  169130. #ifdef USE_ACCURATE_ROUNDING
  169131. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  169132. #else
  169133. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  169134. #endif
  169135. /*
  169136. * Perform dequantization and inverse DCT on one block of coefficients.
  169137. */
  169138. GLOBAL(void)
  169139. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169140. JCOEFPTR coef_block,
  169141. JSAMPARRAY output_buf, JDIMENSION output_col)
  169142. {
  169143. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  169144. DCTELEM tmp10, tmp11, tmp12, tmp13;
  169145. DCTELEM z5, z10, z11, z12, z13;
  169146. JCOEFPTR inptr;
  169147. IFAST_MULT_TYPE * quantptr;
  169148. int * wsptr;
  169149. JSAMPROW outptr;
  169150. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169151. int ctr;
  169152. int workspace[DCTSIZE2]; /* buffers data between passes */
  169153. SHIFT_TEMPS /* for DESCALE */
  169154. ISHIFT_TEMPS /* for IDESCALE */
  169155. /* Pass 1: process columns from input, store into work array. */
  169156. inptr = coef_block;
  169157. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  169158. wsptr = workspace;
  169159. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  169160. /* Due to quantization, we will usually find that many of the input
  169161. * coefficients are zero, especially the AC terms. We can exploit this
  169162. * by short-circuiting the IDCT calculation for any column in which all
  169163. * the AC terms are zero. In that case each output is equal to the
  169164. * DC coefficient (with scale factor as needed).
  169165. * With typical images and quantization tables, half or more of the
  169166. * column DCT calculations can be simplified this way.
  169167. */
  169168. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  169169. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  169170. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  169171. inptr[DCTSIZE*7] == 0) {
  169172. /* AC terms all zero */
  169173. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169174. wsptr[DCTSIZE*0] = dcval;
  169175. wsptr[DCTSIZE*1] = dcval;
  169176. wsptr[DCTSIZE*2] = dcval;
  169177. wsptr[DCTSIZE*3] = dcval;
  169178. wsptr[DCTSIZE*4] = dcval;
  169179. wsptr[DCTSIZE*5] = dcval;
  169180. wsptr[DCTSIZE*6] = dcval;
  169181. wsptr[DCTSIZE*7] = dcval;
  169182. inptr++; /* advance pointers to next column */
  169183. quantptr++;
  169184. wsptr++;
  169185. continue;
  169186. }
  169187. /* Even part */
  169188. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169189. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  169190. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  169191. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  169192. tmp10 = tmp0 + tmp2; /* phase 3 */
  169193. tmp11 = tmp0 - tmp2;
  169194. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  169195. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  169196. tmp0 = tmp10 + tmp13; /* phase 2 */
  169197. tmp3 = tmp10 - tmp13;
  169198. tmp1 = tmp11 + tmp12;
  169199. tmp2 = tmp11 - tmp12;
  169200. /* Odd part */
  169201. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169202. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169203. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169204. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169205. z13 = tmp6 + tmp5; /* phase 6 */
  169206. z10 = tmp6 - tmp5;
  169207. z11 = tmp4 + tmp7;
  169208. z12 = tmp4 - tmp7;
  169209. tmp7 = z11 + z13; /* phase 5 */
  169210. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  169211. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  169212. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  169213. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  169214. tmp6 = tmp12 - tmp7; /* phase 2 */
  169215. tmp5 = tmp11 - tmp6;
  169216. tmp4 = tmp10 + tmp5;
  169217. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  169218. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  169219. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  169220. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  169221. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  169222. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  169223. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  169224. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  169225. inptr++; /* advance pointers to next column */
  169226. quantptr++;
  169227. wsptr++;
  169228. }
  169229. /* Pass 2: process rows from work array, store into output array. */
  169230. /* Note that we must descale the results by a factor of 8 == 2**3, */
  169231. /* and also undo the PASS1_BITS scaling. */
  169232. wsptr = workspace;
  169233. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  169234. outptr = output_buf[ctr] + output_col;
  169235. /* Rows of zeroes can be exploited in the same way as we did with columns.
  169236. * However, the column calculation has created many nonzero AC terms, so
  169237. * the simplification applies less often (typically 5% to 10% of the time).
  169238. * On machines with very fast multiplication, it's possible that the
  169239. * test takes more time than it's worth. In that case this section
  169240. * may be commented out.
  169241. */
  169242. #ifndef NO_ZERO_ROW_TEST
  169243. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  169244. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  169245. /* AC terms all zero */
  169246. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  169247. & RANGE_MASK];
  169248. outptr[0] = dcval;
  169249. outptr[1] = dcval;
  169250. outptr[2] = dcval;
  169251. outptr[3] = dcval;
  169252. outptr[4] = dcval;
  169253. outptr[5] = dcval;
  169254. outptr[6] = dcval;
  169255. outptr[7] = dcval;
  169256. wsptr += DCTSIZE; /* advance pointer to next row */
  169257. continue;
  169258. }
  169259. #endif
  169260. /* Even part */
  169261. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  169262. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  169263. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  169264. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  169265. - tmp13;
  169266. tmp0 = tmp10 + tmp13;
  169267. tmp3 = tmp10 - tmp13;
  169268. tmp1 = tmp11 + tmp12;
  169269. tmp2 = tmp11 - tmp12;
  169270. /* Odd part */
  169271. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  169272. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  169273. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  169274. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  169275. tmp7 = z11 + z13; /* phase 5 */
  169276. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  169277. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  169278. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  169279. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  169280. tmp6 = tmp12 - tmp7; /* phase 2 */
  169281. tmp5 = tmp11 - tmp6;
  169282. tmp4 = tmp10 + tmp5;
  169283. /* Final output stage: scale down by a factor of 8 and range-limit */
  169284. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  169285. & RANGE_MASK];
  169286. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  169287. & RANGE_MASK];
  169288. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  169289. & RANGE_MASK];
  169290. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  169291. & RANGE_MASK];
  169292. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  169293. & RANGE_MASK];
  169294. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  169295. & RANGE_MASK];
  169296. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  169297. & RANGE_MASK];
  169298. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  169299. & RANGE_MASK];
  169300. wsptr += DCTSIZE; /* advance pointer to next row */
  169301. }
  169302. }
  169303. #endif /* DCT_IFAST_SUPPORTED */
  169304. /********* End of inlined file: jidctfst.c *********/
  169305. #undef CONST_BITS
  169306. #undef FIX_1_847759065
  169307. #undef MULTIPLY
  169308. #undef DEQUANTIZE
  169309. /********* Start of inlined file: jidctint.c *********/
  169310. #define JPEG_INTERNALS
  169311. #ifdef DCT_ISLOW_SUPPORTED
  169312. /*
  169313. * This module is specialized to the case DCTSIZE = 8.
  169314. */
  169315. #if DCTSIZE != 8
  169316. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169317. #endif
  169318. /*
  169319. * The poop on this scaling stuff is as follows:
  169320. *
  169321. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  169322. * larger than the true IDCT outputs. The final outputs are therefore
  169323. * a factor of N larger than desired; since N=8 this can be cured by
  169324. * a simple right shift at the end of the algorithm. The advantage of
  169325. * this arrangement is that we save two multiplications per 1-D IDCT,
  169326. * because the y0 and y4 inputs need not be divided by sqrt(N).
  169327. *
  169328. * We have to do addition and subtraction of the integer inputs, which
  169329. * is no problem, and multiplication by fractional constants, which is
  169330. * a problem to do in integer arithmetic. We multiply all the constants
  169331. * by CONST_SCALE and convert them to integer constants (thus retaining
  169332. * CONST_BITS bits of precision in the constants). After doing a
  169333. * multiplication we have to divide the product by CONST_SCALE, with proper
  169334. * rounding, to produce the correct output. This division can be done
  169335. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  169336. * as long as possible so that partial sums can be added together with
  169337. * full fractional precision.
  169338. *
  169339. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  169340. * they are represented to better-than-integral precision. These outputs
  169341. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  169342. * with the recommended scaling. (To scale up 12-bit sample data further, an
  169343. * intermediate INT32 array would be needed.)
  169344. *
  169345. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  169346. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  169347. * shows that the values given below are the most effective.
  169348. */
  169349. #if BITS_IN_JSAMPLE == 8
  169350. #define CONST_BITS 13
  169351. #define PASS1_BITS 2
  169352. #else
  169353. #define CONST_BITS 13
  169354. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  169355. #endif
  169356. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  169357. * causing a lot of useless floating-point operations at run time.
  169358. * To get around this we use the following pre-calculated constants.
  169359. * If you change CONST_BITS you may want to add appropriate values.
  169360. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  169361. */
  169362. #if CONST_BITS == 13
  169363. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  169364. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  169365. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  169366. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  169367. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  169368. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  169369. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  169370. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  169371. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  169372. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  169373. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  169374. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  169375. #else
  169376. #define FIX_0_298631336 FIX(0.298631336)
  169377. #define FIX_0_390180644 FIX(0.390180644)
  169378. #define FIX_0_541196100 FIX(0.541196100)
  169379. #define FIX_0_765366865 FIX(0.765366865)
  169380. #define FIX_0_899976223 FIX(0.899976223)
  169381. #define FIX_1_175875602 FIX(1.175875602)
  169382. #define FIX_1_501321110 FIX(1.501321110)
  169383. #define FIX_1_847759065 FIX(1.847759065)
  169384. #define FIX_1_961570560 FIX(1.961570560)
  169385. #define FIX_2_053119869 FIX(2.053119869)
  169386. #define FIX_2_562915447 FIX(2.562915447)
  169387. #define FIX_3_072711026 FIX(3.072711026)
  169388. #endif
  169389. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  169390. * For 8-bit samples with the recommended scaling, all the variable
  169391. * and constant values involved are no more than 16 bits wide, so a
  169392. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  169393. * For 12-bit samples, a full 32-bit multiplication will be needed.
  169394. */
  169395. #if BITS_IN_JSAMPLE == 8
  169396. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  169397. #else
  169398. #define MULTIPLY(var,const) ((var) * (const))
  169399. #endif
  169400. /* Dequantize a coefficient by multiplying it by the multiplier-table
  169401. * entry; produce an int result. In this module, both inputs and result
  169402. * are 16 bits or less, so either int or short multiply will work.
  169403. */
  169404. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  169405. /*
  169406. * Perform dequantization and inverse DCT on one block of coefficients.
  169407. */
  169408. GLOBAL(void)
  169409. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169410. JCOEFPTR coef_block,
  169411. JSAMPARRAY output_buf, JDIMENSION output_col)
  169412. {
  169413. INT32 tmp0, tmp1, tmp2, tmp3;
  169414. INT32 tmp10, tmp11, tmp12, tmp13;
  169415. INT32 z1, z2, z3, z4, z5;
  169416. JCOEFPTR inptr;
  169417. ISLOW_MULT_TYPE * quantptr;
  169418. int * wsptr;
  169419. JSAMPROW outptr;
  169420. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169421. int ctr;
  169422. int workspace[DCTSIZE2]; /* buffers data between passes */
  169423. SHIFT_TEMPS
  169424. /* Pass 1: process columns from input, store into work array. */
  169425. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  169426. /* furthermore, we scale the results by 2**PASS1_BITS. */
  169427. inptr = coef_block;
  169428. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169429. wsptr = workspace;
  169430. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  169431. /* Due to quantization, we will usually find that many of the input
  169432. * coefficients are zero, especially the AC terms. We can exploit this
  169433. * by short-circuiting the IDCT calculation for any column in which all
  169434. * the AC terms are zero. In that case each output is equal to the
  169435. * DC coefficient (with scale factor as needed).
  169436. * With typical images and quantization tables, half or more of the
  169437. * column DCT calculations can be simplified this way.
  169438. */
  169439. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  169440. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  169441. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  169442. inptr[DCTSIZE*7] == 0) {
  169443. /* AC terms all zero */
  169444. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  169445. wsptr[DCTSIZE*0] = dcval;
  169446. wsptr[DCTSIZE*1] = dcval;
  169447. wsptr[DCTSIZE*2] = dcval;
  169448. wsptr[DCTSIZE*3] = dcval;
  169449. wsptr[DCTSIZE*4] = dcval;
  169450. wsptr[DCTSIZE*5] = dcval;
  169451. wsptr[DCTSIZE*6] = dcval;
  169452. wsptr[DCTSIZE*7] = dcval;
  169453. inptr++; /* advance pointers to next column */
  169454. quantptr++;
  169455. wsptr++;
  169456. continue;
  169457. }
  169458. /* Even part: reverse the even part of the forward DCT. */
  169459. /* The rotator is sqrt(2)*c(-6). */
  169460. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  169461. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  169462. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  169463. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  169464. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  169465. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169466. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  169467. tmp0 = (z2 + z3) << CONST_BITS;
  169468. tmp1 = (z2 - z3) << CONST_BITS;
  169469. tmp10 = tmp0 + tmp3;
  169470. tmp13 = tmp0 - tmp3;
  169471. tmp11 = tmp1 + tmp2;
  169472. tmp12 = tmp1 - tmp2;
  169473. /* Odd part per figure 8; the matrix is unitary and hence its
  169474. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  169475. */
  169476. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169477. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169478. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169479. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169480. z1 = tmp0 + tmp3;
  169481. z2 = tmp1 + tmp2;
  169482. z3 = tmp0 + tmp2;
  169483. z4 = tmp1 + tmp3;
  169484. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  169485. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  169486. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  169487. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  169488. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  169489. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  169490. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  169491. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  169492. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  169493. z3 += z5;
  169494. z4 += z5;
  169495. tmp0 += z1 + z3;
  169496. tmp1 += z2 + z4;
  169497. tmp2 += z2 + z3;
  169498. tmp3 += z1 + z4;
  169499. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  169500. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  169501. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  169502. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  169503. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  169504. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  169505. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  169506. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  169507. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  169508. inptr++; /* advance pointers to next column */
  169509. quantptr++;
  169510. wsptr++;
  169511. }
  169512. /* Pass 2: process rows from work array, store into output array. */
  169513. /* Note that we must descale the results by a factor of 8 == 2**3, */
  169514. /* and also undo the PASS1_BITS scaling. */
  169515. wsptr = workspace;
  169516. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  169517. outptr = output_buf[ctr] + output_col;
  169518. /* Rows of zeroes can be exploited in the same way as we did with columns.
  169519. * However, the column calculation has created many nonzero AC terms, so
  169520. * the simplification applies less often (typically 5% to 10% of the time).
  169521. * On machines with very fast multiplication, it's possible that the
  169522. * test takes more time than it's worth. In that case this section
  169523. * may be commented out.
  169524. */
  169525. #ifndef NO_ZERO_ROW_TEST
  169526. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  169527. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  169528. /* AC terms all zero */
  169529. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  169530. & RANGE_MASK];
  169531. outptr[0] = dcval;
  169532. outptr[1] = dcval;
  169533. outptr[2] = dcval;
  169534. outptr[3] = dcval;
  169535. outptr[4] = dcval;
  169536. outptr[5] = dcval;
  169537. outptr[6] = dcval;
  169538. outptr[7] = dcval;
  169539. wsptr += DCTSIZE; /* advance pointer to next row */
  169540. continue;
  169541. }
  169542. #endif
  169543. /* Even part: reverse the even part of the forward DCT. */
  169544. /* The rotator is sqrt(2)*c(-6). */
  169545. z2 = (INT32) wsptr[2];
  169546. z3 = (INT32) wsptr[6];
  169547. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  169548. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  169549. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  169550. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  169551. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  169552. tmp10 = tmp0 + tmp3;
  169553. tmp13 = tmp0 - tmp3;
  169554. tmp11 = tmp1 + tmp2;
  169555. tmp12 = tmp1 - tmp2;
  169556. /* Odd part per figure 8; the matrix is unitary and hence its
  169557. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  169558. */
  169559. tmp0 = (INT32) wsptr[7];
  169560. tmp1 = (INT32) wsptr[5];
  169561. tmp2 = (INT32) wsptr[3];
  169562. tmp3 = (INT32) wsptr[1];
  169563. z1 = tmp0 + tmp3;
  169564. z2 = tmp1 + tmp2;
  169565. z3 = tmp0 + tmp2;
  169566. z4 = tmp1 + tmp3;
  169567. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  169568. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  169569. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  169570. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  169571. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  169572. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  169573. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  169574. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  169575. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  169576. z3 += z5;
  169577. z4 += z5;
  169578. tmp0 += z1 + z3;
  169579. tmp1 += z2 + z4;
  169580. tmp2 += z2 + z3;
  169581. tmp3 += z1 + z4;
  169582. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  169583. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  169584. CONST_BITS+PASS1_BITS+3)
  169585. & RANGE_MASK];
  169586. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  169587. CONST_BITS+PASS1_BITS+3)
  169588. & RANGE_MASK];
  169589. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  169590. CONST_BITS+PASS1_BITS+3)
  169591. & RANGE_MASK];
  169592. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  169593. CONST_BITS+PASS1_BITS+3)
  169594. & RANGE_MASK];
  169595. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  169596. CONST_BITS+PASS1_BITS+3)
  169597. & RANGE_MASK];
  169598. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  169599. CONST_BITS+PASS1_BITS+3)
  169600. & RANGE_MASK];
  169601. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  169602. CONST_BITS+PASS1_BITS+3)
  169603. & RANGE_MASK];
  169604. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  169605. CONST_BITS+PASS1_BITS+3)
  169606. & RANGE_MASK];
  169607. wsptr += DCTSIZE; /* advance pointer to next row */
  169608. }
  169609. }
  169610. #endif /* DCT_ISLOW_SUPPORTED */
  169611. /********* End of inlined file: jidctint.c *********/
  169612. /********* Start of inlined file: jidctred.c *********/
  169613. #define JPEG_INTERNALS
  169614. #ifdef IDCT_SCALING_SUPPORTED
  169615. /*
  169616. * This module is specialized to the case DCTSIZE = 8.
  169617. */
  169618. #if DCTSIZE != 8
  169619. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169620. #endif
  169621. /* Scaling is the same as in jidctint.c. */
  169622. #if BITS_IN_JSAMPLE == 8
  169623. #define CONST_BITS 13
  169624. #define PASS1_BITS 2
  169625. #else
  169626. #define CONST_BITS 13
  169627. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  169628. #endif
  169629. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  169630. * causing a lot of useless floating-point operations at run time.
  169631. * To get around this we use the following pre-calculated constants.
  169632. * If you change CONST_BITS you may want to add appropriate values.
  169633. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  169634. */
  169635. #if CONST_BITS == 13
  169636. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  169637. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  169638. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  169639. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  169640. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  169641. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  169642. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  169643. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  169644. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  169645. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  169646. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  169647. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  169648. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  169649. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  169650. #else
  169651. #define FIX_0_211164243 FIX(0.211164243)
  169652. #define FIX_0_509795579 FIX(0.509795579)
  169653. #define FIX_0_601344887 FIX(0.601344887)
  169654. #define FIX_0_720959822 FIX(0.720959822)
  169655. #define FIX_0_765366865 FIX(0.765366865)
  169656. #define FIX_0_850430095 FIX(0.850430095)
  169657. #define FIX_0_899976223 FIX(0.899976223)
  169658. #define FIX_1_061594337 FIX(1.061594337)
  169659. #define FIX_1_272758580 FIX(1.272758580)
  169660. #define FIX_1_451774981 FIX(1.451774981)
  169661. #define FIX_1_847759065 FIX(1.847759065)
  169662. #define FIX_2_172734803 FIX(2.172734803)
  169663. #define FIX_2_562915447 FIX(2.562915447)
  169664. #define FIX_3_624509785 FIX(3.624509785)
  169665. #endif
  169666. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  169667. * For 8-bit samples with the recommended scaling, all the variable
  169668. * and constant values involved are no more than 16 bits wide, so a
  169669. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  169670. * For 12-bit samples, a full 32-bit multiplication will be needed.
  169671. */
  169672. #if BITS_IN_JSAMPLE == 8
  169673. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  169674. #else
  169675. #define MULTIPLY(var,const) ((var) * (const))
  169676. #endif
  169677. /* Dequantize a coefficient by multiplying it by the multiplier-table
  169678. * entry; produce an int result. In this module, both inputs and result
  169679. * are 16 bits or less, so either int or short multiply will work.
  169680. */
  169681. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  169682. /*
  169683. * Perform dequantization and inverse DCT on one block of coefficients,
  169684. * producing a reduced-size 4x4 output block.
  169685. */
  169686. GLOBAL(void)
  169687. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169688. JCOEFPTR coef_block,
  169689. JSAMPARRAY output_buf, JDIMENSION output_col)
  169690. {
  169691. INT32 tmp0, tmp2, tmp10, tmp12;
  169692. INT32 z1, z2, z3, z4;
  169693. JCOEFPTR inptr;
  169694. ISLOW_MULT_TYPE * quantptr;
  169695. int * wsptr;
  169696. JSAMPROW outptr;
  169697. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169698. int ctr;
  169699. int workspace[DCTSIZE*4]; /* buffers data between passes */
  169700. SHIFT_TEMPS
  169701. /* Pass 1: process columns from input, store into work array. */
  169702. inptr = coef_block;
  169703. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169704. wsptr = workspace;
  169705. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  169706. /* Don't bother to process column 4, because second pass won't use it */
  169707. if (ctr == DCTSIZE-4)
  169708. continue;
  169709. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  169710. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  169711. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  169712. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  169713. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  169714. wsptr[DCTSIZE*0] = dcval;
  169715. wsptr[DCTSIZE*1] = dcval;
  169716. wsptr[DCTSIZE*2] = dcval;
  169717. wsptr[DCTSIZE*3] = dcval;
  169718. continue;
  169719. }
  169720. /* Even part */
  169721. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169722. tmp0 <<= (CONST_BITS+1);
  169723. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  169724. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  169725. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  169726. tmp10 = tmp0 + tmp2;
  169727. tmp12 = tmp0 - tmp2;
  169728. /* Odd part */
  169729. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169730. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169731. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169732. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169733. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  169734. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  169735. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  169736. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  169737. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  169738. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  169739. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  169740. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  169741. /* Final output stage */
  169742. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  169743. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  169744. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  169745. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  169746. }
  169747. /* Pass 2: process 4 rows from work array, store into output array. */
  169748. wsptr = workspace;
  169749. for (ctr = 0; ctr < 4; ctr++) {
  169750. outptr = output_buf[ctr] + output_col;
  169751. /* It's not clear whether a zero row test is worthwhile here ... */
  169752. #ifndef NO_ZERO_ROW_TEST
  169753. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  169754. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  169755. /* AC terms all zero */
  169756. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  169757. & RANGE_MASK];
  169758. outptr[0] = dcval;
  169759. outptr[1] = dcval;
  169760. outptr[2] = dcval;
  169761. outptr[3] = dcval;
  169762. wsptr += DCTSIZE; /* advance pointer to next row */
  169763. continue;
  169764. }
  169765. #endif
  169766. /* Even part */
  169767. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  169768. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  169769. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  169770. tmp10 = tmp0 + tmp2;
  169771. tmp12 = tmp0 - tmp2;
  169772. /* Odd part */
  169773. z1 = (INT32) wsptr[7];
  169774. z2 = (INT32) wsptr[5];
  169775. z3 = (INT32) wsptr[3];
  169776. z4 = (INT32) wsptr[1];
  169777. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  169778. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  169779. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  169780. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  169781. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  169782. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  169783. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  169784. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  169785. /* Final output stage */
  169786. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  169787. CONST_BITS+PASS1_BITS+3+1)
  169788. & RANGE_MASK];
  169789. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  169790. CONST_BITS+PASS1_BITS+3+1)
  169791. & RANGE_MASK];
  169792. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  169793. CONST_BITS+PASS1_BITS+3+1)
  169794. & RANGE_MASK];
  169795. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  169796. CONST_BITS+PASS1_BITS+3+1)
  169797. & RANGE_MASK];
  169798. wsptr += DCTSIZE; /* advance pointer to next row */
  169799. }
  169800. }
  169801. /*
  169802. * Perform dequantization and inverse DCT on one block of coefficients,
  169803. * producing a reduced-size 2x2 output block.
  169804. */
  169805. GLOBAL(void)
  169806. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169807. JCOEFPTR coef_block,
  169808. JSAMPARRAY output_buf, JDIMENSION output_col)
  169809. {
  169810. INT32 tmp0, tmp10, z1;
  169811. JCOEFPTR inptr;
  169812. ISLOW_MULT_TYPE * quantptr;
  169813. int * wsptr;
  169814. JSAMPROW outptr;
  169815. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169816. int ctr;
  169817. int workspace[DCTSIZE*2]; /* buffers data between passes */
  169818. SHIFT_TEMPS
  169819. /* Pass 1: process columns from input, store into work array. */
  169820. inptr = coef_block;
  169821. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169822. wsptr = workspace;
  169823. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  169824. /* Don't bother to process columns 2,4,6 */
  169825. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  169826. continue;
  169827. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  169828. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  169829. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  169830. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  169831. wsptr[DCTSIZE*0] = dcval;
  169832. wsptr[DCTSIZE*1] = dcval;
  169833. continue;
  169834. }
  169835. /* Even part */
  169836. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169837. tmp10 = z1 << (CONST_BITS+2);
  169838. /* Odd part */
  169839. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169840. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  169841. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169842. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  169843. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169844. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  169845. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169846. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  169847. /* Final output stage */
  169848. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  169849. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  169850. }
  169851. /* Pass 2: process 2 rows from work array, store into output array. */
  169852. wsptr = workspace;
  169853. for (ctr = 0; ctr < 2; ctr++) {
  169854. outptr = output_buf[ctr] + output_col;
  169855. /* It's not clear whether a zero row test is worthwhile here ... */
  169856. #ifndef NO_ZERO_ROW_TEST
  169857. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  169858. /* AC terms all zero */
  169859. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  169860. & RANGE_MASK];
  169861. outptr[0] = dcval;
  169862. outptr[1] = dcval;
  169863. wsptr += DCTSIZE; /* advance pointer to next row */
  169864. continue;
  169865. }
  169866. #endif
  169867. /* Even part */
  169868. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  169869. /* Odd part */
  169870. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  169871. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  169872. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  169873. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  169874. /* Final output stage */
  169875. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  169876. CONST_BITS+PASS1_BITS+3+2)
  169877. & RANGE_MASK];
  169878. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  169879. CONST_BITS+PASS1_BITS+3+2)
  169880. & RANGE_MASK];
  169881. wsptr += DCTSIZE; /* advance pointer to next row */
  169882. }
  169883. }
  169884. /*
  169885. * Perform dequantization and inverse DCT on one block of coefficients,
  169886. * producing a reduced-size 1x1 output block.
  169887. */
  169888. GLOBAL(void)
  169889. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169890. JCOEFPTR coef_block,
  169891. JSAMPARRAY output_buf, JDIMENSION output_col)
  169892. {
  169893. int dcval;
  169894. ISLOW_MULT_TYPE * quantptr;
  169895. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169896. SHIFT_TEMPS
  169897. /* We hardly need an inverse DCT routine for this: just take the
  169898. * average pixel value, which is one-eighth of the DC coefficient.
  169899. */
  169900. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169901. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  169902. dcval = (int) DESCALE((INT32) dcval, 3);
  169903. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  169904. }
  169905. #endif /* IDCT_SCALING_SUPPORTED */
  169906. /********* End of inlined file: jidctred.c *********/
  169907. /********* Start of inlined file: jmemmgr.c *********/
  169908. #define JPEG_INTERNALS
  169909. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  169910. /********* Start of inlined file: jmemsys.h *********/
  169911. #ifndef __jmemsys_h__
  169912. #define __jmemsys_h__
  169913. /* Short forms of external names for systems with brain-damaged linkers. */
  169914. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169915. #define jpeg_get_small jGetSmall
  169916. #define jpeg_free_small jFreeSmall
  169917. #define jpeg_get_large jGetLarge
  169918. #define jpeg_free_large jFreeLarge
  169919. #define jpeg_mem_available jMemAvail
  169920. #define jpeg_open_backing_store jOpenBackStore
  169921. #define jpeg_mem_init jMemInit
  169922. #define jpeg_mem_term jMemTerm
  169923. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169924. /*
  169925. * These two functions are used to allocate and release small chunks of
  169926. * memory. (Typically the total amount requested through jpeg_get_small is
  169927. * no more than 20K or so; this will be requested in chunks of a few K each.)
  169928. * Behavior should be the same as for the standard library functions malloc
  169929. * and free; in particular, jpeg_get_small must return NULL on failure.
  169930. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  169931. * size of the object being freed, just in case it's needed.
  169932. * On an 80x86 machine using small-data memory model, these manage near heap.
  169933. */
  169934. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  169935. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  169936. size_t sizeofobject));
  169937. /*
  169938. * These two functions are used to allocate and release large chunks of
  169939. * memory (up to the total free space designated by jpeg_mem_available).
  169940. * The interface is the same as above, except that on an 80x86 machine,
  169941. * far pointers are used. On most other machines these are identical to
  169942. * the jpeg_get/free_small routines; but we keep them separate anyway,
  169943. * in case a different allocation strategy is desirable for large chunks.
  169944. */
  169945. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  169946. size_t sizeofobject));
  169947. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  169948. size_t sizeofobject));
  169949. /*
  169950. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  169951. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  169952. * matter, but that case should never come into play). This macro is needed
  169953. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  169954. * On those machines, we expect that jconfig.h will provide a proper value.
  169955. * On machines with 32-bit flat address spaces, any large constant may be used.
  169956. *
  169957. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  169958. * size_t and will be a multiple of sizeof(align_type).
  169959. */
  169960. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  169961. #define MAX_ALLOC_CHUNK 1000000000L
  169962. #endif
  169963. /*
  169964. * This routine computes the total space still available for allocation by
  169965. * jpeg_get_large. If more space than this is needed, backing store will be
  169966. * used. NOTE: any memory already allocated must not be counted.
  169967. *
  169968. * There is a minimum space requirement, corresponding to the minimum
  169969. * feasible buffer sizes; jmemmgr.c will request that much space even if
  169970. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  169971. * all working storage in memory, is also passed in case it is useful.
  169972. * Finally, the total space already allocated is passed. If no better
  169973. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  169974. * is often a suitable calculation.
  169975. *
  169976. * It is OK for jpeg_mem_available to underestimate the space available
  169977. * (that'll just lead to more backing-store access than is really necessary).
  169978. * However, an overestimate will lead to failure. Hence it's wise to subtract
  169979. * a slop factor from the true available space. 5% should be enough.
  169980. *
  169981. * On machines with lots of virtual memory, any large constant may be returned.
  169982. * Conversely, zero may be returned to always use the minimum amount of memory.
  169983. */
  169984. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  169985. long min_bytes_needed,
  169986. long max_bytes_needed,
  169987. long already_allocated));
  169988. /*
  169989. * This structure holds whatever state is needed to access a single
  169990. * backing-store object. The read/write/close method pointers are called
  169991. * by jmemmgr.c to manipulate the backing-store object; all other fields
  169992. * are private to the system-dependent backing store routines.
  169993. */
  169994. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  169995. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  169996. typedef unsigned short XMSH; /* type of extended-memory handles */
  169997. typedef unsigned short EMSH; /* type of expanded-memory handles */
  169998. typedef union {
  169999. short file_handle; /* DOS file handle if it's a temp file */
  170000. XMSH xms_handle; /* handle if it's a chunk of XMS */
  170001. EMSH ems_handle; /* handle if it's a chunk of EMS */
  170002. } handle_union;
  170003. #endif /* USE_MSDOS_MEMMGR */
  170004. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  170005. #include <Files.h>
  170006. #endif /* USE_MAC_MEMMGR */
  170007. //typedef struct backing_store_struct * backing_store_ptr;
  170008. typedef struct backing_store_struct {
  170009. /* Methods for reading/writing/closing this backing-store object */
  170010. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  170011. struct backing_store_struct *info,
  170012. void FAR * buffer_address,
  170013. long file_offset, long byte_count));
  170014. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  170015. struct backing_store_struct *info,
  170016. void FAR * buffer_address,
  170017. long file_offset, long byte_count));
  170018. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  170019. struct backing_store_struct *info));
  170020. /* Private fields for system-dependent backing-store management */
  170021. #ifdef USE_MSDOS_MEMMGR
  170022. /* For the MS-DOS manager (jmemdos.c), we need: */
  170023. handle_union handle; /* reference to backing-store storage object */
  170024. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  170025. #else
  170026. #ifdef USE_MAC_MEMMGR
  170027. /* For the Mac manager (jmemmac.c), we need: */
  170028. short temp_file; /* file reference number to temp file */
  170029. FSSpec tempSpec; /* the FSSpec for the temp file */
  170030. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  170031. #else
  170032. /* For a typical implementation with temp files, we need: */
  170033. FILE * temp_file; /* stdio reference to temp file */
  170034. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  170035. #endif
  170036. #endif
  170037. } backing_store_info;
  170038. /*
  170039. * Initial opening of a backing-store object. This must fill in the
  170040. * read/write/close pointers in the object. The read/write routines
  170041. * may take an error exit if the specified maximum file size is exceeded.
  170042. * (If jpeg_mem_available always returns a large value, this routine can
  170043. * just take an error exit.)
  170044. */
  170045. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  170046. struct backing_store_struct *info,
  170047. long total_bytes_needed));
  170048. /*
  170049. * These routines take care of any system-dependent initialization and
  170050. * cleanup required. jpeg_mem_init will be called before anything is
  170051. * allocated (and, therefore, nothing in cinfo is of use except the error
  170052. * manager pointer). It should return a suitable default value for
  170053. * max_memory_to_use; this may subsequently be overridden by the surrounding
  170054. * application. (Note that max_memory_to_use is only important if
  170055. * jpeg_mem_available chooses to consult it ... no one else will.)
  170056. * jpeg_mem_term may assume that all requested memory has been freed and that
  170057. * all opened backing-store objects have been closed.
  170058. */
  170059. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  170060. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  170061. #endif
  170062. /********* End of inlined file: jmemsys.h *********/
  170063. /* import the system-dependent declarations */
  170064. #ifndef NO_GETENV
  170065. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  170066. extern char * getenv JPP((const char * name));
  170067. #endif
  170068. #endif
  170069. /*
  170070. * Some important notes:
  170071. * The allocation routines provided here must never return NULL.
  170072. * They should exit to error_exit if unsuccessful.
  170073. *
  170074. * It's not a good idea to try to merge the sarray and barray routines,
  170075. * even though they are textually almost the same, because samples are
  170076. * usually stored as bytes while coefficients are shorts or ints. Thus,
  170077. * in machines where byte pointers have a different representation from
  170078. * word pointers, the resulting machine code could not be the same.
  170079. */
  170080. /*
  170081. * Many machines require storage alignment: longs must start on 4-byte
  170082. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  170083. * always returns pointers that are multiples of the worst-case alignment
  170084. * requirement, and we had better do so too.
  170085. * There isn't any really portable way to determine the worst-case alignment
  170086. * requirement. This module assumes that the alignment requirement is
  170087. * multiples of sizeof(ALIGN_TYPE).
  170088. * By default, we define ALIGN_TYPE as double. This is necessary on some
  170089. * workstations (where doubles really do need 8-byte alignment) and will work
  170090. * fine on nearly everything. If your machine has lesser alignment needs,
  170091. * you can save a few bytes by making ALIGN_TYPE smaller.
  170092. * The only place I know of where this will NOT work is certain Macintosh
  170093. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  170094. * Doing 10-byte alignment is counterproductive because longwords won't be
  170095. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  170096. * such a compiler.
  170097. */
  170098. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  170099. #define ALIGN_TYPE double
  170100. #endif
  170101. /*
  170102. * We allocate objects from "pools", where each pool is gotten with a single
  170103. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  170104. * overhead within a pool, except for alignment padding. Each pool has a
  170105. * header with a link to the next pool of the same class.
  170106. * Small and large pool headers are identical except that the latter's
  170107. * link pointer must be FAR on 80x86 machines.
  170108. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  170109. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  170110. * of the alignment requirement of ALIGN_TYPE.
  170111. */
  170112. typedef union small_pool_struct * small_pool_ptr;
  170113. typedef union small_pool_struct {
  170114. struct {
  170115. small_pool_ptr next; /* next in list of pools */
  170116. size_t bytes_used; /* how many bytes already used within pool */
  170117. size_t bytes_left; /* bytes still available in this pool */
  170118. } hdr;
  170119. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  170120. } small_pool_hdr;
  170121. typedef union large_pool_struct FAR * large_pool_ptr;
  170122. typedef union large_pool_struct {
  170123. struct {
  170124. large_pool_ptr next; /* next in list of pools */
  170125. size_t bytes_used; /* how many bytes already used within pool */
  170126. size_t bytes_left; /* bytes still available in this pool */
  170127. } hdr;
  170128. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  170129. } large_pool_hdr;
  170130. /*
  170131. * Here is the full definition of a memory manager object.
  170132. */
  170133. typedef struct {
  170134. struct jpeg_memory_mgr pub; /* public fields */
  170135. /* Each pool identifier (lifetime class) names a linked list of pools. */
  170136. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  170137. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  170138. /* Since we only have one lifetime class of virtual arrays, only one
  170139. * linked list is necessary (for each datatype). Note that the virtual
  170140. * array control blocks being linked together are actually stored somewhere
  170141. * in the small-pool list.
  170142. */
  170143. jvirt_sarray_ptr virt_sarray_list;
  170144. jvirt_barray_ptr virt_barray_list;
  170145. /* This counts total space obtained from jpeg_get_small/large */
  170146. long total_space_allocated;
  170147. /* alloc_sarray and alloc_barray set this value for use by virtual
  170148. * array routines.
  170149. */
  170150. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  170151. } my_memory_mgr;
  170152. typedef my_memory_mgr * my_mem_ptr;
  170153. /*
  170154. * The control blocks for virtual arrays.
  170155. * Note that these blocks are allocated in the "small" pool area.
  170156. * System-dependent info for the associated backing store (if any) is hidden
  170157. * inside the backing_store_info struct.
  170158. */
  170159. struct jvirt_sarray_control {
  170160. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  170161. JDIMENSION rows_in_array; /* total virtual array height */
  170162. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  170163. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  170164. JDIMENSION rows_in_mem; /* height of memory buffer */
  170165. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  170166. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  170167. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  170168. boolean pre_zero; /* pre-zero mode requested? */
  170169. boolean dirty; /* do current buffer contents need written? */
  170170. boolean b_s_open; /* is backing-store data valid? */
  170171. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  170172. backing_store_info b_s_info; /* System-dependent control info */
  170173. };
  170174. struct jvirt_barray_control {
  170175. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  170176. JDIMENSION rows_in_array; /* total virtual array height */
  170177. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  170178. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  170179. JDIMENSION rows_in_mem; /* height of memory buffer */
  170180. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  170181. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  170182. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  170183. boolean pre_zero; /* pre-zero mode requested? */
  170184. boolean dirty; /* do current buffer contents need written? */
  170185. boolean b_s_open; /* is backing-store data valid? */
  170186. jvirt_barray_ptr next; /* link to next virtual barray control block */
  170187. backing_store_info b_s_info; /* System-dependent control info */
  170188. };
  170189. #ifdef MEM_STATS /* optional extra stuff for statistics */
  170190. LOCAL(void)
  170191. print_mem_stats (j_common_ptr cinfo, int pool_id)
  170192. {
  170193. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170194. small_pool_ptr shdr_ptr;
  170195. large_pool_ptr lhdr_ptr;
  170196. /* Since this is only a debugging stub, we can cheat a little by using
  170197. * fprintf directly rather than going through the trace message code.
  170198. * This is helpful because message parm array can't handle longs.
  170199. */
  170200. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  170201. pool_id, mem->total_space_allocated);
  170202. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  170203. lhdr_ptr = lhdr_ptr->hdr.next) {
  170204. fprintf(stderr, " Large chunk used %ld\n",
  170205. (long) lhdr_ptr->hdr.bytes_used);
  170206. }
  170207. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  170208. shdr_ptr = shdr_ptr->hdr.next) {
  170209. fprintf(stderr, " Small chunk used %ld free %ld\n",
  170210. (long) shdr_ptr->hdr.bytes_used,
  170211. (long) shdr_ptr->hdr.bytes_left);
  170212. }
  170213. }
  170214. #endif /* MEM_STATS */
  170215. LOCAL(void)
  170216. out_of_memory (j_common_ptr cinfo, int which)
  170217. /* Report an out-of-memory error and stop execution */
  170218. /* If we compiled MEM_STATS support, report alloc requests before dying */
  170219. {
  170220. #ifdef MEM_STATS
  170221. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  170222. #endif
  170223. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  170224. }
  170225. /*
  170226. * Allocation of "small" objects.
  170227. *
  170228. * For these, we use pooled storage. When a new pool must be created,
  170229. * we try to get enough space for the current request plus a "slop" factor,
  170230. * where the slop will be the amount of leftover space in the new pool.
  170231. * The speed vs. space tradeoff is largely determined by the slop values.
  170232. * A different slop value is provided for each pool class (lifetime),
  170233. * and we also distinguish the first pool of a class from later ones.
  170234. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  170235. * machines, but may be too small if longs are 64 bits or more.
  170236. */
  170237. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  170238. {
  170239. 1600, /* first PERMANENT pool */
  170240. 16000 /* first IMAGE pool */
  170241. };
  170242. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  170243. {
  170244. 0, /* additional PERMANENT pools */
  170245. 5000 /* additional IMAGE pools */
  170246. };
  170247. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  170248. METHODDEF(void *)
  170249. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  170250. /* Allocate a "small" object */
  170251. {
  170252. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170253. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  170254. char * data_ptr;
  170255. size_t odd_bytes, min_request, slop;
  170256. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  170257. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  170258. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  170259. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  170260. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  170261. if (odd_bytes > 0)
  170262. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  170263. /* See if space is available in any existing pool */
  170264. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  170265. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170266. prev_hdr_ptr = NULL;
  170267. hdr_ptr = mem->small_list[pool_id];
  170268. while (hdr_ptr != NULL) {
  170269. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  170270. break; /* found pool with enough space */
  170271. prev_hdr_ptr = hdr_ptr;
  170272. hdr_ptr = hdr_ptr->hdr.next;
  170273. }
  170274. /* Time to make a new pool? */
  170275. if (hdr_ptr == NULL) {
  170276. /* min_request is what we need now, slop is what will be leftover */
  170277. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  170278. if (prev_hdr_ptr == NULL) /* first pool in class? */
  170279. slop = first_pool_slop[pool_id];
  170280. else
  170281. slop = extra_pool_slop[pool_id];
  170282. /* Don't ask for more than MAX_ALLOC_CHUNK */
  170283. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  170284. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  170285. /* Try to get space, if fail reduce slop and try again */
  170286. for (;;) {
  170287. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  170288. if (hdr_ptr != NULL)
  170289. break;
  170290. slop /= 2;
  170291. if (slop < MIN_SLOP) /* give up when it gets real small */
  170292. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  170293. }
  170294. mem->total_space_allocated += min_request + slop;
  170295. /* Success, initialize the new pool header and add to end of list */
  170296. hdr_ptr->hdr.next = NULL;
  170297. hdr_ptr->hdr.bytes_used = 0;
  170298. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  170299. if (prev_hdr_ptr == NULL) /* first pool in class? */
  170300. mem->small_list[pool_id] = hdr_ptr;
  170301. else
  170302. prev_hdr_ptr->hdr.next = hdr_ptr;
  170303. }
  170304. /* OK, allocate the object from the current pool */
  170305. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  170306. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  170307. hdr_ptr->hdr.bytes_used += sizeofobject;
  170308. hdr_ptr->hdr.bytes_left -= sizeofobject;
  170309. return (void *) data_ptr;
  170310. }
  170311. /*
  170312. * Allocation of "large" objects.
  170313. *
  170314. * The external semantics of these are the same as "small" objects,
  170315. * except that FAR pointers are used on 80x86. However the pool
  170316. * management heuristics are quite different. We assume that each
  170317. * request is large enough that it may as well be passed directly to
  170318. * jpeg_get_large; the pool management just links everything together
  170319. * so that we can free it all on demand.
  170320. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  170321. * structures. The routines that create these structures (see below)
  170322. * deliberately bunch rows together to ensure a large request size.
  170323. */
  170324. METHODDEF(void FAR *)
  170325. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  170326. /* Allocate a "large" object */
  170327. {
  170328. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170329. large_pool_ptr hdr_ptr;
  170330. size_t odd_bytes;
  170331. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  170332. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  170333. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  170334. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  170335. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  170336. if (odd_bytes > 0)
  170337. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  170338. /* Always make a new pool */
  170339. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  170340. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170341. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  170342. SIZEOF(large_pool_hdr));
  170343. if (hdr_ptr == NULL)
  170344. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  170345. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  170346. /* Success, initialize the new pool header and add to list */
  170347. hdr_ptr->hdr.next = mem->large_list[pool_id];
  170348. /* We maintain space counts in each pool header for statistical purposes,
  170349. * even though they are not needed for allocation.
  170350. */
  170351. hdr_ptr->hdr.bytes_used = sizeofobject;
  170352. hdr_ptr->hdr.bytes_left = 0;
  170353. mem->large_list[pool_id] = hdr_ptr;
  170354. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  170355. }
  170356. /*
  170357. * Creation of 2-D sample arrays.
  170358. * The pointers are in near heap, the samples themselves in FAR heap.
  170359. *
  170360. * To minimize allocation overhead and to allow I/O of large contiguous
  170361. * blocks, we allocate the sample rows in groups of as many rows as possible
  170362. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  170363. * NB: the virtual array control routines, later in this file, know about
  170364. * this chunking of rows. The rowsperchunk value is left in the mem manager
  170365. * object so that it can be saved away if this sarray is the workspace for
  170366. * a virtual array.
  170367. */
  170368. METHODDEF(JSAMPARRAY)
  170369. alloc_sarray (j_common_ptr cinfo, int pool_id,
  170370. JDIMENSION samplesperrow, JDIMENSION numrows)
  170371. /* Allocate a 2-D sample array */
  170372. {
  170373. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170374. JSAMPARRAY result;
  170375. JSAMPROW workspace;
  170376. JDIMENSION rowsperchunk, currow, i;
  170377. long ltemp;
  170378. /* Calculate max # of rows allowed in one allocation chunk */
  170379. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  170380. ((long) samplesperrow * SIZEOF(JSAMPLE));
  170381. if (ltemp <= 0)
  170382. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  170383. if (ltemp < (long) numrows)
  170384. rowsperchunk = (JDIMENSION) ltemp;
  170385. else
  170386. rowsperchunk = numrows;
  170387. mem->last_rowsperchunk = rowsperchunk;
  170388. /* Get space for row pointers (small object) */
  170389. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  170390. (size_t) (numrows * SIZEOF(JSAMPROW)));
  170391. /* Get the rows themselves (large objects) */
  170392. currow = 0;
  170393. while (currow < numrows) {
  170394. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  170395. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  170396. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  170397. * SIZEOF(JSAMPLE)));
  170398. for (i = rowsperchunk; i > 0; i--) {
  170399. result[currow++] = workspace;
  170400. workspace += samplesperrow;
  170401. }
  170402. }
  170403. return result;
  170404. }
  170405. /*
  170406. * Creation of 2-D coefficient-block arrays.
  170407. * This is essentially the same as the code for sample arrays, above.
  170408. */
  170409. METHODDEF(JBLOCKARRAY)
  170410. alloc_barray (j_common_ptr cinfo, int pool_id,
  170411. JDIMENSION blocksperrow, JDIMENSION numrows)
  170412. /* Allocate a 2-D coefficient-block array */
  170413. {
  170414. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170415. JBLOCKARRAY result;
  170416. JBLOCKROW workspace;
  170417. JDIMENSION rowsperchunk, currow, i;
  170418. long ltemp;
  170419. /* Calculate max # of rows allowed in one allocation chunk */
  170420. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  170421. ((long) blocksperrow * SIZEOF(JBLOCK));
  170422. if (ltemp <= 0)
  170423. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  170424. if (ltemp < (long) numrows)
  170425. rowsperchunk = (JDIMENSION) ltemp;
  170426. else
  170427. rowsperchunk = numrows;
  170428. mem->last_rowsperchunk = rowsperchunk;
  170429. /* Get space for row pointers (small object) */
  170430. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  170431. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  170432. /* Get the rows themselves (large objects) */
  170433. currow = 0;
  170434. while (currow < numrows) {
  170435. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  170436. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  170437. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  170438. * SIZEOF(JBLOCK)));
  170439. for (i = rowsperchunk; i > 0; i--) {
  170440. result[currow++] = workspace;
  170441. workspace += blocksperrow;
  170442. }
  170443. }
  170444. return result;
  170445. }
  170446. /*
  170447. * About virtual array management:
  170448. *
  170449. * The above "normal" array routines are only used to allocate strip buffers
  170450. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  170451. * are handled as "virtual" arrays. The array is still accessed a strip at a
  170452. * time, but the memory manager must save the whole array for repeated
  170453. * accesses. The intended implementation is that there is a strip buffer in
  170454. * memory (as high as is possible given the desired memory limit), plus a
  170455. * backing file that holds the rest of the array.
  170456. *
  170457. * The request_virt_array routines are told the total size of the image and
  170458. * the maximum number of rows that will be accessed at once. The in-memory
  170459. * buffer must be at least as large as the maxaccess value.
  170460. *
  170461. * The request routines create control blocks but not the in-memory buffers.
  170462. * That is postponed until realize_virt_arrays is called. At that time the
  170463. * total amount of space needed is known (approximately, anyway), so free
  170464. * memory can be divided up fairly.
  170465. *
  170466. * The access_virt_array routines are responsible for making a specific strip
  170467. * area accessible (after reading or writing the backing file, if necessary).
  170468. * Note that the access routines are told whether the caller intends to modify
  170469. * the accessed strip; during a read-only pass this saves having to rewrite
  170470. * data to disk. The access routines are also responsible for pre-zeroing
  170471. * any newly accessed rows, if pre-zeroing was requested.
  170472. *
  170473. * In current usage, the access requests are usually for nonoverlapping
  170474. * strips; that is, successive access start_row numbers differ by exactly
  170475. * num_rows = maxaccess. This means we can get good performance with simple
  170476. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  170477. * of the access height; then there will never be accesses across bufferload
  170478. * boundaries. The code will still work with overlapping access requests,
  170479. * but it doesn't handle bufferload overlaps very efficiently.
  170480. */
  170481. METHODDEF(jvirt_sarray_ptr)
  170482. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  170483. JDIMENSION samplesperrow, JDIMENSION numrows,
  170484. JDIMENSION maxaccess)
  170485. /* Request a virtual 2-D sample array */
  170486. {
  170487. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170488. jvirt_sarray_ptr result;
  170489. /* Only IMAGE-lifetime virtual arrays are currently supported */
  170490. if (pool_id != JPOOL_IMAGE)
  170491. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170492. /* get control block */
  170493. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  170494. SIZEOF(struct jvirt_sarray_control));
  170495. result->mem_buffer = NULL; /* marks array not yet realized */
  170496. result->rows_in_array = numrows;
  170497. result->samplesperrow = samplesperrow;
  170498. result->maxaccess = maxaccess;
  170499. result->pre_zero = pre_zero;
  170500. result->b_s_open = FALSE; /* no associated backing-store object */
  170501. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  170502. mem->virt_sarray_list = result;
  170503. return result;
  170504. }
  170505. METHODDEF(jvirt_barray_ptr)
  170506. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  170507. JDIMENSION blocksperrow, JDIMENSION numrows,
  170508. JDIMENSION maxaccess)
  170509. /* Request a virtual 2-D coefficient-block array */
  170510. {
  170511. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170512. jvirt_barray_ptr result;
  170513. /* Only IMAGE-lifetime virtual arrays are currently supported */
  170514. if (pool_id != JPOOL_IMAGE)
  170515. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170516. /* get control block */
  170517. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  170518. SIZEOF(struct jvirt_barray_control));
  170519. result->mem_buffer = NULL; /* marks array not yet realized */
  170520. result->rows_in_array = numrows;
  170521. result->blocksperrow = blocksperrow;
  170522. result->maxaccess = maxaccess;
  170523. result->pre_zero = pre_zero;
  170524. result->b_s_open = FALSE; /* no associated backing-store object */
  170525. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  170526. mem->virt_barray_list = result;
  170527. return result;
  170528. }
  170529. METHODDEF(void)
  170530. realize_virt_arrays (j_common_ptr cinfo)
  170531. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  170532. {
  170533. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170534. long space_per_minheight, maximum_space, avail_mem;
  170535. long minheights, max_minheights;
  170536. jvirt_sarray_ptr sptr;
  170537. jvirt_barray_ptr bptr;
  170538. /* Compute the minimum space needed (maxaccess rows in each buffer)
  170539. * and the maximum space needed (full image height in each buffer).
  170540. * These may be of use to the system-dependent jpeg_mem_available routine.
  170541. */
  170542. space_per_minheight = 0;
  170543. maximum_space = 0;
  170544. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  170545. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  170546. space_per_minheight += (long) sptr->maxaccess *
  170547. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  170548. maximum_space += (long) sptr->rows_in_array *
  170549. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  170550. }
  170551. }
  170552. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  170553. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  170554. space_per_minheight += (long) bptr->maxaccess *
  170555. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  170556. maximum_space += (long) bptr->rows_in_array *
  170557. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  170558. }
  170559. }
  170560. if (space_per_minheight <= 0)
  170561. return; /* no unrealized arrays, no work */
  170562. /* Determine amount of memory to actually use; this is system-dependent. */
  170563. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  170564. mem->total_space_allocated);
  170565. /* If the maximum space needed is available, make all the buffers full
  170566. * height; otherwise parcel it out with the same number of minheights
  170567. * in each buffer.
  170568. */
  170569. if (avail_mem >= maximum_space)
  170570. max_minheights = 1000000000L;
  170571. else {
  170572. max_minheights = avail_mem / space_per_minheight;
  170573. /* If there doesn't seem to be enough space, try to get the minimum
  170574. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  170575. */
  170576. if (max_minheights <= 0)
  170577. max_minheights = 1;
  170578. }
  170579. /* Allocate the in-memory buffers and initialize backing store as needed. */
  170580. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  170581. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  170582. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  170583. if (minheights <= max_minheights) {
  170584. /* This buffer fits in memory */
  170585. sptr->rows_in_mem = sptr->rows_in_array;
  170586. } else {
  170587. /* It doesn't fit in memory, create backing store. */
  170588. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  170589. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  170590. (long) sptr->rows_in_array *
  170591. (long) sptr->samplesperrow *
  170592. (long) SIZEOF(JSAMPLE));
  170593. sptr->b_s_open = TRUE;
  170594. }
  170595. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  170596. sptr->samplesperrow, sptr->rows_in_mem);
  170597. sptr->rowsperchunk = mem->last_rowsperchunk;
  170598. sptr->cur_start_row = 0;
  170599. sptr->first_undef_row = 0;
  170600. sptr->dirty = FALSE;
  170601. }
  170602. }
  170603. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  170604. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  170605. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  170606. if (minheights <= max_minheights) {
  170607. /* This buffer fits in memory */
  170608. bptr->rows_in_mem = bptr->rows_in_array;
  170609. } else {
  170610. /* It doesn't fit in memory, create backing store. */
  170611. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  170612. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  170613. (long) bptr->rows_in_array *
  170614. (long) bptr->blocksperrow *
  170615. (long) SIZEOF(JBLOCK));
  170616. bptr->b_s_open = TRUE;
  170617. }
  170618. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  170619. bptr->blocksperrow, bptr->rows_in_mem);
  170620. bptr->rowsperchunk = mem->last_rowsperchunk;
  170621. bptr->cur_start_row = 0;
  170622. bptr->first_undef_row = 0;
  170623. bptr->dirty = FALSE;
  170624. }
  170625. }
  170626. }
  170627. LOCAL(void)
  170628. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  170629. /* Do backing store read or write of a virtual sample array */
  170630. {
  170631. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  170632. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  170633. file_offset = ptr->cur_start_row * bytesperrow;
  170634. /* Loop to read or write each allocation chunk in mem_buffer */
  170635. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  170636. /* One chunk, but check for short chunk at end of buffer */
  170637. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  170638. /* Transfer no more than is currently defined */
  170639. thisrow = (long) ptr->cur_start_row + i;
  170640. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  170641. /* Transfer no more than fits in file */
  170642. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  170643. if (rows <= 0) /* this chunk might be past end of file! */
  170644. break;
  170645. byte_count = rows * bytesperrow;
  170646. if (writing)
  170647. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  170648. (void FAR *) ptr->mem_buffer[i],
  170649. file_offset, byte_count);
  170650. else
  170651. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  170652. (void FAR *) ptr->mem_buffer[i],
  170653. file_offset, byte_count);
  170654. file_offset += byte_count;
  170655. }
  170656. }
  170657. LOCAL(void)
  170658. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  170659. /* Do backing store read or write of a virtual coefficient-block array */
  170660. {
  170661. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  170662. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  170663. file_offset = ptr->cur_start_row * bytesperrow;
  170664. /* Loop to read or write each allocation chunk in mem_buffer */
  170665. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  170666. /* One chunk, but check for short chunk at end of buffer */
  170667. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  170668. /* Transfer no more than is currently defined */
  170669. thisrow = (long) ptr->cur_start_row + i;
  170670. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  170671. /* Transfer no more than fits in file */
  170672. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  170673. if (rows <= 0) /* this chunk might be past end of file! */
  170674. break;
  170675. byte_count = rows * bytesperrow;
  170676. if (writing)
  170677. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  170678. (void FAR *) ptr->mem_buffer[i],
  170679. file_offset, byte_count);
  170680. else
  170681. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  170682. (void FAR *) ptr->mem_buffer[i],
  170683. file_offset, byte_count);
  170684. file_offset += byte_count;
  170685. }
  170686. }
  170687. METHODDEF(JSAMPARRAY)
  170688. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  170689. JDIMENSION start_row, JDIMENSION num_rows,
  170690. boolean writable)
  170691. /* Access the part of a virtual sample array starting at start_row */
  170692. /* and extending for num_rows rows. writable is true if */
  170693. /* caller intends to modify the accessed area. */
  170694. {
  170695. JDIMENSION end_row = start_row + num_rows;
  170696. JDIMENSION undef_row;
  170697. /* debugging check */
  170698. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  170699. ptr->mem_buffer == NULL)
  170700. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170701. /* Make the desired part of the virtual array accessible */
  170702. if (start_row < ptr->cur_start_row ||
  170703. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  170704. if (! ptr->b_s_open)
  170705. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  170706. /* Flush old buffer contents if necessary */
  170707. if (ptr->dirty) {
  170708. do_sarray_io(cinfo, ptr, TRUE);
  170709. ptr->dirty = FALSE;
  170710. }
  170711. /* Decide what part of virtual array to access.
  170712. * Algorithm: if target address > current window, assume forward scan,
  170713. * load starting at target address. If target address < current window,
  170714. * assume backward scan, load so that target area is top of window.
  170715. * Note that when switching from forward write to forward read, will have
  170716. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  170717. */
  170718. if (start_row > ptr->cur_start_row) {
  170719. ptr->cur_start_row = start_row;
  170720. } else {
  170721. /* use long arithmetic here to avoid overflow & unsigned problems */
  170722. long ltemp;
  170723. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  170724. if (ltemp < 0)
  170725. ltemp = 0; /* don't fall off front end of file */
  170726. ptr->cur_start_row = (JDIMENSION) ltemp;
  170727. }
  170728. /* Read in the selected part of the array.
  170729. * During the initial write pass, we will do no actual read
  170730. * because the selected part is all undefined.
  170731. */
  170732. do_sarray_io(cinfo, ptr, FALSE);
  170733. }
  170734. /* Ensure the accessed part of the array is defined; prezero if needed.
  170735. * To improve locality of access, we only prezero the part of the array
  170736. * that the caller is about to access, not the entire in-memory array.
  170737. */
  170738. if (ptr->first_undef_row < end_row) {
  170739. if (ptr->first_undef_row < start_row) {
  170740. if (writable) /* writer skipped over a section of array */
  170741. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170742. undef_row = start_row; /* but reader is allowed to read ahead */
  170743. } else {
  170744. undef_row = ptr->first_undef_row;
  170745. }
  170746. if (writable)
  170747. ptr->first_undef_row = end_row;
  170748. if (ptr->pre_zero) {
  170749. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  170750. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  170751. end_row -= ptr->cur_start_row;
  170752. while (undef_row < end_row) {
  170753. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  170754. undef_row++;
  170755. }
  170756. } else {
  170757. if (! writable) /* reader looking at undefined data */
  170758. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170759. }
  170760. }
  170761. /* Flag the buffer dirty if caller will write in it */
  170762. if (writable)
  170763. ptr->dirty = TRUE;
  170764. /* Return address of proper part of the buffer */
  170765. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  170766. }
  170767. METHODDEF(JBLOCKARRAY)
  170768. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  170769. JDIMENSION start_row, JDIMENSION num_rows,
  170770. boolean writable)
  170771. /* Access the part of a virtual block array starting at start_row */
  170772. /* and extending for num_rows rows. writable is true if */
  170773. /* caller intends to modify the accessed area. */
  170774. {
  170775. JDIMENSION end_row = start_row + num_rows;
  170776. JDIMENSION undef_row;
  170777. /* debugging check */
  170778. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  170779. ptr->mem_buffer == NULL)
  170780. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170781. /* Make the desired part of the virtual array accessible */
  170782. if (start_row < ptr->cur_start_row ||
  170783. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  170784. if (! ptr->b_s_open)
  170785. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  170786. /* Flush old buffer contents if necessary */
  170787. if (ptr->dirty) {
  170788. do_barray_io(cinfo, ptr, TRUE);
  170789. ptr->dirty = FALSE;
  170790. }
  170791. /* Decide what part of virtual array to access.
  170792. * Algorithm: if target address > current window, assume forward scan,
  170793. * load starting at target address. If target address < current window,
  170794. * assume backward scan, load so that target area is top of window.
  170795. * Note that when switching from forward write to forward read, will have
  170796. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  170797. */
  170798. if (start_row > ptr->cur_start_row) {
  170799. ptr->cur_start_row = start_row;
  170800. } else {
  170801. /* use long arithmetic here to avoid overflow & unsigned problems */
  170802. long ltemp;
  170803. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  170804. if (ltemp < 0)
  170805. ltemp = 0; /* don't fall off front end of file */
  170806. ptr->cur_start_row = (JDIMENSION) ltemp;
  170807. }
  170808. /* Read in the selected part of the array.
  170809. * During the initial write pass, we will do no actual read
  170810. * because the selected part is all undefined.
  170811. */
  170812. do_barray_io(cinfo, ptr, FALSE);
  170813. }
  170814. /* Ensure the accessed part of the array is defined; prezero if needed.
  170815. * To improve locality of access, we only prezero the part of the array
  170816. * that the caller is about to access, not the entire in-memory array.
  170817. */
  170818. if (ptr->first_undef_row < end_row) {
  170819. if (ptr->first_undef_row < start_row) {
  170820. if (writable) /* writer skipped over a section of array */
  170821. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170822. undef_row = start_row; /* but reader is allowed to read ahead */
  170823. } else {
  170824. undef_row = ptr->first_undef_row;
  170825. }
  170826. if (writable)
  170827. ptr->first_undef_row = end_row;
  170828. if (ptr->pre_zero) {
  170829. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  170830. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  170831. end_row -= ptr->cur_start_row;
  170832. while (undef_row < end_row) {
  170833. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  170834. undef_row++;
  170835. }
  170836. } else {
  170837. if (! writable) /* reader looking at undefined data */
  170838. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170839. }
  170840. }
  170841. /* Flag the buffer dirty if caller will write in it */
  170842. if (writable)
  170843. ptr->dirty = TRUE;
  170844. /* Return address of proper part of the buffer */
  170845. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  170846. }
  170847. /*
  170848. * Release all objects belonging to a specified pool.
  170849. */
  170850. METHODDEF(void)
  170851. free_pool (j_common_ptr cinfo, int pool_id)
  170852. {
  170853. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170854. small_pool_ptr shdr_ptr;
  170855. large_pool_ptr lhdr_ptr;
  170856. size_t space_freed;
  170857. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  170858. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170859. #ifdef MEM_STATS
  170860. if (cinfo->err->trace_level > 1)
  170861. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  170862. #endif
  170863. /* If freeing IMAGE pool, close any virtual arrays first */
  170864. if (pool_id == JPOOL_IMAGE) {
  170865. jvirt_sarray_ptr sptr;
  170866. jvirt_barray_ptr bptr;
  170867. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  170868. if (sptr->b_s_open) { /* there may be no backing store */
  170869. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  170870. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  170871. }
  170872. }
  170873. mem->virt_sarray_list = NULL;
  170874. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  170875. if (bptr->b_s_open) { /* there may be no backing store */
  170876. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  170877. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  170878. }
  170879. }
  170880. mem->virt_barray_list = NULL;
  170881. }
  170882. /* Release large objects */
  170883. lhdr_ptr = mem->large_list[pool_id];
  170884. mem->large_list[pool_id] = NULL;
  170885. while (lhdr_ptr != NULL) {
  170886. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  170887. space_freed = lhdr_ptr->hdr.bytes_used +
  170888. lhdr_ptr->hdr.bytes_left +
  170889. SIZEOF(large_pool_hdr);
  170890. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  170891. mem->total_space_allocated -= space_freed;
  170892. lhdr_ptr = next_lhdr_ptr;
  170893. }
  170894. /* Release small objects */
  170895. shdr_ptr = mem->small_list[pool_id];
  170896. mem->small_list[pool_id] = NULL;
  170897. while (shdr_ptr != NULL) {
  170898. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  170899. space_freed = shdr_ptr->hdr.bytes_used +
  170900. shdr_ptr->hdr.bytes_left +
  170901. SIZEOF(small_pool_hdr);
  170902. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  170903. mem->total_space_allocated -= space_freed;
  170904. shdr_ptr = next_shdr_ptr;
  170905. }
  170906. }
  170907. /*
  170908. * Close up shop entirely.
  170909. * Note that this cannot be called unless cinfo->mem is non-NULL.
  170910. */
  170911. METHODDEF(void)
  170912. self_destruct (j_common_ptr cinfo)
  170913. {
  170914. int pool;
  170915. /* Close all backing store, release all memory.
  170916. * Releasing pools in reverse order might help avoid fragmentation
  170917. * with some (brain-damaged) malloc libraries.
  170918. */
  170919. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  170920. free_pool(cinfo, pool);
  170921. }
  170922. /* Release the memory manager control block too. */
  170923. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  170924. cinfo->mem = NULL; /* ensures I will be called only once */
  170925. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  170926. }
  170927. /*
  170928. * Memory manager initialization.
  170929. * When this is called, only the error manager pointer is valid in cinfo!
  170930. */
  170931. GLOBAL(void)
  170932. jinit_memory_mgr (j_common_ptr cinfo)
  170933. {
  170934. my_mem_ptr mem;
  170935. long max_to_use;
  170936. int pool;
  170937. size_t test_mac;
  170938. cinfo->mem = NULL; /* for safety if init fails */
  170939. /* Check for configuration errors.
  170940. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  170941. * doesn't reflect any real hardware alignment requirement.
  170942. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  170943. * in common if and only if X is a power of 2, ie has only one one-bit.
  170944. * Some compilers may give an "unreachable code" warning here; ignore it.
  170945. */
  170946. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  170947. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  170948. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  170949. * a multiple of SIZEOF(ALIGN_TYPE).
  170950. * Again, an "unreachable code" warning may be ignored here.
  170951. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  170952. */
  170953. test_mac = (size_t) MAX_ALLOC_CHUNK;
  170954. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  170955. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  170956. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  170957. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  170958. /* Attempt to allocate memory manager's control block */
  170959. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  170960. if (mem == NULL) {
  170961. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  170962. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  170963. }
  170964. /* OK, fill in the method pointers */
  170965. mem->pub.alloc_small = alloc_small;
  170966. mem->pub.alloc_large = alloc_large;
  170967. mem->pub.alloc_sarray = alloc_sarray;
  170968. mem->pub.alloc_barray = alloc_barray;
  170969. mem->pub.request_virt_sarray = request_virt_sarray;
  170970. mem->pub.request_virt_barray = request_virt_barray;
  170971. mem->pub.realize_virt_arrays = realize_virt_arrays;
  170972. mem->pub.access_virt_sarray = access_virt_sarray;
  170973. mem->pub.access_virt_barray = access_virt_barray;
  170974. mem->pub.free_pool = free_pool;
  170975. mem->pub.self_destruct = self_destruct;
  170976. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  170977. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  170978. /* Initialize working state */
  170979. mem->pub.max_memory_to_use = max_to_use;
  170980. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  170981. mem->small_list[pool] = NULL;
  170982. mem->large_list[pool] = NULL;
  170983. }
  170984. mem->virt_sarray_list = NULL;
  170985. mem->virt_barray_list = NULL;
  170986. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  170987. /* Declare ourselves open for business */
  170988. cinfo->mem = & mem->pub;
  170989. /* Check for an environment variable JPEGMEM; if found, override the
  170990. * default max_memory setting from jpeg_mem_init. Note that the
  170991. * surrounding application may again override this value.
  170992. * If your system doesn't support getenv(), define NO_GETENV to disable
  170993. * this feature.
  170994. */
  170995. #ifndef NO_GETENV
  170996. { char * memenv;
  170997. if ((memenv = getenv("JPEGMEM")) != NULL) {
  170998. char ch = 'x';
  170999. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  171000. if (ch == 'm' || ch == 'M')
  171001. max_to_use *= 1000L;
  171002. mem->pub.max_memory_to_use = max_to_use * 1000L;
  171003. }
  171004. }
  171005. }
  171006. #endif
  171007. }
  171008. /********* End of inlined file: jmemmgr.c *********/
  171009. /********* Start of inlined file: jmemnobs.c *********/
  171010. #define JPEG_INTERNALS
  171011. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  171012. extern void * malloc JPP((size_t size));
  171013. extern void free JPP((void *ptr));
  171014. #endif
  171015. /*
  171016. * Memory allocation and freeing are controlled by the regular library
  171017. * routines malloc() and free().
  171018. */
  171019. GLOBAL(void *)
  171020. jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
  171021. {
  171022. return (void *) malloc(sizeofobject);
  171023. }
  171024. GLOBAL(void)
  171025. jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
  171026. {
  171027. free(object);
  171028. }
  171029. /*
  171030. * "Large" objects are treated the same as "small" ones.
  171031. * NB: although we include FAR keywords in the routine declarations,
  171032. * this file won't actually work in 80x86 small/medium model; at least,
  171033. * you probably won't be able to process useful-size images in only 64KB.
  171034. */
  171035. GLOBAL(void FAR *)
  171036. jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
  171037. {
  171038. return (void FAR *) malloc(sizeofobject);
  171039. }
  171040. GLOBAL(void)
  171041. jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
  171042. {
  171043. free(object);
  171044. }
  171045. /*
  171046. * This routine computes the total memory space available for allocation.
  171047. * Here we always say, "we got all you want bud!"
  171048. */
  171049. GLOBAL(long)
  171050. jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
  171051. long max_bytes_needed, long already_allocated)
  171052. {
  171053. return max_bytes_needed;
  171054. }
  171055. /*
  171056. * Backing store (temporary file) management.
  171057. * Since jpeg_mem_available always promised the moon,
  171058. * this should never be called and we can just error out.
  171059. */
  171060. GLOBAL(void)
  171061. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *info,
  171062. long total_bytes_needed)
  171063. {
  171064. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  171065. }
  171066. /*
  171067. * These routines take care of any system-dependent initialization and
  171068. * cleanup required. Here, there isn't any.
  171069. */
  171070. GLOBAL(long)
  171071. jpeg_mem_init (j_common_ptr cinfo)
  171072. {
  171073. return 0; /* just set max_memory_to_use to 0 */
  171074. }
  171075. GLOBAL(void)
  171076. jpeg_mem_term (j_common_ptr cinfo)
  171077. {
  171078. /* no work */
  171079. }
  171080. /********* End of inlined file: jmemnobs.c *********/
  171081. /********* Start of inlined file: jquant1.c *********/
  171082. #define JPEG_INTERNALS
  171083. #ifdef QUANT_1PASS_SUPPORTED
  171084. /*
  171085. * The main purpose of 1-pass quantization is to provide a fast, if not very
  171086. * high quality, colormapped output capability. A 2-pass quantizer usually
  171087. * gives better visual quality; however, for quantized grayscale output this
  171088. * quantizer is perfectly adequate. Dithering is highly recommended with this
  171089. * quantizer, though you can turn it off if you really want to.
  171090. *
  171091. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  171092. * image. We use a map consisting of all combinations of Ncolors[i] color
  171093. * values for the i'th component. The Ncolors[] values are chosen so that
  171094. * their product, the total number of colors, is no more than that requested.
  171095. * (In most cases, the product will be somewhat less.)
  171096. *
  171097. * Since the colormap is orthogonal, the representative value for each color
  171098. * component can be determined without considering the other components;
  171099. * then these indexes can be combined into a colormap index by a standard
  171100. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  171101. * can be precalculated and stored in the lookup table colorindex[].
  171102. * colorindex[i][j] maps pixel value j in component i to the nearest
  171103. * representative value (grid plane) for that component; this index is
  171104. * multiplied by the array stride for component i, so that the
  171105. * index of the colormap entry closest to a given pixel value is just
  171106. * sum( colorindex[component-number][pixel-component-value] )
  171107. * Aside from being fast, this scheme allows for variable spacing between
  171108. * representative values with no additional lookup cost.
  171109. *
  171110. * If gamma correction has been applied in color conversion, it might be wise
  171111. * to adjust the color grid spacing so that the representative colors are
  171112. * equidistant in linear space. At this writing, gamma correction is not
  171113. * implemented by jdcolor, so nothing is done here.
  171114. */
  171115. /* Declarations for ordered dithering.
  171116. *
  171117. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  171118. * dithering is described in many references, for instance Dale Schumacher's
  171119. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  171120. * In place of Schumacher's comparisons against a "threshold" value, we add a
  171121. * "dither" value to the input pixel and then round the result to the nearest
  171122. * output value. The dither value is equivalent to (0.5 - threshold) times
  171123. * the distance between output values. For ordered dithering, we assume that
  171124. * the output colors are equally spaced; if not, results will probably be
  171125. * worse, since the dither may be too much or too little at a given point.
  171126. *
  171127. * The normal calculation would be to form pixel value + dither, range-limit
  171128. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  171129. * We can skip the separate range-limiting step by extending the colorindex
  171130. * table in both directions.
  171131. */
  171132. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  171133. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  171134. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  171135. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  171136. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  171137. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  171138. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  171139. /* Bayer's order-4 dither array. Generated by the code given in
  171140. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  171141. * The values in this array must range from 0 to ODITHER_CELLS-1.
  171142. */
  171143. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  171144. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  171145. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  171146. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  171147. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  171148. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  171149. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  171150. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  171151. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  171152. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  171153. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  171154. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  171155. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  171156. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  171157. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  171158. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  171159. };
  171160. /* Declarations for Floyd-Steinberg dithering.
  171161. *
  171162. * Errors are accumulated into the array fserrors[], at a resolution of
  171163. * 1/16th of a pixel count. The error at a given pixel is propagated
  171164. * to its not-yet-processed neighbors using the standard F-S fractions,
  171165. * ... (here) 7/16
  171166. * 3/16 5/16 1/16
  171167. * We work left-to-right on even rows, right-to-left on odd rows.
  171168. *
  171169. * We can get away with a single array (holding one row's worth of errors)
  171170. * by using it to store the current row's errors at pixel columns not yet
  171171. * processed, but the next row's errors at columns already processed. We
  171172. * need only a few extra variables to hold the errors immediately around the
  171173. * current column. (If we are lucky, those variables are in registers, but
  171174. * even if not, they're probably cheaper to access than array elements are.)
  171175. *
  171176. * The fserrors[] array is indexed [component#][position].
  171177. * We provide (#columns + 2) entries per component; the extra entry at each
  171178. * end saves us from special-casing the first and last pixels.
  171179. *
  171180. * Note: on a wide image, we might not have enough room in a PC's near data
  171181. * segment to hold the error array; so it is allocated with alloc_large.
  171182. */
  171183. #if BITS_IN_JSAMPLE == 8
  171184. typedef INT16 FSERROR; /* 16 bits should be enough */
  171185. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  171186. #else
  171187. typedef INT32 FSERROR; /* may need more than 16 bits */
  171188. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  171189. #endif
  171190. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  171191. /* Private subobject */
  171192. #define MAX_Q_COMPS 4 /* max components I can handle */
  171193. typedef struct {
  171194. struct jpeg_color_quantizer pub; /* public fields */
  171195. /* Initially allocated colormap is saved here */
  171196. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  171197. int sv_actual; /* number of entries in use */
  171198. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  171199. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  171200. * premultiplied as described above. Since colormap indexes must fit into
  171201. * JSAMPLEs, the entries of this array will too.
  171202. */
  171203. boolean is_padded; /* is the colorindex padded for odither? */
  171204. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  171205. /* Variables for ordered dithering */
  171206. int row_index; /* cur row's vertical index in dither matrix */
  171207. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  171208. /* Variables for Floyd-Steinberg dithering */
  171209. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  171210. boolean on_odd_row; /* flag to remember which row we are on */
  171211. } my_cquantizer;
  171212. typedef my_cquantizer * my_cquantize_ptr;
  171213. /*
  171214. * Policy-making subroutines for create_colormap and create_colorindex.
  171215. * These routines determine the colormap to be used. The rest of the module
  171216. * only assumes that the colormap is orthogonal.
  171217. *
  171218. * * select_ncolors decides how to divvy up the available colors
  171219. * among the components.
  171220. * * output_value defines the set of representative values for a component.
  171221. * * largest_input_value defines the mapping from input values to
  171222. * representative values for a component.
  171223. * Note that the latter two routines may impose different policies for
  171224. * different components, though this is not currently done.
  171225. */
  171226. LOCAL(int)
  171227. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  171228. /* Determine allocation of desired colors to components, */
  171229. /* and fill in Ncolors[] array to indicate choice. */
  171230. /* Return value is total number of colors (product of Ncolors[] values). */
  171231. {
  171232. int nc = cinfo->out_color_components; /* number of color components */
  171233. int max_colors = cinfo->desired_number_of_colors;
  171234. int total_colors, iroot, i, j;
  171235. boolean changed;
  171236. long temp;
  171237. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  171238. /* We can allocate at least the nc'th root of max_colors per component. */
  171239. /* Compute floor(nc'th root of max_colors). */
  171240. iroot = 1;
  171241. do {
  171242. iroot++;
  171243. temp = iroot; /* set temp = iroot ** nc */
  171244. for (i = 1; i < nc; i++)
  171245. temp *= iroot;
  171246. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  171247. iroot--; /* now iroot = floor(root) */
  171248. /* Must have at least 2 color values per component */
  171249. if (iroot < 2)
  171250. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  171251. /* Initialize to iroot color values for each component */
  171252. total_colors = 1;
  171253. for (i = 0; i < nc; i++) {
  171254. Ncolors[i] = iroot;
  171255. total_colors *= iroot;
  171256. }
  171257. /* We may be able to increment the count for one or more components without
  171258. * exceeding max_colors, though we know not all can be incremented.
  171259. * Sometimes, the first component can be incremented more than once!
  171260. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  171261. * In RGB colorspace, try to increment G first, then R, then B.
  171262. */
  171263. do {
  171264. changed = FALSE;
  171265. for (i = 0; i < nc; i++) {
  171266. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  171267. /* calculate new total_colors if Ncolors[j] is incremented */
  171268. temp = total_colors / Ncolors[j];
  171269. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  171270. if (temp > (long) max_colors)
  171271. break; /* won't fit, done with this pass */
  171272. Ncolors[j]++; /* OK, apply the increment */
  171273. total_colors = (int) temp;
  171274. changed = TRUE;
  171275. }
  171276. } while (changed);
  171277. return total_colors;
  171278. }
  171279. LOCAL(int)
  171280. output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  171281. /* Return j'th output value, where j will range from 0 to maxj */
  171282. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  171283. {
  171284. /* We always provide values 0 and MAXJSAMPLE for each component;
  171285. * any additional values are equally spaced between these limits.
  171286. * (Forcing the upper and lower values to the limits ensures that
  171287. * dithering can't produce a color outside the selected gamut.)
  171288. */
  171289. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  171290. }
  171291. LOCAL(int)
  171292. largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  171293. /* Return largest input value that should map to j'th output value */
  171294. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  171295. {
  171296. /* Breakpoints are halfway between values returned by output_value */
  171297. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  171298. }
  171299. /*
  171300. * Create the colormap.
  171301. */
  171302. LOCAL(void)
  171303. create_colormap (j_decompress_ptr cinfo)
  171304. {
  171305. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171306. JSAMPARRAY colormap; /* Created colormap */
  171307. int total_colors; /* Number of distinct output colors */
  171308. int i,j,k, nci, blksize, blkdist, ptr, val;
  171309. /* Select number of colors for each component */
  171310. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  171311. /* Report selected color counts */
  171312. if (cinfo->out_color_components == 3)
  171313. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  171314. total_colors, cquantize->Ncolors[0],
  171315. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  171316. else
  171317. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  171318. /* Allocate and fill in the colormap. */
  171319. /* The colors are ordered in the map in standard row-major order, */
  171320. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  171321. colormap = (*cinfo->mem->alloc_sarray)
  171322. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171323. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  171324. /* blksize is number of adjacent repeated entries for a component */
  171325. /* blkdist is distance between groups of identical entries for a component */
  171326. blkdist = total_colors;
  171327. for (i = 0; i < cinfo->out_color_components; i++) {
  171328. /* fill in colormap entries for i'th color component */
  171329. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  171330. blksize = blkdist / nci;
  171331. for (j = 0; j < nci; j++) {
  171332. /* Compute j'th output value (out of nci) for component */
  171333. val = output_value(cinfo, i, j, nci-1);
  171334. /* Fill in all colormap entries that have this value of this component */
  171335. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  171336. /* fill in blksize entries beginning at ptr */
  171337. for (k = 0; k < blksize; k++)
  171338. colormap[i][ptr+k] = (JSAMPLE) val;
  171339. }
  171340. }
  171341. blkdist = blksize; /* blksize of this color is blkdist of next */
  171342. }
  171343. /* Save the colormap in private storage,
  171344. * where it will survive color quantization mode changes.
  171345. */
  171346. cquantize->sv_colormap = colormap;
  171347. cquantize->sv_actual = total_colors;
  171348. }
  171349. /*
  171350. * Create the color index table.
  171351. */
  171352. LOCAL(void)
  171353. create_colorindex (j_decompress_ptr cinfo)
  171354. {
  171355. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171356. JSAMPROW indexptr;
  171357. int i,j,k, nci, blksize, val, pad;
  171358. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  171359. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  171360. * This is not necessary in the other dithering modes. However, we
  171361. * flag whether it was done in case user changes dithering mode.
  171362. */
  171363. if (cinfo->dither_mode == JDITHER_ORDERED) {
  171364. pad = MAXJSAMPLE*2;
  171365. cquantize->is_padded = TRUE;
  171366. } else {
  171367. pad = 0;
  171368. cquantize->is_padded = FALSE;
  171369. }
  171370. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  171371. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171372. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  171373. (JDIMENSION) cinfo->out_color_components);
  171374. /* blksize is number of adjacent repeated entries for a component */
  171375. blksize = cquantize->sv_actual;
  171376. for (i = 0; i < cinfo->out_color_components; i++) {
  171377. /* fill in colorindex entries for i'th color component */
  171378. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  171379. blksize = blksize / nci;
  171380. /* adjust colorindex pointers to provide padding at negative indexes. */
  171381. if (pad)
  171382. cquantize->colorindex[i] += MAXJSAMPLE;
  171383. /* in loop, val = index of current output value, */
  171384. /* and k = largest j that maps to current val */
  171385. indexptr = cquantize->colorindex[i];
  171386. val = 0;
  171387. k = largest_input_value(cinfo, i, 0, nci-1);
  171388. for (j = 0; j <= MAXJSAMPLE; j++) {
  171389. while (j > k) /* advance val if past boundary */
  171390. k = largest_input_value(cinfo, i, ++val, nci-1);
  171391. /* premultiply so that no multiplication needed in main processing */
  171392. indexptr[j] = (JSAMPLE) (val * blksize);
  171393. }
  171394. /* Pad at both ends if necessary */
  171395. if (pad)
  171396. for (j = 1; j <= MAXJSAMPLE; j++) {
  171397. indexptr[-j] = indexptr[0];
  171398. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  171399. }
  171400. }
  171401. }
  171402. /*
  171403. * Create an ordered-dither array for a component having ncolors
  171404. * distinct output values.
  171405. */
  171406. LOCAL(ODITHER_MATRIX_PTR)
  171407. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  171408. {
  171409. ODITHER_MATRIX_PTR odither;
  171410. int j,k;
  171411. INT32 num,den;
  171412. odither = (ODITHER_MATRIX_PTR)
  171413. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171414. SIZEOF(ODITHER_MATRIX));
  171415. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  171416. * Hence the dither value for the matrix cell with fill order f
  171417. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  171418. * On 16-bit-int machine, be careful to avoid overflow.
  171419. */
  171420. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  171421. for (j = 0; j < ODITHER_SIZE; j++) {
  171422. for (k = 0; k < ODITHER_SIZE; k++) {
  171423. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  171424. * MAXJSAMPLE;
  171425. /* Ensure round towards zero despite C's lack of consistency
  171426. * about rounding negative values in integer division...
  171427. */
  171428. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  171429. }
  171430. }
  171431. return odither;
  171432. }
  171433. /*
  171434. * Create the ordered-dither tables.
  171435. * Components having the same number of representative colors may
  171436. * share a dither table.
  171437. */
  171438. LOCAL(void)
  171439. create_odither_tables (j_decompress_ptr cinfo)
  171440. {
  171441. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171442. ODITHER_MATRIX_PTR odither;
  171443. int i, j, nci;
  171444. for (i = 0; i < cinfo->out_color_components; i++) {
  171445. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  171446. odither = NULL; /* search for matching prior component */
  171447. for (j = 0; j < i; j++) {
  171448. if (nci == cquantize->Ncolors[j]) {
  171449. odither = cquantize->odither[j];
  171450. break;
  171451. }
  171452. }
  171453. if (odither == NULL) /* need a new table? */
  171454. odither = make_odither_array(cinfo, nci);
  171455. cquantize->odither[i] = odither;
  171456. }
  171457. }
  171458. /*
  171459. * Map some rows of pixels to the output colormapped representation.
  171460. */
  171461. METHODDEF(void)
  171462. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171463. JSAMPARRAY output_buf, int num_rows)
  171464. /* General case, no dithering */
  171465. {
  171466. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171467. JSAMPARRAY colorindex = cquantize->colorindex;
  171468. register int pixcode, ci;
  171469. register JSAMPROW ptrin, ptrout;
  171470. int row;
  171471. JDIMENSION col;
  171472. JDIMENSION width = cinfo->output_width;
  171473. register int nc = cinfo->out_color_components;
  171474. for (row = 0; row < num_rows; row++) {
  171475. ptrin = input_buf[row];
  171476. ptrout = output_buf[row];
  171477. for (col = width; col > 0; col--) {
  171478. pixcode = 0;
  171479. for (ci = 0; ci < nc; ci++) {
  171480. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  171481. }
  171482. *ptrout++ = (JSAMPLE) pixcode;
  171483. }
  171484. }
  171485. }
  171486. METHODDEF(void)
  171487. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171488. JSAMPARRAY output_buf, int num_rows)
  171489. /* Fast path for out_color_components==3, no dithering */
  171490. {
  171491. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171492. register int pixcode;
  171493. register JSAMPROW ptrin, ptrout;
  171494. JSAMPROW colorindex0 = cquantize->colorindex[0];
  171495. JSAMPROW colorindex1 = cquantize->colorindex[1];
  171496. JSAMPROW colorindex2 = cquantize->colorindex[2];
  171497. int row;
  171498. JDIMENSION col;
  171499. JDIMENSION width = cinfo->output_width;
  171500. for (row = 0; row < num_rows; row++) {
  171501. ptrin = input_buf[row];
  171502. ptrout = output_buf[row];
  171503. for (col = width; col > 0; col--) {
  171504. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  171505. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  171506. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  171507. *ptrout++ = (JSAMPLE) pixcode;
  171508. }
  171509. }
  171510. }
  171511. METHODDEF(void)
  171512. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171513. JSAMPARRAY output_buf, int num_rows)
  171514. /* General case, with ordered dithering */
  171515. {
  171516. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171517. register JSAMPROW input_ptr;
  171518. register JSAMPROW output_ptr;
  171519. JSAMPROW colorindex_ci;
  171520. int * dither; /* points to active row of dither matrix */
  171521. int row_index, col_index; /* current indexes into dither matrix */
  171522. int nc = cinfo->out_color_components;
  171523. int ci;
  171524. int row;
  171525. JDIMENSION col;
  171526. JDIMENSION width = cinfo->output_width;
  171527. for (row = 0; row < num_rows; row++) {
  171528. /* Initialize output values to 0 so can process components separately */
  171529. jzero_far((void FAR *) output_buf[row],
  171530. (size_t) (width * SIZEOF(JSAMPLE)));
  171531. row_index = cquantize->row_index;
  171532. for (ci = 0; ci < nc; ci++) {
  171533. input_ptr = input_buf[row] + ci;
  171534. output_ptr = output_buf[row];
  171535. colorindex_ci = cquantize->colorindex[ci];
  171536. dither = cquantize->odither[ci][row_index];
  171537. col_index = 0;
  171538. for (col = width; col > 0; col--) {
  171539. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  171540. * select output value, accumulate into output code for this pixel.
  171541. * Range-limiting need not be done explicitly, as we have extended
  171542. * the colorindex table to produce the right answers for out-of-range
  171543. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  171544. * required amount of padding.
  171545. */
  171546. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  171547. input_ptr += nc;
  171548. output_ptr++;
  171549. col_index = (col_index + 1) & ODITHER_MASK;
  171550. }
  171551. }
  171552. /* Advance row index for next row */
  171553. row_index = (row_index + 1) & ODITHER_MASK;
  171554. cquantize->row_index = row_index;
  171555. }
  171556. }
  171557. METHODDEF(void)
  171558. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171559. JSAMPARRAY output_buf, int num_rows)
  171560. /* Fast path for out_color_components==3, with ordered dithering */
  171561. {
  171562. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171563. register int pixcode;
  171564. register JSAMPROW input_ptr;
  171565. register JSAMPROW output_ptr;
  171566. JSAMPROW colorindex0 = cquantize->colorindex[0];
  171567. JSAMPROW colorindex1 = cquantize->colorindex[1];
  171568. JSAMPROW colorindex2 = cquantize->colorindex[2];
  171569. int * dither0; /* points to active row of dither matrix */
  171570. int * dither1;
  171571. int * dither2;
  171572. int row_index, col_index; /* current indexes into dither matrix */
  171573. int row;
  171574. JDIMENSION col;
  171575. JDIMENSION width = cinfo->output_width;
  171576. for (row = 0; row < num_rows; row++) {
  171577. row_index = cquantize->row_index;
  171578. input_ptr = input_buf[row];
  171579. output_ptr = output_buf[row];
  171580. dither0 = cquantize->odither[0][row_index];
  171581. dither1 = cquantize->odither[1][row_index];
  171582. dither2 = cquantize->odither[2][row_index];
  171583. col_index = 0;
  171584. for (col = width; col > 0; col--) {
  171585. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  171586. dither0[col_index]]);
  171587. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  171588. dither1[col_index]]);
  171589. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  171590. dither2[col_index]]);
  171591. *output_ptr++ = (JSAMPLE) pixcode;
  171592. col_index = (col_index + 1) & ODITHER_MASK;
  171593. }
  171594. row_index = (row_index + 1) & ODITHER_MASK;
  171595. cquantize->row_index = row_index;
  171596. }
  171597. }
  171598. METHODDEF(void)
  171599. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171600. JSAMPARRAY output_buf, int num_rows)
  171601. /* General case, with Floyd-Steinberg dithering */
  171602. {
  171603. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171604. register LOCFSERROR cur; /* current error or pixel value */
  171605. LOCFSERROR belowerr; /* error for pixel below cur */
  171606. LOCFSERROR bpreverr; /* error for below/prev col */
  171607. LOCFSERROR bnexterr; /* error for below/next col */
  171608. LOCFSERROR delta;
  171609. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  171610. register JSAMPROW input_ptr;
  171611. register JSAMPROW output_ptr;
  171612. JSAMPROW colorindex_ci;
  171613. JSAMPROW colormap_ci;
  171614. int pixcode;
  171615. int nc = cinfo->out_color_components;
  171616. int dir; /* 1 for left-to-right, -1 for right-to-left */
  171617. int dirnc; /* dir * nc */
  171618. int ci;
  171619. int row;
  171620. JDIMENSION col;
  171621. JDIMENSION width = cinfo->output_width;
  171622. JSAMPLE *range_limit = cinfo->sample_range_limit;
  171623. SHIFT_TEMPS
  171624. for (row = 0; row < num_rows; row++) {
  171625. /* Initialize output values to 0 so can process components separately */
  171626. jzero_far((void FAR *) output_buf[row],
  171627. (size_t) (width * SIZEOF(JSAMPLE)));
  171628. for (ci = 0; ci < nc; ci++) {
  171629. input_ptr = input_buf[row] + ci;
  171630. output_ptr = output_buf[row];
  171631. if (cquantize->on_odd_row) {
  171632. /* work right to left in this row */
  171633. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  171634. output_ptr += width-1;
  171635. dir = -1;
  171636. dirnc = -nc;
  171637. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  171638. } else {
  171639. /* work left to right in this row */
  171640. dir = 1;
  171641. dirnc = nc;
  171642. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  171643. }
  171644. colorindex_ci = cquantize->colorindex[ci];
  171645. colormap_ci = cquantize->sv_colormap[ci];
  171646. /* Preset error values: no error propagated to first pixel from left */
  171647. cur = 0;
  171648. /* and no error propagated to row below yet */
  171649. belowerr = bpreverr = 0;
  171650. for (col = width; col > 0; col--) {
  171651. /* cur holds the error propagated from the previous pixel on the
  171652. * current line. Add the error propagated from the previous line
  171653. * to form the complete error correction term for this pixel, and
  171654. * round the error term (which is expressed * 16) to an integer.
  171655. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  171656. * for either sign of the error value.
  171657. * Note: errorptr points to *previous* column's array entry.
  171658. */
  171659. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  171660. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  171661. * The maximum error is +- MAXJSAMPLE; this sets the required size
  171662. * of the range_limit array.
  171663. */
  171664. cur += GETJSAMPLE(*input_ptr);
  171665. cur = GETJSAMPLE(range_limit[cur]);
  171666. /* Select output value, accumulate into output code for this pixel */
  171667. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  171668. *output_ptr += (JSAMPLE) pixcode;
  171669. /* Compute actual representation error at this pixel */
  171670. /* Note: we can do this even though we don't have the final */
  171671. /* pixel code, because the colormap is orthogonal. */
  171672. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  171673. /* Compute error fractions to be propagated to adjacent pixels.
  171674. * Add these into the running sums, and simultaneously shift the
  171675. * next-line error sums left by 1 column.
  171676. */
  171677. bnexterr = cur;
  171678. delta = cur * 2;
  171679. cur += delta; /* form error * 3 */
  171680. errorptr[0] = (FSERROR) (bpreverr + cur);
  171681. cur += delta; /* form error * 5 */
  171682. bpreverr = belowerr + cur;
  171683. belowerr = bnexterr;
  171684. cur += delta; /* form error * 7 */
  171685. /* At this point cur contains the 7/16 error value to be propagated
  171686. * to the next pixel on the current line, and all the errors for the
  171687. * next line have been shifted over. We are therefore ready to move on.
  171688. */
  171689. input_ptr += dirnc; /* advance input ptr to next column */
  171690. output_ptr += dir; /* advance output ptr to next column */
  171691. errorptr += dir; /* advance errorptr to current column */
  171692. }
  171693. /* Post-loop cleanup: we must unload the final error value into the
  171694. * final fserrors[] entry. Note we need not unload belowerr because
  171695. * it is for the dummy column before or after the actual array.
  171696. */
  171697. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  171698. }
  171699. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  171700. }
  171701. }
  171702. /*
  171703. * Allocate workspace for Floyd-Steinberg errors.
  171704. */
  171705. LOCAL(void)
  171706. alloc_fs_workspace (j_decompress_ptr cinfo)
  171707. {
  171708. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171709. size_t arraysize;
  171710. int i;
  171711. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  171712. for (i = 0; i < cinfo->out_color_components; i++) {
  171713. cquantize->fserrors[i] = (FSERRPTR)
  171714. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  171715. }
  171716. }
  171717. /*
  171718. * Initialize for one-pass color quantization.
  171719. */
  171720. METHODDEF(void)
  171721. start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  171722. {
  171723. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  171724. size_t arraysize;
  171725. int i;
  171726. /* Install my colormap. */
  171727. cinfo->colormap = cquantize->sv_colormap;
  171728. cinfo->actual_number_of_colors = cquantize->sv_actual;
  171729. /* Initialize for desired dithering mode. */
  171730. switch (cinfo->dither_mode) {
  171731. case JDITHER_NONE:
  171732. if (cinfo->out_color_components == 3)
  171733. cquantize->pub.color_quantize = color_quantize3;
  171734. else
  171735. cquantize->pub.color_quantize = color_quantize;
  171736. break;
  171737. case JDITHER_ORDERED:
  171738. if (cinfo->out_color_components == 3)
  171739. cquantize->pub.color_quantize = quantize3_ord_dither;
  171740. else
  171741. cquantize->pub.color_quantize = quantize_ord_dither;
  171742. cquantize->row_index = 0; /* initialize state for ordered dither */
  171743. /* If user changed to ordered dither from another mode,
  171744. * we must recreate the color index table with padding.
  171745. * This will cost extra space, but probably isn't very likely.
  171746. */
  171747. if (! cquantize->is_padded)
  171748. create_colorindex(cinfo);
  171749. /* Create ordered-dither tables if we didn't already. */
  171750. if (cquantize->odither[0] == NULL)
  171751. create_odither_tables(cinfo);
  171752. break;
  171753. case JDITHER_FS:
  171754. cquantize->pub.color_quantize = quantize_fs_dither;
  171755. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  171756. /* Allocate Floyd-Steinberg workspace if didn't already. */
  171757. if (cquantize->fserrors[0] == NULL)
  171758. alloc_fs_workspace(cinfo);
  171759. /* Initialize the propagated errors to zero. */
  171760. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  171761. for (i = 0; i < cinfo->out_color_components; i++)
  171762. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  171763. break;
  171764. default:
  171765. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171766. break;
  171767. }
  171768. }
  171769. /*
  171770. * Finish up at the end of the pass.
  171771. */
  171772. METHODDEF(void)
  171773. finish_pass_1_quant (j_decompress_ptr cinfo)
  171774. {
  171775. /* no work in 1-pass case */
  171776. }
  171777. /*
  171778. * Switch to a new external colormap between output passes.
  171779. * Shouldn't get to this module!
  171780. */
  171781. METHODDEF(void)
  171782. new_color_map_1_quant (j_decompress_ptr cinfo)
  171783. {
  171784. ERREXIT(cinfo, JERR_MODE_CHANGE);
  171785. }
  171786. /*
  171787. * Module initialization routine for 1-pass color quantization.
  171788. */
  171789. GLOBAL(void)
  171790. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  171791. {
  171792. my_cquantize_ptr cquantize;
  171793. cquantize = (my_cquantize_ptr)
  171794. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171795. SIZEOF(my_cquantizer));
  171796. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  171797. cquantize->pub.start_pass = start_pass_1_quant;
  171798. cquantize->pub.finish_pass = finish_pass_1_quant;
  171799. cquantize->pub.new_color_map = new_color_map_1_quant;
  171800. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  171801. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  171802. /* Make sure my internal arrays won't overflow */
  171803. if (cinfo->out_color_components > MAX_Q_COMPS)
  171804. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  171805. /* Make sure colormap indexes can be represented by JSAMPLEs */
  171806. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  171807. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  171808. /* Create the colormap and color index table. */
  171809. create_colormap(cinfo);
  171810. create_colorindex(cinfo);
  171811. /* Allocate Floyd-Steinberg workspace now if requested.
  171812. * We do this now since it is FAR storage and may affect the memory
  171813. * manager's space calculations. If the user changes to FS dither
  171814. * mode in a later pass, we will allocate the space then, and will
  171815. * possibly overrun the max_memory_to_use setting.
  171816. */
  171817. if (cinfo->dither_mode == JDITHER_FS)
  171818. alloc_fs_workspace(cinfo);
  171819. }
  171820. #endif /* QUANT_1PASS_SUPPORTED */
  171821. /********* End of inlined file: jquant1.c *********/
  171822. /********* Start of inlined file: jquant2.c *********/
  171823. #define JPEG_INTERNALS
  171824. #ifdef QUANT_2PASS_SUPPORTED
  171825. /*
  171826. * This module implements the well-known Heckbert paradigm for color
  171827. * quantization. Most of the ideas used here can be traced back to
  171828. * Heckbert's seminal paper
  171829. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  171830. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  171831. *
  171832. * In the first pass over the image, we accumulate a histogram showing the
  171833. * usage count of each possible color. To keep the histogram to a reasonable
  171834. * size, we reduce the precision of the input; typical practice is to retain
  171835. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  171836. * in the same histogram cell.
  171837. *
  171838. * Next, the color-selection step begins with a box representing the whole
  171839. * color space, and repeatedly splits the "largest" remaining box until we
  171840. * have as many boxes as desired colors. Then the mean color in each
  171841. * remaining box becomes one of the possible output colors.
  171842. *
  171843. * The second pass over the image maps each input pixel to the closest output
  171844. * color (optionally after applying a Floyd-Steinberg dithering correction).
  171845. * This mapping is logically trivial, but making it go fast enough requires
  171846. * considerable care.
  171847. *
  171848. * Heckbert-style quantizers vary a good deal in their policies for choosing
  171849. * the "largest" box and deciding where to cut it. The particular policies
  171850. * used here have proved out well in experimental comparisons, but better ones
  171851. * may yet be found.
  171852. *
  171853. * In earlier versions of the IJG code, this module quantized in YCbCr color
  171854. * space, processing the raw upsampled data without a color conversion step.
  171855. * This allowed the color conversion math to be done only once per colormap
  171856. * entry, not once per pixel. However, that optimization precluded other
  171857. * useful optimizations (such as merging color conversion with upsampling)
  171858. * and it also interfered with desired capabilities such as quantizing to an
  171859. * externally-supplied colormap. We have therefore abandoned that approach.
  171860. * The present code works in the post-conversion color space, typically RGB.
  171861. *
  171862. * To improve the visual quality of the results, we actually work in scaled
  171863. * RGB space, giving G distances more weight than R, and R in turn more than
  171864. * B. To do everything in integer math, we must use integer scale factors.
  171865. * The 2/3/1 scale factors used here correspond loosely to the relative
  171866. * weights of the colors in the NTSC grayscale equation.
  171867. * If you want to use this code to quantize a non-RGB color space, you'll
  171868. * probably need to change these scale factors.
  171869. */
  171870. #define R_SCALE 2 /* scale R distances by this much */
  171871. #define G_SCALE 3 /* scale G distances by this much */
  171872. #define B_SCALE 1 /* and B by this much */
  171873. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  171874. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  171875. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  171876. * you'll get compile errors until you extend this logic. In that case
  171877. * you'll probably want to tweak the histogram sizes too.
  171878. */
  171879. #if RGB_RED == 0
  171880. #define C0_SCALE R_SCALE
  171881. #endif
  171882. #if RGB_BLUE == 0
  171883. #define C0_SCALE B_SCALE
  171884. #endif
  171885. #if RGB_GREEN == 1
  171886. #define C1_SCALE G_SCALE
  171887. #endif
  171888. #if RGB_RED == 2
  171889. #define C2_SCALE R_SCALE
  171890. #endif
  171891. #if RGB_BLUE == 2
  171892. #define C2_SCALE B_SCALE
  171893. #endif
  171894. /*
  171895. * First we have the histogram data structure and routines for creating it.
  171896. *
  171897. * The number of bits of precision can be adjusted by changing these symbols.
  171898. * We recommend keeping 6 bits for G and 5 each for R and B.
  171899. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  171900. * better results; if you are short of memory, 5 bits all around will save
  171901. * some space but degrade the results.
  171902. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  171903. * (preferably unsigned long) for each cell. In practice this is overkill;
  171904. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  171905. * and clamping those that do overflow to the maximum value will give close-
  171906. * enough results. This reduces the recommended histogram size from 256Kb
  171907. * to 128Kb, which is a useful savings on PC-class machines.
  171908. * (In the second pass the histogram space is re-used for pixel mapping data;
  171909. * in that capacity, each cell must be able to store zero to the number of
  171910. * desired colors. 16 bits/cell is plenty for that too.)
  171911. * Since the JPEG code is intended to run in small memory model on 80x86
  171912. * machines, we can't just allocate the histogram in one chunk. Instead
  171913. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  171914. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  171915. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  171916. * on 80x86 machines, the pointer row is in near memory but the actual
  171917. * arrays are in far memory (same arrangement as we use for image arrays).
  171918. */
  171919. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  171920. /* These will do the right thing for either R,G,B or B,G,R color order,
  171921. * but you may not like the results for other color orders.
  171922. */
  171923. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  171924. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  171925. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  171926. /* Number of elements along histogram axes. */
  171927. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  171928. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  171929. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  171930. /* These are the amounts to shift an input value to get a histogram index. */
  171931. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  171932. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  171933. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  171934. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  171935. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  171936. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  171937. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  171938. typedef hist2d * hist3d; /* type for top-level pointer */
  171939. /* Declarations for Floyd-Steinberg dithering.
  171940. *
  171941. * Errors are accumulated into the array fserrors[], at a resolution of
  171942. * 1/16th of a pixel count. The error at a given pixel is propagated
  171943. * to its not-yet-processed neighbors using the standard F-S fractions,
  171944. * ... (here) 7/16
  171945. * 3/16 5/16 1/16
  171946. * We work left-to-right on even rows, right-to-left on odd rows.
  171947. *
  171948. * We can get away with a single array (holding one row's worth of errors)
  171949. * by using it to store the current row's errors at pixel columns not yet
  171950. * processed, but the next row's errors at columns already processed. We
  171951. * need only a few extra variables to hold the errors immediately around the
  171952. * current column. (If we are lucky, those variables are in registers, but
  171953. * even if not, they're probably cheaper to access than array elements are.)
  171954. *
  171955. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  171956. * each end saves us from special-casing the first and last pixels.
  171957. * Each entry is three values long, one value for each color component.
  171958. *
  171959. * Note: on a wide image, we might not have enough room in a PC's near data
  171960. * segment to hold the error array; so it is allocated with alloc_large.
  171961. */
  171962. #if BITS_IN_JSAMPLE == 8
  171963. typedef INT16 FSERROR; /* 16 bits should be enough */
  171964. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  171965. #else
  171966. typedef INT32 FSERROR; /* may need more than 16 bits */
  171967. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  171968. #endif
  171969. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  171970. /* Private subobject */
  171971. typedef struct {
  171972. struct jpeg_color_quantizer pub; /* public fields */
  171973. /* Space for the eventually created colormap is stashed here */
  171974. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  171975. int desired; /* desired # of colors = size of colormap */
  171976. /* Variables for accumulating image statistics */
  171977. hist3d histogram; /* pointer to the histogram */
  171978. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  171979. /* Variables for Floyd-Steinberg dithering */
  171980. FSERRPTR fserrors; /* accumulated errors */
  171981. boolean on_odd_row; /* flag to remember which row we are on */
  171982. int * error_limiter; /* table for clamping the applied error */
  171983. } my_cquantizer2;
  171984. typedef my_cquantizer2 * my_cquantize_ptr2;
  171985. /*
  171986. * Prescan some rows of pixels.
  171987. * In this module the prescan simply updates the histogram, which has been
  171988. * initialized to zeroes by start_pass.
  171989. * An output_buf parameter is required by the method signature, but no data
  171990. * is actually output (in fact the buffer controller is probably passing a
  171991. * NULL pointer).
  171992. */
  171993. METHODDEF(void)
  171994. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171995. JSAMPARRAY output_buf, int num_rows)
  171996. {
  171997. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171998. register JSAMPROW ptr;
  171999. register histptr histp;
  172000. register hist3d histogram = cquantize->histogram;
  172001. int row;
  172002. JDIMENSION col;
  172003. JDIMENSION width = cinfo->output_width;
  172004. for (row = 0; row < num_rows; row++) {
  172005. ptr = input_buf[row];
  172006. for (col = width; col > 0; col--) {
  172007. /* get pixel value and index into the histogram */
  172008. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  172009. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  172010. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  172011. /* increment, check for overflow and undo increment if so. */
  172012. if (++(*histp) <= 0)
  172013. (*histp)--;
  172014. ptr += 3;
  172015. }
  172016. }
  172017. }
  172018. /*
  172019. * Next we have the really interesting routines: selection of a colormap
  172020. * given the completed histogram.
  172021. * These routines work with a list of "boxes", each representing a rectangular
  172022. * subset of the input color space (to histogram precision).
  172023. */
  172024. typedef struct {
  172025. /* The bounds of the box (inclusive); expressed as histogram indexes */
  172026. int c0min, c0max;
  172027. int c1min, c1max;
  172028. int c2min, c2max;
  172029. /* The volume (actually 2-norm) of the box */
  172030. INT32 volume;
  172031. /* The number of nonzero histogram cells within this box */
  172032. long colorcount;
  172033. } box;
  172034. typedef box * boxptr;
  172035. LOCAL(boxptr)
  172036. find_biggest_color_pop (boxptr boxlist, int numboxes)
  172037. /* Find the splittable box with the largest color population */
  172038. /* Returns NULL if no splittable boxes remain */
  172039. {
  172040. register boxptr boxp;
  172041. register int i;
  172042. register long maxc = 0;
  172043. boxptr which = NULL;
  172044. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  172045. if (boxp->colorcount > maxc && boxp->volume > 0) {
  172046. which = boxp;
  172047. maxc = boxp->colorcount;
  172048. }
  172049. }
  172050. return which;
  172051. }
  172052. LOCAL(boxptr)
  172053. find_biggest_volume (boxptr boxlist, int numboxes)
  172054. /* Find the splittable box with the largest (scaled) volume */
  172055. /* Returns NULL if no splittable boxes remain */
  172056. {
  172057. register boxptr boxp;
  172058. register int i;
  172059. register INT32 maxv = 0;
  172060. boxptr which = NULL;
  172061. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  172062. if (boxp->volume > maxv) {
  172063. which = boxp;
  172064. maxv = boxp->volume;
  172065. }
  172066. }
  172067. return which;
  172068. }
  172069. LOCAL(void)
  172070. update_box (j_decompress_ptr cinfo, boxptr boxp)
  172071. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  172072. /* and recompute its volume and population */
  172073. {
  172074. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172075. hist3d histogram = cquantize->histogram;
  172076. histptr histp;
  172077. int c0,c1,c2;
  172078. int c0min,c0max,c1min,c1max,c2min,c2max;
  172079. INT32 dist0,dist1,dist2;
  172080. long ccount;
  172081. c0min = boxp->c0min; c0max = boxp->c0max;
  172082. c1min = boxp->c1min; c1max = boxp->c1max;
  172083. c2min = boxp->c2min; c2max = boxp->c2max;
  172084. if (c0max > c0min)
  172085. for (c0 = c0min; c0 <= c0max; c0++)
  172086. for (c1 = c1min; c1 <= c1max; c1++) {
  172087. histp = & histogram[c0][c1][c2min];
  172088. for (c2 = c2min; c2 <= c2max; c2++)
  172089. if (*histp++ != 0) {
  172090. boxp->c0min = c0min = c0;
  172091. goto have_c0min;
  172092. }
  172093. }
  172094. have_c0min:
  172095. if (c0max > c0min)
  172096. for (c0 = c0max; c0 >= c0min; c0--)
  172097. for (c1 = c1min; c1 <= c1max; c1++) {
  172098. histp = & histogram[c0][c1][c2min];
  172099. for (c2 = c2min; c2 <= c2max; c2++)
  172100. if (*histp++ != 0) {
  172101. boxp->c0max = c0max = c0;
  172102. goto have_c0max;
  172103. }
  172104. }
  172105. have_c0max:
  172106. if (c1max > c1min)
  172107. for (c1 = c1min; c1 <= c1max; c1++)
  172108. for (c0 = c0min; c0 <= c0max; c0++) {
  172109. histp = & histogram[c0][c1][c2min];
  172110. for (c2 = c2min; c2 <= c2max; c2++)
  172111. if (*histp++ != 0) {
  172112. boxp->c1min = c1min = c1;
  172113. goto have_c1min;
  172114. }
  172115. }
  172116. have_c1min:
  172117. if (c1max > c1min)
  172118. for (c1 = c1max; c1 >= c1min; c1--)
  172119. for (c0 = c0min; c0 <= c0max; c0++) {
  172120. histp = & histogram[c0][c1][c2min];
  172121. for (c2 = c2min; c2 <= c2max; c2++)
  172122. if (*histp++ != 0) {
  172123. boxp->c1max = c1max = c1;
  172124. goto have_c1max;
  172125. }
  172126. }
  172127. have_c1max:
  172128. if (c2max > c2min)
  172129. for (c2 = c2min; c2 <= c2max; c2++)
  172130. for (c0 = c0min; c0 <= c0max; c0++) {
  172131. histp = & histogram[c0][c1min][c2];
  172132. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  172133. if (*histp != 0) {
  172134. boxp->c2min = c2min = c2;
  172135. goto have_c2min;
  172136. }
  172137. }
  172138. have_c2min:
  172139. if (c2max > c2min)
  172140. for (c2 = c2max; c2 >= c2min; c2--)
  172141. for (c0 = c0min; c0 <= c0max; c0++) {
  172142. histp = & histogram[c0][c1min][c2];
  172143. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  172144. if (*histp != 0) {
  172145. boxp->c2max = c2max = c2;
  172146. goto have_c2max;
  172147. }
  172148. }
  172149. have_c2max:
  172150. /* Update box volume.
  172151. * We use 2-norm rather than real volume here; this biases the method
  172152. * against making long narrow boxes, and it has the side benefit that
  172153. * a box is splittable iff norm > 0.
  172154. * Since the differences are expressed in histogram-cell units,
  172155. * we have to shift back to JSAMPLE units to get consistent distances;
  172156. * after which, we scale according to the selected distance scale factors.
  172157. */
  172158. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  172159. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  172160. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  172161. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  172162. /* Now scan remaining volume of box and compute population */
  172163. ccount = 0;
  172164. for (c0 = c0min; c0 <= c0max; c0++)
  172165. for (c1 = c1min; c1 <= c1max; c1++) {
  172166. histp = & histogram[c0][c1][c2min];
  172167. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  172168. if (*histp != 0) {
  172169. ccount++;
  172170. }
  172171. }
  172172. boxp->colorcount = ccount;
  172173. }
  172174. LOCAL(int)
  172175. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  172176. int desired_colors)
  172177. /* Repeatedly select and split the largest box until we have enough boxes */
  172178. {
  172179. int n,lb;
  172180. int c0,c1,c2,cmax;
  172181. register boxptr b1,b2;
  172182. while (numboxes < desired_colors) {
  172183. /* Select box to split.
  172184. * Current algorithm: by population for first half, then by volume.
  172185. */
  172186. if (numboxes*2 <= desired_colors) {
  172187. b1 = find_biggest_color_pop(boxlist, numboxes);
  172188. } else {
  172189. b1 = find_biggest_volume(boxlist, numboxes);
  172190. }
  172191. if (b1 == NULL) /* no splittable boxes left! */
  172192. break;
  172193. b2 = &boxlist[numboxes]; /* where new box will go */
  172194. /* Copy the color bounds to the new box. */
  172195. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  172196. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  172197. /* Choose which axis to split the box on.
  172198. * Current algorithm: longest scaled axis.
  172199. * See notes in update_box about scaling distances.
  172200. */
  172201. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  172202. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  172203. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  172204. /* We want to break any ties in favor of green, then red, blue last.
  172205. * This code does the right thing for R,G,B or B,G,R color orders only.
  172206. */
  172207. #if RGB_RED == 0
  172208. cmax = c1; n = 1;
  172209. if (c0 > cmax) { cmax = c0; n = 0; }
  172210. if (c2 > cmax) { n = 2; }
  172211. #else
  172212. cmax = c1; n = 1;
  172213. if (c2 > cmax) { cmax = c2; n = 2; }
  172214. if (c0 > cmax) { n = 0; }
  172215. #endif
  172216. /* Choose split point along selected axis, and update box bounds.
  172217. * Current algorithm: split at halfway point.
  172218. * (Since the box has been shrunk to minimum volume,
  172219. * any split will produce two nonempty subboxes.)
  172220. * Note that lb value is max for lower box, so must be < old max.
  172221. */
  172222. switch (n) {
  172223. case 0:
  172224. lb = (b1->c0max + b1->c0min) / 2;
  172225. b1->c0max = lb;
  172226. b2->c0min = lb+1;
  172227. break;
  172228. case 1:
  172229. lb = (b1->c1max + b1->c1min) / 2;
  172230. b1->c1max = lb;
  172231. b2->c1min = lb+1;
  172232. break;
  172233. case 2:
  172234. lb = (b1->c2max + b1->c2min) / 2;
  172235. b1->c2max = lb;
  172236. b2->c2min = lb+1;
  172237. break;
  172238. }
  172239. /* Update stats for boxes */
  172240. update_box(cinfo, b1);
  172241. update_box(cinfo, b2);
  172242. numboxes++;
  172243. }
  172244. return numboxes;
  172245. }
  172246. LOCAL(void)
  172247. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  172248. /* Compute representative color for a box, put it in colormap[icolor] */
  172249. {
  172250. /* Current algorithm: mean weighted by pixels (not colors) */
  172251. /* Note it is important to get the rounding correct! */
  172252. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172253. hist3d histogram = cquantize->histogram;
  172254. histptr histp;
  172255. int c0,c1,c2;
  172256. int c0min,c0max,c1min,c1max,c2min,c2max;
  172257. long count;
  172258. long total = 0;
  172259. long c0total = 0;
  172260. long c1total = 0;
  172261. long c2total = 0;
  172262. c0min = boxp->c0min; c0max = boxp->c0max;
  172263. c1min = boxp->c1min; c1max = boxp->c1max;
  172264. c2min = boxp->c2min; c2max = boxp->c2max;
  172265. for (c0 = c0min; c0 <= c0max; c0++)
  172266. for (c1 = c1min; c1 <= c1max; c1++) {
  172267. histp = & histogram[c0][c1][c2min];
  172268. for (c2 = c2min; c2 <= c2max; c2++) {
  172269. if ((count = *histp++) != 0) {
  172270. total += count;
  172271. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  172272. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  172273. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  172274. }
  172275. }
  172276. }
  172277. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  172278. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  172279. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  172280. }
  172281. LOCAL(void)
  172282. select_colors (j_decompress_ptr cinfo, int desired_colors)
  172283. /* Master routine for color selection */
  172284. {
  172285. boxptr boxlist;
  172286. int numboxes;
  172287. int i;
  172288. /* Allocate workspace for box list */
  172289. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  172290. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  172291. /* Initialize one box containing whole space */
  172292. numboxes = 1;
  172293. boxlist[0].c0min = 0;
  172294. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  172295. boxlist[0].c1min = 0;
  172296. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  172297. boxlist[0].c2min = 0;
  172298. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  172299. /* Shrink it to actually-used volume and set its statistics */
  172300. update_box(cinfo, & boxlist[0]);
  172301. /* Perform median-cut to produce final box list */
  172302. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  172303. /* Compute the representative color for each box, fill colormap */
  172304. for (i = 0; i < numboxes; i++)
  172305. compute_color(cinfo, & boxlist[i], i);
  172306. cinfo->actual_number_of_colors = numboxes;
  172307. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  172308. }
  172309. /*
  172310. * These routines are concerned with the time-critical task of mapping input
  172311. * colors to the nearest color in the selected colormap.
  172312. *
  172313. * We re-use the histogram space as an "inverse color map", essentially a
  172314. * cache for the results of nearest-color searches. All colors within a
  172315. * histogram cell will be mapped to the same colormap entry, namely the one
  172316. * closest to the cell's center. This may not be quite the closest entry to
  172317. * the actual input color, but it's almost as good. A zero in the cache
  172318. * indicates we haven't found the nearest color for that cell yet; the array
  172319. * is cleared to zeroes before starting the mapping pass. When we find the
  172320. * nearest color for a cell, its colormap index plus one is recorded in the
  172321. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  172322. * when they need to use an unfilled entry in the cache.
  172323. *
  172324. * Our method of efficiently finding nearest colors is based on the "locally
  172325. * sorted search" idea described by Heckbert and on the incremental distance
  172326. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  172327. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  172328. * the distances from a given colormap entry to each cell of the histogram can
  172329. * be computed quickly using an incremental method: the differences between
  172330. * distances to adjacent cells themselves differ by a constant. This allows a
  172331. * fairly fast implementation of the "brute force" approach of computing the
  172332. * distance from every colormap entry to every histogram cell. Unfortunately,
  172333. * it needs a work array to hold the best-distance-so-far for each histogram
  172334. * cell (because the inner loop has to be over cells, not colormap entries).
  172335. * The work array elements have to be INT32s, so the work array would need
  172336. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  172337. *
  172338. * To get around these problems, we apply Thomas' method to compute the
  172339. * nearest colors for only the cells within a small subbox of the histogram.
  172340. * The work array need be only as big as the subbox, so the memory usage
  172341. * problem is solved. Furthermore, we need not fill subboxes that are never
  172342. * referenced in pass2; many images use only part of the color gamut, so a
  172343. * fair amount of work is saved. An additional advantage of this
  172344. * approach is that we can apply Heckbert's locality criterion to quickly
  172345. * eliminate colormap entries that are far away from the subbox; typically
  172346. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  172347. * and we need not compute their distances to individual cells in the subbox.
  172348. * The speed of this approach is heavily influenced by the subbox size: too
  172349. * small means too much overhead, too big loses because Heckbert's criterion
  172350. * can't eliminate as many colormap entries. Empirically the best subbox
  172351. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  172352. *
  172353. * Thomas' article also describes a refined method which is asymptotically
  172354. * faster than the brute-force method, but it is also far more complex and
  172355. * cannot efficiently be applied to small subboxes. It is therefore not
  172356. * useful for programs intended to be portable to DOS machines. On machines
  172357. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  172358. * refined method might be faster than the present code --- but then again,
  172359. * it might not be any faster, and it's certainly more complicated.
  172360. */
  172361. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  172362. #define BOX_C0_LOG (HIST_C0_BITS-3)
  172363. #define BOX_C1_LOG (HIST_C1_BITS-3)
  172364. #define BOX_C2_LOG (HIST_C2_BITS-3)
  172365. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  172366. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  172367. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  172368. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  172369. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  172370. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  172371. /*
  172372. * The next three routines implement inverse colormap filling. They could
  172373. * all be folded into one big routine, but splitting them up this way saves
  172374. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  172375. * and may allow some compilers to produce better code by registerizing more
  172376. * inner-loop variables.
  172377. */
  172378. LOCAL(int)
  172379. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  172380. JSAMPLE colorlist[])
  172381. /* Locate the colormap entries close enough to an update box to be candidates
  172382. * for the nearest entry to some cell(s) in the update box. The update box
  172383. * is specified by the center coordinates of its first cell. The number of
  172384. * candidate colormap entries is returned, and their colormap indexes are
  172385. * placed in colorlist[].
  172386. * This routine uses Heckbert's "locally sorted search" criterion to select
  172387. * the colors that need further consideration.
  172388. */
  172389. {
  172390. int numcolors = cinfo->actual_number_of_colors;
  172391. int maxc0, maxc1, maxc2;
  172392. int centerc0, centerc1, centerc2;
  172393. int i, x, ncolors;
  172394. INT32 minmaxdist, min_dist, max_dist, tdist;
  172395. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  172396. /* Compute true coordinates of update box's upper corner and center.
  172397. * Actually we compute the coordinates of the center of the upper-corner
  172398. * histogram cell, which are the upper bounds of the volume we care about.
  172399. * Note that since ">>" rounds down, the "center" values may be closer to
  172400. * min than to max; hence comparisons to them must be "<=", not "<".
  172401. */
  172402. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  172403. centerc0 = (minc0 + maxc0) >> 1;
  172404. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  172405. centerc1 = (minc1 + maxc1) >> 1;
  172406. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  172407. centerc2 = (minc2 + maxc2) >> 1;
  172408. /* For each color in colormap, find:
  172409. * 1. its minimum squared-distance to any point in the update box
  172410. * (zero if color is within update box);
  172411. * 2. its maximum squared-distance to any point in the update box.
  172412. * Both of these can be found by considering only the corners of the box.
  172413. * We save the minimum distance for each color in mindist[];
  172414. * only the smallest maximum distance is of interest.
  172415. */
  172416. minmaxdist = 0x7FFFFFFFL;
  172417. for (i = 0; i < numcolors; i++) {
  172418. /* We compute the squared-c0-distance term, then add in the other two. */
  172419. x = GETJSAMPLE(cinfo->colormap[0][i]);
  172420. if (x < minc0) {
  172421. tdist = (x - minc0) * C0_SCALE;
  172422. min_dist = tdist*tdist;
  172423. tdist = (x - maxc0) * C0_SCALE;
  172424. max_dist = tdist*tdist;
  172425. } else if (x > maxc0) {
  172426. tdist = (x - maxc0) * C0_SCALE;
  172427. min_dist = tdist*tdist;
  172428. tdist = (x - minc0) * C0_SCALE;
  172429. max_dist = tdist*tdist;
  172430. } else {
  172431. /* within cell range so no contribution to min_dist */
  172432. min_dist = 0;
  172433. if (x <= centerc0) {
  172434. tdist = (x - maxc0) * C0_SCALE;
  172435. max_dist = tdist*tdist;
  172436. } else {
  172437. tdist = (x - minc0) * C0_SCALE;
  172438. max_dist = tdist*tdist;
  172439. }
  172440. }
  172441. x = GETJSAMPLE(cinfo->colormap[1][i]);
  172442. if (x < minc1) {
  172443. tdist = (x - minc1) * C1_SCALE;
  172444. min_dist += tdist*tdist;
  172445. tdist = (x - maxc1) * C1_SCALE;
  172446. max_dist += tdist*tdist;
  172447. } else if (x > maxc1) {
  172448. tdist = (x - maxc1) * C1_SCALE;
  172449. min_dist += tdist*tdist;
  172450. tdist = (x - minc1) * C1_SCALE;
  172451. max_dist += tdist*tdist;
  172452. } else {
  172453. /* within cell range so no contribution to min_dist */
  172454. if (x <= centerc1) {
  172455. tdist = (x - maxc1) * C1_SCALE;
  172456. max_dist += tdist*tdist;
  172457. } else {
  172458. tdist = (x - minc1) * C1_SCALE;
  172459. max_dist += tdist*tdist;
  172460. }
  172461. }
  172462. x = GETJSAMPLE(cinfo->colormap[2][i]);
  172463. if (x < minc2) {
  172464. tdist = (x - minc2) * C2_SCALE;
  172465. min_dist += tdist*tdist;
  172466. tdist = (x - maxc2) * C2_SCALE;
  172467. max_dist += tdist*tdist;
  172468. } else if (x > maxc2) {
  172469. tdist = (x - maxc2) * C2_SCALE;
  172470. min_dist += tdist*tdist;
  172471. tdist = (x - minc2) * C2_SCALE;
  172472. max_dist += tdist*tdist;
  172473. } else {
  172474. /* within cell range so no contribution to min_dist */
  172475. if (x <= centerc2) {
  172476. tdist = (x - maxc2) * C2_SCALE;
  172477. max_dist += tdist*tdist;
  172478. } else {
  172479. tdist = (x - minc2) * C2_SCALE;
  172480. max_dist += tdist*tdist;
  172481. }
  172482. }
  172483. mindist[i] = min_dist; /* save away the results */
  172484. if (max_dist < minmaxdist)
  172485. minmaxdist = max_dist;
  172486. }
  172487. /* Now we know that no cell in the update box is more than minmaxdist
  172488. * away from some colormap entry. Therefore, only colors that are
  172489. * within minmaxdist of some part of the box need be considered.
  172490. */
  172491. ncolors = 0;
  172492. for (i = 0; i < numcolors; i++) {
  172493. if (mindist[i] <= minmaxdist)
  172494. colorlist[ncolors++] = (JSAMPLE) i;
  172495. }
  172496. return ncolors;
  172497. }
  172498. LOCAL(void)
  172499. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  172500. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  172501. /* Find the closest colormap entry for each cell in the update box,
  172502. * given the list of candidate colors prepared by find_nearby_colors.
  172503. * Return the indexes of the closest entries in the bestcolor[] array.
  172504. * This routine uses Thomas' incremental distance calculation method to
  172505. * find the distance from a colormap entry to successive cells in the box.
  172506. */
  172507. {
  172508. int ic0, ic1, ic2;
  172509. int i, icolor;
  172510. register INT32 * bptr; /* pointer into bestdist[] array */
  172511. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  172512. INT32 dist0, dist1; /* initial distance values */
  172513. register INT32 dist2; /* current distance in inner loop */
  172514. INT32 xx0, xx1; /* distance increments */
  172515. register INT32 xx2;
  172516. INT32 inc0, inc1, inc2; /* initial values for increments */
  172517. /* This array holds the distance to the nearest-so-far color for each cell */
  172518. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  172519. /* Initialize best-distance for each cell of the update box */
  172520. bptr = bestdist;
  172521. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  172522. *bptr++ = 0x7FFFFFFFL;
  172523. /* For each color selected by find_nearby_colors,
  172524. * compute its distance to the center of each cell in the box.
  172525. * If that's less than best-so-far, update best distance and color number.
  172526. */
  172527. /* Nominal steps between cell centers ("x" in Thomas article) */
  172528. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  172529. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  172530. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  172531. for (i = 0; i < numcolors; i++) {
  172532. icolor = GETJSAMPLE(colorlist[i]);
  172533. /* Compute (square of) distance from minc0/c1/c2 to this color */
  172534. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  172535. dist0 = inc0*inc0;
  172536. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  172537. dist0 += inc1*inc1;
  172538. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  172539. dist0 += inc2*inc2;
  172540. /* Form the initial difference increments */
  172541. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  172542. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  172543. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  172544. /* Now loop over all cells in box, updating distance per Thomas method */
  172545. bptr = bestdist;
  172546. cptr = bestcolor;
  172547. xx0 = inc0;
  172548. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  172549. dist1 = dist0;
  172550. xx1 = inc1;
  172551. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  172552. dist2 = dist1;
  172553. xx2 = inc2;
  172554. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  172555. if (dist2 < *bptr) {
  172556. *bptr = dist2;
  172557. *cptr = (JSAMPLE) icolor;
  172558. }
  172559. dist2 += xx2;
  172560. xx2 += 2 * STEP_C2 * STEP_C2;
  172561. bptr++;
  172562. cptr++;
  172563. }
  172564. dist1 += xx1;
  172565. xx1 += 2 * STEP_C1 * STEP_C1;
  172566. }
  172567. dist0 += xx0;
  172568. xx0 += 2 * STEP_C0 * STEP_C0;
  172569. }
  172570. }
  172571. }
  172572. LOCAL(void)
  172573. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  172574. /* Fill the inverse-colormap entries in the update box that contains */
  172575. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  172576. /* we can fill as many others as we wish.) */
  172577. {
  172578. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172579. hist3d histogram = cquantize->histogram;
  172580. int minc0, minc1, minc2; /* lower left corner of update box */
  172581. int ic0, ic1, ic2;
  172582. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  172583. register histptr cachep; /* pointer into main cache array */
  172584. /* This array lists the candidate colormap indexes. */
  172585. JSAMPLE colorlist[MAXNUMCOLORS];
  172586. int numcolors; /* number of candidate colors */
  172587. /* This array holds the actually closest colormap index for each cell. */
  172588. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  172589. /* Convert cell coordinates to update box ID */
  172590. c0 >>= BOX_C0_LOG;
  172591. c1 >>= BOX_C1_LOG;
  172592. c2 >>= BOX_C2_LOG;
  172593. /* Compute true coordinates of update box's origin corner.
  172594. * Actually we compute the coordinates of the center of the corner
  172595. * histogram cell, which are the lower bounds of the volume we care about.
  172596. */
  172597. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  172598. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  172599. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  172600. /* Determine which colormap entries are close enough to be candidates
  172601. * for the nearest entry to some cell in the update box.
  172602. */
  172603. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  172604. /* Determine the actually nearest colors. */
  172605. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  172606. bestcolor);
  172607. /* Save the best color numbers (plus 1) in the main cache array */
  172608. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  172609. c1 <<= BOX_C1_LOG;
  172610. c2 <<= BOX_C2_LOG;
  172611. cptr = bestcolor;
  172612. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  172613. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  172614. cachep = & histogram[c0+ic0][c1+ic1][c2];
  172615. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  172616. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  172617. }
  172618. }
  172619. }
  172620. }
  172621. /*
  172622. * Map some rows of pixels to the output colormapped representation.
  172623. */
  172624. METHODDEF(void)
  172625. pass2_no_dither (j_decompress_ptr cinfo,
  172626. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  172627. /* This version performs no dithering */
  172628. {
  172629. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172630. hist3d histogram = cquantize->histogram;
  172631. register JSAMPROW inptr, outptr;
  172632. register histptr cachep;
  172633. register int c0, c1, c2;
  172634. int row;
  172635. JDIMENSION col;
  172636. JDIMENSION width = cinfo->output_width;
  172637. for (row = 0; row < num_rows; row++) {
  172638. inptr = input_buf[row];
  172639. outptr = output_buf[row];
  172640. for (col = width; col > 0; col--) {
  172641. /* get pixel value and index into the cache */
  172642. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  172643. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  172644. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  172645. cachep = & histogram[c0][c1][c2];
  172646. /* If we have not seen this color before, find nearest colormap entry */
  172647. /* and update the cache */
  172648. if (*cachep == 0)
  172649. fill_inverse_cmap(cinfo, c0,c1,c2);
  172650. /* Now emit the colormap index for this cell */
  172651. *outptr++ = (JSAMPLE) (*cachep - 1);
  172652. }
  172653. }
  172654. }
  172655. METHODDEF(void)
  172656. pass2_fs_dither (j_decompress_ptr cinfo,
  172657. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  172658. /* This version performs Floyd-Steinberg dithering */
  172659. {
  172660. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172661. hist3d histogram = cquantize->histogram;
  172662. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  172663. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  172664. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  172665. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  172666. JSAMPROW inptr; /* => current input pixel */
  172667. JSAMPROW outptr; /* => current output pixel */
  172668. histptr cachep;
  172669. int dir; /* +1 or -1 depending on direction */
  172670. int dir3; /* 3*dir, for advancing inptr & errorptr */
  172671. int row;
  172672. JDIMENSION col;
  172673. JDIMENSION width = cinfo->output_width;
  172674. JSAMPLE *range_limit = cinfo->sample_range_limit;
  172675. int *error_limit = cquantize->error_limiter;
  172676. JSAMPROW colormap0 = cinfo->colormap[0];
  172677. JSAMPROW colormap1 = cinfo->colormap[1];
  172678. JSAMPROW colormap2 = cinfo->colormap[2];
  172679. SHIFT_TEMPS
  172680. for (row = 0; row < num_rows; row++) {
  172681. inptr = input_buf[row];
  172682. outptr = output_buf[row];
  172683. if (cquantize->on_odd_row) {
  172684. /* work right to left in this row */
  172685. inptr += (width-1) * 3; /* so point to rightmost pixel */
  172686. outptr += width-1;
  172687. dir = -1;
  172688. dir3 = -3;
  172689. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  172690. cquantize->on_odd_row = FALSE; /* flip for next time */
  172691. } else {
  172692. /* work left to right in this row */
  172693. dir = 1;
  172694. dir3 = 3;
  172695. errorptr = cquantize->fserrors; /* => entry before first real column */
  172696. cquantize->on_odd_row = TRUE; /* flip for next time */
  172697. }
  172698. /* Preset error values: no error propagated to first pixel from left */
  172699. cur0 = cur1 = cur2 = 0;
  172700. /* and no error propagated to row below yet */
  172701. belowerr0 = belowerr1 = belowerr2 = 0;
  172702. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  172703. for (col = width; col > 0; col--) {
  172704. /* curN holds the error propagated from the previous pixel on the
  172705. * current line. Add the error propagated from the previous line
  172706. * to form the complete error correction term for this pixel, and
  172707. * round the error term (which is expressed * 16) to an integer.
  172708. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  172709. * for either sign of the error value.
  172710. * Note: errorptr points to *previous* column's array entry.
  172711. */
  172712. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  172713. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  172714. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  172715. /* Limit the error using transfer function set by init_error_limit.
  172716. * See comments with init_error_limit for rationale.
  172717. */
  172718. cur0 = error_limit[cur0];
  172719. cur1 = error_limit[cur1];
  172720. cur2 = error_limit[cur2];
  172721. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  172722. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  172723. * this sets the required size of the range_limit array.
  172724. */
  172725. cur0 += GETJSAMPLE(inptr[0]);
  172726. cur1 += GETJSAMPLE(inptr[1]);
  172727. cur2 += GETJSAMPLE(inptr[2]);
  172728. cur0 = GETJSAMPLE(range_limit[cur0]);
  172729. cur1 = GETJSAMPLE(range_limit[cur1]);
  172730. cur2 = GETJSAMPLE(range_limit[cur2]);
  172731. /* Index into the cache with adjusted pixel value */
  172732. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  172733. /* If we have not seen this color before, find nearest colormap */
  172734. /* entry and update the cache */
  172735. if (*cachep == 0)
  172736. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  172737. /* Now emit the colormap index for this cell */
  172738. { register int pixcode = *cachep - 1;
  172739. *outptr = (JSAMPLE) pixcode;
  172740. /* Compute representation error for this pixel */
  172741. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  172742. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  172743. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  172744. }
  172745. /* Compute error fractions to be propagated to adjacent pixels.
  172746. * Add these into the running sums, and simultaneously shift the
  172747. * next-line error sums left by 1 column.
  172748. */
  172749. { register LOCFSERROR bnexterr, delta;
  172750. bnexterr = cur0; /* Process component 0 */
  172751. delta = cur0 * 2;
  172752. cur0 += delta; /* form error * 3 */
  172753. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  172754. cur0 += delta; /* form error * 5 */
  172755. bpreverr0 = belowerr0 + cur0;
  172756. belowerr0 = bnexterr;
  172757. cur0 += delta; /* form error * 7 */
  172758. bnexterr = cur1; /* Process component 1 */
  172759. delta = cur1 * 2;
  172760. cur1 += delta; /* form error * 3 */
  172761. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  172762. cur1 += delta; /* form error * 5 */
  172763. bpreverr1 = belowerr1 + cur1;
  172764. belowerr1 = bnexterr;
  172765. cur1 += delta; /* form error * 7 */
  172766. bnexterr = cur2; /* Process component 2 */
  172767. delta = cur2 * 2;
  172768. cur2 += delta; /* form error * 3 */
  172769. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  172770. cur2 += delta; /* form error * 5 */
  172771. bpreverr2 = belowerr2 + cur2;
  172772. belowerr2 = bnexterr;
  172773. cur2 += delta; /* form error * 7 */
  172774. }
  172775. /* At this point curN contains the 7/16 error value to be propagated
  172776. * to the next pixel on the current line, and all the errors for the
  172777. * next line have been shifted over. We are therefore ready to move on.
  172778. */
  172779. inptr += dir3; /* Advance pixel pointers to next column */
  172780. outptr += dir;
  172781. errorptr += dir3; /* advance errorptr to current column */
  172782. }
  172783. /* Post-loop cleanup: we must unload the final error values into the
  172784. * final fserrors[] entry. Note we need not unload belowerrN because
  172785. * it is for the dummy column before or after the actual array.
  172786. */
  172787. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  172788. errorptr[1] = (FSERROR) bpreverr1;
  172789. errorptr[2] = (FSERROR) bpreverr2;
  172790. }
  172791. }
  172792. /*
  172793. * Initialize the error-limiting transfer function (lookup table).
  172794. * The raw F-S error computation can potentially compute error values of up to
  172795. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  172796. * much less, otherwise obviously wrong pixels will be created. (Typical
  172797. * effects include weird fringes at color-area boundaries, isolated bright
  172798. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  172799. * is to ensure that the "corners" of the color cube are allocated as output
  172800. * colors; then repeated errors in the same direction cannot cause cascading
  172801. * error buildup. However, that only prevents the error from getting
  172802. * completely out of hand; Aaron Giles reports that error limiting improves
  172803. * the results even with corner colors allocated.
  172804. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  172805. * well, but the smoother transfer function used below is even better. Thanks
  172806. * to Aaron Giles for this idea.
  172807. */
  172808. LOCAL(void)
  172809. init_error_limit (j_decompress_ptr cinfo)
  172810. /* Allocate and fill in the error_limiter table */
  172811. {
  172812. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172813. int * table;
  172814. int in, out;
  172815. table = (int *) (*cinfo->mem->alloc_small)
  172816. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  172817. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  172818. cquantize->error_limiter = table;
  172819. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  172820. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  172821. out = 0;
  172822. for (in = 0; in < STEPSIZE; in++, out++) {
  172823. table[in] = out; table[-in] = -out;
  172824. }
  172825. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  172826. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  172827. table[in] = out; table[-in] = -out;
  172828. }
  172829. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  172830. for (; in <= MAXJSAMPLE; in++) {
  172831. table[in] = out; table[-in] = -out;
  172832. }
  172833. #undef STEPSIZE
  172834. }
  172835. /*
  172836. * Finish up at the end of each pass.
  172837. */
  172838. METHODDEF(void)
  172839. finish_pass1 (j_decompress_ptr cinfo)
  172840. {
  172841. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172842. /* Select the representative colors and fill in cinfo->colormap */
  172843. cinfo->colormap = cquantize->sv_colormap;
  172844. select_colors(cinfo, cquantize->desired);
  172845. /* Force next pass to zero the color index table */
  172846. cquantize->needs_zeroed = TRUE;
  172847. }
  172848. METHODDEF(void)
  172849. finish_pass2 (j_decompress_ptr cinfo)
  172850. {
  172851. /* no work */
  172852. }
  172853. /*
  172854. * Initialize for each processing pass.
  172855. */
  172856. METHODDEF(void)
  172857. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  172858. {
  172859. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172860. hist3d histogram = cquantize->histogram;
  172861. int i;
  172862. /* Only F-S dithering or no dithering is supported. */
  172863. /* If user asks for ordered dither, give him F-S. */
  172864. if (cinfo->dither_mode != JDITHER_NONE)
  172865. cinfo->dither_mode = JDITHER_FS;
  172866. if (is_pre_scan) {
  172867. /* Set up method pointers */
  172868. cquantize->pub.color_quantize = prescan_quantize;
  172869. cquantize->pub.finish_pass = finish_pass1;
  172870. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  172871. } else {
  172872. /* Set up method pointers */
  172873. if (cinfo->dither_mode == JDITHER_FS)
  172874. cquantize->pub.color_quantize = pass2_fs_dither;
  172875. else
  172876. cquantize->pub.color_quantize = pass2_no_dither;
  172877. cquantize->pub.finish_pass = finish_pass2;
  172878. /* Make sure color count is acceptable */
  172879. i = cinfo->actual_number_of_colors;
  172880. if (i < 1)
  172881. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  172882. if (i > MAXNUMCOLORS)
  172883. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  172884. if (cinfo->dither_mode == JDITHER_FS) {
  172885. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  172886. (3 * SIZEOF(FSERROR)));
  172887. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  172888. if (cquantize->fserrors == NULL)
  172889. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  172890. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  172891. /* Initialize the propagated errors to zero. */
  172892. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  172893. /* Make the error-limit table if we didn't already. */
  172894. if (cquantize->error_limiter == NULL)
  172895. init_error_limit(cinfo);
  172896. cquantize->on_odd_row = FALSE;
  172897. }
  172898. }
  172899. /* Zero the histogram or inverse color map, if necessary */
  172900. if (cquantize->needs_zeroed) {
  172901. for (i = 0; i < HIST_C0_ELEMS; i++) {
  172902. jzero_far((void FAR *) histogram[i],
  172903. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  172904. }
  172905. cquantize->needs_zeroed = FALSE;
  172906. }
  172907. }
  172908. /*
  172909. * Switch to a new external colormap between output passes.
  172910. */
  172911. METHODDEF(void)
  172912. new_color_map_2_quant (j_decompress_ptr cinfo)
  172913. {
  172914. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172915. /* Reset the inverse color map */
  172916. cquantize->needs_zeroed = TRUE;
  172917. }
  172918. /*
  172919. * Module initialization routine for 2-pass color quantization.
  172920. */
  172921. GLOBAL(void)
  172922. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  172923. {
  172924. my_cquantize_ptr2 cquantize;
  172925. int i;
  172926. cquantize = (my_cquantize_ptr2)
  172927. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172928. SIZEOF(my_cquantizer2));
  172929. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  172930. cquantize->pub.start_pass = start_pass_2_quant;
  172931. cquantize->pub.new_color_map = new_color_map_2_quant;
  172932. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  172933. cquantize->error_limiter = NULL;
  172934. /* Make sure jdmaster didn't give me a case I can't handle */
  172935. if (cinfo->out_color_components != 3)
  172936. ERREXIT(cinfo, JERR_NOTIMPL);
  172937. /* Allocate the histogram/inverse colormap storage */
  172938. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  172939. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  172940. for (i = 0; i < HIST_C0_ELEMS; i++) {
  172941. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  172942. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172943. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  172944. }
  172945. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  172946. /* Allocate storage for the completed colormap, if required.
  172947. * We do this now since it is FAR storage and may affect
  172948. * the memory manager's space calculations.
  172949. */
  172950. if (cinfo->enable_2pass_quant) {
  172951. /* Make sure color count is acceptable */
  172952. int desired = cinfo->desired_number_of_colors;
  172953. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  172954. if (desired < 8)
  172955. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  172956. /* Make sure colormap indexes can be represented by JSAMPLEs */
  172957. if (desired > MAXNUMCOLORS)
  172958. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  172959. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  172960. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  172961. cquantize->desired = desired;
  172962. } else
  172963. cquantize->sv_colormap = NULL;
  172964. /* Only F-S dithering or no dithering is supported. */
  172965. /* If user asks for ordered dither, give him F-S. */
  172966. if (cinfo->dither_mode != JDITHER_NONE)
  172967. cinfo->dither_mode = JDITHER_FS;
  172968. /* Allocate Floyd-Steinberg workspace if necessary.
  172969. * This isn't really needed until pass 2, but again it is FAR storage.
  172970. * Although we will cope with a later change in dither_mode,
  172971. * we do not promise to honor max_memory_to_use if dither_mode changes.
  172972. */
  172973. if (cinfo->dither_mode == JDITHER_FS) {
  172974. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  172975. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172976. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  172977. /* Might as well create the error-limiting table too. */
  172978. init_error_limit(cinfo);
  172979. }
  172980. }
  172981. #endif /* QUANT_2PASS_SUPPORTED */
  172982. /********* End of inlined file: jquant2.c *********/
  172983. /********* Start of inlined file: jutils.c *********/
  172984. #define JPEG_INTERNALS
  172985. /*
  172986. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  172987. * of a DCT block read in natural order (left to right, top to bottom).
  172988. */
  172989. #if 0 /* This table is not actually needed in v6a */
  172990. const int jpeg_zigzag_order[DCTSIZE2] = {
  172991. 0, 1, 5, 6, 14, 15, 27, 28,
  172992. 2, 4, 7, 13, 16, 26, 29, 42,
  172993. 3, 8, 12, 17, 25, 30, 41, 43,
  172994. 9, 11, 18, 24, 31, 40, 44, 53,
  172995. 10, 19, 23, 32, 39, 45, 52, 54,
  172996. 20, 22, 33, 38, 46, 51, 55, 60,
  172997. 21, 34, 37, 47, 50, 56, 59, 61,
  172998. 35, 36, 48, 49, 57, 58, 62, 63
  172999. };
  173000. #endif
  173001. /*
  173002. * jpeg_natural_order[i] is the natural-order position of the i'th element
  173003. * of zigzag order.
  173004. *
  173005. * When reading corrupted data, the Huffman decoders could attempt
  173006. * to reference an entry beyond the end of this array (if the decoded
  173007. * zero run length reaches past the end of the block). To prevent
  173008. * wild stores without adding an inner-loop test, we put some extra
  173009. * "63"s after the real entries. This will cause the extra coefficient
  173010. * to be stored in location 63 of the block, not somewhere random.
  173011. * The worst case would be a run-length of 15, which means we need 16
  173012. * fake entries.
  173013. */
  173014. const int jpeg_natural_order[DCTSIZE2+16] = {
  173015. 0, 1, 8, 16, 9, 2, 3, 10,
  173016. 17, 24, 32, 25, 18, 11, 4, 5,
  173017. 12, 19, 26, 33, 40, 48, 41, 34,
  173018. 27, 20, 13, 6, 7, 14, 21, 28,
  173019. 35, 42, 49, 56, 57, 50, 43, 36,
  173020. 29, 22, 15, 23, 30, 37, 44, 51,
  173021. 58, 59, 52, 45, 38, 31, 39, 46,
  173022. 53, 60, 61, 54, 47, 55, 62, 63,
  173023. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  173024. 63, 63, 63, 63, 63, 63, 63, 63
  173025. };
  173026. /*
  173027. * Arithmetic utilities
  173028. */
  173029. GLOBAL(long)
  173030. jdiv_round_up (long a, long b)
  173031. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  173032. /* Assumes a >= 0, b > 0 */
  173033. {
  173034. return (a + b - 1L) / b;
  173035. }
  173036. GLOBAL(long)
  173037. jround_up (long a, long b)
  173038. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  173039. /* Assumes a >= 0, b > 0 */
  173040. {
  173041. a += b - 1L;
  173042. return a - (a % b);
  173043. }
  173044. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  173045. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  173046. * are FAR and we're assuming a small-pointer memory model. However, some
  173047. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  173048. * in the small-model libraries. These will be used if USE_FMEM is defined.
  173049. * Otherwise, the routines below do it the hard way. (The performance cost
  173050. * is not all that great, because these routines aren't very heavily used.)
  173051. */
  173052. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  173053. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  173054. #define FMEMZERO(target,size) MEMZERO(target,size)
  173055. #else /* 80x86 case, define if we can */
  173056. #ifdef USE_FMEM
  173057. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  173058. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  173059. #endif
  173060. #endif
  173061. GLOBAL(void)
  173062. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  173063. JSAMPARRAY output_array, int dest_row,
  173064. int num_rows, JDIMENSION num_cols)
  173065. /* Copy some rows of samples from one place to another.
  173066. * num_rows rows are copied from input_array[source_row++]
  173067. * to output_array[dest_row++]; these areas may overlap for duplication.
  173068. * The source and destination arrays must be at least as wide as num_cols.
  173069. */
  173070. {
  173071. register JSAMPROW inptr, outptr;
  173072. #ifdef FMEMCOPY
  173073. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  173074. #else
  173075. register JDIMENSION count;
  173076. #endif
  173077. register int row;
  173078. input_array += source_row;
  173079. output_array += dest_row;
  173080. for (row = num_rows; row > 0; row--) {
  173081. inptr = *input_array++;
  173082. outptr = *output_array++;
  173083. #ifdef FMEMCOPY
  173084. FMEMCOPY(outptr, inptr, count);
  173085. #else
  173086. for (count = num_cols; count > 0; count--)
  173087. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  173088. #endif
  173089. }
  173090. }
  173091. GLOBAL(void)
  173092. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  173093. JDIMENSION num_blocks)
  173094. /* Copy a row of coefficient blocks from one place to another. */
  173095. {
  173096. #ifdef FMEMCOPY
  173097. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  173098. #else
  173099. register JCOEFPTR inptr, outptr;
  173100. register long count;
  173101. inptr = (JCOEFPTR) input_row;
  173102. outptr = (JCOEFPTR) output_row;
  173103. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  173104. *outptr++ = *inptr++;
  173105. }
  173106. #endif
  173107. }
  173108. GLOBAL(void)
  173109. jzero_far (void FAR * target, size_t bytestozero)
  173110. /* Zero out a chunk of FAR memory. */
  173111. /* This might be sample-array data, block-array data, or alloc_large data. */
  173112. {
  173113. #ifdef FMEMZERO
  173114. FMEMZERO(target, bytestozero);
  173115. #else
  173116. register char FAR * ptr = (char FAR *) target;
  173117. register size_t count;
  173118. for (count = bytestozero; count > 0; count--) {
  173119. *ptr++ = 0;
  173120. }
  173121. #endif
  173122. }
  173123. /********* End of inlined file: jutils.c *********/
  173124. /********* Start of inlined file: transupp.c *********/
  173125. /* Although this file really shouldn't have access to the library internals,
  173126. * it's helpful to let it call jround_up() and jcopy_block_row().
  173127. */
  173128. #define JPEG_INTERNALS
  173129. /********* Start of inlined file: transupp.h *********/
  173130. /* If you happen not to want the image transform support, disable it here */
  173131. #ifndef TRANSFORMS_SUPPORTED
  173132. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  173133. #endif
  173134. /* Short forms of external names for systems with brain-damaged linkers. */
  173135. #ifdef NEED_SHORT_EXTERNAL_NAMES
  173136. #define jtransform_request_workspace jTrRequest
  173137. #define jtransform_adjust_parameters jTrAdjust
  173138. #define jtransform_execute_transformation jTrExec
  173139. #define jcopy_markers_setup jCMrkSetup
  173140. #define jcopy_markers_execute jCMrkExec
  173141. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  173142. /*
  173143. * Codes for supported types of image transformations.
  173144. */
  173145. typedef enum {
  173146. JXFORM_NONE, /* no transformation */
  173147. JXFORM_FLIP_H, /* horizontal flip */
  173148. JXFORM_FLIP_V, /* vertical flip */
  173149. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  173150. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  173151. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  173152. JXFORM_ROT_180, /* 180-degree rotation */
  173153. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  173154. } JXFORM_CODE;
  173155. /*
  173156. * Although rotating and flipping data expressed as DCT coefficients is not
  173157. * hard, there is an asymmetry in the JPEG format specification for images
  173158. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  173159. * image edges are padded out to the next iMCU boundary with junk data; but
  173160. * no padding is possible at the top and left edges. If we were to flip
  173161. * the whole image including the pad data, then pad garbage would become
  173162. * visible at the top and/or left, and real pixels would disappear into the
  173163. * pad margins --- perhaps permanently, since encoders & decoders may not
  173164. * bother to preserve DCT blocks that appear to be completely outside the
  173165. * nominal image area. So, we have to exclude any partial iMCUs from the
  173166. * basic transformation.
  173167. *
  173168. * Transpose is the only transformation that can handle partial iMCUs at the
  173169. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  173170. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  173171. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  173172. * The other transforms are defined as combinations of these basic transforms
  173173. * and process edge blocks in a way that preserves the equivalence.
  173174. *
  173175. * The "trim" option causes untransformable partial iMCUs to be dropped;
  173176. * this is not strictly lossless, but it usually gives the best-looking
  173177. * result for odd-size images. Note that when this option is active,
  173178. * the expected mathematical equivalences between the transforms may not hold.
  173179. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  173180. * followed by -rot 180 -trim trims both edges.)
  173181. *
  173182. * We also offer a "force to grayscale" option, which simply discards the
  173183. * chrominance channels of a YCbCr image. This is lossless in the sense that
  173184. * the luminance channel is preserved exactly. It's not the same kind of
  173185. * thing as the rotate/flip transformations, but it's convenient to handle it
  173186. * as part of this package, mainly because the transformation routines have to
  173187. * be aware of the option to know how many components to work on.
  173188. */
  173189. typedef struct {
  173190. /* Options: set by caller */
  173191. JXFORM_CODE transform; /* image transform operator */
  173192. boolean trim; /* if TRUE, trim partial MCUs as needed */
  173193. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  173194. /* Internal workspace: caller should not touch these */
  173195. int num_components; /* # of components in workspace */
  173196. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  173197. } jpeg_transform_info;
  173198. #if TRANSFORMS_SUPPORTED
  173199. /* Request any required workspace */
  173200. EXTERN(void) jtransform_request_workspace
  173201. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  173202. /* Adjust output image parameters */
  173203. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  173204. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173205. jvirt_barray_ptr *src_coef_arrays,
  173206. jpeg_transform_info *info));
  173207. /* Execute the actual transformation, if any */
  173208. EXTERN(void) jtransform_execute_transformation
  173209. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173210. jvirt_barray_ptr *src_coef_arrays,
  173211. jpeg_transform_info *info));
  173212. #endif /* TRANSFORMS_SUPPORTED */
  173213. /*
  173214. * Support for copying optional markers from source to destination file.
  173215. */
  173216. typedef enum {
  173217. JCOPYOPT_NONE, /* copy no optional markers */
  173218. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  173219. JCOPYOPT_ALL /* copy all optional markers */
  173220. } JCOPY_OPTION;
  173221. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  173222. /* Setup decompression object to save desired markers in memory */
  173223. EXTERN(void) jcopy_markers_setup
  173224. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  173225. /* Copy markers saved in the given source object to the destination object */
  173226. EXTERN(void) jcopy_markers_execute
  173227. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173228. JCOPY_OPTION option));
  173229. /********* End of inlined file: transupp.h *********/
  173230. /* My own external interface */
  173231. #if TRANSFORMS_SUPPORTED
  173232. /*
  173233. * Lossless image transformation routines. These routines work on DCT
  173234. * coefficient arrays and thus do not require any lossy decompression
  173235. * or recompression of the image.
  173236. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  173237. *
  173238. * Horizontal flipping is done in-place, using a single top-to-bottom
  173239. * pass through the virtual source array. It will thus be much the
  173240. * fastest option for images larger than main memory.
  173241. *
  173242. * The other routines require a set of destination virtual arrays, so they
  173243. * need twice as much memory as jpegtran normally does. The destination
  173244. * arrays are always written in normal scan order (top to bottom) because
  173245. * the virtual array manager expects this. The source arrays will be scanned
  173246. * in the corresponding order, which means multiple passes through the source
  173247. * arrays for most of the transforms. That could result in much thrashing
  173248. * if the image is larger than main memory.
  173249. *
  173250. * Some notes about the operating environment of the individual transform
  173251. * routines:
  173252. * 1. Both the source and destination virtual arrays are allocated from the
  173253. * source JPEG object, and therefore should be manipulated by calling the
  173254. * source's memory manager.
  173255. * 2. The destination's component count should be used. It may be smaller
  173256. * than the source's when forcing to grayscale.
  173257. * 3. Likewise the destination's sampling factors should be used. When
  173258. * forcing to grayscale the destination's sampling factors will be all 1,
  173259. * and we may as well take that as the effective iMCU size.
  173260. * 4. When "trim" is in effect, the destination's dimensions will be the
  173261. * trimmed values but the source's will be untrimmed.
  173262. * 5. All the routines assume that the source and destination buffers are
  173263. * padded out to a full iMCU boundary. This is true, although for the
  173264. * source buffer it is an undocumented property of jdcoefct.c.
  173265. * Notes 2,3,4 boil down to this: generally we should use the destination's
  173266. * dimensions and ignore the source's.
  173267. */
  173268. LOCAL(void)
  173269. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173270. jvirt_barray_ptr *src_coef_arrays)
  173271. /* Horizontal flip; done in-place, so no separate dest array is required */
  173272. {
  173273. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  173274. int ci, k, offset_y;
  173275. JBLOCKARRAY buffer;
  173276. JCOEFPTR ptr1, ptr2;
  173277. JCOEF temp1, temp2;
  173278. jpeg_component_info *compptr;
  173279. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  173280. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  173281. * mirroring by changing the signs of odd-numbered columns.
  173282. * Partial iMCUs at the right edge are left untouched.
  173283. */
  173284. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  173285. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173286. compptr = dstinfo->comp_info + ci;
  173287. comp_width = MCU_cols * compptr->h_samp_factor;
  173288. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  173289. blk_y += compptr->v_samp_factor) {
  173290. buffer = (*srcinfo->mem->access_virt_barray)
  173291. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  173292. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173293. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173294. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  173295. ptr1 = buffer[offset_y][blk_x];
  173296. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  173297. /* this unrolled loop doesn't need to know which row it's on... */
  173298. for (k = 0; k < DCTSIZE2; k += 2) {
  173299. temp1 = *ptr1; /* swap even column */
  173300. temp2 = *ptr2;
  173301. *ptr1++ = temp2;
  173302. *ptr2++ = temp1;
  173303. temp1 = *ptr1; /* swap odd column with sign change */
  173304. temp2 = *ptr2;
  173305. *ptr1++ = -temp2;
  173306. *ptr2++ = -temp1;
  173307. }
  173308. }
  173309. }
  173310. }
  173311. }
  173312. }
  173313. LOCAL(void)
  173314. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173315. jvirt_barray_ptr *src_coef_arrays,
  173316. jvirt_barray_ptr *dst_coef_arrays)
  173317. /* Vertical flip */
  173318. {
  173319. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  173320. int ci, i, j, offset_y;
  173321. JBLOCKARRAY src_buffer, dst_buffer;
  173322. JBLOCKROW src_row_ptr, dst_row_ptr;
  173323. JCOEFPTR src_ptr, dst_ptr;
  173324. jpeg_component_info *compptr;
  173325. /* We output into a separate array because we can't touch different
  173326. * rows of the source virtual array simultaneously. Otherwise, this
  173327. * is a pretty straightforward analog of horizontal flip.
  173328. * Within a DCT block, vertical mirroring is done by changing the signs
  173329. * of odd-numbered rows.
  173330. * Partial iMCUs at the bottom edge are copied verbatim.
  173331. */
  173332. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  173333. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173334. compptr = dstinfo->comp_info + ci;
  173335. comp_height = MCU_rows * compptr->v_samp_factor;
  173336. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173337. dst_blk_y += compptr->v_samp_factor) {
  173338. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173339. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173340. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173341. if (dst_blk_y < comp_height) {
  173342. /* Row is within the mirrorable area. */
  173343. src_buffer = (*srcinfo->mem->access_virt_barray)
  173344. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  173345. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  173346. (JDIMENSION) compptr->v_samp_factor, FALSE);
  173347. } else {
  173348. /* Bottom-edge blocks will be copied verbatim. */
  173349. src_buffer = (*srcinfo->mem->access_virt_barray)
  173350. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  173351. (JDIMENSION) compptr->v_samp_factor, FALSE);
  173352. }
  173353. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173354. if (dst_blk_y < comp_height) {
  173355. /* Row is within the mirrorable area. */
  173356. dst_row_ptr = dst_buffer[offset_y];
  173357. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  173358. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  173359. dst_blk_x++) {
  173360. dst_ptr = dst_row_ptr[dst_blk_x];
  173361. src_ptr = src_row_ptr[dst_blk_x];
  173362. for (i = 0; i < DCTSIZE; i += 2) {
  173363. /* copy even row */
  173364. for (j = 0; j < DCTSIZE; j++)
  173365. *dst_ptr++ = *src_ptr++;
  173366. /* copy odd row with sign change */
  173367. for (j = 0; j < DCTSIZE; j++)
  173368. *dst_ptr++ = - *src_ptr++;
  173369. }
  173370. }
  173371. } else {
  173372. /* Just copy row verbatim. */
  173373. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  173374. compptr->width_in_blocks);
  173375. }
  173376. }
  173377. }
  173378. }
  173379. }
  173380. LOCAL(void)
  173381. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173382. jvirt_barray_ptr *src_coef_arrays,
  173383. jvirt_barray_ptr *dst_coef_arrays)
  173384. /* Transpose source into destination */
  173385. {
  173386. JDIMENSION dst_blk_x, dst_blk_y;
  173387. int ci, i, j, offset_x, offset_y;
  173388. JBLOCKARRAY src_buffer, dst_buffer;
  173389. JCOEFPTR src_ptr, dst_ptr;
  173390. jpeg_component_info *compptr;
  173391. /* Transposing pixels within a block just requires transposing the
  173392. * DCT coefficients.
  173393. * Partial iMCUs at the edges require no special treatment; we simply
  173394. * process all the available DCT blocks for every component.
  173395. */
  173396. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173397. compptr = dstinfo->comp_info + ci;
  173398. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173399. dst_blk_y += compptr->v_samp_factor) {
  173400. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173401. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173402. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173403. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173404. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  173405. dst_blk_x += compptr->h_samp_factor) {
  173406. src_buffer = (*srcinfo->mem->access_virt_barray)
  173407. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  173408. (JDIMENSION) compptr->h_samp_factor, FALSE);
  173409. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  173410. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  173411. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  173412. for (i = 0; i < DCTSIZE; i++)
  173413. for (j = 0; j < DCTSIZE; j++)
  173414. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173415. }
  173416. }
  173417. }
  173418. }
  173419. }
  173420. }
  173421. LOCAL(void)
  173422. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173423. jvirt_barray_ptr *src_coef_arrays,
  173424. jvirt_barray_ptr *dst_coef_arrays)
  173425. /* 90 degree rotation is equivalent to
  173426. * 1. Transposing the image;
  173427. * 2. Horizontal mirroring.
  173428. * These two steps are merged into a single processing routine.
  173429. */
  173430. {
  173431. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  173432. int ci, i, j, offset_x, offset_y;
  173433. JBLOCKARRAY src_buffer, dst_buffer;
  173434. JCOEFPTR src_ptr, dst_ptr;
  173435. jpeg_component_info *compptr;
  173436. /* Because of the horizontal mirror step, we can't process partial iMCUs
  173437. * at the (output) right edge properly. They just get transposed and
  173438. * not mirrored.
  173439. */
  173440. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  173441. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173442. compptr = dstinfo->comp_info + ci;
  173443. comp_width = MCU_cols * compptr->h_samp_factor;
  173444. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173445. dst_blk_y += compptr->v_samp_factor) {
  173446. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173447. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173448. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173449. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173450. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  173451. dst_blk_x += compptr->h_samp_factor) {
  173452. src_buffer = (*srcinfo->mem->access_virt_barray)
  173453. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  173454. (JDIMENSION) compptr->h_samp_factor, FALSE);
  173455. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  173456. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  173457. if (dst_blk_x < comp_width) {
  173458. /* Block is within the mirrorable area. */
  173459. dst_ptr = dst_buffer[offset_y]
  173460. [comp_width - dst_blk_x - offset_x - 1];
  173461. for (i = 0; i < DCTSIZE; i++) {
  173462. for (j = 0; j < DCTSIZE; j++)
  173463. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173464. i++;
  173465. for (j = 0; j < DCTSIZE; j++)
  173466. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173467. }
  173468. } else {
  173469. /* Edge blocks are transposed but not mirrored. */
  173470. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  173471. for (i = 0; i < DCTSIZE; i++)
  173472. for (j = 0; j < DCTSIZE; j++)
  173473. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173474. }
  173475. }
  173476. }
  173477. }
  173478. }
  173479. }
  173480. }
  173481. LOCAL(void)
  173482. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173483. jvirt_barray_ptr *src_coef_arrays,
  173484. jvirt_barray_ptr *dst_coef_arrays)
  173485. /* 270 degree rotation is equivalent to
  173486. * 1. Horizontal mirroring;
  173487. * 2. Transposing the image.
  173488. * These two steps are merged into a single processing routine.
  173489. */
  173490. {
  173491. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  173492. int ci, i, j, offset_x, offset_y;
  173493. JBLOCKARRAY src_buffer, dst_buffer;
  173494. JCOEFPTR src_ptr, dst_ptr;
  173495. jpeg_component_info *compptr;
  173496. /* Because of the horizontal mirror step, we can't process partial iMCUs
  173497. * at the (output) bottom edge properly. They just get transposed and
  173498. * not mirrored.
  173499. */
  173500. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  173501. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173502. compptr = dstinfo->comp_info + ci;
  173503. comp_height = MCU_rows * compptr->v_samp_factor;
  173504. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173505. dst_blk_y += compptr->v_samp_factor) {
  173506. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173507. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173508. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173509. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173510. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  173511. dst_blk_x += compptr->h_samp_factor) {
  173512. src_buffer = (*srcinfo->mem->access_virt_barray)
  173513. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  173514. (JDIMENSION) compptr->h_samp_factor, FALSE);
  173515. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  173516. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  173517. if (dst_blk_y < comp_height) {
  173518. /* Block is within the mirrorable area. */
  173519. src_ptr = src_buffer[offset_x]
  173520. [comp_height - dst_blk_y - offset_y - 1];
  173521. for (i = 0; i < DCTSIZE; i++) {
  173522. for (j = 0; j < DCTSIZE; j++) {
  173523. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173524. j++;
  173525. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173526. }
  173527. }
  173528. } else {
  173529. /* Edge blocks are transposed but not mirrored. */
  173530. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  173531. for (i = 0; i < DCTSIZE; i++)
  173532. for (j = 0; j < DCTSIZE; j++)
  173533. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173534. }
  173535. }
  173536. }
  173537. }
  173538. }
  173539. }
  173540. }
  173541. LOCAL(void)
  173542. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173543. jvirt_barray_ptr *src_coef_arrays,
  173544. jvirt_barray_ptr *dst_coef_arrays)
  173545. /* 180 degree rotation is equivalent to
  173546. * 1. Vertical mirroring;
  173547. * 2. Horizontal mirroring.
  173548. * These two steps are merged into a single processing routine.
  173549. */
  173550. {
  173551. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  173552. int ci, i, j, offset_y;
  173553. JBLOCKARRAY src_buffer, dst_buffer;
  173554. JBLOCKROW src_row_ptr, dst_row_ptr;
  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. if (dst_blk_y < comp_height) {
  173569. /* Row is within the vertically mirrorable area. */
  173570. src_buffer = (*srcinfo->mem->access_virt_barray)
  173571. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  173572. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  173573. (JDIMENSION) compptr->v_samp_factor, FALSE);
  173574. } else {
  173575. /* Bottom-edge rows are only mirrored horizontally. */
  173576. src_buffer = (*srcinfo->mem->access_virt_barray)
  173577. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  173578. (JDIMENSION) compptr->v_samp_factor, FALSE);
  173579. }
  173580. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173581. if (dst_blk_y < comp_height) {
  173582. /* Row is within the mirrorable area. */
  173583. dst_row_ptr = dst_buffer[offset_y];
  173584. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  173585. /* Process the blocks that can be mirrored both ways. */
  173586. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  173587. dst_ptr = dst_row_ptr[dst_blk_x];
  173588. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  173589. for (i = 0; i < DCTSIZE; i += 2) {
  173590. /* For even row, negate every odd column. */
  173591. for (j = 0; j < DCTSIZE; j += 2) {
  173592. *dst_ptr++ = *src_ptr++;
  173593. *dst_ptr++ = - *src_ptr++;
  173594. }
  173595. /* For odd row, negate every even column. */
  173596. for (j = 0; j < DCTSIZE; j += 2) {
  173597. *dst_ptr++ = - *src_ptr++;
  173598. *dst_ptr++ = *src_ptr++;
  173599. }
  173600. }
  173601. }
  173602. /* Any remaining right-edge blocks are only mirrored vertically. */
  173603. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  173604. dst_ptr = dst_row_ptr[dst_blk_x];
  173605. src_ptr = src_row_ptr[dst_blk_x];
  173606. for (i = 0; i < DCTSIZE; i += 2) {
  173607. for (j = 0; j < DCTSIZE; j++)
  173608. *dst_ptr++ = *src_ptr++;
  173609. for (j = 0; j < DCTSIZE; j++)
  173610. *dst_ptr++ = - *src_ptr++;
  173611. }
  173612. }
  173613. } else {
  173614. /* Remaining rows are just mirrored horizontally. */
  173615. dst_row_ptr = dst_buffer[offset_y];
  173616. src_row_ptr = src_buffer[offset_y];
  173617. /* Process the blocks that can be mirrored. */
  173618. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  173619. dst_ptr = dst_row_ptr[dst_blk_x];
  173620. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  173621. for (i = 0; i < DCTSIZE2; i += 2) {
  173622. *dst_ptr++ = *src_ptr++;
  173623. *dst_ptr++ = - *src_ptr++;
  173624. }
  173625. }
  173626. /* Any remaining right-edge blocks are only copied. */
  173627. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  173628. dst_ptr = dst_row_ptr[dst_blk_x];
  173629. src_ptr = src_row_ptr[dst_blk_x];
  173630. for (i = 0; i < DCTSIZE2; i++)
  173631. *dst_ptr++ = *src_ptr++;
  173632. }
  173633. }
  173634. }
  173635. }
  173636. }
  173637. }
  173638. LOCAL(void)
  173639. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173640. jvirt_barray_ptr *src_coef_arrays,
  173641. jvirt_barray_ptr *dst_coef_arrays)
  173642. /* Transverse transpose is equivalent to
  173643. * 1. 180 degree rotation;
  173644. * 2. Transposition;
  173645. * or
  173646. * 1. Horizontal mirroring;
  173647. * 2. Transposition;
  173648. * 3. Horizontal mirroring.
  173649. * These steps are merged into a single processing routine.
  173650. */
  173651. {
  173652. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  173653. int ci, i, j, offset_x, offset_y;
  173654. JBLOCKARRAY src_buffer, dst_buffer;
  173655. JCOEFPTR src_ptr, dst_ptr;
  173656. jpeg_component_info *compptr;
  173657. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  173658. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  173659. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173660. compptr = dstinfo->comp_info + ci;
  173661. comp_width = MCU_cols * compptr->h_samp_factor;
  173662. comp_height = MCU_rows * compptr->v_samp_factor;
  173663. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  173664. dst_blk_y += compptr->v_samp_factor) {
  173665. dst_buffer = (*srcinfo->mem->access_virt_barray)
  173666. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  173667. (JDIMENSION) compptr->v_samp_factor, TRUE);
  173668. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  173669. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  173670. dst_blk_x += compptr->h_samp_factor) {
  173671. src_buffer = (*srcinfo->mem->access_virt_barray)
  173672. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  173673. (JDIMENSION) compptr->h_samp_factor, FALSE);
  173674. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  173675. if (dst_blk_y < comp_height) {
  173676. src_ptr = src_buffer[offset_x]
  173677. [comp_height - dst_blk_y - offset_y - 1];
  173678. if (dst_blk_x < comp_width) {
  173679. /* Block is within the mirrorable area. */
  173680. dst_ptr = dst_buffer[offset_y]
  173681. [comp_width - dst_blk_x - offset_x - 1];
  173682. for (i = 0; i < DCTSIZE; i++) {
  173683. for (j = 0; j < DCTSIZE; j++) {
  173684. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173685. j++;
  173686. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173687. }
  173688. i++;
  173689. for (j = 0; j < DCTSIZE; j++) {
  173690. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173691. j++;
  173692. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173693. }
  173694. }
  173695. } else {
  173696. /* Right-edge blocks are mirrored in y only */
  173697. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  173698. for (i = 0; i < DCTSIZE; i++) {
  173699. for (j = 0; j < DCTSIZE; j++) {
  173700. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173701. j++;
  173702. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173703. }
  173704. }
  173705. }
  173706. } else {
  173707. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  173708. if (dst_blk_x < comp_width) {
  173709. /* Bottom-edge blocks are mirrored in x only */
  173710. dst_ptr = dst_buffer[offset_y]
  173711. [comp_width - dst_blk_x - offset_x - 1];
  173712. for (i = 0; i < DCTSIZE; i++) {
  173713. for (j = 0; j < DCTSIZE; j++)
  173714. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173715. i++;
  173716. for (j = 0; j < DCTSIZE; j++)
  173717. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  173718. }
  173719. } else {
  173720. /* At lower right corner, just transpose, no mirroring */
  173721. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  173722. for (i = 0; i < DCTSIZE; i++)
  173723. for (j = 0; j < DCTSIZE; j++)
  173724. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  173725. }
  173726. }
  173727. }
  173728. }
  173729. }
  173730. }
  173731. }
  173732. }
  173733. /* Request any required workspace.
  173734. *
  173735. * We allocate the workspace virtual arrays from the source decompression
  173736. * object, so that all the arrays (both the original data and the workspace)
  173737. * will be taken into account while making memory management decisions.
  173738. * Hence, this routine must be called after jpeg_read_header (which reads
  173739. * the image dimensions) and before jpeg_read_coefficients (which realizes
  173740. * the source's virtual arrays).
  173741. */
  173742. GLOBAL(void)
  173743. jtransform_request_workspace (j_decompress_ptr srcinfo,
  173744. jpeg_transform_info *info)
  173745. {
  173746. jvirt_barray_ptr *coef_arrays = NULL;
  173747. jpeg_component_info *compptr;
  173748. int ci;
  173749. if (info->force_grayscale &&
  173750. srcinfo->jpeg_color_space == JCS_YCbCr &&
  173751. srcinfo->num_components == 3) {
  173752. /* We'll only process the first component */
  173753. info->num_components = 1;
  173754. } else {
  173755. /* Process all the components */
  173756. info->num_components = srcinfo->num_components;
  173757. }
  173758. switch (info->transform) {
  173759. case JXFORM_NONE:
  173760. case JXFORM_FLIP_H:
  173761. /* Don't need a workspace array */
  173762. break;
  173763. case JXFORM_FLIP_V:
  173764. case JXFORM_ROT_180:
  173765. /* Need workspace arrays having same dimensions as source image.
  173766. * Note that we allocate arrays padded out to the next iMCU boundary,
  173767. * so that transform routines need not worry about missing edge blocks.
  173768. */
  173769. coef_arrays = (jvirt_barray_ptr *)
  173770. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  173771. SIZEOF(jvirt_barray_ptr) * info->num_components);
  173772. for (ci = 0; ci < info->num_components; ci++) {
  173773. compptr = srcinfo->comp_info + ci;
  173774. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  173775. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  173776. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  173777. (long) compptr->h_samp_factor),
  173778. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  173779. (long) compptr->v_samp_factor),
  173780. (JDIMENSION) compptr->v_samp_factor);
  173781. }
  173782. break;
  173783. case JXFORM_TRANSPOSE:
  173784. case JXFORM_TRANSVERSE:
  173785. case JXFORM_ROT_90:
  173786. case JXFORM_ROT_270:
  173787. /* Need workspace arrays having transposed dimensions.
  173788. * Note that we allocate arrays padded out to the next iMCU boundary,
  173789. * so that transform routines need not worry about missing edge blocks.
  173790. */
  173791. coef_arrays = (jvirt_barray_ptr *)
  173792. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  173793. SIZEOF(jvirt_barray_ptr) * info->num_components);
  173794. for (ci = 0; ci < info->num_components; ci++) {
  173795. compptr = srcinfo->comp_info + ci;
  173796. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  173797. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  173798. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  173799. (long) compptr->v_samp_factor),
  173800. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  173801. (long) compptr->h_samp_factor),
  173802. (JDIMENSION) compptr->h_samp_factor);
  173803. }
  173804. break;
  173805. }
  173806. info->workspace_coef_arrays = coef_arrays;
  173807. }
  173808. /* Transpose destination image parameters */
  173809. LOCAL(void)
  173810. transpose_critical_parameters (j_compress_ptr dstinfo)
  173811. {
  173812. int tblno, i, j, ci, itemp;
  173813. jpeg_component_info *compptr;
  173814. JQUANT_TBL *qtblptr;
  173815. JDIMENSION dtemp;
  173816. UINT16 qtemp;
  173817. /* Transpose basic image dimensions */
  173818. dtemp = dstinfo->image_width;
  173819. dstinfo->image_width = dstinfo->image_height;
  173820. dstinfo->image_height = dtemp;
  173821. /* Transpose sampling factors */
  173822. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173823. compptr = dstinfo->comp_info + ci;
  173824. itemp = compptr->h_samp_factor;
  173825. compptr->h_samp_factor = compptr->v_samp_factor;
  173826. compptr->v_samp_factor = itemp;
  173827. }
  173828. /* Transpose quantization tables */
  173829. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  173830. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  173831. if (qtblptr != NULL) {
  173832. for (i = 0; i < DCTSIZE; i++) {
  173833. for (j = 0; j < i; j++) {
  173834. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  173835. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  173836. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  173837. }
  173838. }
  173839. }
  173840. }
  173841. }
  173842. /* Trim off any partial iMCUs on the indicated destination edge */
  173843. LOCAL(void)
  173844. trim_right_edge (j_compress_ptr dstinfo)
  173845. {
  173846. int ci, max_h_samp_factor;
  173847. JDIMENSION MCU_cols;
  173848. /* We have to compute max_h_samp_factor ourselves,
  173849. * because it hasn't been set yet in the destination
  173850. * (and we don't want to use the source's value).
  173851. */
  173852. max_h_samp_factor = 1;
  173853. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173854. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  173855. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  173856. }
  173857. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  173858. if (MCU_cols > 0) /* can't trim to 0 pixels */
  173859. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  173860. }
  173861. LOCAL(void)
  173862. trim_bottom_edge (j_compress_ptr dstinfo)
  173863. {
  173864. int ci, max_v_samp_factor;
  173865. JDIMENSION MCU_rows;
  173866. /* We have to compute max_v_samp_factor ourselves,
  173867. * because it hasn't been set yet in the destination
  173868. * (and we don't want to use the source's value).
  173869. */
  173870. max_v_samp_factor = 1;
  173871. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173872. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  173873. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  173874. }
  173875. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  173876. if (MCU_rows > 0) /* can't trim to 0 pixels */
  173877. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  173878. }
  173879. /* Adjust output image parameters as needed.
  173880. *
  173881. * This must be called after jpeg_copy_critical_parameters()
  173882. * and before jpeg_write_coefficients().
  173883. *
  173884. * The return value is the set of virtual coefficient arrays to be written
  173885. * (either the ones allocated by jtransform_request_workspace, or the
  173886. * original source data arrays). The caller will need to pass this value
  173887. * to jpeg_write_coefficients().
  173888. */
  173889. GLOBAL(jvirt_barray_ptr *)
  173890. jtransform_adjust_parameters (j_decompress_ptr srcinfo,
  173891. j_compress_ptr dstinfo,
  173892. jvirt_barray_ptr *src_coef_arrays,
  173893. jpeg_transform_info *info)
  173894. {
  173895. /* If force-to-grayscale is requested, adjust destination parameters */
  173896. if (info->force_grayscale) {
  173897. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  173898. * properly. Among other things, the target h_samp_factor & v_samp_factor
  173899. * will get set to 1, which typically won't match the source.
  173900. * In fact we do this even if the source is already grayscale; that
  173901. * provides an easy way of coercing a grayscale JPEG with funny sampling
  173902. * factors to the customary 1,1. (Some decoders fail on other factors.)
  173903. */
  173904. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  173905. dstinfo->num_components == 3) ||
  173906. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  173907. dstinfo->num_components == 1)) {
  173908. /* We have to preserve the source's quantization table number. */
  173909. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  173910. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  173911. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  173912. } else {
  173913. /* Sorry, can't do it */
  173914. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  173915. }
  173916. }
  173917. /* Correct the destination's image dimensions etc if necessary */
  173918. switch (info->transform) {
  173919. case JXFORM_NONE:
  173920. /* Nothing to do */
  173921. break;
  173922. case JXFORM_FLIP_H:
  173923. if (info->trim)
  173924. trim_right_edge(dstinfo);
  173925. break;
  173926. case JXFORM_FLIP_V:
  173927. if (info->trim)
  173928. trim_bottom_edge(dstinfo);
  173929. break;
  173930. case JXFORM_TRANSPOSE:
  173931. transpose_critical_parameters(dstinfo);
  173932. /* transpose does NOT have to trim anything */
  173933. break;
  173934. case JXFORM_TRANSVERSE:
  173935. transpose_critical_parameters(dstinfo);
  173936. if (info->trim) {
  173937. trim_right_edge(dstinfo);
  173938. trim_bottom_edge(dstinfo);
  173939. }
  173940. break;
  173941. case JXFORM_ROT_90:
  173942. transpose_critical_parameters(dstinfo);
  173943. if (info->trim)
  173944. trim_right_edge(dstinfo);
  173945. break;
  173946. case JXFORM_ROT_180:
  173947. if (info->trim) {
  173948. trim_right_edge(dstinfo);
  173949. trim_bottom_edge(dstinfo);
  173950. }
  173951. break;
  173952. case JXFORM_ROT_270:
  173953. transpose_critical_parameters(dstinfo);
  173954. if (info->trim)
  173955. trim_bottom_edge(dstinfo);
  173956. break;
  173957. }
  173958. /* Return the appropriate output data set */
  173959. if (info->workspace_coef_arrays != NULL)
  173960. return info->workspace_coef_arrays;
  173961. return src_coef_arrays;
  173962. }
  173963. /* Execute the actual transformation, if any.
  173964. *
  173965. * This must be called *after* jpeg_write_coefficients, because it depends
  173966. * on jpeg_write_coefficients to have computed subsidiary values such as
  173967. * the per-component width and height fields in the destination object.
  173968. *
  173969. * Note that some transformations will modify the source data arrays!
  173970. */
  173971. GLOBAL(void)
  173972. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  173973. j_compress_ptr dstinfo,
  173974. jvirt_barray_ptr *src_coef_arrays,
  173975. jpeg_transform_info *info)
  173976. {
  173977. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  173978. switch (info->transform) {
  173979. case JXFORM_NONE:
  173980. break;
  173981. case JXFORM_FLIP_H:
  173982. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  173983. break;
  173984. case JXFORM_FLIP_V:
  173985. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173986. break;
  173987. case JXFORM_TRANSPOSE:
  173988. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173989. break;
  173990. case JXFORM_TRANSVERSE:
  173991. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173992. break;
  173993. case JXFORM_ROT_90:
  173994. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173995. break;
  173996. case JXFORM_ROT_180:
  173997. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173998. break;
  173999. case JXFORM_ROT_270:
  174000. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  174001. break;
  174002. }
  174003. }
  174004. #endif /* TRANSFORMS_SUPPORTED */
  174005. /* Setup decompression object to save desired markers in memory.
  174006. * This must be called before jpeg_read_header() to have the desired effect.
  174007. */
  174008. GLOBAL(void)
  174009. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  174010. {
  174011. #ifdef SAVE_MARKERS_SUPPORTED
  174012. int m;
  174013. /* Save comments except under NONE option */
  174014. if (option != JCOPYOPT_NONE) {
  174015. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  174016. }
  174017. /* Save all types of APPn markers iff ALL option */
  174018. if (option == JCOPYOPT_ALL) {
  174019. for (m = 0; m < 16; m++)
  174020. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  174021. }
  174022. #endif /* SAVE_MARKERS_SUPPORTED */
  174023. }
  174024. /* Copy markers saved in the given source object to the destination object.
  174025. * This should be called just after jpeg_start_compress() or
  174026. * jpeg_write_coefficients().
  174027. * Note that those routines will have written the SOI, and also the
  174028. * JFIF APP0 or Adobe APP14 markers if selected.
  174029. */
  174030. GLOBAL(void)
  174031. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174032. JCOPY_OPTION option)
  174033. {
  174034. jpeg_saved_marker_ptr marker;
  174035. /* In the current implementation, we don't actually need to examine the
  174036. * option flag here; we just copy everything that got saved.
  174037. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  174038. * if the encoder library already wrote one.
  174039. */
  174040. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  174041. if (dstinfo->write_JFIF_header &&
  174042. marker->marker == JPEG_APP0 &&
  174043. marker->data_length >= 5 &&
  174044. GETJOCTET(marker->data[0]) == 0x4A &&
  174045. GETJOCTET(marker->data[1]) == 0x46 &&
  174046. GETJOCTET(marker->data[2]) == 0x49 &&
  174047. GETJOCTET(marker->data[3]) == 0x46 &&
  174048. GETJOCTET(marker->data[4]) == 0)
  174049. continue; /* reject duplicate JFIF */
  174050. if (dstinfo->write_Adobe_marker &&
  174051. marker->marker == JPEG_APP0+14 &&
  174052. marker->data_length >= 5 &&
  174053. GETJOCTET(marker->data[0]) == 0x41 &&
  174054. GETJOCTET(marker->data[1]) == 0x64 &&
  174055. GETJOCTET(marker->data[2]) == 0x6F &&
  174056. GETJOCTET(marker->data[3]) == 0x62 &&
  174057. GETJOCTET(marker->data[4]) == 0x65)
  174058. continue; /* reject duplicate Adobe */
  174059. #ifdef NEED_FAR_POINTERS
  174060. /* We could use jpeg_write_marker if the data weren't FAR... */
  174061. {
  174062. unsigned int i;
  174063. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  174064. for (i = 0; i < marker->data_length; i++)
  174065. jpeg_write_m_byte(dstinfo, marker->data[i]);
  174066. }
  174067. #else
  174068. jpeg_write_marker(dstinfo, marker->marker,
  174069. marker->data, marker->data_length);
  174070. #endif
  174071. }
  174072. }
  174073. /********* End of inlined file: transupp.c *********/
  174074. }
  174075. }
  174076. #if JUCE_MSVC
  174077. #pragma warning (pop)
  174078. #endif
  174079. BEGIN_JUCE_NAMESPACE
  174080. using namespace jpeglibNamespace;
  174081. struct JPEGDecodingFailure {};
  174082. static void fatalErrorHandler (j_common_ptr)
  174083. {
  174084. throw JPEGDecodingFailure();
  174085. }
  174086. static void silentErrorCallback1 (j_common_ptr) {}
  174087. static void silentErrorCallback2 (j_common_ptr, int) {}
  174088. static void silentErrorCallback3 (j_common_ptr, char*) {}
  174089. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  174090. {
  174091. zerostruct (err);
  174092. err.error_exit = fatalErrorHandler;
  174093. err.emit_message = silentErrorCallback2;
  174094. err.output_message = silentErrorCallback1;
  174095. err.format_message = silentErrorCallback3;
  174096. err.reset_error_mgr = silentErrorCallback1;
  174097. }
  174098. static void dummyCallback1 (j_decompress_ptr) throw()
  174099. {
  174100. }
  174101. static void jpegSkip (j_decompress_ptr decompStruct, long num) throw()
  174102. {
  174103. decompStruct->src->next_input_byte += num;
  174104. num = jmin (num, (int) decompStruct->src->bytes_in_buffer);
  174105. decompStruct->src->bytes_in_buffer -= num;
  174106. }
  174107. static boolean jpegFill (j_decompress_ptr) throw()
  174108. {
  174109. return 0;
  174110. }
  174111. Image* juce_loadJPEGImageFromStream (InputStream& in) throw()
  174112. {
  174113. MemoryBlock mb;
  174114. in.readIntoMemoryBlock (mb);
  174115. Image* image = 0;
  174116. if (mb.getSize() > 16)
  174117. {
  174118. struct jpeg_decompress_struct jpegDecompStruct;
  174119. struct jpeg_error_mgr jerr;
  174120. setupSilentErrorHandler (jerr);
  174121. jpegDecompStruct.err = &jerr;
  174122. jpeg_create_decompress (&jpegDecompStruct);
  174123. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  174124. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  174125. jpegDecompStruct.src->init_source = dummyCallback1;
  174126. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  174127. jpegDecompStruct.src->skip_input_data = jpegSkip;
  174128. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  174129. jpegDecompStruct.src->term_source = dummyCallback1;
  174130. jpegDecompStruct.src->next_input_byte = (const unsigned char*) mb.getData();
  174131. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  174132. try
  174133. {
  174134. jpeg_read_header (&jpegDecompStruct, TRUE);
  174135. jpeg_calc_output_dimensions (&jpegDecompStruct);
  174136. const int width = jpegDecompStruct.output_width;
  174137. const int height = jpegDecompStruct.output_height;
  174138. jpegDecompStruct.out_color_space = JCS_RGB;
  174139. JSAMPARRAY buffer
  174140. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  174141. JPOOL_IMAGE,
  174142. width * 3, 1);
  174143. if (jpeg_start_decompress (&jpegDecompStruct))
  174144. {
  174145. image = new Image (Image::RGB, width, height, false);
  174146. for (int y = 0; y < height; ++y)
  174147. {
  174148. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  174149. int stride, pixelStride;
  174150. uint8* pixels = image->lockPixelDataReadWrite (0, y, width, 1, stride, pixelStride);
  174151. const uint8* src = *buffer;
  174152. uint8* dest = pixels;
  174153. for (int i = width; --i >= 0;)
  174154. {
  174155. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  174156. dest += pixelStride;
  174157. src += 3;
  174158. }
  174159. image->releasePixelDataReadWrite (pixels);
  174160. }
  174161. jpeg_finish_decompress (&jpegDecompStruct);
  174162. }
  174163. jpeg_destroy_decompress (&jpegDecompStruct);
  174164. }
  174165. catch (...)
  174166. {}
  174167. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  174168. }
  174169. return image;
  174170. }
  174171. static const int bufferSize = 512;
  174172. struct JuceJpegDest : public jpeg_destination_mgr
  174173. {
  174174. OutputStream* output;
  174175. char* buffer;
  174176. };
  174177. static void jpegWriteInit (j_compress_ptr) throw()
  174178. {
  174179. }
  174180. static void jpegWriteTerminate (j_compress_ptr cinfo) throw()
  174181. {
  174182. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  174183. const int numToWrite = bufferSize - dest->free_in_buffer;
  174184. dest->output->write (dest->buffer, numToWrite);
  174185. }
  174186. static boolean jpegWriteFlush (j_compress_ptr cinfo) throw()
  174187. {
  174188. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  174189. const int numToWrite = bufferSize;
  174190. dest->next_output_byte = (JOCTET*) dest->buffer;
  174191. dest->free_in_buffer = bufferSize;
  174192. return dest->output->write (dest->buffer, numToWrite);
  174193. }
  174194. bool juce_writeJPEGImageToStream (const Image& image,
  174195. OutputStream& out,
  174196. float quality) throw()
  174197. {
  174198. if (image.hasAlphaChannel())
  174199. {
  174200. // this method could fill the background in white and still save the image..
  174201. jassertfalse
  174202. return true;
  174203. }
  174204. struct jpeg_compress_struct jpegCompStruct;
  174205. struct jpeg_error_mgr jerr;
  174206. setupSilentErrorHandler (jerr);
  174207. jpegCompStruct.err = &jerr;
  174208. jpeg_create_compress (&jpegCompStruct);
  174209. JuceJpegDest dest;
  174210. jpegCompStruct.dest = &dest;
  174211. dest.output = &out;
  174212. dest.buffer = (char*) juce_malloc (bufferSize);
  174213. dest.next_output_byte = (JOCTET*) dest.buffer;
  174214. dest.free_in_buffer = bufferSize;
  174215. dest.init_destination = jpegWriteInit;
  174216. dest.empty_output_buffer = jpegWriteFlush;
  174217. dest.term_destination = jpegWriteTerminate;
  174218. jpegCompStruct.image_width = image.getWidth();
  174219. jpegCompStruct.image_height = image.getHeight();
  174220. jpegCompStruct.input_components = 3;
  174221. jpegCompStruct.in_color_space = JCS_RGB;
  174222. jpegCompStruct.write_JFIF_header = 1;
  174223. jpegCompStruct.X_density = 72;
  174224. jpegCompStruct.Y_density = 72;
  174225. jpeg_set_defaults (&jpegCompStruct);
  174226. jpegCompStruct.dct_method = JDCT_FLOAT;
  174227. jpegCompStruct.optimize_coding = 1;
  174228. // jpegCompStruct.smoothing_factor = 10;
  174229. if (quality < 0.0f)
  174230. quality = 0.85f;
  174231. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundFloatToInt (quality * 100.0f)), TRUE);
  174232. jpeg_start_compress (&jpegCompStruct, TRUE);
  174233. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  174234. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  174235. JPOOL_IMAGE,
  174236. strideBytes, 1);
  174237. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  174238. {
  174239. int stride, pixelStride;
  174240. const uint8* pixels = image.lockPixelDataReadOnly (0, jpegCompStruct.next_scanline, jpegCompStruct.image_width, 1, stride, pixelStride);
  174241. const uint8* src = pixels;
  174242. uint8* dst = *buffer;
  174243. for (int i = jpegCompStruct.image_width; --i >= 0;)
  174244. {
  174245. *dst++ = ((const PixelRGB*) src)->getRed();
  174246. *dst++ = ((const PixelRGB*) src)->getGreen();
  174247. *dst++ = ((const PixelRGB*) src)->getBlue();
  174248. src += pixelStride;
  174249. }
  174250. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  174251. image.releasePixelDataReadOnly (pixels);
  174252. }
  174253. jpeg_finish_compress (&jpegCompStruct);
  174254. jpeg_destroy_compress (&jpegCompStruct);
  174255. juce_free (dest.buffer);
  174256. out.flush();
  174257. return true;
  174258. }
  174259. END_JUCE_NAMESPACE
  174260. /********* End of inlined file: juce_JPEGLoader.cpp *********/
  174261. /********* Start of inlined file: juce_PNGLoader.cpp *********/
  174262. #ifdef _MSC_VER
  174263. #pragma warning (push)
  174264. #pragma warning (disable: 4390 4611)
  174265. #endif
  174266. namespace zlibNamespace
  174267. {
  174268. #undef OS_CODE
  174269. #undef fdopen
  174270. #undef OS_CODE
  174271. }
  174272. namespace pnglibNamespace
  174273. {
  174274. using namespace zlibNamespace;
  174275. using ::malloc;
  174276. using ::free;
  174277. extern "C"
  174278. {
  174279. using ::abs;
  174280. #define PNG_INTERNAL
  174281. #define NO_DUMMY_DECL
  174282. #define PNG_SETJMP_NOT_SUPPORTED
  174283. /********* Start of inlined file: png.h *********/
  174284. /* png.h - header file for PNG reference library
  174285. *
  174286. * libpng version 1.2.21 - October 4, 2007
  174287. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  174288. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  174289. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  174290. *
  174291. * Authors and maintainers:
  174292. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  174293. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  174294. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  174295. * See also "Contributing Authors", below.
  174296. *
  174297. * Note about libpng version numbers:
  174298. *
  174299. * Due to various miscommunications, unforeseen code incompatibilities
  174300. * and occasional factors outside the authors' control, version numbering
  174301. * on the library has not always been consistent and straightforward.
  174302. * The following table summarizes matters since version 0.89c, which was
  174303. * the first widely used release:
  174304. *
  174305. * source png.h png.h shared-lib
  174306. * version string int version
  174307. * ------- ------ ----- ----------
  174308. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  174309. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  174310. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  174311. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  174312. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  174313. * 0.97c 0.97 97 2.0.97
  174314. * 0.98 0.98 98 2.0.98
  174315. * 0.99 0.99 98 2.0.99
  174316. * 0.99a-m 0.99 99 2.0.99
  174317. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  174318. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  174319. * 1.0.1 png.h string is 10001 2.1.0
  174320. * 1.0.1a-e identical to the 10002 from here on, the shared library
  174321. * 1.0.2 source version) 10002 is 2.V where V is the source code
  174322. * 1.0.2a-b 10003 version, except as noted.
  174323. * 1.0.3 10003
  174324. * 1.0.3a-d 10004
  174325. * 1.0.4 10004
  174326. * 1.0.4a-f 10005
  174327. * 1.0.5 (+ 2 patches) 10005
  174328. * 1.0.5a-d 10006
  174329. * 1.0.5e-r 10100 (not source compatible)
  174330. * 1.0.5s-v 10006 (not binary compatible)
  174331. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  174332. * 1.0.6d-f 10007 (still binary incompatible)
  174333. * 1.0.6g 10007
  174334. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  174335. * 1.0.6i 10007 10.6i
  174336. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  174337. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  174338. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  174339. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  174340. * 1.0.7 1 10007 (still compatible)
  174341. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  174342. * 1.0.8rc1 1 10008 2.1.0.8rc1
  174343. * 1.0.8 1 10008 2.1.0.8
  174344. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  174345. * 1.0.9rc1 1 10009 2.1.0.9rc1
  174346. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  174347. * 1.0.9rc2 1 10009 2.1.0.9rc2
  174348. * 1.0.9 1 10009 2.1.0.9
  174349. * 1.0.10beta1 1 10010 2.1.0.10beta1
  174350. * 1.0.10rc1 1 10010 2.1.0.10rc1
  174351. * 1.0.10 1 10010 2.1.0.10
  174352. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  174353. * 1.0.11rc1 1 10011 2.1.0.11rc1
  174354. * 1.0.11 1 10011 2.1.0.11
  174355. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  174356. * 1.0.12rc1 2 10012 2.1.0.12rc1
  174357. * 1.0.12 2 10012 2.1.0.12
  174358. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  174359. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  174360. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  174361. * 1.2.0rc1 3 10200 3.1.2.0rc1
  174362. * 1.2.0 3 10200 3.1.2.0
  174363. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  174364. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  174365. * 1.2.1 3 10201 3.1.2.1
  174366. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  174367. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  174368. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  174369. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  174370. * 1.0.13 10 10013 10.so.0.1.0.13
  174371. * 1.2.2 12 10202 12.so.0.1.2.2
  174372. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  174373. * 1.2.3 12 10203 12.so.0.1.2.3
  174374. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  174375. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  174376. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  174377. * 1.0.14 10 10014 10.so.0.1.0.14
  174378. * 1.2.4 13 10204 12.so.0.1.2.4
  174379. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  174380. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  174381. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  174382. * 1.0.15 10 10015 10.so.0.1.0.15
  174383. * 1.2.5 13 10205 12.so.0.1.2.5
  174384. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  174385. * 1.0.16 10 10016 10.so.0.1.0.16
  174386. * 1.2.6 13 10206 12.so.0.1.2.6
  174387. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  174388. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  174389. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  174390. * 1.0.17 10 10017 10.so.0.1.0.17
  174391. * 1.2.7 13 10207 12.so.0.1.2.7
  174392. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  174393. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  174394. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  174395. * 1.0.18 10 10018 10.so.0.1.0.18
  174396. * 1.2.8 13 10208 12.so.0.1.2.8
  174397. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  174398. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  174399. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  174400. * 1.2.9 13 10209 12.so.0.9[.0]
  174401. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  174402. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  174403. * 1.2.10 13 10210 12.so.0.10[.0]
  174404. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  174405. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  174406. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  174407. * 1.0.19 10 10019 10.so.0.19[.0]
  174408. * 1.2.11 13 10211 12.so.0.11[.0]
  174409. * 1.0.20 10 10020 10.so.0.20[.0]
  174410. * 1.2.12 13 10212 12.so.0.12[.0]
  174411. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  174412. * 1.0.21 10 10021 10.so.0.21[.0]
  174413. * 1.2.13 13 10213 12.so.0.13[.0]
  174414. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  174415. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  174416. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  174417. * 1.0.22 10 10022 10.so.0.22[.0]
  174418. * 1.2.14 13 10214 12.so.0.14[.0]
  174419. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  174420. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  174421. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  174422. * 1.0.23 10 10023 10.so.0.23[.0]
  174423. * 1.2.15 13 10215 12.so.0.15[.0]
  174424. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  174425. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  174426. * 1.0.24 10 10024 10.so.0.24[.0]
  174427. * 1.2.16 13 10216 12.so.0.16[.0]
  174428. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  174429. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  174430. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  174431. * 1.0.25 10 10025 10.so.0.25[.0]
  174432. * 1.2.17 13 10217 12.so.0.17[.0]
  174433. * 1.0.26 10 10026 10.so.0.26[.0]
  174434. * 1.2.18 13 10218 12.so.0.18[.0]
  174435. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  174436. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  174437. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  174438. * 1.0.27 10 10027 10.so.0.27[.0]
  174439. * 1.2.19 13 10219 12.so.0.19[.0]
  174440. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  174441. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  174442. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  174443. * 1.0.28 10 10028 10.so.0.28[.0]
  174444. * 1.2.20 13 10220 12.so.0.20[.0]
  174445. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  174446. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  174447. * 1.0.29 10 10029 10.so.0.29[.0]
  174448. * 1.2.21 13 10221 12.so.0.21[.0]
  174449. *
  174450. * Henceforth the source version will match the shared-library major
  174451. * and minor numbers; the shared-library major version number will be
  174452. * used for changes in backward compatibility, as it is intended. The
  174453. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  174454. * for applications, is an unsigned integer of the form xyyzz corresponding
  174455. * to the source version x.y.z (leading zeros in y and z). Beta versions
  174456. * were given the previous public release number plus a letter, until
  174457. * version 1.0.6j; from then on they were given the upcoming public
  174458. * release number plus "betaNN" or "rcN".
  174459. *
  174460. * Binary incompatibility exists only when applications make direct access
  174461. * to the info_ptr or png_ptr members through png.h, and the compiled
  174462. * application is loaded with a different version of the library.
  174463. *
  174464. * DLLNUM will change each time there are forward or backward changes
  174465. * in binary compatibility (e.g., when a new feature is added).
  174466. *
  174467. * See libpng.txt or libpng.3 for more information. The PNG specification
  174468. * is available as a W3C Recommendation and as an ISO Specification,
  174469. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  174470. */
  174471. /*
  174472. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  174473. *
  174474. * If you modify libpng you may insert additional notices immediately following
  174475. * this sentence.
  174476. *
  174477. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  174478. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  174479. * distributed according to the same disclaimer and license as libpng-1.2.5
  174480. * with the following individual added to the list of Contributing Authors:
  174481. *
  174482. * Cosmin Truta
  174483. *
  174484. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  174485. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  174486. * distributed according to the same disclaimer and license as libpng-1.0.6
  174487. * with the following individuals added to the list of Contributing Authors:
  174488. *
  174489. * Simon-Pierre Cadieux
  174490. * Eric S. Raymond
  174491. * Gilles Vollant
  174492. *
  174493. * and with the following additions to the disclaimer:
  174494. *
  174495. * There is no warranty against interference with your enjoyment of the
  174496. * library or against infringement. There is no warranty that our
  174497. * efforts or the library will fulfill any of your particular purposes
  174498. * or needs. This library is provided with all faults, and the entire
  174499. * risk of satisfactory quality, performance, accuracy, and effort is with
  174500. * the user.
  174501. *
  174502. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  174503. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  174504. * distributed according to the same disclaimer and license as libpng-0.96,
  174505. * with the following individuals added to the list of Contributing Authors:
  174506. *
  174507. * Tom Lane
  174508. * Glenn Randers-Pehrson
  174509. * Willem van Schaik
  174510. *
  174511. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  174512. * Copyright (c) 1996, 1997 Andreas Dilger
  174513. * Distributed according to the same disclaimer and license as libpng-0.88,
  174514. * with the following individuals added to the list of Contributing Authors:
  174515. *
  174516. * John Bowler
  174517. * Kevin Bracey
  174518. * Sam Bushell
  174519. * Magnus Holmgren
  174520. * Greg Roelofs
  174521. * Tom Tanner
  174522. *
  174523. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  174524. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  174525. *
  174526. * For the purposes of this copyright and license, "Contributing Authors"
  174527. * is defined as the following set of individuals:
  174528. *
  174529. * Andreas Dilger
  174530. * Dave Martindale
  174531. * Guy Eric Schalnat
  174532. * Paul Schmidt
  174533. * Tim Wegner
  174534. *
  174535. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  174536. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  174537. * including, without limitation, the warranties of merchantability and of
  174538. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  174539. * assume no liability for direct, indirect, incidental, special, exemplary,
  174540. * or consequential damages, which may result from the use of the PNG
  174541. * Reference Library, even if advised of the possibility of such damage.
  174542. *
  174543. * Permission is hereby granted to use, copy, modify, and distribute this
  174544. * source code, or portions hereof, for any purpose, without fee, subject
  174545. * to the following restrictions:
  174546. *
  174547. * 1. The origin of this source code must not be misrepresented.
  174548. *
  174549. * 2. Altered versions must be plainly marked as such and
  174550. * must not be misrepresented as being the original source.
  174551. *
  174552. * 3. This Copyright notice may not be removed or altered from
  174553. * any source or altered source distribution.
  174554. *
  174555. * The Contributing Authors and Group 42, Inc. specifically permit, without
  174556. * fee, and encourage the use of this source code as a component to
  174557. * supporting the PNG file format in commercial products. If you use this
  174558. * source code in a product, acknowledgment is not required but would be
  174559. * appreciated.
  174560. */
  174561. /*
  174562. * A "png_get_copyright" function is available, for convenient use in "about"
  174563. * boxes and the like:
  174564. *
  174565. * printf("%s",png_get_copyright(NULL));
  174566. *
  174567. * Also, the PNG logo (in PNG format, of course) is supplied in the
  174568. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  174569. */
  174570. /*
  174571. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  174572. * certification mark of the Open Source Initiative.
  174573. */
  174574. /*
  174575. * The contributing authors would like to thank all those who helped
  174576. * with testing, bug fixes, and patience. This wouldn't have been
  174577. * possible without all of you.
  174578. *
  174579. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  174580. */
  174581. /*
  174582. * Y2K compliance in libpng:
  174583. * =========================
  174584. *
  174585. * October 4, 2007
  174586. *
  174587. * Since the PNG Development group is an ad-hoc body, we can't make
  174588. * an official declaration.
  174589. *
  174590. * This is your unofficial assurance that libpng from version 0.71 and
  174591. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  174592. * versions were also Y2K compliant.
  174593. *
  174594. * Libpng only has three year fields. One is a 2-byte unsigned integer
  174595. * that will hold years up to 65535. The other two hold the date in text
  174596. * format, and will hold years up to 9999.
  174597. *
  174598. * The integer is
  174599. * "png_uint_16 year" in png_time_struct.
  174600. *
  174601. * The strings are
  174602. * "png_charp time_buffer" in png_struct and
  174603. * "near_time_buffer", which is a local character string in png.c.
  174604. *
  174605. * There are seven time-related functions:
  174606. * png.c: png_convert_to_rfc_1123() in png.c
  174607. * (formerly png_convert_to_rfc_1152() in error)
  174608. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  174609. * png_convert_from_time_t() in pngwrite.c
  174610. * png_get_tIME() in pngget.c
  174611. * png_handle_tIME() in pngrutil.c, called in pngread.c
  174612. * png_set_tIME() in pngset.c
  174613. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  174614. *
  174615. * All handle dates properly in a Y2K environment. The
  174616. * png_convert_from_time_t() function calls gmtime() to convert from system
  174617. * clock time, which returns (year - 1900), which we properly convert to
  174618. * the full 4-digit year. There is a possibility that applications using
  174619. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  174620. * function, or that they are incorrectly passing only a 2-digit year
  174621. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  174622. * but this is not under our control. The libpng documentation has always
  174623. * stated that it works with 4-digit years, and the APIs have been
  174624. * documented as such.
  174625. *
  174626. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  174627. * integer to hold the year, and can hold years as large as 65535.
  174628. *
  174629. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  174630. * no date-related code.
  174631. *
  174632. * Glenn Randers-Pehrson
  174633. * libpng maintainer
  174634. * PNG Development Group
  174635. */
  174636. #ifndef PNG_H
  174637. #define PNG_H
  174638. /* This is not the place to learn how to use libpng. The file libpng.txt
  174639. * describes how to use libpng, and the file example.c summarizes it
  174640. * with some code on which to build. This file is useful for looking
  174641. * at the actual function definitions and structure components.
  174642. */
  174643. /* Version information for png.h - this should match the version in png.c */
  174644. #define PNG_LIBPNG_VER_STRING "1.2.21"
  174645. #define PNG_HEADER_VERSION_STRING \
  174646. " libpng version 1.2.21 - October 4, 2007\n"
  174647. #define PNG_LIBPNG_VER_SONUM 0
  174648. #define PNG_LIBPNG_VER_DLLNUM 13
  174649. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  174650. #define PNG_LIBPNG_VER_MAJOR 1
  174651. #define PNG_LIBPNG_VER_MINOR 2
  174652. #define PNG_LIBPNG_VER_RELEASE 21
  174653. /* This should match the numeric part of the final component of
  174654. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  174655. #define PNG_LIBPNG_VER_BUILD 0
  174656. /* Release Status */
  174657. #define PNG_LIBPNG_BUILD_ALPHA 1
  174658. #define PNG_LIBPNG_BUILD_BETA 2
  174659. #define PNG_LIBPNG_BUILD_RC 3
  174660. #define PNG_LIBPNG_BUILD_STABLE 4
  174661. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  174662. /* Release-Specific Flags */
  174663. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  174664. PNG_LIBPNG_BUILD_STABLE only */
  174665. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  174666. PNG_LIBPNG_BUILD_SPECIAL */
  174667. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  174668. PNG_LIBPNG_BUILD_PRIVATE */
  174669. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  174670. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  174671. * We must not include leading zeros.
  174672. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  174673. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  174674. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  174675. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  174676. #ifndef PNG_VERSION_INFO_ONLY
  174677. /* include the compression library's header */
  174678. #endif
  174679. /* include all user configurable info, including optional assembler routines */
  174680. /********* Start of inlined file: pngconf.h *********/
  174681. /* pngconf.h - machine configurable file for libpng
  174682. *
  174683. * libpng version 1.2.21 - October 4, 2007
  174684. * For conditions of distribution and use, see copyright notice in png.h
  174685. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  174686. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  174687. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  174688. */
  174689. /* Any machine specific code is near the front of this file, so if you
  174690. * are configuring libpng for a machine, you may want to read the section
  174691. * starting here down to where it starts to typedef png_color, png_text,
  174692. * and png_info.
  174693. */
  174694. #ifndef PNGCONF_H
  174695. #define PNGCONF_H
  174696. #define PNG_1_2_X
  174697. // These are some Juce config settings that should remove any unnecessary code bloat..
  174698. #define PNG_NO_STDIO 1
  174699. #define PNG_DEBUG 0
  174700. #define PNG_NO_WARNINGS 1
  174701. #define PNG_NO_ERROR_TEXT 1
  174702. #define PNG_NO_ERROR_NUMBERS 1
  174703. #define PNG_NO_USER_MEM 1
  174704. #define PNG_NO_READ_iCCP 1
  174705. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  174706. #define PNG_NO_READ_USER_CHUNKS 1
  174707. #define PNG_NO_READ_iTXt 1
  174708. #define PNG_NO_READ_sCAL 1
  174709. #define PNG_NO_READ_sPLT 1
  174710. #define png_error(a, b) png_err(a)
  174711. #define png_warning(a, b)
  174712. #define png_chunk_error(a, b) png_err(a)
  174713. #define png_chunk_warning(a, b)
  174714. /*
  174715. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  174716. * includes the resource compiler for Windows DLL configurations.
  174717. */
  174718. #ifdef PNG_USER_CONFIG
  174719. # ifndef PNG_USER_PRIVATEBUILD
  174720. # define PNG_USER_PRIVATEBUILD
  174721. # endif
  174722. #include "pngusr.h"
  174723. #endif
  174724. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  174725. #ifdef PNG_CONFIGURE_LIBPNG
  174726. #ifdef HAVE_CONFIG_H
  174727. #include "config.h"
  174728. #endif
  174729. #endif
  174730. /*
  174731. * Added at libpng-1.2.8
  174732. *
  174733. * If you create a private DLL you need to define in "pngusr.h" the followings:
  174734. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  174735. * the DLL was built>
  174736. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  174737. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  174738. * distinguish your DLL from those of the official release. These
  174739. * correspond to the trailing letters that come after the version
  174740. * number and must match your private DLL name>
  174741. * e.g. // private DLL "libpng13gx.dll"
  174742. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  174743. *
  174744. * The following macros are also at your disposal if you want to complete the
  174745. * DLL VERSIONINFO structure.
  174746. * - PNG_USER_VERSIONINFO_COMMENTS
  174747. * - PNG_USER_VERSIONINFO_COMPANYNAME
  174748. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  174749. */
  174750. #ifdef __STDC__
  174751. #ifdef SPECIALBUILD
  174752. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  174753. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  174754. #endif
  174755. #ifdef PRIVATEBUILD
  174756. # pragma message("PRIVATEBUILD is deprecated.\
  174757. Use PNG_USER_PRIVATEBUILD instead.")
  174758. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  174759. #endif
  174760. #endif /* __STDC__ */
  174761. #ifndef PNG_VERSION_INFO_ONLY
  174762. /* End of material added to libpng-1.2.8 */
  174763. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  174764. Restored at libpng-1.2.21 */
  174765. # define PNG_WARN_UNINITIALIZED_ROW 1
  174766. /* End of material added at libpng-1.2.19/1.2.21 */
  174767. /* This is the size of the compression buffer, and thus the size of
  174768. * an IDAT chunk. Make this whatever size you feel is best for your
  174769. * machine. One of these will be allocated per png_struct. When this
  174770. * is full, it writes the data to the disk, and does some other
  174771. * calculations. Making this an extremely small size will slow
  174772. * the library down, but you may want to experiment to determine
  174773. * where it becomes significant, if you are concerned with memory
  174774. * usage. Note that zlib allocates at least 32Kb also. For readers,
  174775. * this describes the size of the buffer available to read the data in.
  174776. * Unless this gets smaller than the size of a row (compressed),
  174777. * it should not make much difference how big this is.
  174778. */
  174779. #ifndef PNG_ZBUF_SIZE
  174780. # define PNG_ZBUF_SIZE 8192
  174781. #endif
  174782. /* Enable if you want a write-only libpng */
  174783. #ifndef PNG_NO_READ_SUPPORTED
  174784. # define PNG_READ_SUPPORTED
  174785. #endif
  174786. /* Enable if you want a read-only libpng */
  174787. #ifndef PNG_NO_WRITE_SUPPORTED
  174788. # define PNG_WRITE_SUPPORTED
  174789. #endif
  174790. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  174791. support PNGs that are embedded in MNG datastreams */
  174792. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  174793. # ifndef PNG_MNG_FEATURES_SUPPORTED
  174794. # define PNG_MNG_FEATURES_SUPPORTED
  174795. # endif
  174796. #endif
  174797. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  174798. # ifndef PNG_FLOATING_POINT_SUPPORTED
  174799. # define PNG_FLOATING_POINT_SUPPORTED
  174800. # endif
  174801. #endif
  174802. /* If you are running on a machine where you cannot allocate more
  174803. * than 64K of memory at once, uncomment this. While libpng will not
  174804. * normally need that much memory in a chunk (unless you load up a very
  174805. * large file), zlib needs to know how big of a chunk it can use, and
  174806. * libpng thus makes sure to check any memory allocation to verify it
  174807. * will fit into memory.
  174808. #define PNG_MAX_MALLOC_64K
  174809. */
  174810. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  174811. # define PNG_MAX_MALLOC_64K
  174812. #endif
  174813. /* Special munging to support doing things the 'cygwin' way:
  174814. * 'Normal' png-on-win32 defines/defaults:
  174815. * PNG_BUILD_DLL -- building dll
  174816. * PNG_USE_DLL -- building an application, linking to dll
  174817. * (no define) -- building static library, or building an
  174818. * application and linking to the static lib
  174819. * 'Cygwin' defines/defaults:
  174820. * PNG_BUILD_DLL -- (ignored) building the dll
  174821. * (no define) -- (ignored) building an application, linking to the dll
  174822. * PNG_STATIC -- (ignored) building the static lib, or building an
  174823. * application that links to the static lib.
  174824. * ALL_STATIC -- (ignored) building various static libs, or building an
  174825. * application that links to the static libs.
  174826. * Thus,
  174827. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  174828. * this bit of #ifdefs will define the 'correct' config variables based on
  174829. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  174830. * unnecessary.
  174831. *
  174832. * Also, the precedence order is:
  174833. * ALL_STATIC (since we can't #undef something outside our namespace)
  174834. * PNG_BUILD_DLL
  174835. * PNG_STATIC
  174836. * (nothing) == PNG_USE_DLL
  174837. *
  174838. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  174839. * of auto-import in binutils, we no longer need to worry about
  174840. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  174841. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  174842. * to __declspec() stuff. However, we DO need to worry about
  174843. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  174844. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  174845. */
  174846. #if defined(__CYGWIN__)
  174847. # if defined(ALL_STATIC)
  174848. # if defined(PNG_BUILD_DLL)
  174849. # undef PNG_BUILD_DLL
  174850. # endif
  174851. # if defined(PNG_USE_DLL)
  174852. # undef PNG_USE_DLL
  174853. # endif
  174854. # if defined(PNG_DLL)
  174855. # undef PNG_DLL
  174856. # endif
  174857. # if !defined(PNG_STATIC)
  174858. # define PNG_STATIC
  174859. # endif
  174860. # else
  174861. # if defined (PNG_BUILD_DLL)
  174862. # if defined(PNG_STATIC)
  174863. # undef PNG_STATIC
  174864. # endif
  174865. # if defined(PNG_USE_DLL)
  174866. # undef PNG_USE_DLL
  174867. # endif
  174868. # if !defined(PNG_DLL)
  174869. # define PNG_DLL
  174870. # endif
  174871. # else
  174872. # if defined(PNG_STATIC)
  174873. # if defined(PNG_USE_DLL)
  174874. # undef PNG_USE_DLL
  174875. # endif
  174876. # if defined(PNG_DLL)
  174877. # undef PNG_DLL
  174878. # endif
  174879. # else
  174880. # if !defined(PNG_USE_DLL)
  174881. # define PNG_USE_DLL
  174882. # endif
  174883. # if !defined(PNG_DLL)
  174884. # define PNG_DLL
  174885. # endif
  174886. # endif
  174887. # endif
  174888. # endif
  174889. #endif
  174890. /* This protects us against compilers that run on a windowing system
  174891. * and thus don't have or would rather us not use the stdio types:
  174892. * stdin, stdout, and stderr. The only one currently used is stderr
  174893. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  174894. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  174895. * will also prevent these, plus will prevent the entire set of stdio
  174896. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  174897. * unless (PNG_DEBUG > 0) has been #defined.
  174898. *
  174899. * #define PNG_NO_CONSOLE_IO
  174900. * #define PNG_NO_STDIO
  174901. */
  174902. #if defined(_WIN32_WCE)
  174903. # include <windows.h>
  174904. /* Console I/O functions are not supported on WindowsCE */
  174905. # define PNG_NO_CONSOLE_IO
  174906. # ifdef PNG_DEBUG
  174907. # undef PNG_DEBUG
  174908. # endif
  174909. #endif
  174910. #ifdef PNG_BUILD_DLL
  174911. # ifndef PNG_CONSOLE_IO_SUPPORTED
  174912. # ifndef PNG_NO_CONSOLE_IO
  174913. # define PNG_NO_CONSOLE_IO
  174914. # endif
  174915. # endif
  174916. #endif
  174917. # ifdef PNG_NO_STDIO
  174918. # ifndef PNG_NO_CONSOLE_IO
  174919. # define PNG_NO_CONSOLE_IO
  174920. # endif
  174921. # ifdef PNG_DEBUG
  174922. # if (PNG_DEBUG > 0)
  174923. # include <stdio.h>
  174924. # endif
  174925. # endif
  174926. # else
  174927. # if !defined(_WIN32_WCE)
  174928. /* "stdio.h" functions are not supported on WindowsCE */
  174929. # include <stdio.h>
  174930. # endif
  174931. # endif
  174932. /* This macro protects us against machines that don't have function
  174933. * prototypes (ie K&R style headers). If your compiler does not handle
  174934. * function prototypes, define this macro and use the included ansi2knr.
  174935. * I've always been able to use _NO_PROTO as the indicator, but you may
  174936. * need to drag the empty declaration out in front of here, or change the
  174937. * ifdef to suit your own needs.
  174938. */
  174939. #ifndef PNGARG
  174940. #ifdef OF /* zlib prototype munger */
  174941. # define PNGARG(arglist) OF(arglist)
  174942. #else
  174943. #ifdef _NO_PROTO
  174944. # define PNGARG(arglist) ()
  174945. # ifndef PNG_TYPECAST_NULL
  174946. # define PNG_TYPECAST_NULL
  174947. # endif
  174948. #else
  174949. # define PNGARG(arglist) arglist
  174950. #endif /* _NO_PROTO */
  174951. #endif /* OF */
  174952. #endif /* PNGARG */
  174953. /* Try to determine if we are compiling on a Mac. Note that testing for
  174954. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  174955. * on non-Mac platforms.
  174956. */
  174957. #ifndef MACOS
  174958. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  174959. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  174960. # define MACOS
  174961. # endif
  174962. #endif
  174963. /* enough people need this for various reasons to include it here */
  174964. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  174965. # include <sys/types.h>
  174966. #endif
  174967. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  174968. # define PNG_SETJMP_SUPPORTED
  174969. #endif
  174970. #ifdef PNG_SETJMP_SUPPORTED
  174971. /* This is an attempt to force a single setjmp behaviour on Linux. If
  174972. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  174973. */
  174974. # ifdef __linux__
  174975. # ifdef _BSD_SOURCE
  174976. # define PNG_SAVE_BSD_SOURCE
  174977. # undef _BSD_SOURCE
  174978. # endif
  174979. # ifdef _SETJMP_H
  174980. /* If you encounter a compiler error here, see the explanation
  174981. * near the end of INSTALL.
  174982. */
  174983. __png.h__ already includes setjmp.h;
  174984. __dont__ include it again.;
  174985. # endif
  174986. # endif /* __linux__ */
  174987. /* include setjmp.h for error handling */
  174988. # include <setjmp.h>
  174989. # ifdef __linux__
  174990. # ifdef PNG_SAVE_BSD_SOURCE
  174991. # define _BSD_SOURCE
  174992. # undef PNG_SAVE_BSD_SOURCE
  174993. # endif
  174994. # endif /* __linux__ */
  174995. #endif /* PNG_SETJMP_SUPPORTED */
  174996. #ifdef BSD
  174997. # include <strings.h>
  174998. #else
  174999. # include <string.h>
  175000. #endif
  175001. /* Other defines for things like memory and the like can go here. */
  175002. #ifdef PNG_INTERNAL
  175003. #include <stdlib.h>
  175004. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  175005. * aren't usually used outside the library (as far as I know), so it is
  175006. * debatable if they should be exported at all. In the future, when it is
  175007. * possible to have run-time registry of chunk-handling functions, some of
  175008. * these will be made available again.
  175009. #define PNG_EXTERN extern
  175010. */
  175011. #define PNG_EXTERN
  175012. /* Other defines specific to compilers can go here. Try to keep
  175013. * them inside an appropriate ifdef/endif pair for portability.
  175014. */
  175015. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  175016. # if defined(MACOS)
  175017. /* We need to check that <math.h> hasn't already been included earlier
  175018. * as it seems it doesn't agree with <fp.h>, yet we should really use
  175019. * <fp.h> if possible.
  175020. */
  175021. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  175022. # include <fp.h>
  175023. # endif
  175024. # else
  175025. # include <math.h>
  175026. # endif
  175027. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  175028. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  175029. * MATH=68881
  175030. */
  175031. # include <m68881.h>
  175032. # endif
  175033. #endif
  175034. /* Codewarrior on NT has linking problems without this. */
  175035. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  175036. # define PNG_ALWAYS_EXTERN
  175037. #endif
  175038. /* This provides the non-ANSI (far) memory allocation routines. */
  175039. #if defined(__TURBOC__) && defined(__MSDOS__)
  175040. # include <mem.h>
  175041. # include <alloc.h>
  175042. #endif
  175043. /* I have no idea why is this necessary... */
  175044. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  175045. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  175046. # include <malloc.h>
  175047. #endif
  175048. /* This controls how fine the dithering gets. As this allocates
  175049. * a largish chunk of memory (32K), those who are not as concerned
  175050. * with dithering quality can decrease some or all of these.
  175051. */
  175052. #ifndef PNG_DITHER_RED_BITS
  175053. # define PNG_DITHER_RED_BITS 5
  175054. #endif
  175055. #ifndef PNG_DITHER_GREEN_BITS
  175056. # define PNG_DITHER_GREEN_BITS 5
  175057. #endif
  175058. #ifndef PNG_DITHER_BLUE_BITS
  175059. # define PNG_DITHER_BLUE_BITS 5
  175060. #endif
  175061. /* This controls how fine the gamma correction becomes when you
  175062. * are only interested in 8 bits anyway. Increasing this value
  175063. * results in more memory being used, and more pow() functions
  175064. * being called to fill in the gamma tables. Don't set this value
  175065. * less then 8, and even that may not work (I haven't tested it).
  175066. */
  175067. #ifndef PNG_MAX_GAMMA_8
  175068. # define PNG_MAX_GAMMA_8 11
  175069. #endif
  175070. /* This controls how much a difference in gamma we can tolerate before
  175071. * we actually start doing gamma conversion.
  175072. */
  175073. #ifndef PNG_GAMMA_THRESHOLD
  175074. # define PNG_GAMMA_THRESHOLD 0.05
  175075. #endif
  175076. #endif /* PNG_INTERNAL */
  175077. /* The following uses const char * instead of char * for error
  175078. * and warning message functions, so some compilers won't complain.
  175079. * If you do not want to use const, define PNG_NO_CONST here.
  175080. */
  175081. #ifndef PNG_NO_CONST
  175082. # define PNG_CONST const
  175083. #else
  175084. # define PNG_CONST
  175085. #endif
  175086. /* The following defines give you the ability to remove code from the
  175087. * library that you will not be using. I wish I could figure out how to
  175088. * automate this, but I can't do that without making it seriously hard
  175089. * on the users. So if you are not using an ability, change the #define
  175090. * to and #undef, and that part of the library will not be compiled. If
  175091. * your linker can't find a function, you may want to make sure the
  175092. * ability is defined here. Some of these depend upon some others being
  175093. * defined. I haven't figured out all the interactions here, so you may
  175094. * have to experiment awhile to get everything to compile. If you are
  175095. * creating or using a shared library, you probably shouldn't touch this,
  175096. * as it will affect the size of the structures, and this will cause bad
  175097. * things to happen if the library and/or application ever change.
  175098. */
  175099. /* Any features you will not be using can be undef'ed here */
  175100. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  175101. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  175102. * on the compile line, then pick and choose which ones to define without
  175103. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  175104. * if you only want to have a png-compliant reader/writer but don't need
  175105. * any of the extra transformations. This saves about 80 kbytes in a
  175106. * typical installation of the library. (PNG_NO_* form added in version
  175107. * 1.0.1c, for consistency)
  175108. */
  175109. /* The size of the png_text structure changed in libpng-1.0.6 when
  175110. * iTXt support was added. iTXt support was turned off by default through
  175111. * libpng-1.2.x, to support old apps that malloc the png_text structure
  175112. * instead of calling png_set_text() and letting libpng malloc it. It
  175113. * was turned on by default in libpng-1.3.0.
  175114. */
  175115. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  175116. # ifndef PNG_NO_iTXt_SUPPORTED
  175117. # define PNG_NO_iTXt_SUPPORTED
  175118. # endif
  175119. # ifndef PNG_NO_READ_iTXt
  175120. # define PNG_NO_READ_iTXt
  175121. # endif
  175122. # ifndef PNG_NO_WRITE_iTXt
  175123. # define PNG_NO_WRITE_iTXt
  175124. # endif
  175125. #endif
  175126. #if !defined(PNG_NO_iTXt_SUPPORTED)
  175127. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  175128. # define PNG_READ_iTXt
  175129. # endif
  175130. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  175131. # define PNG_WRITE_iTXt
  175132. # endif
  175133. #endif
  175134. /* The following support, added after version 1.0.0, can be turned off here en
  175135. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  175136. * with old applications that require the length of png_struct and png_info
  175137. * to remain unchanged.
  175138. */
  175139. #ifdef PNG_LEGACY_SUPPORTED
  175140. # define PNG_NO_FREE_ME
  175141. # define PNG_NO_READ_UNKNOWN_CHUNKS
  175142. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  175143. # define PNG_NO_READ_USER_CHUNKS
  175144. # define PNG_NO_READ_iCCP
  175145. # define PNG_NO_WRITE_iCCP
  175146. # define PNG_NO_READ_iTXt
  175147. # define PNG_NO_WRITE_iTXt
  175148. # define PNG_NO_READ_sCAL
  175149. # define PNG_NO_WRITE_sCAL
  175150. # define PNG_NO_READ_sPLT
  175151. # define PNG_NO_WRITE_sPLT
  175152. # define PNG_NO_INFO_IMAGE
  175153. # define PNG_NO_READ_RGB_TO_GRAY
  175154. # define PNG_NO_READ_USER_TRANSFORM
  175155. # define PNG_NO_WRITE_USER_TRANSFORM
  175156. # define PNG_NO_USER_MEM
  175157. # define PNG_NO_READ_EMPTY_PLTE
  175158. # define PNG_NO_MNG_FEATURES
  175159. # define PNG_NO_FIXED_POINT_SUPPORTED
  175160. #endif
  175161. /* Ignore attempt to turn off both floating and fixed point support */
  175162. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  175163. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  175164. # define PNG_FIXED_POINT_SUPPORTED
  175165. #endif
  175166. #ifndef PNG_NO_FREE_ME
  175167. # define PNG_FREE_ME_SUPPORTED
  175168. #endif
  175169. #if defined(PNG_READ_SUPPORTED)
  175170. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  175171. !defined(PNG_NO_READ_TRANSFORMS)
  175172. # define PNG_READ_TRANSFORMS_SUPPORTED
  175173. #endif
  175174. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  175175. # ifndef PNG_NO_READ_EXPAND
  175176. # define PNG_READ_EXPAND_SUPPORTED
  175177. # endif
  175178. # ifndef PNG_NO_READ_SHIFT
  175179. # define PNG_READ_SHIFT_SUPPORTED
  175180. # endif
  175181. # ifndef PNG_NO_READ_PACK
  175182. # define PNG_READ_PACK_SUPPORTED
  175183. # endif
  175184. # ifndef PNG_NO_READ_BGR
  175185. # define PNG_READ_BGR_SUPPORTED
  175186. # endif
  175187. # ifndef PNG_NO_READ_SWAP
  175188. # define PNG_READ_SWAP_SUPPORTED
  175189. # endif
  175190. # ifndef PNG_NO_READ_PACKSWAP
  175191. # define PNG_READ_PACKSWAP_SUPPORTED
  175192. # endif
  175193. # ifndef PNG_NO_READ_INVERT
  175194. # define PNG_READ_INVERT_SUPPORTED
  175195. # endif
  175196. # ifndef PNG_NO_READ_DITHER
  175197. # define PNG_READ_DITHER_SUPPORTED
  175198. # endif
  175199. # ifndef PNG_NO_READ_BACKGROUND
  175200. # define PNG_READ_BACKGROUND_SUPPORTED
  175201. # endif
  175202. # ifndef PNG_NO_READ_16_TO_8
  175203. # define PNG_READ_16_TO_8_SUPPORTED
  175204. # endif
  175205. # ifndef PNG_NO_READ_FILLER
  175206. # define PNG_READ_FILLER_SUPPORTED
  175207. # endif
  175208. # ifndef PNG_NO_READ_GAMMA
  175209. # define PNG_READ_GAMMA_SUPPORTED
  175210. # endif
  175211. # ifndef PNG_NO_READ_GRAY_TO_RGB
  175212. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  175213. # endif
  175214. # ifndef PNG_NO_READ_SWAP_ALPHA
  175215. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  175216. # endif
  175217. # ifndef PNG_NO_READ_INVERT_ALPHA
  175218. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  175219. # endif
  175220. # ifndef PNG_NO_READ_STRIP_ALPHA
  175221. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  175222. # endif
  175223. # ifndef PNG_NO_READ_USER_TRANSFORM
  175224. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  175225. # endif
  175226. # ifndef PNG_NO_READ_RGB_TO_GRAY
  175227. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  175228. # endif
  175229. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  175230. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  175231. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  175232. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  175233. #endif /* about interlacing capability! You'll */
  175234. /* still have interlacing unless you change the following line: */
  175235. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  175236. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  175237. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  175238. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  175239. # endif
  175240. #endif
  175241. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  175242. /* Deprecated, will be removed from version 2.0.0.
  175243. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  175244. #ifndef PNG_NO_READ_EMPTY_PLTE
  175245. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  175246. #endif
  175247. #endif
  175248. #endif /* PNG_READ_SUPPORTED */
  175249. #if defined(PNG_WRITE_SUPPORTED)
  175250. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  175251. !defined(PNG_NO_WRITE_TRANSFORMS)
  175252. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  175253. #endif
  175254. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  175255. # ifndef PNG_NO_WRITE_SHIFT
  175256. # define PNG_WRITE_SHIFT_SUPPORTED
  175257. # endif
  175258. # ifndef PNG_NO_WRITE_PACK
  175259. # define PNG_WRITE_PACK_SUPPORTED
  175260. # endif
  175261. # ifndef PNG_NO_WRITE_BGR
  175262. # define PNG_WRITE_BGR_SUPPORTED
  175263. # endif
  175264. # ifndef PNG_NO_WRITE_SWAP
  175265. # define PNG_WRITE_SWAP_SUPPORTED
  175266. # endif
  175267. # ifndef PNG_NO_WRITE_PACKSWAP
  175268. # define PNG_WRITE_PACKSWAP_SUPPORTED
  175269. # endif
  175270. # ifndef PNG_NO_WRITE_INVERT
  175271. # define PNG_WRITE_INVERT_SUPPORTED
  175272. # endif
  175273. # ifndef PNG_NO_WRITE_FILLER
  175274. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  175275. # endif
  175276. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  175277. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  175278. # endif
  175279. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  175280. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  175281. # endif
  175282. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  175283. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  175284. # endif
  175285. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  175286. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  175287. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  175288. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  175289. encoders, but can cause trouble
  175290. if left undefined */
  175291. #endif
  175292. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  175293. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  175294. defined(PNG_FLOATING_POINT_SUPPORTED)
  175295. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  175296. #endif
  175297. #ifndef PNG_NO_WRITE_FLUSH
  175298. # define PNG_WRITE_FLUSH_SUPPORTED
  175299. #endif
  175300. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  175301. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  175302. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  175303. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  175304. #endif
  175305. #endif
  175306. #endif /* PNG_WRITE_SUPPORTED */
  175307. #ifndef PNG_1_0_X
  175308. # ifndef PNG_NO_ERROR_NUMBERS
  175309. # define PNG_ERROR_NUMBERS_SUPPORTED
  175310. # endif
  175311. #endif /* PNG_1_0_X */
  175312. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  175313. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  175314. # ifndef PNG_NO_USER_TRANSFORM_PTR
  175315. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  175316. # endif
  175317. #endif
  175318. #ifndef PNG_NO_STDIO
  175319. # define PNG_TIME_RFC1123_SUPPORTED
  175320. #endif
  175321. /* This adds extra functions in pngget.c for accessing data from the
  175322. * info pointer (added in version 0.99)
  175323. * png_get_image_width()
  175324. * png_get_image_height()
  175325. * png_get_bit_depth()
  175326. * png_get_color_type()
  175327. * png_get_compression_type()
  175328. * png_get_filter_type()
  175329. * png_get_interlace_type()
  175330. * png_get_pixel_aspect_ratio()
  175331. * png_get_pixels_per_meter()
  175332. * png_get_x_offset_pixels()
  175333. * png_get_y_offset_pixels()
  175334. * png_get_x_offset_microns()
  175335. * png_get_y_offset_microns()
  175336. */
  175337. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  175338. # define PNG_EASY_ACCESS_SUPPORTED
  175339. #endif
  175340. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  175341. * and removed from version 1.2.20. The following will be removed
  175342. * from libpng-1.4.0
  175343. */
  175344. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  175345. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  175346. # define PNG_OPTIMIZED_CODE_SUPPORTED
  175347. # endif
  175348. #endif
  175349. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  175350. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  175351. # define PNG_ASSEMBLER_CODE_SUPPORTED
  175352. # endif
  175353. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  175354. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  175355. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  175356. # define PNG_NO_MMX_CODE
  175357. # endif
  175358. # endif
  175359. # if defined(__APPLE__)
  175360. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  175361. # define PNG_NO_MMX_CODE
  175362. # endif
  175363. # endif
  175364. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  175365. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  175366. # define PNG_NO_MMX_CODE
  175367. # endif
  175368. # endif
  175369. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  175370. # define PNG_MMX_CODE_SUPPORTED
  175371. # endif
  175372. #endif
  175373. /* end of obsolete code to be removed from libpng-1.4.0 */
  175374. #if !defined(PNG_1_0_X)
  175375. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  175376. # define PNG_USER_MEM_SUPPORTED
  175377. #endif
  175378. #endif /* PNG_1_0_X */
  175379. /* Added at libpng-1.2.6 */
  175380. #if !defined(PNG_1_0_X)
  175381. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  175382. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  175383. # define PNG_SET_USER_LIMITS_SUPPORTED
  175384. #endif
  175385. #endif
  175386. #endif /* PNG_1_0_X */
  175387. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  175388. * how large, set these limits to 0x7fffffffL
  175389. */
  175390. #ifndef PNG_USER_WIDTH_MAX
  175391. # define PNG_USER_WIDTH_MAX 1000000L
  175392. #endif
  175393. #ifndef PNG_USER_HEIGHT_MAX
  175394. # define PNG_USER_HEIGHT_MAX 1000000L
  175395. #endif
  175396. /* These are currently experimental features, define them if you want */
  175397. /* very little testing */
  175398. /*
  175399. #ifdef PNG_READ_SUPPORTED
  175400. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  175401. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  175402. # endif
  175403. #endif
  175404. */
  175405. /* This is only for PowerPC big-endian and 680x0 systems */
  175406. /* some testing */
  175407. /*
  175408. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  175409. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  175410. #endif
  175411. */
  175412. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  175413. /*
  175414. #define PNG_NO_POINTER_INDEXING
  175415. */
  175416. /* These functions are turned off by default, as they will be phased out. */
  175417. /*
  175418. #define PNG_USELESS_TESTS_SUPPORTED
  175419. #define PNG_CORRECT_PALETTE_SUPPORTED
  175420. */
  175421. /* Any chunks you are not interested in, you can undef here. The
  175422. * ones that allocate memory may be expecially important (hIST,
  175423. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  175424. * a bit smaller.
  175425. */
  175426. #if defined(PNG_READ_SUPPORTED) && \
  175427. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  175428. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  175429. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  175430. #endif
  175431. #if defined(PNG_WRITE_SUPPORTED) && \
  175432. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  175433. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  175434. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  175435. #endif
  175436. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  175437. #ifdef PNG_NO_READ_TEXT
  175438. # define PNG_NO_READ_iTXt
  175439. # define PNG_NO_READ_tEXt
  175440. # define PNG_NO_READ_zTXt
  175441. #endif
  175442. #ifndef PNG_NO_READ_bKGD
  175443. # define PNG_READ_bKGD_SUPPORTED
  175444. # define PNG_bKGD_SUPPORTED
  175445. #endif
  175446. #ifndef PNG_NO_READ_cHRM
  175447. # define PNG_READ_cHRM_SUPPORTED
  175448. # define PNG_cHRM_SUPPORTED
  175449. #endif
  175450. #ifndef PNG_NO_READ_gAMA
  175451. # define PNG_READ_gAMA_SUPPORTED
  175452. # define PNG_gAMA_SUPPORTED
  175453. #endif
  175454. #ifndef PNG_NO_READ_hIST
  175455. # define PNG_READ_hIST_SUPPORTED
  175456. # define PNG_hIST_SUPPORTED
  175457. #endif
  175458. #ifndef PNG_NO_READ_iCCP
  175459. # define PNG_READ_iCCP_SUPPORTED
  175460. # define PNG_iCCP_SUPPORTED
  175461. #endif
  175462. #ifndef PNG_NO_READ_iTXt
  175463. # ifndef PNG_READ_iTXt_SUPPORTED
  175464. # define PNG_READ_iTXt_SUPPORTED
  175465. # endif
  175466. # ifndef PNG_iTXt_SUPPORTED
  175467. # define PNG_iTXt_SUPPORTED
  175468. # endif
  175469. #endif
  175470. #ifndef PNG_NO_READ_oFFs
  175471. # define PNG_READ_oFFs_SUPPORTED
  175472. # define PNG_oFFs_SUPPORTED
  175473. #endif
  175474. #ifndef PNG_NO_READ_pCAL
  175475. # define PNG_READ_pCAL_SUPPORTED
  175476. # define PNG_pCAL_SUPPORTED
  175477. #endif
  175478. #ifndef PNG_NO_READ_sCAL
  175479. # define PNG_READ_sCAL_SUPPORTED
  175480. # define PNG_sCAL_SUPPORTED
  175481. #endif
  175482. #ifndef PNG_NO_READ_pHYs
  175483. # define PNG_READ_pHYs_SUPPORTED
  175484. # define PNG_pHYs_SUPPORTED
  175485. #endif
  175486. #ifndef PNG_NO_READ_sBIT
  175487. # define PNG_READ_sBIT_SUPPORTED
  175488. # define PNG_sBIT_SUPPORTED
  175489. #endif
  175490. #ifndef PNG_NO_READ_sPLT
  175491. # define PNG_READ_sPLT_SUPPORTED
  175492. # define PNG_sPLT_SUPPORTED
  175493. #endif
  175494. #ifndef PNG_NO_READ_sRGB
  175495. # define PNG_READ_sRGB_SUPPORTED
  175496. # define PNG_sRGB_SUPPORTED
  175497. #endif
  175498. #ifndef PNG_NO_READ_tEXt
  175499. # define PNG_READ_tEXt_SUPPORTED
  175500. # define PNG_tEXt_SUPPORTED
  175501. #endif
  175502. #ifndef PNG_NO_READ_tIME
  175503. # define PNG_READ_tIME_SUPPORTED
  175504. # define PNG_tIME_SUPPORTED
  175505. #endif
  175506. #ifndef PNG_NO_READ_tRNS
  175507. # define PNG_READ_tRNS_SUPPORTED
  175508. # define PNG_tRNS_SUPPORTED
  175509. #endif
  175510. #ifndef PNG_NO_READ_zTXt
  175511. # define PNG_READ_zTXt_SUPPORTED
  175512. # define PNG_zTXt_SUPPORTED
  175513. #endif
  175514. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  175515. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  175516. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  175517. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  175518. # endif
  175519. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  175520. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  175521. # endif
  175522. #endif
  175523. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  175524. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  175525. # define PNG_READ_USER_CHUNKS_SUPPORTED
  175526. # define PNG_USER_CHUNKS_SUPPORTED
  175527. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  175528. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  175529. # endif
  175530. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  175531. # undef PNG_NO_HANDLE_AS_UNKNOWN
  175532. # endif
  175533. #endif
  175534. #ifndef PNG_NO_READ_OPT_PLTE
  175535. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  175536. #endif /* optional PLTE chunk in RGB and RGBA images */
  175537. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  175538. defined(PNG_READ_zTXt_SUPPORTED)
  175539. # define PNG_READ_TEXT_SUPPORTED
  175540. # define PNG_TEXT_SUPPORTED
  175541. #endif
  175542. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  175543. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  175544. #ifdef PNG_NO_WRITE_TEXT
  175545. # define PNG_NO_WRITE_iTXt
  175546. # define PNG_NO_WRITE_tEXt
  175547. # define PNG_NO_WRITE_zTXt
  175548. #endif
  175549. #ifndef PNG_NO_WRITE_bKGD
  175550. # define PNG_WRITE_bKGD_SUPPORTED
  175551. # ifndef PNG_bKGD_SUPPORTED
  175552. # define PNG_bKGD_SUPPORTED
  175553. # endif
  175554. #endif
  175555. #ifndef PNG_NO_WRITE_cHRM
  175556. # define PNG_WRITE_cHRM_SUPPORTED
  175557. # ifndef PNG_cHRM_SUPPORTED
  175558. # define PNG_cHRM_SUPPORTED
  175559. # endif
  175560. #endif
  175561. #ifndef PNG_NO_WRITE_gAMA
  175562. # define PNG_WRITE_gAMA_SUPPORTED
  175563. # ifndef PNG_gAMA_SUPPORTED
  175564. # define PNG_gAMA_SUPPORTED
  175565. # endif
  175566. #endif
  175567. #ifndef PNG_NO_WRITE_hIST
  175568. # define PNG_WRITE_hIST_SUPPORTED
  175569. # ifndef PNG_hIST_SUPPORTED
  175570. # define PNG_hIST_SUPPORTED
  175571. # endif
  175572. #endif
  175573. #ifndef PNG_NO_WRITE_iCCP
  175574. # define PNG_WRITE_iCCP_SUPPORTED
  175575. # ifndef PNG_iCCP_SUPPORTED
  175576. # define PNG_iCCP_SUPPORTED
  175577. # endif
  175578. #endif
  175579. #ifndef PNG_NO_WRITE_iTXt
  175580. # ifndef PNG_WRITE_iTXt_SUPPORTED
  175581. # define PNG_WRITE_iTXt_SUPPORTED
  175582. # endif
  175583. # ifndef PNG_iTXt_SUPPORTED
  175584. # define PNG_iTXt_SUPPORTED
  175585. # endif
  175586. #endif
  175587. #ifndef PNG_NO_WRITE_oFFs
  175588. # define PNG_WRITE_oFFs_SUPPORTED
  175589. # ifndef PNG_oFFs_SUPPORTED
  175590. # define PNG_oFFs_SUPPORTED
  175591. # endif
  175592. #endif
  175593. #ifndef PNG_NO_WRITE_pCAL
  175594. # define PNG_WRITE_pCAL_SUPPORTED
  175595. # ifndef PNG_pCAL_SUPPORTED
  175596. # define PNG_pCAL_SUPPORTED
  175597. # endif
  175598. #endif
  175599. #ifndef PNG_NO_WRITE_sCAL
  175600. # define PNG_WRITE_sCAL_SUPPORTED
  175601. # ifndef PNG_sCAL_SUPPORTED
  175602. # define PNG_sCAL_SUPPORTED
  175603. # endif
  175604. #endif
  175605. #ifndef PNG_NO_WRITE_pHYs
  175606. # define PNG_WRITE_pHYs_SUPPORTED
  175607. # ifndef PNG_pHYs_SUPPORTED
  175608. # define PNG_pHYs_SUPPORTED
  175609. # endif
  175610. #endif
  175611. #ifndef PNG_NO_WRITE_sBIT
  175612. # define PNG_WRITE_sBIT_SUPPORTED
  175613. # ifndef PNG_sBIT_SUPPORTED
  175614. # define PNG_sBIT_SUPPORTED
  175615. # endif
  175616. #endif
  175617. #ifndef PNG_NO_WRITE_sPLT
  175618. # define PNG_WRITE_sPLT_SUPPORTED
  175619. # ifndef PNG_sPLT_SUPPORTED
  175620. # define PNG_sPLT_SUPPORTED
  175621. # endif
  175622. #endif
  175623. #ifndef PNG_NO_WRITE_sRGB
  175624. # define PNG_WRITE_sRGB_SUPPORTED
  175625. # ifndef PNG_sRGB_SUPPORTED
  175626. # define PNG_sRGB_SUPPORTED
  175627. # endif
  175628. #endif
  175629. #ifndef PNG_NO_WRITE_tEXt
  175630. # define PNG_WRITE_tEXt_SUPPORTED
  175631. # ifndef PNG_tEXt_SUPPORTED
  175632. # define PNG_tEXt_SUPPORTED
  175633. # endif
  175634. #endif
  175635. #ifndef PNG_NO_WRITE_tIME
  175636. # define PNG_WRITE_tIME_SUPPORTED
  175637. # ifndef PNG_tIME_SUPPORTED
  175638. # define PNG_tIME_SUPPORTED
  175639. # endif
  175640. #endif
  175641. #ifndef PNG_NO_WRITE_tRNS
  175642. # define PNG_WRITE_tRNS_SUPPORTED
  175643. # ifndef PNG_tRNS_SUPPORTED
  175644. # define PNG_tRNS_SUPPORTED
  175645. # endif
  175646. #endif
  175647. #ifndef PNG_NO_WRITE_zTXt
  175648. # define PNG_WRITE_zTXt_SUPPORTED
  175649. # ifndef PNG_zTXt_SUPPORTED
  175650. # define PNG_zTXt_SUPPORTED
  175651. # endif
  175652. #endif
  175653. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  175654. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  175655. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  175656. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  175657. # endif
  175658. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  175659. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  175660. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  175661. # endif
  175662. # endif
  175663. #endif
  175664. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  175665. defined(PNG_WRITE_zTXt_SUPPORTED)
  175666. # define PNG_WRITE_TEXT_SUPPORTED
  175667. # ifndef PNG_TEXT_SUPPORTED
  175668. # define PNG_TEXT_SUPPORTED
  175669. # endif
  175670. #endif
  175671. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  175672. /* Turn this off to disable png_read_png() and
  175673. * png_write_png() and leave the row_pointers member
  175674. * out of the info structure.
  175675. */
  175676. #ifndef PNG_NO_INFO_IMAGE
  175677. # define PNG_INFO_IMAGE_SUPPORTED
  175678. #endif
  175679. /* need the time information for reading tIME chunks */
  175680. #if defined(PNG_tIME_SUPPORTED)
  175681. # if !defined(_WIN32_WCE)
  175682. /* "time.h" functions are not supported on WindowsCE */
  175683. # include <time.h>
  175684. # endif
  175685. #endif
  175686. /* Some typedefs to get us started. These should be safe on most of the
  175687. * common platforms. The typedefs should be at least as large as the
  175688. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  175689. * don't have to be exactly that size. Some compilers dislike passing
  175690. * unsigned shorts as function parameters, so you may be better off using
  175691. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  175692. * want to have unsigned int for png_uint_32 instead of unsigned long.
  175693. */
  175694. typedef unsigned long png_uint_32;
  175695. typedef long png_int_32;
  175696. typedef unsigned short png_uint_16;
  175697. typedef short png_int_16;
  175698. typedef unsigned char png_byte;
  175699. /* This is usually size_t. It is typedef'ed just in case you need it to
  175700. change (I'm not sure if you will or not, so I thought I'd be safe) */
  175701. #ifdef PNG_SIZE_T
  175702. typedef PNG_SIZE_T png_size_t;
  175703. # define png_sizeof(x) png_convert_size(sizeof (x))
  175704. #else
  175705. typedef size_t png_size_t;
  175706. # define png_sizeof(x) sizeof (x)
  175707. #endif
  175708. /* The following is needed for medium model support. It cannot be in the
  175709. * PNG_INTERNAL section. Needs modification for other compilers besides
  175710. * MSC. Model independent support declares all arrays and pointers to be
  175711. * large using the far keyword. The zlib version used must also support
  175712. * model independent data. As of version zlib 1.0.4, the necessary changes
  175713. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  175714. * changes that are needed. (Tim Wegner)
  175715. */
  175716. /* Separate compiler dependencies (problem here is that zlib.h always
  175717. defines FAR. (SJT) */
  175718. #ifdef __BORLANDC__
  175719. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  175720. # define LDATA 1
  175721. # else
  175722. # define LDATA 0
  175723. # endif
  175724. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  175725. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  175726. # define PNG_MAX_MALLOC_64K
  175727. # if (LDATA != 1)
  175728. # ifndef FAR
  175729. # define FAR __far
  175730. # endif
  175731. # define USE_FAR_KEYWORD
  175732. # endif /* LDATA != 1 */
  175733. /* Possibly useful for moving data out of default segment.
  175734. * Uncomment it if you want. Could also define FARDATA as
  175735. * const if your compiler supports it. (SJT)
  175736. # define FARDATA FAR
  175737. */
  175738. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  175739. #endif /* __BORLANDC__ */
  175740. /* Suggest testing for specific compiler first before testing for
  175741. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  175742. * making reliance oncertain keywords suspect. (SJT)
  175743. */
  175744. /* MSC Medium model */
  175745. #if defined(FAR)
  175746. # if defined(M_I86MM)
  175747. # define USE_FAR_KEYWORD
  175748. # define FARDATA FAR
  175749. # include <dos.h>
  175750. # endif
  175751. #endif
  175752. /* SJT: default case */
  175753. #ifndef FAR
  175754. # define FAR
  175755. #endif
  175756. /* At this point FAR is always defined */
  175757. #ifndef FARDATA
  175758. # define FARDATA
  175759. #endif
  175760. /* Typedef for floating-point numbers that are converted
  175761. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  175762. typedef png_int_32 png_fixed_point;
  175763. /* Add typedefs for pointers */
  175764. typedef void FAR * png_voidp;
  175765. typedef png_byte FAR * png_bytep;
  175766. typedef png_uint_32 FAR * png_uint_32p;
  175767. typedef png_int_32 FAR * png_int_32p;
  175768. typedef png_uint_16 FAR * png_uint_16p;
  175769. typedef png_int_16 FAR * png_int_16p;
  175770. typedef PNG_CONST char FAR * png_const_charp;
  175771. typedef char FAR * png_charp;
  175772. typedef png_fixed_point FAR * png_fixed_point_p;
  175773. #ifndef PNG_NO_STDIO
  175774. #if defined(_WIN32_WCE)
  175775. typedef HANDLE png_FILE_p;
  175776. #else
  175777. typedef FILE * png_FILE_p;
  175778. #endif
  175779. #endif
  175780. #ifdef PNG_FLOATING_POINT_SUPPORTED
  175781. typedef double FAR * png_doublep;
  175782. #endif
  175783. /* Pointers to pointers; i.e. arrays */
  175784. typedef png_byte FAR * FAR * png_bytepp;
  175785. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  175786. typedef png_int_32 FAR * FAR * png_int_32pp;
  175787. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  175788. typedef png_int_16 FAR * FAR * png_int_16pp;
  175789. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  175790. typedef char FAR * FAR * png_charpp;
  175791. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  175792. #ifdef PNG_FLOATING_POINT_SUPPORTED
  175793. typedef double FAR * FAR * png_doublepp;
  175794. #endif
  175795. /* Pointers to pointers to pointers; i.e., pointer to array */
  175796. typedef char FAR * FAR * FAR * png_charppp;
  175797. #if 0
  175798. /* SPC - Is this stuff deprecated? */
  175799. /* It'll be removed as of libpng-1.3.0 - GR-P */
  175800. /* libpng typedefs for types in zlib. If zlib changes
  175801. * or another compression library is used, then change these.
  175802. * Eliminates need to change all the source files.
  175803. */
  175804. typedef charf * png_zcharp;
  175805. typedef charf * FAR * png_zcharpp;
  175806. typedef z_stream FAR * png_zstreamp;
  175807. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  175808. /*
  175809. * Define PNG_BUILD_DLL if the module being built is a Windows
  175810. * LIBPNG DLL.
  175811. *
  175812. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  175813. * It is equivalent to Microsoft predefined macro _DLL that is
  175814. * automatically defined when you compile using the share
  175815. * version of the CRT (C Run-Time library)
  175816. *
  175817. * The cygwin mods make this behavior a little different:
  175818. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  175819. * Define PNG_STATIC if you are building a static library for use with cygwin,
  175820. * -or- if you are building an application that you want to link to the
  175821. * static library.
  175822. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  175823. * the other flags is defined.
  175824. */
  175825. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  175826. # define PNG_DLL
  175827. #endif
  175828. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  175829. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  175830. * command-line override
  175831. */
  175832. #if defined(__CYGWIN__)
  175833. # if !defined(PNG_STATIC)
  175834. # if defined(PNG_USE_GLOBAL_ARRAYS)
  175835. # undef PNG_USE_GLOBAL_ARRAYS
  175836. # endif
  175837. # if !defined(PNG_USE_LOCAL_ARRAYS)
  175838. # define PNG_USE_LOCAL_ARRAYS
  175839. # endif
  175840. # else
  175841. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  175842. # if defined(PNG_USE_GLOBAL_ARRAYS)
  175843. # undef PNG_USE_GLOBAL_ARRAYS
  175844. # endif
  175845. # endif
  175846. # endif
  175847. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  175848. # define PNG_USE_LOCAL_ARRAYS
  175849. # endif
  175850. #endif
  175851. /* Do not use global arrays (helps with building DLL's)
  175852. * They are no longer used in libpng itself, since version 1.0.5c,
  175853. * but might be required for some pre-1.0.5c applications.
  175854. */
  175855. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  175856. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  175857. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  175858. # define PNG_USE_LOCAL_ARRAYS
  175859. # else
  175860. # define PNG_USE_GLOBAL_ARRAYS
  175861. # endif
  175862. #endif
  175863. #if defined(__CYGWIN__)
  175864. # undef PNGAPI
  175865. # define PNGAPI __cdecl
  175866. # undef PNG_IMPEXP
  175867. # define PNG_IMPEXP
  175868. #endif
  175869. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  175870. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  175871. * Don't ignore those warnings; you must also reset the default calling
  175872. * convention in your compiler to match your PNGAPI, and you must build
  175873. * zlib and your applications the same way you build libpng.
  175874. */
  175875. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  175876. # ifndef PNG_NO_MODULEDEF
  175877. # define PNG_NO_MODULEDEF
  175878. # endif
  175879. #endif
  175880. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  175881. # define PNG_IMPEXP
  175882. #endif
  175883. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  175884. (( defined(_Windows) || defined(_WINDOWS) || \
  175885. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  175886. # ifndef PNGAPI
  175887. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  175888. # define PNGAPI __cdecl
  175889. # else
  175890. # define PNGAPI _cdecl
  175891. # endif
  175892. # endif
  175893. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  175894. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  175895. # define PNG_IMPEXP
  175896. # endif
  175897. # if !defined(PNG_IMPEXP)
  175898. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  175899. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  175900. /* Borland/Microsoft */
  175901. # if defined(_MSC_VER) || defined(__BORLANDC__)
  175902. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  175903. # define PNG_EXPORT PNG_EXPORT_TYPE1
  175904. # else
  175905. # define PNG_EXPORT PNG_EXPORT_TYPE2
  175906. # if defined(PNG_BUILD_DLL)
  175907. # define PNG_IMPEXP __export
  175908. # else
  175909. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  175910. VC++ */
  175911. # endif /* Exists in Borland C++ for
  175912. C++ classes (== huge) */
  175913. # endif
  175914. # endif
  175915. # if !defined(PNG_IMPEXP)
  175916. # if defined(PNG_BUILD_DLL)
  175917. # define PNG_IMPEXP __declspec(dllexport)
  175918. # else
  175919. # define PNG_IMPEXP __declspec(dllimport)
  175920. # endif
  175921. # endif
  175922. # endif /* PNG_IMPEXP */
  175923. #else /* !(DLL || non-cygwin WINDOWS) */
  175924. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  175925. # ifndef PNGAPI
  175926. # define PNGAPI _System
  175927. # endif
  175928. # else
  175929. # if 0 /* ... other platforms, with other meanings */
  175930. # endif
  175931. # endif
  175932. #endif
  175933. #ifndef PNGAPI
  175934. # define PNGAPI
  175935. #endif
  175936. #ifndef PNG_IMPEXP
  175937. # define PNG_IMPEXP
  175938. #endif
  175939. #ifdef PNG_BUILDSYMS
  175940. # ifndef PNG_EXPORT
  175941. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  175942. # endif
  175943. # ifdef PNG_USE_GLOBAL_ARRAYS
  175944. # ifndef PNG_EXPORT_VAR
  175945. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  175946. # endif
  175947. # endif
  175948. #endif
  175949. #ifndef PNG_EXPORT
  175950. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  175951. #endif
  175952. #ifdef PNG_USE_GLOBAL_ARRAYS
  175953. # ifndef PNG_EXPORT_VAR
  175954. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  175955. # endif
  175956. #endif
  175957. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  175958. * functions that are passed far data must be model independent.
  175959. */
  175960. #ifndef PNG_ABORT
  175961. # define PNG_ABORT() abort()
  175962. #endif
  175963. #ifdef PNG_SETJMP_SUPPORTED
  175964. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  175965. #else
  175966. # define png_jmpbuf(png_ptr) \
  175967. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  175968. #endif
  175969. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  175970. /* use this to make far-to-near assignments */
  175971. # define CHECK 1
  175972. # define NOCHECK 0
  175973. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  175974. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  175975. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  175976. # define png_strcpy _fstrcpy
  175977. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  175978. # define png_strlen _fstrlen
  175979. # define png_memcmp _fmemcmp /* SJT: added */
  175980. # define png_memcpy _fmemcpy
  175981. # define png_memset _fmemset
  175982. #else /* use the usual functions */
  175983. # define CVT_PTR(ptr) (ptr)
  175984. # define CVT_PTR_NOCHECK(ptr) (ptr)
  175985. # ifndef PNG_NO_SNPRINTF
  175986. # ifdef _MSC_VER
  175987. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  175988. # define png_snprintf2 _snprintf
  175989. # define png_snprintf6 _snprintf
  175990. # else
  175991. # define png_snprintf snprintf /* Added to v 1.2.19 */
  175992. # define png_snprintf2 snprintf
  175993. # define png_snprintf6 snprintf
  175994. # endif
  175995. # else
  175996. /* You don't have or don't want to use snprintf(). Caution: Using
  175997. * sprintf instead of snprintf exposes your application to accidental
  175998. * or malevolent buffer overflows. If you don't have snprintf()
  175999. * as a general rule you should provide one (you can get one from
  176000. * Portable OpenSSH). */
  176001. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  176002. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  176003. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  176004. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  176005. # endif
  176006. # define png_strcpy strcpy
  176007. # define png_strncpy strncpy /* Added to v 1.2.6 */
  176008. # define png_strlen strlen
  176009. # define png_memcmp memcmp /* SJT: added */
  176010. # define png_memcpy memcpy
  176011. # define png_memset memset
  176012. #endif
  176013. /* End of memory model independent support */
  176014. /* Just a little check that someone hasn't tried to define something
  176015. * contradictory.
  176016. */
  176017. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  176018. # undef PNG_ZBUF_SIZE
  176019. # define PNG_ZBUF_SIZE 65536L
  176020. #endif
  176021. /* Added at libpng-1.2.8 */
  176022. #endif /* PNG_VERSION_INFO_ONLY */
  176023. #endif /* PNGCONF_H */
  176024. /********* End of inlined file: pngconf.h *********/
  176025. #ifdef _MSC_VER
  176026. #pragma warning (disable: 4996 4100)
  176027. #endif
  176028. /*
  176029. * Added at libpng-1.2.8 */
  176030. /* Ref MSDN: Private as priority over Special
  176031. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  176032. * procedures. If this value is given, the StringFileInfo block must
  176033. * contain a PrivateBuild string.
  176034. *
  176035. * VS_FF_SPECIALBUILD File *was* built by the original company using
  176036. * standard release procedures but is a variation of the standard
  176037. * file of the same version number. If this value is given, the
  176038. * StringFileInfo block must contain a SpecialBuild string.
  176039. */
  176040. #if defined(PNG_USER_PRIVATEBUILD)
  176041. # define PNG_LIBPNG_BUILD_TYPE \
  176042. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  176043. #else
  176044. # if defined(PNG_LIBPNG_SPECIALBUILD)
  176045. # define PNG_LIBPNG_BUILD_TYPE \
  176046. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  176047. # else
  176048. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  176049. # endif
  176050. #endif
  176051. #ifndef PNG_VERSION_INFO_ONLY
  176052. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  176053. #ifdef __cplusplus
  176054. extern "C" {
  176055. #endif /* __cplusplus */
  176056. /* This file is arranged in several sections. The first section contains
  176057. * structure and type definitions. The second section contains the external
  176058. * library functions, while the third has the internal library functions,
  176059. * which applications aren't expected to use directly.
  176060. */
  176061. #ifndef PNG_NO_TYPECAST_NULL
  176062. #define int_p_NULL (int *)NULL
  176063. #define png_bytep_NULL (png_bytep)NULL
  176064. #define png_bytepp_NULL (png_bytepp)NULL
  176065. #define png_doublep_NULL (png_doublep)NULL
  176066. #define png_error_ptr_NULL (png_error_ptr)NULL
  176067. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  176068. #define png_free_ptr_NULL (png_free_ptr)NULL
  176069. #define png_infopp_NULL (png_infopp)NULL
  176070. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  176071. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  176072. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  176073. #define png_structp_NULL (png_structp)NULL
  176074. #define png_uint_16p_NULL (png_uint_16p)NULL
  176075. #define png_voidp_NULL (png_voidp)NULL
  176076. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  176077. #else
  176078. #define int_p_NULL NULL
  176079. #define png_bytep_NULL NULL
  176080. #define png_bytepp_NULL NULL
  176081. #define png_doublep_NULL NULL
  176082. #define png_error_ptr_NULL NULL
  176083. #define png_flush_ptr_NULL NULL
  176084. #define png_free_ptr_NULL NULL
  176085. #define png_infopp_NULL NULL
  176086. #define png_malloc_ptr_NULL NULL
  176087. #define png_read_status_ptr_NULL NULL
  176088. #define png_rw_ptr_NULL NULL
  176089. #define png_structp_NULL NULL
  176090. #define png_uint_16p_NULL NULL
  176091. #define png_voidp_NULL NULL
  176092. #define png_write_status_ptr_NULL NULL
  176093. #endif
  176094. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  176095. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  176096. /* Version information for C files, stored in png.c. This had better match
  176097. * the version above.
  176098. */
  176099. #ifdef PNG_USE_GLOBAL_ARRAYS
  176100. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  176101. /* need room for 99.99.99beta99z */
  176102. #else
  176103. #define png_libpng_ver png_get_header_ver(NULL)
  176104. #endif
  176105. #ifdef PNG_USE_GLOBAL_ARRAYS
  176106. /* This was removed in version 1.0.5c */
  176107. /* Structures to facilitate easy interlacing. See png.c for more details */
  176108. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  176109. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  176110. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  176111. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  176112. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  176113. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  176114. /* This isn't currently used. If you need it, see png.c for more details.
  176115. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  176116. */
  176117. #endif
  176118. #endif /* PNG_NO_EXTERN */
  176119. /* Three color definitions. The order of the red, green, and blue, (and the
  176120. * exact size) is not important, although the size of the fields need to
  176121. * be png_byte or png_uint_16 (as defined below).
  176122. */
  176123. typedef struct png_color_struct
  176124. {
  176125. png_byte red;
  176126. png_byte green;
  176127. png_byte blue;
  176128. } png_color;
  176129. typedef png_color FAR * png_colorp;
  176130. typedef png_color FAR * FAR * png_colorpp;
  176131. typedef struct png_color_16_struct
  176132. {
  176133. png_byte index; /* used for palette files */
  176134. png_uint_16 red; /* for use in red green blue files */
  176135. png_uint_16 green;
  176136. png_uint_16 blue;
  176137. png_uint_16 gray; /* for use in grayscale files */
  176138. } png_color_16;
  176139. typedef png_color_16 FAR * png_color_16p;
  176140. typedef png_color_16 FAR * FAR * png_color_16pp;
  176141. typedef struct png_color_8_struct
  176142. {
  176143. png_byte red; /* for use in red green blue files */
  176144. png_byte green;
  176145. png_byte blue;
  176146. png_byte gray; /* for use in grayscale files */
  176147. png_byte alpha; /* for alpha channel files */
  176148. } png_color_8;
  176149. typedef png_color_8 FAR * png_color_8p;
  176150. typedef png_color_8 FAR * FAR * png_color_8pp;
  176151. /*
  176152. * The following two structures are used for the in-core representation
  176153. * of sPLT chunks.
  176154. */
  176155. typedef struct png_sPLT_entry_struct
  176156. {
  176157. png_uint_16 red;
  176158. png_uint_16 green;
  176159. png_uint_16 blue;
  176160. png_uint_16 alpha;
  176161. png_uint_16 frequency;
  176162. } png_sPLT_entry;
  176163. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  176164. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  176165. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  176166. * occupy the LSB of their respective members, and the MSB of each member
  176167. * is zero-filled. The frequency member always occupies the full 16 bits.
  176168. */
  176169. typedef struct png_sPLT_struct
  176170. {
  176171. png_charp name; /* palette name */
  176172. png_byte depth; /* depth of palette samples */
  176173. png_sPLT_entryp entries; /* palette entries */
  176174. png_int_32 nentries; /* number of palette entries */
  176175. } png_sPLT_t;
  176176. typedef png_sPLT_t FAR * png_sPLT_tp;
  176177. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  176178. #ifdef PNG_TEXT_SUPPORTED
  176179. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  176180. * and whether that contents is compressed or not. The "key" field
  176181. * points to a regular zero-terminated C string. The "text", "lang", and
  176182. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  176183. * However, the * structure returned by png_get_text() will always contain
  176184. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  176185. * so they can be safely used in printf() and other string-handling functions.
  176186. */
  176187. typedef struct png_text_struct
  176188. {
  176189. int compression; /* compression value:
  176190. -1: tEXt, none
  176191. 0: zTXt, deflate
  176192. 1: iTXt, none
  176193. 2: iTXt, deflate */
  176194. png_charp key; /* keyword, 1-79 character description of "text" */
  176195. png_charp text; /* comment, may be an empty string (ie "")
  176196. or a NULL pointer */
  176197. png_size_t text_length; /* length of the text string */
  176198. #ifdef PNG_iTXt_SUPPORTED
  176199. png_size_t itxt_length; /* length of the itxt string */
  176200. png_charp lang; /* language code, 0-79 characters
  176201. or a NULL pointer */
  176202. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  176203. chars or a NULL pointer */
  176204. #endif
  176205. } png_text;
  176206. typedef png_text FAR * png_textp;
  176207. typedef png_text FAR * FAR * png_textpp;
  176208. #endif
  176209. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  176210. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  176211. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  176212. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  176213. #define PNG_TEXT_COMPRESSION_NONE -1
  176214. #define PNG_TEXT_COMPRESSION_zTXt 0
  176215. #define PNG_ITXT_COMPRESSION_NONE 1
  176216. #define PNG_ITXT_COMPRESSION_zTXt 2
  176217. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  176218. /* png_time is a way to hold the time in an machine independent way.
  176219. * Two conversions are provided, both from time_t and struct tm. There
  176220. * is no portable way to convert to either of these structures, as far
  176221. * as I know. If you know of a portable way, send it to me. As a side
  176222. * note - PNG has always been Year 2000 compliant!
  176223. */
  176224. typedef struct png_time_struct
  176225. {
  176226. png_uint_16 year; /* full year, as in, 1995 */
  176227. png_byte month; /* month of year, 1 - 12 */
  176228. png_byte day; /* day of month, 1 - 31 */
  176229. png_byte hour; /* hour of day, 0 - 23 */
  176230. png_byte minute; /* minute of hour, 0 - 59 */
  176231. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  176232. } png_time;
  176233. typedef png_time FAR * png_timep;
  176234. typedef png_time FAR * FAR * png_timepp;
  176235. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176236. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  176237. * no specific support. The idea is that we can use this to queue
  176238. * up private chunks for output even though the library doesn't actually
  176239. * know about their semantics.
  176240. */
  176241. typedef struct png_unknown_chunk_t
  176242. {
  176243. png_byte name[5];
  176244. png_byte *data;
  176245. png_size_t size;
  176246. /* libpng-using applications should NOT directly modify this byte. */
  176247. png_byte location; /* mode of operation at read time */
  176248. }
  176249. png_unknown_chunk;
  176250. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  176251. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  176252. #endif
  176253. /* png_info is a structure that holds the information in a PNG file so
  176254. * that the application can find out the characteristics of the image.
  176255. * If you are reading the file, this structure will tell you what is
  176256. * in the PNG file. If you are writing the file, fill in the information
  176257. * you want to put into the PNG file, then call png_write_info().
  176258. * The names chosen should be very close to the PNG specification, so
  176259. * consult that document for information about the meaning of each field.
  176260. *
  176261. * With libpng < 0.95, it was only possible to directly set and read the
  176262. * the values in the png_info_struct, which meant that the contents and
  176263. * order of the values had to remain fixed. With libpng 0.95 and later,
  176264. * however, there are now functions that abstract the contents of
  176265. * png_info_struct from the application, so this makes it easier to use
  176266. * libpng with dynamic libraries, and even makes it possible to use
  176267. * libraries that don't have all of the libpng ancillary chunk-handing
  176268. * functionality.
  176269. *
  176270. * In any case, the order of the parameters in png_info_struct should NOT
  176271. * be changed for as long as possible to keep compatibility with applications
  176272. * that use the old direct-access method with png_info_struct.
  176273. *
  176274. * The following members may have allocated storage attached that should be
  176275. * cleaned up before the structure is discarded: palette, trans, text,
  176276. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  176277. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  176278. * are automatically freed when the info structure is deallocated, if they were
  176279. * allocated internally by libpng. This behavior can be changed by means
  176280. * of the png_data_freer() function.
  176281. *
  176282. * More allocation details: all the chunk-reading functions that
  176283. * change these members go through the corresponding png_set_*
  176284. * functions. A function to clear these members is available: see
  176285. * png_free_data(). The png_set_* functions do not depend on being
  176286. * able to point info structure members to any of the storage they are
  176287. * passed (they make their own copies), EXCEPT that the png_set_text
  176288. * functions use the same storage passed to them in the text_ptr or
  176289. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  176290. * functions do not make their own copies.
  176291. */
  176292. typedef struct png_info_struct
  176293. {
  176294. /* the following are necessary for every PNG file */
  176295. png_uint_32 width; /* width of image in pixels (from IHDR) */
  176296. png_uint_32 height; /* height of image in pixels (from IHDR) */
  176297. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  176298. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  176299. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  176300. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  176301. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  176302. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  176303. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  176304. /* The following three should have been named *_method not *_type */
  176305. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  176306. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  176307. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  176308. /* The following is informational only on read, and not used on writes. */
  176309. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  176310. png_byte pixel_depth; /* number of bits per pixel */
  176311. png_byte spare_byte; /* to align the data, and for future use */
  176312. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  176313. /* The rest of the data is optional. If you are reading, check the
  176314. * valid field to see if the information in these are valid. If you
  176315. * are writing, set the valid field to those chunks you want written,
  176316. * and initialize the appropriate fields below.
  176317. */
  176318. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  176319. /* The gAMA chunk describes the gamma characteristics of the system
  176320. * on which the image was created, normally in the range [1.0, 2.5].
  176321. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  176322. */
  176323. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  176324. #endif
  176325. #if defined(PNG_sRGB_SUPPORTED)
  176326. /* GR-P, 0.96a */
  176327. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  176328. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  176329. #endif
  176330. #if defined(PNG_TEXT_SUPPORTED)
  176331. /* The tEXt, and zTXt chunks contain human-readable textual data in
  176332. * uncompressed, compressed, and optionally compressed forms, respectively.
  176333. * The data in "text" is an array of pointers to uncompressed,
  176334. * null-terminated C strings. Each chunk has a keyword that describes the
  176335. * textual data contained in that chunk. Keywords are not required to be
  176336. * unique, and the text string may be empty. Any number of text chunks may
  176337. * be in an image.
  176338. */
  176339. int num_text; /* number of comments read/to write */
  176340. int max_text; /* current size of text array */
  176341. png_textp text; /* array of comments read/to write */
  176342. #endif /* PNG_TEXT_SUPPORTED */
  176343. #if defined(PNG_tIME_SUPPORTED)
  176344. /* The tIME chunk holds the last time the displayed image data was
  176345. * modified. See the png_time struct for the contents of this struct.
  176346. */
  176347. png_time mod_time;
  176348. #endif
  176349. #if defined(PNG_sBIT_SUPPORTED)
  176350. /* The sBIT chunk specifies the number of significant high-order bits
  176351. * in the pixel data. Values are in the range [1, bit_depth], and are
  176352. * only specified for the channels in the pixel data. The contents of
  176353. * the low-order bits is not specified. Data is valid if
  176354. * (valid & PNG_INFO_sBIT) is non-zero.
  176355. */
  176356. png_color_8 sig_bit; /* significant bits in color channels */
  176357. #endif
  176358. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  176359. defined(PNG_READ_BACKGROUND_SUPPORTED)
  176360. /* The tRNS chunk supplies transparency data for paletted images and
  176361. * other image types that don't need a full alpha channel. There are
  176362. * "num_trans" transparency values for a paletted image, stored in the
  176363. * same order as the palette colors, starting from index 0. Values
  176364. * for the data are in the range [0, 255], ranging from fully transparent
  176365. * to fully opaque, respectively. For non-paletted images, there is a
  176366. * single color specified that should be treated as fully transparent.
  176367. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  176368. */
  176369. png_bytep trans; /* transparent values for paletted image */
  176370. png_color_16 trans_values; /* transparent color for non-palette image */
  176371. #endif
  176372. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176373. /* The bKGD chunk gives the suggested image background color if the
  176374. * display program does not have its own background color and the image
  176375. * is needs to composited onto a background before display. The colors
  176376. * in "background" are normally in the same color space/depth as the
  176377. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  176378. */
  176379. png_color_16 background;
  176380. #endif
  176381. #if defined(PNG_oFFs_SUPPORTED)
  176382. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  176383. * and downwards from the top-left corner of the display, page, or other
  176384. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  176385. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  176386. */
  176387. png_int_32 x_offset; /* x offset on page */
  176388. png_int_32 y_offset; /* y offset on page */
  176389. png_byte offset_unit_type; /* offset units type */
  176390. #endif
  176391. #if defined(PNG_pHYs_SUPPORTED)
  176392. /* The pHYs chunk gives the physical pixel density of the image for
  176393. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  176394. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  176395. */
  176396. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  176397. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  176398. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  176399. #endif
  176400. #if defined(PNG_hIST_SUPPORTED)
  176401. /* The hIST chunk contains the relative frequency or importance of the
  176402. * various palette entries, so that a viewer can intelligently select a
  176403. * reduced-color palette, if required. Data is an array of "num_palette"
  176404. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  176405. * is non-zero.
  176406. */
  176407. png_uint_16p hist;
  176408. #endif
  176409. #ifdef PNG_cHRM_SUPPORTED
  176410. /* The cHRM chunk describes the CIE color characteristics of the monitor
  176411. * on which the PNG was created. This data allows the viewer to do gamut
  176412. * mapping of the input image to ensure that the viewer sees the same
  176413. * colors in the image as the creator. Values are in the range
  176414. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  176415. */
  176416. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176417. float x_white;
  176418. float y_white;
  176419. float x_red;
  176420. float y_red;
  176421. float x_green;
  176422. float y_green;
  176423. float x_blue;
  176424. float y_blue;
  176425. #endif
  176426. #endif
  176427. #if defined(PNG_pCAL_SUPPORTED)
  176428. /* The pCAL chunk describes a transformation between the stored pixel
  176429. * values and original physical data values used to create the image.
  176430. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  176431. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  176432. * (possibly non-linear) transformation function given by "pcal_type"
  176433. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  176434. * defines below, and the PNG-Group's PNG extensions document for a
  176435. * complete description of the transformations and how they should be
  176436. * implemented, and for a description of the ASCII parameter strings.
  176437. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  176438. */
  176439. png_charp pcal_purpose; /* pCAL chunk description string */
  176440. png_int_32 pcal_X0; /* minimum value */
  176441. png_int_32 pcal_X1; /* maximum value */
  176442. png_charp pcal_units; /* Latin-1 string giving physical units */
  176443. png_charpp pcal_params; /* ASCII strings containing parameter values */
  176444. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  176445. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  176446. #endif
  176447. /* New members added in libpng-1.0.6 */
  176448. #ifdef PNG_FREE_ME_SUPPORTED
  176449. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  176450. #endif
  176451. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176452. /* storage for unknown chunks that the library doesn't recognize. */
  176453. png_unknown_chunkp unknown_chunks;
  176454. png_size_t unknown_chunks_num;
  176455. #endif
  176456. #if defined(PNG_iCCP_SUPPORTED)
  176457. /* iCCP chunk data. */
  176458. png_charp iccp_name; /* profile name */
  176459. png_charp iccp_profile; /* International Color Consortium profile data */
  176460. /* Note to maintainer: should be png_bytep */
  176461. png_uint_32 iccp_proflen; /* ICC profile data length */
  176462. png_byte iccp_compression; /* Always zero */
  176463. #endif
  176464. #if defined(PNG_sPLT_SUPPORTED)
  176465. /* data on sPLT chunks (there may be more than one). */
  176466. png_sPLT_tp splt_palettes;
  176467. png_uint_32 splt_palettes_num;
  176468. #endif
  176469. #if defined(PNG_sCAL_SUPPORTED)
  176470. /* The sCAL chunk describes the actual physical dimensions of the
  176471. * subject matter of the graphic. The chunk contains a unit specification
  176472. * a byte value, and two ASCII strings representing floating-point
  176473. * values. The values are width and height corresponsing to one pixel
  176474. * in the image. This external representation is converted to double
  176475. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  176476. */
  176477. png_byte scal_unit; /* unit of physical scale */
  176478. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176479. double scal_pixel_width; /* width of one pixel */
  176480. double scal_pixel_height; /* height of one pixel */
  176481. #endif
  176482. #ifdef PNG_FIXED_POINT_SUPPORTED
  176483. png_charp scal_s_width; /* string containing height */
  176484. png_charp scal_s_height; /* string containing width */
  176485. #endif
  176486. #endif
  176487. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  176488. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  176489. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  176490. png_bytepp row_pointers; /* the image bits */
  176491. #endif
  176492. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  176493. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  176494. #endif
  176495. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  176496. png_fixed_point int_x_white;
  176497. png_fixed_point int_y_white;
  176498. png_fixed_point int_x_red;
  176499. png_fixed_point int_y_red;
  176500. png_fixed_point int_x_green;
  176501. png_fixed_point int_y_green;
  176502. png_fixed_point int_x_blue;
  176503. png_fixed_point int_y_blue;
  176504. #endif
  176505. } png_info;
  176506. typedef png_info FAR * png_infop;
  176507. typedef png_info FAR * FAR * png_infopp;
  176508. /* Maximum positive integer used in PNG is (2^31)-1 */
  176509. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  176510. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  176511. #define PNG_SIZE_MAX ((png_size_t)(-1))
  176512. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176513. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  176514. #define PNG_MAX_UINT PNG_UINT_31_MAX
  176515. #endif
  176516. /* These describe the color_type field in png_info. */
  176517. /* color type masks */
  176518. #define PNG_COLOR_MASK_PALETTE 1
  176519. #define PNG_COLOR_MASK_COLOR 2
  176520. #define PNG_COLOR_MASK_ALPHA 4
  176521. /* color types. Note that not all combinations are legal */
  176522. #define PNG_COLOR_TYPE_GRAY 0
  176523. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  176524. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  176525. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  176526. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  176527. /* aliases */
  176528. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  176529. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  176530. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  176531. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  176532. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  176533. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  176534. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  176535. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  176536. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  176537. /* These are for the interlacing type. These values should NOT be changed. */
  176538. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  176539. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  176540. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  176541. /* These are for the oFFs chunk. These values should NOT be changed. */
  176542. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  176543. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  176544. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  176545. /* These are for the pCAL chunk. These values should NOT be changed. */
  176546. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  176547. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  176548. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  176549. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  176550. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  176551. /* These are for the sCAL chunk. These values should NOT be changed. */
  176552. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  176553. #define PNG_SCALE_METER 1 /* meters per pixel */
  176554. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  176555. #define PNG_SCALE_LAST 3 /* Not a valid value */
  176556. /* These are for the pHYs chunk. These values should NOT be changed. */
  176557. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  176558. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  176559. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  176560. /* These are for the sRGB chunk. These values should NOT be changed. */
  176561. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  176562. #define PNG_sRGB_INTENT_RELATIVE 1
  176563. #define PNG_sRGB_INTENT_SATURATION 2
  176564. #define PNG_sRGB_INTENT_ABSOLUTE 3
  176565. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  176566. /* This is for text chunks */
  176567. #define PNG_KEYWORD_MAX_LENGTH 79
  176568. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  176569. #define PNG_MAX_PALETTE_LENGTH 256
  176570. /* These determine if an ancillary chunk's data has been successfully read
  176571. * from the PNG header, or if the application has filled in the corresponding
  176572. * data in the info_struct to be written into the output file. The values
  176573. * of the PNG_INFO_<chunk> defines should NOT be changed.
  176574. */
  176575. #define PNG_INFO_gAMA 0x0001
  176576. #define PNG_INFO_sBIT 0x0002
  176577. #define PNG_INFO_cHRM 0x0004
  176578. #define PNG_INFO_PLTE 0x0008
  176579. #define PNG_INFO_tRNS 0x0010
  176580. #define PNG_INFO_bKGD 0x0020
  176581. #define PNG_INFO_hIST 0x0040
  176582. #define PNG_INFO_pHYs 0x0080
  176583. #define PNG_INFO_oFFs 0x0100
  176584. #define PNG_INFO_tIME 0x0200
  176585. #define PNG_INFO_pCAL 0x0400
  176586. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  176587. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  176588. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  176589. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  176590. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  176591. /* This is used for the transformation routines, as some of them
  176592. * change these values for the row. It also should enable using
  176593. * the routines for other purposes.
  176594. */
  176595. typedef struct png_row_info_struct
  176596. {
  176597. png_uint_32 width; /* width of row */
  176598. png_uint_32 rowbytes; /* number of bytes in row */
  176599. png_byte color_type; /* color type of row */
  176600. png_byte bit_depth; /* bit depth of row */
  176601. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  176602. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  176603. } png_row_info;
  176604. typedef png_row_info FAR * png_row_infop;
  176605. typedef png_row_info FAR * FAR * png_row_infopp;
  176606. /* These are the function types for the I/O functions and for the functions
  176607. * that allow the user to override the default I/O functions with his or her
  176608. * own. The png_error_ptr type should match that of user-supplied warning
  176609. * and error functions, while the png_rw_ptr type should match that of the
  176610. * user read/write data functions.
  176611. */
  176612. typedef struct png_struct_def png_struct;
  176613. typedef png_struct FAR * png_structp;
  176614. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  176615. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  176616. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  176617. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  176618. int));
  176619. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  176620. int));
  176621. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  176622. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  176623. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  176624. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  176625. png_uint_32, int));
  176626. #endif
  176627. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  176628. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  176629. defined(PNG_LEGACY_SUPPORTED)
  176630. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  176631. png_row_infop, png_bytep));
  176632. #endif
  176633. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  176634. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  176635. #endif
  176636. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176637. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  176638. #endif
  176639. /* Transform masks for the high-level interface */
  176640. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  176641. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  176642. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  176643. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  176644. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  176645. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  176646. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  176647. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  176648. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  176649. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  176650. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  176651. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  176652. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  176653. /* Flags for MNG supported features */
  176654. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  176655. #define PNG_FLAG_MNG_FILTER_64 0x04
  176656. #define PNG_ALL_MNG_FEATURES 0x05
  176657. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  176658. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  176659. /* The structure that holds the information to read and write PNG files.
  176660. * The only people who need to care about what is inside of this are the
  176661. * people who will be modifying the library for their own special needs.
  176662. * It should NOT be accessed directly by an application, except to store
  176663. * the jmp_buf.
  176664. */
  176665. struct png_struct_def
  176666. {
  176667. #ifdef PNG_SETJMP_SUPPORTED
  176668. jmp_buf jmpbuf; /* used in png_error */
  176669. #endif
  176670. png_error_ptr error_fn; /* function for printing errors and aborting */
  176671. png_error_ptr warning_fn; /* function for printing warnings */
  176672. png_voidp error_ptr; /* user supplied struct for error functions */
  176673. png_rw_ptr write_data_fn; /* function for writing output data */
  176674. png_rw_ptr read_data_fn; /* function for reading input data */
  176675. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  176676. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  176677. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  176678. #endif
  176679. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  176680. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  176681. #endif
  176682. /* These were added in libpng-1.0.2 */
  176683. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  176684. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  176685. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  176686. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  176687. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  176688. png_byte user_transform_channels; /* channels in user transformed pixels */
  176689. #endif
  176690. #endif
  176691. png_uint_32 mode; /* tells us where we are in the PNG file */
  176692. png_uint_32 flags; /* flags indicating various things to libpng */
  176693. png_uint_32 transformations; /* which transformations to perform */
  176694. z_stream zstream; /* pointer to decompression structure (below) */
  176695. png_bytep zbuf; /* buffer for zlib */
  176696. png_size_t zbuf_size; /* size of zbuf */
  176697. int zlib_level; /* holds zlib compression level */
  176698. int zlib_method; /* holds zlib compression method */
  176699. int zlib_window_bits; /* holds zlib compression window bits */
  176700. int zlib_mem_level; /* holds zlib compression memory level */
  176701. int zlib_strategy; /* holds zlib compression strategy */
  176702. png_uint_32 width; /* width of image in pixels */
  176703. png_uint_32 height; /* height of image in pixels */
  176704. png_uint_32 num_rows; /* number of rows in current pass */
  176705. png_uint_32 usr_width; /* width of row at start of write */
  176706. png_uint_32 rowbytes; /* size of row in bytes */
  176707. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  176708. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  176709. png_uint_32 row_number; /* current row in interlace pass */
  176710. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  176711. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  176712. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  176713. png_bytep up_row; /* buffer to save "up" row when filtering */
  176714. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  176715. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  176716. png_row_info row_info; /* used for transformation routines */
  176717. png_uint_32 idat_size; /* current IDAT size for read */
  176718. png_uint_32 crc; /* current chunk CRC value */
  176719. png_colorp palette; /* palette from the input file */
  176720. png_uint_16 num_palette; /* number of color entries in palette */
  176721. png_uint_16 num_trans; /* number of transparency values */
  176722. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  176723. png_byte compression; /* file compression type (always 0) */
  176724. png_byte filter; /* file filter type (always 0) */
  176725. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  176726. png_byte pass; /* current interlace pass (0 - 6) */
  176727. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  176728. png_byte color_type; /* color type of file */
  176729. png_byte bit_depth; /* bit depth of file */
  176730. png_byte usr_bit_depth; /* bit depth of users row */
  176731. png_byte pixel_depth; /* number of bits per pixel */
  176732. png_byte channels; /* number of channels in file */
  176733. png_byte usr_channels; /* channels at start of write */
  176734. png_byte sig_bytes; /* magic bytes read/written from start of file */
  176735. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  176736. #ifdef PNG_LEGACY_SUPPORTED
  176737. png_byte filler; /* filler byte for pixel expansion */
  176738. #else
  176739. png_uint_16 filler; /* filler bytes for pixel expansion */
  176740. #endif
  176741. #endif
  176742. #if defined(PNG_bKGD_SUPPORTED)
  176743. png_byte background_gamma_type;
  176744. # ifdef PNG_FLOATING_POINT_SUPPORTED
  176745. float background_gamma;
  176746. # endif
  176747. png_color_16 background; /* background color in screen gamma space */
  176748. #if defined(PNG_READ_GAMMA_SUPPORTED)
  176749. png_color_16 background_1; /* background normalized to gamma 1.0 */
  176750. #endif
  176751. #endif /* PNG_bKGD_SUPPORTED */
  176752. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  176753. png_flush_ptr output_flush_fn;/* Function for flushing output */
  176754. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  176755. png_uint_32 flush_rows; /* number of rows written since last flush */
  176756. #endif
  176757. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176758. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  176759. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176760. float gamma; /* file gamma value */
  176761. float screen_gamma; /* screen gamma value (display_exponent) */
  176762. #endif
  176763. #endif
  176764. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176765. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  176766. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  176767. png_bytep gamma_to_1; /* converts from file to 1.0 */
  176768. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  176769. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  176770. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  176771. #endif
  176772. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  176773. png_color_8 sig_bit; /* significant bits in each available channel */
  176774. #endif
  176775. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  176776. png_color_8 shift; /* shift for significant bit tranformation */
  176777. #endif
  176778. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  176779. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176780. png_bytep trans; /* transparency values for paletted files */
  176781. png_color_16 trans_values; /* transparency values for non-paletted files */
  176782. #endif
  176783. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  176784. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  176785. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  176786. png_progressive_info_ptr info_fn; /* called after header data fully read */
  176787. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  176788. png_progressive_end_ptr end_fn; /* called after image is complete */
  176789. png_bytep save_buffer_ptr; /* current location in save_buffer */
  176790. png_bytep save_buffer; /* buffer for previously read data */
  176791. png_bytep current_buffer_ptr; /* current location in current_buffer */
  176792. png_bytep current_buffer; /* buffer for recently used data */
  176793. png_uint_32 push_length; /* size of current input chunk */
  176794. png_uint_32 skip_length; /* bytes to skip in input data */
  176795. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  176796. png_size_t save_buffer_max; /* total size of save_buffer */
  176797. png_size_t buffer_size; /* total amount of available input data */
  176798. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  176799. int process_mode; /* what push library is currently doing */
  176800. int cur_palette; /* current push library palette index */
  176801. # if defined(PNG_TEXT_SUPPORTED)
  176802. png_size_t current_text_size; /* current size of text input data */
  176803. png_size_t current_text_left; /* how much text left to read in input */
  176804. png_charp current_text; /* current text chunk buffer */
  176805. png_charp current_text_ptr; /* current location in current_text */
  176806. # endif /* PNG_TEXT_SUPPORTED */
  176807. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  176808. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  176809. /* for the Borland special 64K segment handler */
  176810. png_bytepp offset_table_ptr;
  176811. png_bytep offset_table;
  176812. png_uint_16 offset_table_number;
  176813. png_uint_16 offset_table_count;
  176814. png_uint_16 offset_table_count_free;
  176815. #endif
  176816. #if defined(PNG_READ_DITHER_SUPPORTED)
  176817. png_bytep palette_lookup; /* lookup table for dithering */
  176818. png_bytep dither_index; /* index translation for palette files */
  176819. #endif
  176820. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  176821. png_uint_16p hist; /* histogram */
  176822. #endif
  176823. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  176824. png_byte heuristic_method; /* heuristic for row filter selection */
  176825. png_byte num_prev_filters; /* number of weights for previous rows */
  176826. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  176827. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  176828. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  176829. png_uint_16p filter_costs; /* relative filter calculation cost */
  176830. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  176831. #endif
  176832. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  176833. png_charp time_buffer; /* String to hold RFC 1123 time text */
  176834. #endif
  176835. /* New members added in libpng-1.0.6 */
  176836. #ifdef PNG_FREE_ME_SUPPORTED
  176837. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  176838. #endif
  176839. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  176840. png_voidp user_chunk_ptr;
  176841. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  176842. #endif
  176843. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176844. int num_chunk_list;
  176845. png_bytep chunk_list;
  176846. #endif
  176847. /* New members added in libpng-1.0.3 */
  176848. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  176849. png_byte rgb_to_gray_status;
  176850. /* These were changed from png_byte in libpng-1.0.6 */
  176851. png_uint_16 rgb_to_gray_red_coeff;
  176852. png_uint_16 rgb_to_gray_green_coeff;
  176853. png_uint_16 rgb_to_gray_blue_coeff;
  176854. #endif
  176855. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  176856. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  176857. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  176858. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  176859. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  176860. #ifdef PNG_1_0_X
  176861. png_byte mng_features_permitted;
  176862. #else
  176863. png_uint_32 mng_features_permitted;
  176864. #endif /* PNG_1_0_X */
  176865. #endif
  176866. /* New member added in libpng-1.0.7 */
  176867. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176868. png_fixed_point int_gamma;
  176869. #endif
  176870. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  176871. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  176872. png_byte filter_type;
  176873. #endif
  176874. #if defined(PNG_1_0_X)
  176875. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  176876. png_uint_32 row_buf_size;
  176877. #endif
  176878. /* New members added in libpng-1.2.0 */
  176879. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  176880. # if !defined(PNG_1_0_X)
  176881. # if defined(PNG_MMX_CODE_SUPPORTED)
  176882. png_byte mmx_bitdepth_threshold;
  176883. png_uint_32 mmx_rowbytes_threshold;
  176884. # endif
  176885. png_uint_32 asm_flags;
  176886. # endif
  176887. #endif
  176888. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  176889. #ifdef PNG_USER_MEM_SUPPORTED
  176890. png_voidp mem_ptr; /* user supplied struct for mem functions */
  176891. png_malloc_ptr malloc_fn; /* function for allocating memory */
  176892. png_free_ptr free_fn; /* function for freeing memory */
  176893. #endif
  176894. /* New member added in libpng-1.0.13 and 1.2.0 */
  176895. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  176896. #if defined(PNG_READ_DITHER_SUPPORTED)
  176897. /* The following three members were added at version 1.0.14 and 1.2.4 */
  176898. png_bytep dither_sort; /* working sort array */
  176899. png_bytep index_to_palette; /* where the original index currently is */
  176900. /* in the palette */
  176901. png_bytep palette_to_index; /* which original index points to this */
  176902. /* palette color */
  176903. #endif
  176904. /* New members added in libpng-1.0.16 and 1.2.6 */
  176905. png_byte compression_type;
  176906. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  176907. png_uint_32 user_width_max;
  176908. png_uint_32 user_height_max;
  176909. #endif
  176910. /* New member added in libpng-1.0.25 and 1.2.17 */
  176911. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176912. /* storage for unknown chunk that the library doesn't recognize. */
  176913. png_unknown_chunk unknown_chunk;
  176914. #endif
  176915. };
  176916. /* This triggers a compiler error in png.c, if png.c and png.h
  176917. * do not agree upon the version number.
  176918. */
  176919. typedef png_structp version_1_2_21;
  176920. typedef png_struct FAR * FAR * png_structpp;
  176921. /* Here are the function definitions most commonly used. This is not
  176922. * the place to find out how to use libpng. See libpng.txt for the
  176923. * full explanation, see example.c for the summary. This just provides
  176924. * a simple one line description of the use of each function.
  176925. */
  176926. /* Returns the version number of the library */
  176927. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  176928. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  176929. * Handling more than 8 bytes from the beginning of the file is an error.
  176930. */
  176931. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  176932. int num_bytes));
  176933. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  176934. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  176935. * signature, and non-zero otherwise. Having num_to_check == 0 or
  176936. * start > 7 will always fail (ie return non-zero).
  176937. */
  176938. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  176939. png_size_t num_to_check));
  176940. /* Simple signature checking function. This is the same as calling
  176941. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  176942. */
  176943. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  176944. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  176945. extern PNG_EXPORT(png_structp,png_create_read_struct)
  176946. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176947. png_error_ptr error_fn, png_error_ptr warn_fn));
  176948. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  176949. extern PNG_EXPORT(png_structp,png_create_write_struct)
  176950. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176951. png_error_ptr error_fn, png_error_ptr warn_fn));
  176952. #ifdef PNG_WRITE_SUPPORTED
  176953. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  176954. PNGARG((png_structp png_ptr));
  176955. #endif
  176956. #ifdef PNG_WRITE_SUPPORTED
  176957. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  176958. PNGARG((png_structp png_ptr, png_uint_32 size));
  176959. #endif
  176960. /* Reset the compression stream */
  176961. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  176962. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  176963. #ifdef PNG_USER_MEM_SUPPORTED
  176964. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  176965. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176966. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  176967. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  176968. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  176969. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176970. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  176971. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  176972. #endif
  176973. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  176974. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  176975. png_bytep chunk_name, png_bytep data, png_size_t length));
  176976. /* Write the start of a PNG chunk - length and chunk name. */
  176977. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  176978. png_bytep chunk_name, png_uint_32 length));
  176979. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  176980. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  176981. png_bytep data, png_size_t length));
  176982. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  176983. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  176984. /* Allocate and initialize the info structure */
  176985. extern PNG_EXPORT(png_infop,png_create_info_struct)
  176986. PNGARG((png_structp png_ptr));
  176987. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176988. /* Initialize the info structure (old interface - DEPRECATED) */
  176989. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  176990. #undef png_info_init
  176991. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  176992. png_sizeof(png_info));
  176993. #endif
  176994. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  176995. png_size_t png_info_struct_size));
  176996. /* Writes all the PNG information before the image. */
  176997. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  176998. png_infop info_ptr));
  176999. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  177000. png_infop info_ptr));
  177001. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177002. /* read the information before the actual image data. */
  177003. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  177004. png_infop info_ptr));
  177005. #endif
  177006. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  177007. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  177008. PNGARG((png_structp png_ptr, png_timep ptime));
  177009. #endif
  177010. #if !defined(_WIN32_WCE)
  177011. /* "time.h" functions are not supported on WindowsCE */
  177012. #if defined(PNG_WRITE_tIME_SUPPORTED)
  177013. /* convert from a struct tm to png_time */
  177014. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  177015. struct tm FAR * ttime));
  177016. /* convert from time_t to png_time. Uses gmtime() */
  177017. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  177018. time_t ttime));
  177019. #endif /* PNG_WRITE_tIME_SUPPORTED */
  177020. #endif /* _WIN32_WCE */
  177021. #if defined(PNG_READ_EXPAND_SUPPORTED)
  177022. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  177023. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  177024. #if !defined(PNG_1_0_X)
  177025. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  177026. png_ptr));
  177027. #endif
  177028. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  177029. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  177030. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177031. /* Deprecated */
  177032. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  177033. #endif
  177034. #endif
  177035. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  177036. /* Use blue, green, red order for pixels. */
  177037. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  177038. #endif
  177039. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  177040. /* Expand the grayscale to 24-bit RGB if necessary. */
  177041. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  177042. #endif
  177043. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  177044. /* Reduce RGB to grayscale. */
  177045. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177046. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  177047. int error_action, double red, double green ));
  177048. #endif
  177049. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  177050. int error_action, png_fixed_point red, png_fixed_point green ));
  177051. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  177052. png_ptr));
  177053. #endif
  177054. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  177055. png_colorp palette));
  177056. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  177057. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  177058. #endif
  177059. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  177060. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  177061. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  177062. #endif
  177063. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  177064. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  177065. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  177066. #endif
  177067. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  177068. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  177069. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  177070. png_uint_32 filler, int flags));
  177071. /* The values of the PNG_FILLER_ defines should NOT be changed */
  177072. #define PNG_FILLER_BEFORE 0
  177073. #define PNG_FILLER_AFTER 1
  177074. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  177075. #if !defined(PNG_1_0_X)
  177076. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  177077. png_uint_32 filler, int flags));
  177078. #endif
  177079. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  177080. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  177081. /* Swap bytes in 16-bit depth files. */
  177082. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  177083. #endif
  177084. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  177085. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  177086. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  177087. #endif
  177088. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  177089. /* Swap packing order of pixels in bytes. */
  177090. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  177091. #endif
  177092. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  177093. /* Converts files to legal bit depths. */
  177094. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  177095. png_color_8p true_bits));
  177096. #endif
  177097. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  177098. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  177099. /* Have the code handle the interlacing. Returns the number of passes. */
  177100. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  177101. #endif
  177102. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  177103. /* Invert monochrome files */
  177104. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  177105. #endif
  177106. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  177107. /* Handle alpha and tRNS by replacing with a background color. */
  177108. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177109. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  177110. png_color_16p background_color, int background_gamma_code,
  177111. int need_expand, double background_gamma));
  177112. #endif
  177113. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  177114. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  177115. #define PNG_BACKGROUND_GAMMA_FILE 2
  177116. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  177117. #endif
  177118. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  177119. /* strip the second byte of information from a 16-bit depth file. */
  177120. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  177121. #endif
  177122. #if defined(PNG_READ_DITHER_SUPPORTED)
  177123. /* Turn on dithering, and reduce the palette to the number of colors available. */
  177124. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  177125. png_colorp palette, int num_palette, int maximum_colors,
  177126. png_uint_16p histogram, int full_dither));
  177127. #endif
  177128. #if defined(PNG_READ_GAMMA_SUPPORTED)
  177129. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  177130. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177131. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  177132. double screen_gamma, double default_file_gamma));
  177133. #endif
  177134. #endif
  177135. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177136. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  177137. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  177138. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  177139. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  177140. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  177141. int empty_plte_permitted));
  177142. #endif
  177143. #endif
  177144. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  177145. /* Set how many lines between output flushes - 0 for no flushing */
  177146. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  177147. /* Flush the current PNG output buffer */
  177148. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  177149. #endif
  177150. /* optional update palette with requested transformations */
  177151. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  177152. /* optional call to update the users info structure */
  177153. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  177154. png_infop info_ptr));
  177155. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177156. /* read one or more rows of image data. */
  177157. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  177158. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  177159. #endif
  177160. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177161. /* read a row of data. */
  177162. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  177163. png_bytep row,
  177164. png_bytep display_row));
  177165. #endif
  177166. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177167. /* read the whole image into memory at once. */
  177168. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  177169. png_bytepp image));
  177170. #endif
  177171. /* write a row of image data */
  177172. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  177173. png_bytep row));
  177174. /* write a few rows of image data */
  177175. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  177176. png_bytepp row, png_uint_32 num_rows));
  177177. /* write the image data */
  177178. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  177179. png_bytepp image));
  177180. /* writes the end of the PNG file. */
  177181. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  177182. png_infop info_ptr));
  177183. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  177184. /* read the end of the PNG file. */
  177185. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  177186. png_infop info_ptr));
  177187. #endif
  177188. /* free any memory associated with the png_info_struct */
  177189. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  177190. png_infopp info_ptr_ptr));
  177191. /* free any memory associated with the png_struct and the png_info_structs */
  177192. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  177193. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  177194. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  177195. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  177196. png_infop end_info_ptr));
  177197. /* free any memory associated with the png_struct and the png_info_structs */
  177198. extern PNG_EXPORT(void,png_destroy_write_struct)
  177199. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  177200. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  177201. extern void png_write_destroy PNGARG((png_structp png_ptr));
  177202. /* set the libpng method of handling chunk CRC errors */
  177203. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  177204. int crit_action, int ancil_action));
  177205. /* Values for png_set_crc_action() to say how to handle CRC errors in
  177206. * ancillary and critical chunks, and whether to use the data contained
  177207. * therein. Note that it is impossible to "discard" data in a critical
  177208. * chunk. For versions prior to 0.90, the action was always error/quit,
  177209. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  177210. * chunks is warn/discard. These values should NOT be changed.
  177211. *
  177212. * value action:critical action:ancillary
  177213. */
  177214. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  177215. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  177216. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  177217. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  177218. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  177219. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  177220. /* These functions give the user control over the scan-line filtering in
  177221. * libpng and the compression methods used by zlib. These functions are
  177222. * mainly useful for testing, as the defaults should work with most users.
  177223. * Those users who are tight on memory or want faster performance at the
  177224. * expense of compression can modify them. See the compression library
  177225. * header file (zlib.h) for an explination of the compression functions.
  177226. */
  177227. /* set the filtering method(s) used by libpng. Currently, the only valid
  177228. * value for "method" is 0.
  177229. */
  177230. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  177231. int filters));
  177232. /* Flags for png_set_filter() to say which filters to use. The flags
  177233. * are chosen so that they don't conflict with real filter types
  177234. * below, in case they are supplied instead of the #defined constants.
  177235. * These values should NOT be changed.
  177236. */
  177237. #define PNG_NO_FILTERS 0x00
  177238. #define PNG_FILTER_NONE 0x08
  177239. #define PNG_FILTER_SUB 0x10
  177240. #define PNG_FILTER_UP 0x20
  177241. #define PNG_FILTER_AVG 0x40
  177242. #define PNG_FILTER_PAETH 0x80
  177243. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  177244. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  177245. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  177246. * These defines should NOT be changed.
  177247. */
  177248. #define PNG_FILTER_VALUE_NONE 0
  177249. #define PNG_FILTER_VALUE_SUB 1
  177250. #define PNG_FILTER_VALUE_UP 2
  177251. #define PNG_FILTER_VALUE_AVG 3
  177252. #define PNG_FILTER_VALUE_PAETH 4
  177253. #define PNG_FILTER_VALUE_LAST 5
  177254. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  177255. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  177256. * defines, either the default (minimum-sum-of-absolute-differences), or
  177257. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  177258. *
  177259. * Weights are factors >= 1.0, indicating how important it is to keep the
  177260. * filter type consistent between rows. Larger numbers mean the current
  177261. * filter is that many times as likely to be the same as the "num_weights"
  177262. * previous filters. This is cumulative for each previous row with a weight.
  177263. * There needs to be "num_weights" values in "filter_weights", or it can be
  177264. * NULL if the weights aren't being specified. Weights have no influence on
  177265. * the selection of the first row filter. Well chosen weights can (in theory)
  177266. * improve the compression for a given image.
  177267. *
  177268. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  177269. * filter type. Higher costs indicate more decoding expense, and are
  177270. * therefore less likely to be selected over a filter with lower computational
  177271. * costs. There needs to be a value in "filter_costs" for each valid filter
  177272. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  177273. * setting the costs. Costs try to improve the speed of decompression without
  177274. * unduly increasing the compressed image size.
  177275. *
  177276. * A negative weight or cost indicates the default value is to be used, and
  177277. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  177278. * The default values for both weights and costs are currently 1.0, but may
  177279. * change if good general weighting/cost heuristics can be found. If both
  177280. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  177281. * to the UNWEIGHTED method, but with added encoding time/computation.
  177282. */
  177283. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177284. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  177285. int heuristic_method, int num_weights, png_doublep filter_weights,
  177286. png_doublep filter_costs));
  177287. #endif
  177288. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  177289. /* Heuristic used for row filter selection. These defines should NOT be
  177290. * changed.
  177291. */
  177292. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  177293. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  177294. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  177295. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  177296. /* Set the library compression level. Currently, valid values range from
  177297. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  177298. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  177299. * shown that zlib compression levels 3-6 usually perform as well as level 9
  177300. * for PNG images, and do considerably fewer caclulations. In the future,
  177301. * these values may not correspond directly to the zlib compression levels.
  177302. */
  177303. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  177304. int level));
  177305. extern PNG_EXPORT(void,png_set_compression_mem_level)
  177306. PNGARG((png_structp png_ptr, int mem_level));
  177307. extern PNG_EXPORT(void,png_set_compression_strategy)
  177308. PNGARG((png_structp png_ptr, int strategy));
  177309. extern PNG_EXPORT(void,png_set_compression_window_bits)
  177310. PNGARG((png_structp png_ptr, int window_bits));
  177311. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  177312. int method));
  177313. /* These next functions are called for input/output, memory, and error
  177314. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  177315. * and call standard C I/O routines such as fread(), fwrite(), and
  177316. * fprintf(). These functions can be made to use other I/O routines
  177317. * at run time for those applications that need to handle I/O in a
  177318. * different manner by calling png_set_???_fn(). See libpng.txt for
  177319. * more information.
  177320. */
  177321. #if !defined(PNG_NO_STDIO)
  177322. /* Initialize the input/output for the PNG file to the default functions. */
  177323. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  177324. #endif
  177325. /* Replace the (error and abort), and warning functions with user
  177326. * supplied functions. If no messages are to be printed you must still
  177327. * write and use replacement functions. The replacement error_fn should
  177328. * still do a longjmp to the last setjmp location if you are using this
  177329. * method of error handling. If error_fn or warning_fn is NULL, the
  177330. * default function will be used.
  177331. */
  177332. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  177333. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  177334. /* Return the user pointer associated with the error functions */
  177335. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  177336. /* Replace the default data output functions with a user supplied one(s).
  177337. * If buffered output is not used, then output_flush_fn can be set to NULL.
  177338. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  177339. * output_flush_fn will be ignored (and thus can be NULL).
  177340. */
  177341. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  177342. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  177343. /* Replace the default data input function with a user supplied one. */
  177344. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  177345. png_voidp io_ptr, png_rw_ptr read_data_fn));
  177346. /* Return the user pointer associated with the I/O functions */
  177347. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  177348. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  177349. png_read_status_ptr read_row_fn));
  177350. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  177351. png_write_status_ptr write_row_fn));
  177352. #ifdef PNG_USER_MEM_SUPPORTED
  177353. /* Replace the default memory allocation functions with user supplied one(s). */
  177354. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  177355. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  177356. /* Return the user pointer associated with the memory functions */
  177357. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  177358. #endif
  177359. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  177360. defined(PNG_LEGACY_SUPPORTED)
  177361. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  177362. png_ptr, png_user_transform_ptr read_user_transform_fn));
  177363. #endif
  177364. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  177365. defined(PNG_LEGACY_SUPPORTED)
  177366. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  177367. png_ptr, png_user_transform_ptr write_user_transform_fn));
  177368. #endif
  177369. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  177370. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  177371. defined(PNG_LEGACY_SUPPORTED)
  177372. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  177373. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  177374. int user_transform_channels));
  177375. /* Return the user pointer associated with the user transform functions */
  177376. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  177377. PNGARG((png_structp png_ptr));
  177378. #endif
  177379. #ifdef PNG_USER_CHUNKS_SUPPORTED
  177380. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  177381. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  177382. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  177383. png_ptr));
  177384. #endif
  177385. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  177386. /* Sets the function callbacks for the push reader, and a pointer to a
  177387. * user-defined structure available to the callback functions.
  177388. */
  177389. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  177390. png_voidp progressive_ptr,
  177391. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  177392. png_progressive_end_ptr end_fn));
  177393. /* returns the user pointer associated with the push read functions */
  177394. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  177395. PNGARG((png_structp png_ptr));
  177396. /* function to be called when data becomes available */
  177397. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  177398. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  177399. /* function that combines rows. Not very much different than the
  177400. * png_combine_row() call. Is this even used?????
  177401. */
  177402. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  177403. png_bytep old_row, png_bytep new_row));
  177404. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  177405. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  177406. png_uint_32 size));
  177407. #if defined(PNG_1_0_X)
  177408. # define png_malloc_warn png_malloc
  177409. #else
  177410. /* Added at libpng version 1.2.4 */
  177411. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  177412. png_uint_32 size));
  177413. #endif
  177414. /* frees a pointer allocated by png_malloc() */
  177415. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  177416. #if defined(PNG_1_0_X)
  177417. /* Function to allocate memory for zlib. */
  177418. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  177419. uInt size));
  177420. /* Function to free memory for zlib */
  177421. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  177422. #endif
  177423. /* Free data that was allocated internally */
  177424. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  177425. png_infop info_ptr, png_uint_32 free_me, int num));
  177426. #ifdef PNG_FREE_ME_SUPPORTED
  177427. /* Reassign responsibility for freeing existing data, whether allocated
  177428. * by libpng or by the application */
  177429. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  177430. png_infop info_ptr, int freer, png_uint_32 mask));
  177431. #endif
  177432. /* assignments for png_data_freer */
  177433. #define PNG_DESTROY_WILL_FREE_DATA 1
  177434. #define PNG_SET_WILL_FREE_DATA 1
  177435. #define PNG_USER_WILL_FREE_DATA 2
  177436. /* Flags for png_ptr->free_me and info_ptr->free_me */
  177437. #define PNG_FREE_HIST 0x0008
  177438. #define PNG_FREE_ICCP 0x0010
  177439. #define PNG_FREE_SPLT 0x0020
  177440. #define PNG_FREE_ROWS 0x0040
  177441. #define PNG_FREE_PCAL 0x0080
  177442. #define PNG_FREE_SCAL 0x0100
  177443. #define PNG_FREE_UNKN 0x0200
  177444. #define PNG_FREE_LIST 0x0400
  177445. #define PNG_FREE_PLTE 0x1000
  177446. #define PNG_FREE_TRNS 0x2000
  177447. #define PNG_FREE_TEXT 0x4000
  177448. #define PNG_FREE_ALL 0x7fff
  177449. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  177450. #ifdef PNG_USER_MEM_SUPPORTED
  177451. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  177452. png_uint_32 size));
  177453. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  177454. png_voidp ptr));
  177455. #endif
  177456. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  177457. png_voidp s1, png_voidp s2, png_uint_32 size));
  177458. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  177459. png_voidp s1, int value, png_uint_32 size));
  177460. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  177461. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  177462. int check));
  177463. #endif /* USE_FAR_KEYWORD */
  177464. #ifndef PNG_NO_ERROR_TEXT
  177465. /* Fatal error in PNG image of libpng - can't continue */
  177466. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  177467. png_const_charp error_message));
  177468. /* The same, but the chunk name is prepended to the error string. */
  177469. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  177470. png_const_charp error_message));
  177471. #else
  177472. /* Fatal error in PNG image of libpng - can't continue */
  177473. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  177474. #endif
  177475. #ifndef PNG_NO_WARNINGS
  177476. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  177477. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  177478. png_const_charp warning_message));
  177479. #ifdef PNG_READ_SUPPORTED
  177480. /* Non-fatal error in libpng, chunk name is prepended to message. */
  177481. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  177482. png_const_charp warning_message));
  177483. #endif /* PNG_READ_SUPPORTED */
  177484. #endif /* PNG_NO_WARNINGS */
  177485. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  177486. * Similarly, the png_get_<chunk> calls are used to read values from the
  177487. * png_info_struct, either storing the parameters in the passed variables, or
  177488. * setting pointers into the png_info_struct where the data is stored. The
  177489. * png_get_<chunk> functions return a non-zero value if the data was available
  177490. * in info_ptr, or return zero and do not change any of the parameters if the
  177491. * data was not available.
  177492. *
  177493. * These functions should be used instead of directly accessing png_info
  177494. * to avoid problems with future changes in the size and internal layout of
  177495. * png_info_struct.
  177496. */
  177497. /* Returns "flag" if chunk data is valid in info_ptr. */
  177498. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  177499. png_infop info_ptr, png_uint_32 flag));
  177500. /* Returns number of bytes needed to hold a transformed row. */
  177501. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  177502. png_infop info_ptr));
  177503. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  177504. /* Returns row_pointers, which is an array of pointers to scanlines that was
  177505. returned from png_read_png(). */
  177506. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  177507. png_infop info_ptr));
  177508. /* Set row_pointers, which is an array of pointers to scanlines for use
  177509. by png_write_png(). */
  177510. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  177511. png_infop info_ptr, png_bytepp row_pointers));
  177512. #endif
  177513. /* Returns number of color channels in image. */
  177514. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  177515. png_infop info_ptr));
  177516. #ifdef PNG_EASY_ACCESS_SUPPORTED
  177517. /* Returns image width in pixels. */
  177518. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  177519. png_ptr, png_infop info_ptr));
  177520. /* Returns image height in pixels. */
  177521. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  177522. png_ptr, png_infop info_ptr));
  177523. /* Returns image bit_depth. */
  177524. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  177525. png_ptr, png_infop info_ptr));
  177526. /* Returns image color_type. */
  177527. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  177528. png_ptr, png_infop info_ptr));
  177529. /* Returns image filter_type. */
  177530. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  177531. png_ptr, png_infop info_ptr));
  177532. /* Returns image interlace_type. */
  177533. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  177534. png_ptr, png_infop info_ptr));
  177535. /* Returns image compression_type. */
  177536. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  177537. png_ptr, png_infop info_ptr));
  177538. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  177539. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  177540. png_ptr, png_infop info_ptr));
  177541. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  177542. png_ptr, png_infop info_ptr));
  177543. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  177544. png_ptr, png_infop info_ptr));
  177545. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  177546. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177547. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  177548. png_ptr, png_infop info_ptr));
  177549. #endif
  177550. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  177551. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  177552. png_ptr, png_infop info_ptr));
  177553. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  177554. png_ptr, png_infop info_ptr));
  177555. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  177556. png_ptr, png_infop info_ptr));
  177557. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  177558. png_ptr, png_infop info_ptr));
  177559. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  177560. /* Returns pointer to signature string read from PNG header */
  177561. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  177562. png_infop info_ptr));
  177563. #if defined(PNG_bKGD_SUPPORTED)
  177564. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  177565. png_infop info_ptr, png_color_16p *background));
  177566. #endif
  177567. #if defined(PNG_bKGD_SUPPORTED)
  177568. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  177569. png_infop info_ptr, png_color_16p background));
  177570. #endif
  177571. #if defined(PNG_cHRM_SUPPORTED)
  177572. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177573. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  177574. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  177575. double *red_y, double *green_x, double *green_y, double *blue_x,
  177576. double *blue_y));
  177577. #endif
  177578. #ifdef PNG_FIXED_POINT_SUPPORTED
  177579. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  177580. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  177581. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  177582. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  177583. *int_blue_x, png_fixed_point *int_blue_y));
  177584. #endif
  177585. #endif
  177586. #if defined(PNG_cHRM_SUPPORTED)
  177587. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177588. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  177589. png_infop info_ptr, double white_x, double white_y, double red_x,
  177590. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  177591. #endif
  177592. #ifdef PNG_FIXED_POINT_SUPPORTED
  177593. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  177594. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  177595. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  177596. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  177597. png_fixed_point int_blue_y));
  177598. #endif
  177599. #endif
  177600. #if defined(PNG_gAMA_SUPPORTED)
  177601. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177602. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  177603. png_infop info_ptr, double *file_gamma));
  177604. #endif
  177605. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  177606. png_infop info_ptr, png_fixed_point *int_file_gamma));
  177607. #endif
  177608. #if defined(PNG_gAMA_SUPPORTED)
  177609. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177610. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  177611. png_infop info_ptr, double file_gamma));
  177612. #endif
  177613. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  177614. png_infop info_ptr, png_fixed_point int_file_gamma));
  177615. #endif
  177616. #if defined(PNG_hIST_SUPPORTED)
  177617. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  177618. png_infop info_ptr, png_uint_16p *hist));
  177619. #endif
  177620. #if defined(PNG_hIST_SUPPORTED)
  177621. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  177622. png_infop info_ptr, png_uint_16p hist));
  177623. #endif
  177624. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  177625. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  177626. int *bit_depth, int *color_type, int *interlace_method,
  177627. int *compression_method, int *filter_method));
  177628. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  177629. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  177630. int color_type, int interlace_method, int compression_method,
  177631. int filter_method));
  177632. #if defined(PNG_oFFs_SUPPORTED)
  177633. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  177634. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  177635. int *unit_type));
  177636. #endif
  177637. #if defined(PNG_oFFs_SUPPORTED)
  177638. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  177639. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  177640. int unit_type));
  177641. #endif
  177642. #if defined(PNG_pCAL_SUPPORTED)
  177643. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  177644. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  177645. int *type, int *nparams, png_charp *units, png_charpp *params));
  177646. #endif
  177647. #if defined(PNG_pCAL_SUPPORTED)
  177648. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  177649. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  177650. int type, int nparams, png_charp units, png_charpp params));
  177651. #endif
  177652. #if defined(PNG_pHYs_SUPPORTED)
  177653. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  177654. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  177655. #endif
  177656. #if defined(PNG_pHYs_SUPPORTED)
  177657. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  177658. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  177659. #endif
  177660. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  177661. png_infop info_ptr, png_colorp *palette, int *num_palette));
  177662. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  177663. png_infop info_ptr, png_colorp palette, int num_palette));
  177664. #if defined(PNG_sBIT_SUPPORTED)
  177665. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  177666. png_infop info_ptr, png_color_8p *sig_bit));
  177667. #endif
  177668. #if defined(PNG_sBIT_SUPPORTED)
  177669. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  177670. png_infop info_ptr, png_color_8p sig_bit));
  177671. #endif
  177672. #if defined(PNG_sRGB_SUPPORTED)
  177673. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  177674. png_infop info_ptr, int *intent));
  177675. #endif
  177676. #if defined(PNG_sRGB_SUPPORTED)
  177677. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  177678. png_infop info_ptr, int intent));
  177679. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  177680. png_infop info_ptr, int intent));
  177681. #endif
  177682. #if defined(PNG_iCCP_SUPPORTED)
  177683. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  177684. png_infop info_ptr, png_charpp name, int *compression_type,
  177685. png_charpp profile, png_uint_32 *proflen));
  177686. /* Note to maintainer: profile should be png_bytepp */
  177687. #endif
  177688. #if defined(PNG_iCCP_SUPPORTED)
  177689. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  177690. png_infop info_ptr, png_charp name, int compression_type,
  177691. png_charp profile, png_uint_32 proflen));
  177692. /* Note to maintainer: profile should be png_bytep */
  177693. #endif
  177694. #if defined(PNG_sPLT_SUPPORTED)
  177695. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  177696. png_infop info_ptr, png_sPLT_tpp entries));
  177697. #endif
  177698. #if defined(PNG_sPLT_SUPPORTED)
  177699. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  177700. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  177701. #endif
  177702. #if defined(PNG_TEXT_SUPPORTED)
  177703. /* png_get_text also returns the number of text chunks in *num_text */
  177704. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  177705. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  177706. #endif
  177707. /*
  177708. * Note while png_set_text() will accept a structure whose text,
  177709. * language, and translated keywords are NULL pointers, the structure
  177710. * returned by png_get_text will always contain regular
  177711. * zero-terminated C strings. They might be empty strings but
  177712. * they will never be NULL pointers.
  177713. */
  177714. #if defined(PNG_TEXT_SUPPORTED)
  177715. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  177716. png_infop info_ptr, png_textp text_ptr, int num_text));
  177717. #endif
  177718. #if defined(PNG_tIME_SUPPORTED)
  177719. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  177720. png_infop info_ptr, png_timep *mod_time));
  177721. #endif
  177722. #if defined(PNG_tIME_SUPPORTED)
  177723. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  177724. png_infop info_ptr, png_timep mod_time));
  177725. #endif
  177726. #if defined(PNG_tRNS_SUPPORTED)
  177727. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  177728. png_infop info_ptr, png_bytep *trans, int *num_trans,
  177729. png_color_16p *trans_values));
  177730. #endif
  177731. #if defined(PNG_tRNS_SUPPORTED)
  177732. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  177733. png_infop info_ptr, png_bytep trans, int num_trans,
  177734. png_color_16p trans_values));
  177735. #endif
  177736. #if defined(PNG_tRNS_SUPPORTED)
  177737. #endif
  177738. #if defined(PNG_sCAL_SUPPORTED)
  177739. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177740. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  177741. png_infop info_ptr, int *unit, double *width, double *height));
  177742. #else
  177743. #ifdef PNG_FIXED_POINT_SUPPORTED
  177744. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  177745. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  177746. #endif
  177747. #endif
  177748. #endif /* PNG_sCAL_SUPPORTED */
  177749. #if defined(PNG_sCAL_SUPPORTED)
  177750. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177751. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  177752. png_infop info_ptr, int unit, double width, double height));
  177753. #else
  177754. #ifdef PNG_FIXED_POINT_SUPPORTED
  177755. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  177756. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  177757. #endif
  177758. #endif
  177759. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  177760. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177761. /* provide a list of chunks and how they are to be handled, if the built-in
  177762. handling or default unknown chunk handling is not desired. Any chunks not
  177763. listed will be handled in the default manner. The IHDR and IEND chunks
  177764. must not be listed.
  177765. keep = 0: follow default behaviour
  177766. = 1: do not keep
  177767. = 2: keep only if safe-to-copy
  177768. = 3: keep even if unsafe-to-copy
  177769. */
  177770. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  177771. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  177772. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  177773. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  177774. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  177775. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  177776. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  177777. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  177778. #endif
  177779. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  177780. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  177781. chunk_name));
  177782. #endif
  177783. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  177784. If you need to turn it off for a chunk that your application has freed,
  177785. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  177786. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  177787. png_infop info_ptr, int mask));
  177788. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  177789. /* The "params" pointer is currently not used and is for future expansion. */
  177790. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  177791. png_infop info_ptr,
  177792. int transforms,
  177793. png_voidp params));
  177794. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  177795. png_infop info_ptr,
  177796. int transforms,
  177797. png_voidp params));
  177798. #endif
  177799. /* Define PNG_DEBUG at compile time for debugging information. Higher
  177800. * numbers for PNG_DEBUG mean more debugging information. This has
  177801. * only been added since version 0.95 so it is not implemented throughout
  177802. * libpng yet, but more support will be added as needed.
  177803. */
  177804. #ifdef PNG_DEBUG
  177805. #if (PNG_DEBUG > 0)
  177806. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  177807. #include <crtdbg.h>
  177808. #if (PNG_DEBUG > 1)
  177809. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  177810. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  177811. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  177812. #endif
  177813. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  177814. #ifndef PNG_DEBUG_FILE
  177815. #define PNG_DEBUG_FILE stderr
  177816. #endif /* PNG_DEBUG_FILE */
  177817. #if (PNG_DEBUG > 1)
  177818. #define png_debug(l,m) \
  177819. { \
  177820. int num_tabs=l; \
  177821. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  177822. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  177823. }
  177824. #define png_debug1(l,m,p1) \
  177825. { \
  177826. int num_tabs=l; \
  177827. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  177828. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  177829. }
  177830. #define png_debug2(l,m,p1,p2) \
  177831. { \
  177832. int num_tabs=l; \
  177833. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  177834. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  177835. }
  177836. #endif /* (PNG_DEBUG > 1) */
  177837. #endif /* _MSC_VER */
  177838. #endif /* (PNG_DEBUG > 0) */
  177839. #endif /* PNG_DEBUG */
  177840. #ifndef png_debug
  177841. #define png_debug(l, m)
  177842. #endif
  177843. #ifndef png_debug1
  177844. #define png_debug1(l, m, p1)
  177845. #endif
  177846. #ifndef png_debug2
  177847. #define png_debug2(l, m, p1, p2)
  177848. #endif
  177849. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  177850. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  177851. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  177852. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  177853. #ifdef PNG_MNG_FEATURES_SUPPORTED
  177854. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  177855. png_ptr, png_uint_32 mng_features_permitted));
  177856. #endif
  177857. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  177858. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  177859. #define PNG_HANDLE_CHUNK_NEVER 1
  177860. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  177861. #define PNG_HANDLE_CHUNK_ALWAYS 3
  177862. /* Added to version 1.2.0 */
  177863. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  177864. #if defined(PNG_MMX_CODE_SUPPORTED)
  177865. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  177866. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  177867. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  177868. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  177869. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  177870. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  177871. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  177872. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  177873. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  177874. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  177875. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  177876. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  177877. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  177878. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  177879. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  177880. #define PNG_MMX_WRITE_FLAGS ( 0 )
  177881. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  177882. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  177883. | PNG_MMX_READ_FLAGS \
  177884. | PNG_MMX_WRITE_FLAGS )
  177885. #define PNG_SELECT_READ 1
  177886. #define PNG_SELECT_WRITE 2
  177887. #endif /* PNG_MMX_CODE_SUPPORTED */
  177888. #if !defined(PNG_1_0_X)
  177889. /* pngget.c */
  177890. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  177891. PNGARG((int flag_select, int *compilerID));
  177892. /* pngget.c */
  177893. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  177894. PNGARG((int flag_select));
  177895. /* pngget.c */
  177896. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  177897. PNGARG((png_structp png_ptr));
  177898. /* pngget.c */
  177899. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  177900. PNGARG((png_structp png_ptr));
  177901. /* pngget.c */
  177902. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  177903. PNGARG((png_structp png_ptr));
  177904. /* pngset.c */
  177905. extern PNG_EXPORT(void,png_set_asm_flags)
  177906. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  177907. /* pngset.c */
  177908. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  177909. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  177910. png_uint_32 mmx_rowbytes_threshold));
  177911. #endif /* PNG_1_0_X */
  177912. #if !defined(PNG_1_0_X)
  177913. /* png.c, pnggccrd.c, or pngvcrd.c */
  177914. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  177915. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  177916. /* Strip the prepended error numbers ("#nnn ") from error and warning
  177917. * messages before passing them to the error or warning handler. */
  177918. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  177919. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  177920. png_ptr, png_uint_32 strip_mode));
  177921. #endif
  177922. #endif /* PNG_1_0_X */
  177923. /* Added at libpng-1.2.6 */
  177924. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  177925. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  177926. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  177927. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  177928. png_ptr));
  177929. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  177930. png_ptr));
  177931. #endif
  177932. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  177933. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  177934. /* With these routines we avoid an integer divide, which will be slower on
  177935. * most machines. However, it does take more operations than the corresponding
  177936. * divide method, so it may be slower on a few RISC systems. There are two
  177937. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  177938. *
  177939. * Note that the rounding factors are NOT supposed to be the same! 128 and
  177940. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  177941. * standard method.
  177942. *
  177943. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  177944. */
  177945. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  177946. # define png_composite(composite, fg, alpha, bg) \
  177947. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  177948. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  177949. (png_uint_16)(alpha)) + (png_uint_16)128); \
  177950. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  177951. # define png_composite_16(composite, fg, alpha, bg) \
  177952. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  177953. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  177954. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  177955. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  177956. #else /* standard method using integer division */
  177957. # define png_composite(composite, fg, alpha, bg) \
  177958. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  177959. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  177960. (png_uint_16)127) / 255)
  177961. # define png_composite_16(composite, fg, alpha, bg) \
  177962. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  177963. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  177964. (png_uint_32)32767) / (png_uint_32)65535L)
  177965. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  177966. /* Inline macros to do direct reads of bytes from the input buffer. These
  177967. * require that you are using an architecture that uses PNG byte ordering
  177968. * (MSB first) and supports unaligned data storage. I think that PowerPC
  177969. * in big-endian mode and 680x0 are the only ones that will support this.
  177970. * The x86 line of processors definitely do not. The png_get_int_32()
  177971. * routine also assumes we are using two's complement format for negative
  177972. * values, which is almost certainly true.
  177973. */
  177974. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  177975. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  177976. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  177977. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  177978. #else
  177979. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  177980. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  177981. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  177982. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  177983. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  177984. PNGARG((png_structp png_ptr, png_bytep buf));
  177985. /* No png_get_int_16 -- may be added if there's a real need for it. */
  177986. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  177987. */
  177988. extern PNG_EXPORT(void,png_save_uint_32)
  177989. PNGARG((png_bytep buf, png_uint_32 i));
  177990. extern PNG_EXPORT(void,png_save_int_32)
  177991. PNGARG((png_bytep buf, png_int_32 i));
  177992. /* Place a 16-bit number into a buffer in PNG byte order.
  177993. * The parameter is declared unsigned int, not png_uint_16,
  177994. * just to avoid potential problems on pre-ANSI C compilers.
  177995. */
  177996. extern PNG_EXPORT(void,png_save_uint_16)
  177997. PNGARG((png_bytep buf, unsigned int i));
  177998. /* No png_save_int_16 -- may be added if there's a real need for it. */
  177999. /* ************************************************************************* */
  178000. /* These next functions are used internally in the code. They generally
  178001. * shouldn't be used unless you are writing code to add or replace some
  178002. * functionality in libpng. More information about most functions can
  178003. * be found in the files where the functions are located.
  178004. */
  178005. /* Various modes of operation, that are visible to applications because
  178006. * they are used for unknown chunk location.
  178007. */
  178008. #define PNG_HAVE_IHDR 0x01
  178009. #define PNG_HAVE_PLTE 0x02
  178010. #define PNG_HAVE_IDAT 0x04
  178011. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  178012. #define PNG_HAVE_IEND 0x10
  178013. #if defined(PNG_INTERNAL)
  178014. /* More modes of operation. Note that after an init, mode is set to
  178015. * zero automatically when the structure is created.
  178016. */
  178017. #define PNG_HAVE_gAMA 0x20
  178018. #define PNG_HAVE_cHRM 0x40
  178019. #define PNG_HAVE_sRGB 0x80
  178020. #define PNG_HAVE_CHUNK_HEADER 0x100
  178021. #define PNG_WROTE_tIME 0x200
  178022. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  178023. #define PNG_BACKGROUND_IS_GRAY 0x800
  178024. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  178025. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  178026. /* flags for the transformations the PNG library does on the image data */
  178027. #define PNG_BGR 0x0001
  178028. #define PNG_INTERLACE 0x0002
  178029. #define PNG_PACK 0x0004
  178030. #define PNG_SHIFT 0x0008
  178031. #define PNG_SWAP_BYTES 0x0010
  178032. #define PNG_INVERT_MONO 0x0020
  178033. #define PNG_DITHER 0x0040
  178034. #define PNG_BACKGROUND 0x0080
  178035. #define PNG_BACKGROUND_EXPAND 0x0100
  178036. /* 0x0200 unused */
  178037. #define PNG_16_TO_8 0x0400
  178038. #define PNG_RGBA 0x0800
  178039. #define PNG_EXPAND 0x1000
  178040. #define PNG_GAMMA 0x2000
  178041. #define PNG_GRAY_TO_RGB 0x4000
  178042. #define PNG_FILLER 0x8000L
  178043. #define PNG_PACKSWAP 0x10000L
  178044. #define PNG_SWAP_ALPHA 0x20000L
  178045. #define PNG_STRIP_ALPHA 0x40000L
  178046. #define PNG_INVERT_ALPHA 0x80000L
  178047. #define PNG_USER_TRANSFORM 0x100000L
  178048. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  178049. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  178050. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  178051. /* 0x800000L Unused */
  178052. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  178053. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  178054. /* 0x4000000L unused */
  178055. /* 0x8000000L unused */
  178056. /* 0x10000000L unused */
  178057. /* 0x20000000L unused */
  178058. /* 0x40000000L unused */
  178059. /* flags for png_create_struct */
  178060. #define PNG_STRUCT_PNG 0x0001
  178061. #define PNG_STRUCT_INFO 0x0002
  178062. /* Scaling factor for filter heuristic weighting calculations */
  178063. #define PNG_WEIGHT_SHIFT 8
  178064. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  178065. #define PNG_COST_SHIFT 3
  178066. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  178067. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  178068. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  178069. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  178070. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  178071. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  178072. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  178073. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  178074. #define PNG_FLAG_ROW_INIT 0x0040
  178075. #define PNG_FLAG_FILLER_AFTER 0x0080
  178076. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  178077. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  178078. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  178079. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  178080. #define PNG_FLAG_FREE_PLTE 0x1000
  178081. #define PNG_FLAG_FREE_TRNS 0x2000
  178082. #define PNG_FLAG_FREE_HIST 0x4000
  178083. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  178084. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  178085. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  178086. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  178087. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  178088. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  178089. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  178090. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  178091. /* 0x800000L unused */
  178092. /* 0x1000000L unused */
  178093. /* 0x2000000L unused */
  178094. /* 0x4000000L unused */
  178095. /* 0x8000000L unused */
  178096. /* 0x10000000L unused */
  178097. /* 0x20000000L unused */
  178098. /* 0x40000000L unused */
  178099. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  178100. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  178101. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  178102. PNG_FLAG_CRC_CRITICAL_IGNORE)
  178103. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  178104. PNG_FLAG_CRC_CRITICAL_MASK)
  178105. /* save typing and make code easier to understand */
  178106. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  178107. abs((int)((c1).green) - (int)((c2).green)) + \
  178108. abs((int)((c1).blue) - (int)((c2).blue)))
  178109. /* Added to libpng-1.2.6 JB */
  178110. #define PNG_ROWBYTES(pixel_bits, width) \
  178111. ((pixel_bits) >= 8 ? \
  178112. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  178113. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  178114. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  178115. ideal-delta..ideal+delta. Each argument is evaluated twice.
  178116. "ideal" and "delta" should be constants, normally simple
  178117. integers, "value" a variable. Added to libpng-1.2.6 JB */
  178118. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  178119. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  178120. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  178121. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  178122. /* place to hold the signature string for a PNG file. */
  178123. #ifdef PNG_USE_GLOBAL_ARRAYS
  178124. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  178125. #else
  178126. #endif
  178127. #endif /* PNG_NO_EXTERN */
  178128. /* Constant strings for known chunk types. If you need to add a chunk,
  178129. * define the name here, and add an invocation of the macro in png.c and
  178130. * wherever it's needed.
  178131. */
  178132. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  178133. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  178134. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  178135. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  178136. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  178137. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  178138. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  178139. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  178140. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  178141. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  178142. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  178143. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  178144. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  178145. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  178146. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  178147. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  178148. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  178149. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  178150. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  178151. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  178152. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  178153. #ifdef PNG_USE_GLOBAL_ARRAYS
  178154. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  178155. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  178156. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  178157. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  178158. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  178159. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  178160. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  178161. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  178162. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  178163. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  178164. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  178165. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  178166. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  178167. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  178168. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  178169. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  178170. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  178171. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  178172. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  178173. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  178174. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  178175. #endif /* PNG_USE_GLOBAL_ARRAYS */
  178176. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178177. /* Initialize png_ptr struct for reading, and allocate any other memory.
  178178. * (old interface - DEPRECATED - use png_create_read_struct instead).
  178179. */
  178180. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  178181. #undef png_read_init
  178182. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  178183. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  178184. #endif
  178185. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  178186. png_const_charp user_png_ver, png_size_t png_struct_size));
  178187. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178188. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  178189. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  178190. png_info_size));
  178191. #endif
  178192. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178193. /* Initialize png_ptr struct for writing, and allocate any other memory.
  178194. * (old interface - DEPRECATED - use png_create_write_struct instead).
  178195. */
  178196. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  178197. #undef png_write_init
  178198. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  178199. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  178200. #endif
  178201. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  178202. png_const_charp user_png_ver, png_size_t png_struct_size));
  178203. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  178204. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  178205. png_info_size));
  178206. /* Allocate memory for an internal libpng struct */
  178207. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  178208. /* Free memory from internal libpng struct */
  178209. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  178210. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  178211. malloc_fn, png_voidp mem_ptr));
  178212. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  178213. png_free_ptr free_fn, png_voidp mem_ptr));
  178214. /* Free any memory that info_ptr points to and reset struct. */
  178215. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  178216. png_infop info_ptr));
  178217. #ifndef PNG_1_0_X
  178218. /* Function to allocate memory for zlib. */
  178219. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  178220. /* Function to free memory for zlib */
  178221. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  178222. #ifdef PNG_SIZE_T
  178223. /* Function to convert a sizeof an item to png_sizeof item */
  178224. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  178225. #endif
  178226. /* Next four functions are used internally as callbacks. PNGAPI is required
  178227. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  178228. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  178229. png_bytep data, png_size_t length));
  178230. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178231. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  178232. png_bytep buffer, png_size_t length));
  178233. #endif
  178234. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  178235. png_bytep data, png_size_t length));
  178236. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  178237. #if !defined(PNG_NO_STDIO)
  178238. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  178239. #endif
  178240. #endif
  178241. #else /* PNG_1_0_X */
  178242. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178243. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  178244. png_bytep buffer, png_size_t length));
  178245. #endif
  178246. #endif /* PNG_1_0_X */
  178247. /* Reset the CRC variable */
  178248. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  178249. /* Write the "data" buffer to whatever output you are using. */
  178250. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  178251. png_size_t length));
  178252. /* Read data from whatever input you are using into the "data" buffer */
  178253. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  178254. png_size_t length));
  178255. /* Read bytes into buf, and update png_ptr->crc */
  178256. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  178257. png_size_t length));
  178258. /* Decompress data in a chunk that uses compression */
  178259. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  178260. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  178261. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  178262. int comp_type, png_charp chunkdata, png_size_t chunklength,
  178263. png_size_t prefix_length, png_size_t *data_length));
  178264. #endif
  178265. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  178266. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  178267. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  178268. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  178269. /* Calculate the CRC over a section of data. Note that we are only
  178270. * passing a maximum of 64K on systems that have this as a memory limit,
  178271. * since this is the maximum buffer size we can specify.
  178272. */
  178273. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  178274. png_size_t length));
  178275. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  178276. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  178277. #endif
  178278. /* simple function to write the signature */
  178279. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  178280. /* write various chunks */
  178281. /* Write the IHDR chunk, and update the png_struct with the necessary
  178282. * information.
  178283. */
  178284. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  178285. png_uint_32 height,
  178286. int bit_depth, int color_type, int compression_method, int filter_method,
  178287. int interlace_method));
  178288. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  178289. png_uint_32 num_pal));
  178290. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  178291. png_size_t length));
  178292. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  178293. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  178294. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178295. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  178296. #endif
  178297. #ifdef PNG_FIXED_POINT_SUPPORTED
  178298. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  178299. file_gamma));
  178300. #endif
  178301. #endif
  178302. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  178303. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  178304. int color_type));
  178305. #endif
  178306. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  178307. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178308. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  178309. double white_x, double white_y,
  178310. double red_x, double red_y, double green_x, double green_y,
  178311. double blue_x, double blue_y));
  178312. #endif
  178313. #ifdef PNG_FIXED_POINT_SUPPORTED
  178314. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  178315. png_fixed_point int_white_x, png_fixed_point int_white_y,
  178316. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  178317. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  178318. png_fixed_point int_blue_y));
  178319. #endif
  178320. #endif
  178321. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  178322. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  178323. int intent));
  178324. #endif
  178325. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  178326. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  178327. png_charp name, int compression_type,
  178328. png_charp profile, int proflen));
  178329. /* Note to maintainer: profile should be png_bytep */
  178330. #endif
  178331. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  178332. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  178333. png_sPLT_tp palette));
  178334. #endif
  178335. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  178336. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  178337. png_color_16p values, int number, int color_type));
  178338. #endif
  178339. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  178340. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  178341. png_color_16p values, int color_type));
  178342. #endif
  178343. #if defined(PNG_WRITE_hIST_SUPPORTED)
  178344. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  178345. int num_hist));
  178346. #endif
  178347. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  178348. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  178349. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  178350. png_charp key, png_charpp new_key));
  178351. #endif
  178352. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  178353. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  178354. png_charp text, png_size_t text_len));
  178355. #endif
  178356. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  178357. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  178358. png_charp text, png_size_t text_len, int compression));
  178359. #endif
  178360. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  178361. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  178362. int compression, png_charp key, png_charp lang, png_charp lang_key,
  178363. png_charp text));
  178364. #endif
  178365. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  178366. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  178367. png_infop info_ptr, png_textp text_ptr, int num_text));
  178368. #endif
  178369. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  178370. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  178371. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  178372. #endif
  178373. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  178374. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  178375. png_int_32 X0, png_int_32 X1, int type, int nparams,
  178376. png_charp units, png_charpp params));
  178377. #endif
  178378. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  178379. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  178380. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  178381. int unit_type));
  178382. #endif
  178383. #if defined(PNG_WRITE_tIME_SUPPORTED)
  178384. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  178385. png_timep mod_time));
  178386. #endif
  178387. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  178388. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  178389. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  178390. int unit, double width, double height));
  178391. #else
  178392. #ifdef PNG_FIXED_POINT_SUPPORTED
  178393. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  178394. int unit, png_charp width, png_charp height));
  178395. #endif
  178396. #endif
  178397. #endif
  178398. /* Called when finished processing a row of data */
  178399. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  178400. /* Internal use only. Called before first row of data */
  178401. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  178402. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178403. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  178404. #endif
  178405. /* combine a row of data, dealing with alpha, etc. if requested */
  178406. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  178407. int mask));
  178408. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  178409. /* expand an interlaced row */
  178410. /* OLD pre-1.0.9 interface:
  178411. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  178412. png_bytep row, int pass, png_uint_32 transformations));
  178413. */
  178414. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  178415. #endif
  178416. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  178417. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  178418. /* grab pixels out of a row for an interlaced pass */
  178419. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  178420. png_bytep row, int pass));
  178421. #endif
  178422. /* unfilter a row */
  178423. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  178424. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  178425. /* Choose the best filter to use and filter the row data */
  178426. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  178427. png_row_infop row_info));
  178428. /* Write out the filtered row. */
  178429. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  178430. png_bytep filtered_row));
  178431. /* finish a row while reading, dealing with interlacing passes, etc. */
  178432. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  178433. /* initialize the row buffers, etc. */
  178434. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  178435. /* optional call to update the users info structure */
  178436. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  178437. png_infop info_ptr));
  178438. /* these are the functions that do the transformations */
  178439. #if defined(PNG_READ_FILLER_SUPPORTED)
  178440. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  178441. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  178442. #endif
  178443. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  178444. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  178445. png_bytep row));
  178446. #endif
  178447. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  178448. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  178449. png_bytep row));
  178450. #endif
  178451. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  178452. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  178453. png_bytep row));
  178454. #endif
  178455. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  178456. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  178457. png_bytep row));
  178458. #endif
  178459. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  178460. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  178461. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  178462. png_bytep row, png_uint_32 flags));
  178463. #endif
  178464. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  178465. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  178466. #endif
  178467. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  178468. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  178469. #endif
  178470. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  178471. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  178472. row_info, png_bytep row));
  178473. #endif
  178474. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  178475. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  178476. png_bytep row));
  178477. #endif
  178478. #if defined(PNG_READ_PACK_SUPPORTED)
  178479. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  178480. #endif
  178481. #if defined(PNG_READ_SHIFT_SUPPORTED)
  178482. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  178483. png_color_8p sig_bits));
  178484. #endif
  178485. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  178486. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  178487. #endif
  178488. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  178489. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  178490. #endif
  178491. #if defined(PNG_READ_DITHER_SUPPORTED)
  178492. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  178493. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  178494. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  178495. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  178496. png_colorp palette, int num_palette));
  178497. # endif
  178498. #endif
  178499. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  178500. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  178501. #endif
  178502. #if defined(PNG_WRITE_PACK_SUPPORTED)
  178503. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  178504. png_bytep row, png_uint_32 bit_depth));
  178505. #endif
  178506. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  178507. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  178508. png_color_8p bit_depth));
  178509. #endif
  178510. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  178511. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178512. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  178513. png_color_16p trans_values, png_color_16p background,
  178514. png_color_16p background_1,
  178515. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  178516. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  178517. png_uint_16pp gamma_16_to_1, int gamma_shift));
  178518. #else
  178519. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  178520. png_color_16p trans_values, png_color_16p background));
  178521. #endif
  178522. #endif
  178523. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178524. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  178525. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  178526. int gamma_shift));
  178527. #endif
  178528. #if defined(PNG_READ_EXPAND_SUPPORTED)
  178529. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  178530. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  178531. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  178532. png_bytep row, png_color_16p trans_value));
  178533. #endif
  178534. /* The following decodes the appropriate chunks, and does error correction,
  178535. * then calls the appropriate callback for the chunk if it is valid.
  178536. */
  178537. /* decode the IHDR chunk */
  178538. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  178539. png_uint_32 length));
  178540. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  178541. png_uint_32 length));
  178542. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  178543. png_uint_32 length));
  178544. #if defined(PNG_READ_bKGD_SUPPORTED)
  178545. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  178546. png_uint_32 length));
  178547. #endif
  178548. #if defined(PNG_READ_cHRM_SUPPORTED)
  178549. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  178550. png_uint_32 length));
  178551. #endif
  178552. #if defined(PNG_READ_gAMA_SUPPORTED)
  178553. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  178554. png_uint_32 length));
  178555. #endif
  178556. #if defined(PNG_READ_hIST_SUPPORTED)
  178557. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  178558. png_uint_32 length));
  178559. #endif
  178560. #if defined(PNG_READ_iCCP_SUPPORTED)
  178561. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  178562. png_uint_32 length));
  178563. #endif /* PNG_READ_iCCP_SUPPORTED */
  178564. #if defined(PNG_READ_iTXt_SUPPORTED)
  178565. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  178566. png_uint_32 length));
  178567. #endif
  178568. #if defined(PNG_READ_oFFs_SUPPORTED)
  178569. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  178570. png_uint_32 length));
  178571. #endif
  178572. #if defined(PNG_READ_pCAL_SUPPORTED)
  178573. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  178574. png_uint_32 length));
  178575. #endif
  178576. #if defined(PNG_READ_pHYs_SUPPORTED)
  178577. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  178578. png_uint_32 length));
  178579. #endif
  178580. #if defined(PNG_READ_sBIT_SUPPORTED)
  178581. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  178582. png_uint_32 length));
  178583. #endif
  178584. #if defined(PNG_READ_sCAL_SUPPORTED)
  178585. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  178586. png_uint_32 length));
  178587. #endif
  178588. #if defined(PNG_READ_sPLT_SUPPORTED)
  178589. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  178590. png_uint_32 length));
  178591. #endif /* PNG_READ_sPLT_SUPPORTED */
  178592. #if defined(PNG_READ_sRGB_SUPPORTED)
  178593. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  178594. png_uint_32 length));
  178595. #endif
  178596. #if defined(PNG_READ_tEXt_SUPPORTED)
  178597. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  178598. png_uint_32 length));
  178599. #endif
  178600. #if defined(PNG_READ_tIME_SUPPORTED)
  178601. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  178602. png_uint_32 length));
  178603. #endif
  178604. #if defined(PNG_READ_tRNS_SUPPORTED)
  178605. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  178606. png_uint_32 length));
  178607. #endif
  178608. #if defined(PNG_READ_zTXt_SUPPORTED)
  178609. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  178610. png_uint_32 length));
  178611. #endif
  178612. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  178613. png_infop info_ptr, png_uint_32 length));
  178614. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  178615. png_bytep chunk_name));
  178616. /* handle the transformations for reading and writing */
  178617. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  178618. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  178619. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  178620. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178621. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  178622. png_infop info_ptr));
  178623. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  178624. png_infop info_ptr));
  178625. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  178626. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  178627. png_uint_32 length));
  178628. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  178629. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  178630. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  178631. png_bytep buffer, png_size_t buffer_length));
  178632. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  178633. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  178634. png_bytep buffer, png_size_t buffer_length));
  178635. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  178636. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  178637. png_infop info_ptr, png_uint_32 length));
  178638. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  178639. png_infop info_ptr));
  178640. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  178641. png_infop info_ptr));
  178642. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  178643. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  178644. png_infop info_ptr));
  178645. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  178646. png_infop info_ptr));
  178647. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  178648. #if defined(PNG_READ_tEXt_SUPPORTED)
  178649. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  178650. png_infop info_ptr, png_uint_32 length));
  178651. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  178652. png_infop info_ptr));
  178653. #endif
  178654. #if defined(PNG_READ_zTXt_SUPPORTED)
  178655. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  178656. png_infop info_ptr, png_uint_32 length));
  178657. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  178658. png_infop info_ptr));
  178659. #endif
  178660. #if defined(PNG_READ_iTXt_SUPPORTED)
  178661. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  178662. png_infop info_ptr, png_uint_32 length));
  178663. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  178664. png_infop info_ptr));
  178665. #endif
  178666. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  178667. #ifdef PNG_MNG_FEATURES_SUPPORTED
  178668. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  178669. png_bytep row));
  178670. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  178671. png_bytep row));
  178672. #endif
  178673. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  178674. #if defined(PNG_MMX_CODE_SUPPORTED)
  178675. /* png.c */ /* PRIVATE */
  178676. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  178677. #endif
  178678. #endif
  178679. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  178680. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  178681. png_infop info_ptr));
  178682. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  178683. png_infop info_ptr));
  178684. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  178685. png_infop info_ptr));
  178686. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  178687. png_infop info_ptr));
  178688. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  178689. png_infop info_ptr));
  178690. #if defined(PNG_pHYs_SUPPORTED)
  178691. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  178692. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  178693. #endif /* PNG_pHYs_SUPPORTED */
  178694. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  178695. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  178696. #endif /* PNG_INTERNAL */
  178697. #ifdef __cplusplus
  178698. }
  178699. #endif
  178700. #endif /* PNG_VERSION_INFO_ONLY */
  178701. /* do not put anything past this line */
  178702. #endif /* PNG_H */
  178703. /********* End of inlined file: png.h *********/
  178704. #define PNG_NO_EXTERN
  178705. /********* Start of inlined file: png.c *********/
  178706. /* png.c - location for general purpose libpng functions
  178707. *
  178708. * Last changed in libpng 1.2.21 [October 4, 2007]
  178709. * For conditions of distribution and use, see copyright notice in png.h
  178710. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  178711. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  178712. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  178713. */
  178714. #define PNG_INTERNAL
  178715. #define PNG_NO_EXTERN
  178716. /* Generate a compiler error if there is an old png.h in the search path. */
  178717. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  178718. /* Version information for C files. This had better match the version
  178719. * string defined in png.h. */
  178720. #ifdef PNG_USE_GLOBAL_ARRAYS
  178721. /* png_libpng_ver was changed to a function in version 1.0.5c */
  178722. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  178723. #ifdef PNG_READ_SUPPORTED
  178724. /* png_sig was changed to a function in version 1.0.5c */
  178725. /* Place to hold the signature string for a PNG file. */
  178726. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  178727. #endif /* PNG_READ_SUPPORTED */
  178728. /* Invoke global declarations for constant strings for known chunk types */
  178729. PNG_IHDR;
  178730. PNG_IDAT;
  178731. PNG_IEND;
  178732. PNG_PLTE;
  178733. PNG_bKGD;
  178734. PNG_cHRM;
  178735. PNG_gAMA;
  178736. PNG_hIST;
  178737. PNG_iCCP;
  178738. PNG_iTXt;
  178739. PNG_oFFs;
  178740. PNG_pCAL;
  178741. PNG_sCAL;
  178742. PNG_pHYs;
  178743. PNG_sBIT;
  178744. PNG_sPLT;
  178745. PNG_sRGB;
  178746. PNG_tEXt;
  178747. PNG_tIME;
  178748. PNG_tRNS;
  178749. PNG_zTXt;
  178750. #ifdef PNG_READ_SUPPORTED
  178751. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  178752. /* start of interlace block */
  178753. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  178754. /* offset to next interlace block */
  178755. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  178756. /* start of interlace block in the y direction */
  178757. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  178758. /* offset to next interlace block in the y direction */
  178759. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  178760. /* Height of interlace block. This is not currently used - if you need
  178761. * it, uncomment it here and in png.h
  178762. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  178763. */
  178764. /* Mask to determine which pixels are valid in a pass */
  178765. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  178766. /* Mask to determine which pixels to overwrite while displaying */
  178767. PNG_CONST int FARDATA png_pass_dsp_mask[]
  178768. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  178769. #endif /* PNG_READ_SUPPORTED */
  178770. #endif /* PNG_USE_GLOBAL_ARRAYS */
  178771. /* Tells libpng that we have already handled the first "num_bytes" bytes
  178772. * of the PNG file signature. If the PNG data is embedded into another
  178773. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  178774. * or write any of the magic bytes before it starts on the IHDR.
  178775. */
  178776. #ifdef PNG_READ_SUPPORTED
  178777. void PNGAPI
  178778. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  178779. {
  178780. if(png_ptr == NULL) return;
  178781. png_debug(1, "in png_set_sig_bytes\n");
  178782. if (num_bytes > 8)
  178783. png_error(png_ptr, "Too many bytes for PNG signature.");
  178784. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  178785. }
  178786. /* Checks whether the supplied bytes match the PNG signature. We allow
  178787. * checking less than the full 8-byte signature so that those apps that
  178788. * already read the first few bytes of a file to determine the file type
  178789. * can simply check the remaining bytes for extra assurance. Returns
  178790. * an integer less than, equal to, or greater than zero if sig is found,
  178791. * respectively, to be less than, to match, or be greater than the correct
  178792. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  178793. */
  178794. int PNGAPI
  178795. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  178796. {
  178797. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  178798. if (num_to_check > 8)
  178799. num_to_check = 8;
  178800. else if (num_to_check < 1)
  178801. return (-1);
  178802. if (start > 7)
  178803. return (-1);
  178804. if (start + num_to_check > 8)
  178805. num_to_check = 8 - start;
  178806. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  178807. }
  178808. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  178809. /* (Obsolete) function to check signature bytes. It does not allow one
  178810. * to check a partial signature. This function might be removed in the
  178811. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  178812. */
  178813. int PNGAPI
  178814. png_check_sig(png_bytep sig, int num)
  178815. {
  178816. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  178817. }
  178818. #endif
  178819. #endif /* PNG_READ_SUPPORTED */
  178820. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  178821. /* Function to allocate memory for zlib and clear it to 0. */
  178822. #ifdef PNG_1_0_X
  178823. voidpf PNGAPI
  178824. #else
  178825. voidpf /* private */
  178826. #endif
  178827. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  178828. {
  178829. png_voidp ptr;
  178830. png_structp p=(png_structp)png_ptr;
  178831. png_uint_32 save_flags=p->flags;
  178832. png_uint_32 num_bytes;
  178833. if(png_ptr == NULL) return (NULL);
  178834. if (items > PNG_UINT_32_MAX/size)
  178835. {
  178836. png_warning (p, "Potential overflow in png_zalloc()");
  178837. return (NULL);
  178838. }
  178839. num_bytes = (png_uint_32)items * size;
  178840. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  178841. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  178842. p->flags=save_flags;
  178843. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  178844. if (ptr == NULL)
  178845. return ((voidpf)ptr);
  178846. if (num_bytes > (png_uint_32)0x8000L)
  178847. {
  178848. png_memset(ptr, 0, (png_size_t)0x8000L);
  178849. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  178850. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  178851. }
  178852. else
  178853. {
  178854. png_memset(ptr, 0, (png_size_t)num_bytes);
  178855. }
  178856. #endif
  178857. return ((voidpf)ptr);
  178858. }
  178859. /* function to free memory for zlib */
  178860. #ifdef PNG_1_0_X
  178861. void PNGAPI
  178862. #else
  178863. void /* private */
  178864. #endif
  178865. png_zfree(voidpf png_ptr, voidpf ptr)
  178866. {
  178867. png_free((png_structp)png_ptr, (png_voidp)ptr);
  178868. }
  178869. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  178870. * in case CRC is > 32 bits to leave the top bits 0.
  178871. */
  178872. void /* PRIVATE */
  178873. png_reset_crc(png_structp png_ptr)
  178874. {
  178875. png_ptr->crc = crc32(0, Z_NULL, 0);
  178876. }
  178877. /* Calculate the CRC over a section of data. We can only pass as
  178878. * much data to this routine as the largest single buffer size. We
  178879. * also check that this data will actually be used before going to the
  178880. * trouble of calculating it.
  178881. */
  178882. void /* PRIVATE */
  178883. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  178884. {
  178885. int need_crc = 1;
  178886. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  178887. {
  178888. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  178889. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  178890. need_crc = 0;
  178891. }
  178892. else /* critical */
  178893. {
  178894. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  178895. need_crc = 0;
  178896. }
  178897. if (need_crc)
  178898. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  178899. }
  178900. /* Allocate the memory for an info_struct for the application. We don't
  178901. * really need the png_ptr, but it could potentially be useful in the
  178902. * future. This should be used in favour of malloc(png_sizeof(png_info))
  178903. * and png_info_init() so that applications that want to use a shared
  178904. * libpng don't have to be recompiled if png_info changes size.
  178905. */
  178906. png_infop PNGAPI
  178907. png_create_info_struct(png_structp png_ptr)
  178908. {
  178909. png_infop info_ptr;
  178910. png_debug(1, "in png_create_info_struct\n");
  178911. if(png_ptr == NULL) return (NULL);
  178912. #ifdef PNG_USER_MEM_SUPPORTED
  178913. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  178914. png_ptr->malloc_fn, png_ptr->mem_ptr);
  178915. #else
  178916. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  178917. #endif
  178918. if (info_ptr != NULL)
  178919. png_info_init_3(&info_ptr, png_sizeof(png_info));
  178920. return (info_ptr);
  178921. }
  178922. /* This function frees the memory associated with a single info struct.
  178923. * Normally, one would use either png_destroy_read_struct() or
  178924. * png_destroy_write_struct() to free an info struct, but this may be
  178925. * useful for some applications.
  178926. */
  178927. void PNGAPI
  178928. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  178929. {
  178930. png_infop info_ptr = NULL;
  178931. if(png_ptr == NULL) return;
  178932. png_debug(1, "in png_destroy_info_struct\n");
  178933. if (info_ptr_ptr != NULL)
  178934. info_ptr = *info_ptr_ptr;
  178935. if (info_ptr != NULL)
  178936. {
  178937. png_info_destroy(png_ptr, info_ptr);
  178938. #ifdef PNG_USER_MEM_SUPPORTED
  178939. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  178940. png_ptr->mem_ptr);
  178941. #else
  178942. png_destroy_struct((png_voidp)info_ptr);
  178943. #endif
  178944. *info_ptr_ptr = NULL;
  178945. }
  178946. }
  178947. /* Initialize the info structure. This is now an internal function (0.89)
  178948. * and applications using it are urged to use png_create_info_struct()
  178949. * instead.
  178950. */
  178951. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  178952. #undef png_info_init
  178953. void PNGAPI
  178954. png_info_init(png_infop info_ptr)
  178955. {
  178956. /* We only come here via pre-1.0.12-compiled applications */
  178957. png_info_init_3(&info_ptr, 0);
  178958. }
  178959. #endif
  178960. void PNGAPI
  178961. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  178962. {
  178963. png_infop info_ptr = *ptr_ptr;
  178964. if(info_ptr == NULL) return;
  178965. png_debug(1, "in png_info_init_3\n");
  178966. if(png_sizeof(png_info) > png_info_struct_size)
  178967. {
  178968. png_destroy_struct(info_ptr);
  178969. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  178970. *ptr_ptr = info_ptr;
  178971. }
  178972. /* set everything to 0 */
  178973. png_memset(info_ptr, 0, png_sizeof (png_info));
  178974. }
  178975. #ifdef PNG_FREE_ME_SUPPORTED
  178976. void PNGAPI
  178977. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  178978. int freer, png_uint_32 mask)
  178979. {
  178980. png_debug(1, "in png_data_freer\n");
  178981. if (png_ptr == NULL || info_ptr == NULL)
  178982. return;
  178983. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  178984. info_ptr->free_me |= mask;
  178985. else if(freer == PNG_USER_WILL_FREE_DATA)
  178986. info_ptr->free_me &= ~mask;
  178987. else
  178988. png_warning(png_ptr,
  178989. "Unknown freer parameter in png_data_freer.");
  178990. }
  178991. #endif
  178992. void PNGAPI
  178993. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  178994. int num)
  178995. {
  178996. png_debug(1, "in png_free_data\n");
  178997. if (png_ptr == NULL || info_ptr == NULL)
  178998. return;
  178999. #if defined(PNG_TEXT_SUPPORTED)
  179000. /* free text item num or (if num == -1) all text items */
  179001. #ifdef PNG_FREE_ME_SUPPORTED
  179002. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  179003. #else
  179004. if (mask & PNG_FREE_TEXT)
  179005. #endif
  179006. {
  179007. if (num != -1)
  179008. {
  179009. if (info_ptr->text && info_ptr->text[num].key)
  179010. {
  179011. png_free(png_ptr, info_ptr->text[num].key);
  179012. info_ptr->text[num].key = NULL;
  179013. }
  179014. }
  179015. else
  179016. {
  179017. int i;
  179018. for (i = 0; i < info_ptr->num_text; i++)
  179019. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  179020. png_free(png_ptr, info_ptr->text);
  179021. info_ptr->text = NULL;
  179022. info_ptr->num_text=0;
  179023. }
  179024. }
  179025. #endif
  179026. #if defined(PNG_tRNS_SUPPORTED)
  179027. /* free any tRNS entry */
  179028. #ifdef PNG_FREE_ME_SUPPORTED
  179029. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  179030. #else
  179031. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  179032. #endif
  179033. {
  179034. png_free(png_ptr, info_ptr->trans);
  179035. info_ptr->valid &= ~PNG_INFO_tRNS;
  179036. #ifndef PNG_FREE_ME_SUPPORTED
  179037. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  179038. #endif
  179039. info_ptr->trans = NULL;
  179040. }
  179041. #endif
  179042. #if defined(PNG_sCAL_SUPPORTED)
  179043. /* free any sCAL entry */
  179044. #ifdef PNG_FREE_ME_SUPPORTED
  179045. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  179046. #else
  179047. if (mask & PNG_FREE_SCAL)
  179048. #endif
  179049. {
  179050. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  179051. png_free(png_ptr, info_ptr->scal_s_width);
  179052. png_free(png_ptr, info_ptr->scal_s_height);
  179053. info_ptr->scal_s_width = NULL;
  179054. info_ptr->scal_s_height = NULL;
  179055. #endif
  179056. info_ptr->valid &= ~PNG_INFO_sCAL;
  179057. }
  179058. #endif
  179059. #if defined(PNG_pCAL_SUPPORTED)
  179060. /* free any pCAL entry */
  179061. #ifdef PNG_FREE_ME_SUPPORTED
  179062. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  179063. #else
  179064. if (mask & PNG_FREE_PCAL)
  179065. #endif
  179066. {
  179067. png_free(png_ptr, info_ptr->pcal_purpose);
  179068. png_free(png_ptr, info_ptr->pcal_units);
  179069. info_ptr->pcal_purpose = NULL;
  179070. info_ptr->pcal_units = NULL;
  179071. if (info_ptr->pcal_params != NULL)
  179072. {
  179073. int i;
  179074. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  179075. {
  179076. png_free(png_ptr, info_ptr->pcal_params[i]);
  179077. info_ptr->pcal_params[i]=NULL;
  179078. }
  179079. png_free(png_ptr, info_ptr->pcal_params);
  179080. info_ptr->pcal_params = NULL;
  179081. }
  179082. info_ptr->valid &= ~PNG_INFO_pCAL;
  179083. }
  179084. #endif
  179085. #if defined(PNG_iCCP_SUPPORTED)
  179086. /* free any iCCP entry */
  179087. #ifdef PNG_FREE_ME_SUPPORTED
  179088. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  179089. #else
  179090. if (mask & PNG_FREE_ICCP)
  179091. #endif
  179092. {
  179093. png_free(png_ptr, info_ptr->iccp_name);
  179094. png_free(png_ptr, info_ptr->iccp_profile);
  179095. info_ptr->iccp_name = NULL;
  179096. info_ptr->iccp_profile = NULL;
  179097. info_ptr->valid &= ~PNG_INFO_iCCP;
  179098. }
  179099. #endif
  179100. #if defined(PNG_sPLT_SUPPORTED)
  179101. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  179102. #ifdef PNG_FREE_ME_SUPPORTED
  179103. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  179104. #else
  179105. if (mask & PNG_FREE_SPLT)
  179106. #endif
  179107. {
  179108. if (num != -1)
  179109. {
  179110. if(info_ptr->splt_palettes)
  179111. {
  179112. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  179113. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  179114. info_ptr->splt_palettes[num].name = NULL;
  179115. info_ptr->splt_palettes[num].entries = NULL;
  179116. }
  179117. }
  179118. else
  179119. {
  179120. if(info_ptr->splt_palettes_num)
  179121. {
  179122. int i;
  179123. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  179124. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  179125. png_free(png_ptr, info_ptr->splt_palettes);
  179126. info_ptr->splt_palettes = NULL;
  179127. info_ptr->splt_palettes_num = 0;
  179128. }
  179129. info_ptr->valid &= ~PNG_INFO_sPLT;
  179130. }
  179131. }
  179132. #endif
  179133. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179134. if(png_ptr->unknown_chunk.data)
  179135. {
  179136. png_free(png_ptr, png_ptr->unknown_chunk.data);
  179137. png_ptr->unknown_chunk.data = NULL;
  179138. }
  179139. #ifdef PNG_FREE_ME_SUPPORTED
  179140. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  179141. #else
  179142. if (mask & PNG_FREE_UNKN)
  179143. #endif
  179144. {
  179145. if (num != -1)
  179146. {
  179147. if(info_ptr->unknown_chunks)
  179148. {
  179149. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  179150. info_ptr->unknown_chunks[num].data = NULL;
  179151. }
  179152. }
  179153. else
  179154. {
  179155. int i;
  179156. if(info_ptr->unknown_chunks_num)
  179157. {
  179158. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  179159. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  179160. png_free(png_ptr, info_ptr->unknown_chunks);
  179161. info_ptr->unknown_chunks = NULL;
  179162. info_ptr->unknown_chunks_num = 0;
  179163. }
  179164. }
  179165. }
  179166. #endif
  179167. #if defined(PNG_hIST_SUPPORTED)
  179168. /* free any hIST entry */
  179169. #ifdef PNG_FREE_ME_SUPPORTED
  179170. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  179171. #else
  179172. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  179173. #endif
  179174. {
  179175. png_free(png_ptr, info_ptr->hist);
  179176. info_ptr->hist = NULL;
  179177. info_ptr->valid &= ~PNG_INFO_hIST;
  179178. #ifndef PNG_FREE_ME_SUPPORTED
  179179. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  179180. #endif
  179181. }
  179182. #endif
  179183. /* free any PLTE entry that was internally allocated */
  179184. #ifdef PNG_FREE_ME_SUPPORTED
  179185. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  179186. #else
  179187. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  179188. #endif
  179189. {
  179190. png_zfree(png_ptr, info_ptr->palette);
  179191. info_ptr->palette = NULL;
  179192. info_ptr->valid &= ~PNG_INFO_PLTE;
  179193. #ifndef PNG_FREE_ME_SUPPORTED
  179194. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  179195. #endif
  179196. info_ptr->num_palette = 0;
  179197. }
  179198. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179199. /* free any image bits attached to the info structure */
  179200. #ifdef PNG_FREE_ME_SUPPORTED
  179201. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  179202. #else
  179203. if (mask & PNG_FREE_ROWS)
  179204. #endif
  179205. {
  179206. if(info_ptr->row_pointers)
  179207. {
  179208. int row;
  179209. for (row = 0; row < (int)info_ptr->height; row++)
  179210. {
  179211. png_free(png_ptr, info_ptr->row_pointers[row]);
  179212. info_ptr->row_pointers[row]=NULL;
  179213. }
  179214. png_free(png_ptr, info_ptr->row_pointers);
  179215. info_ptr->row_pointers=NULL;
  179216. }
  179217. info_ptr->valid &= ~PNG_INFO_IDAT;
  179218. }
  179219. #endif
  179220. #ifdef PNG_FREE_ME_SUPPORTED
  179221. if(num == -1)
  179222. info_ptr->free_me &= ~mask;
  179223. else
  179224. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  179225. #endif
  179226. }
  179227. /* This is an internal routine to free any memory that the info struct is
  179228. * pointing to before re-using it or freeing the struct itself. Recall
  179229. * that png_free() checks for NULL pointers for us.
  179230. */
  179231. void /* PRIVATE */
  179232. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  179233. {
  179234. png_debug(1, "in png_info_destroy\n");
  179235. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  179236. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179237. if (png_ptr->num_chunk_list)
  179238. {
  179239. png_free(png_ptr, png_ptr->chunk_list);
  179240. png_ptr->chunk_list=NULL;
  179241. png_ptr->num_chunk_list=0;
  179242. }
  179243. #endif
  179244. png_info_init_3(&info_ptr, png_sizeof(png_info));
  179245. }
  179246. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  179247. /* This function returns a pointer to the io_ptr associated with the user
  179248. * functions. The application should free any memory associated with this
  179249. * pointer before png_write_destroy() or png_read_destroy() are called.
  179250. */
  179251. png_voidp PNGAPI
  179252. png_get_io_ptr(png_structp png_ptr)
  179253. {
  179254. if(png_ptr == NULL) return (NULL);
  179255. return (png_ptr->io_ptr);
  179256. }
  179257. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179258. #if !defined(PNG_NO_STDIO)
  179259. /* Initialize the default input/output functions for the PNG file. If you
  179260. * use your own read or write routines, you can call either png_set_read_fn()
  179261. * or png_set_write_fn() instead of png_init_io(). If you have defined
  179262. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  179263. * necessarily available.
  179264. */
  179265. void PNGAPI
  179266. png_init_io(png_structp png_ptr, png_FILE_p fp)
  179267. {
  179268. png_debug(1, "in png_init_io\n");
  179269. if(png_ptr == NULL) return;
  179270. png_ptr->io_ptr = (png_voidp)fp;
  179271. }
  179272. #endif
  179273. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  179274. /* Convert the supplied time into an RFC 1123 string suitable for use in
  179275. * a "Creation Time" or other text-based time string.
  179276. */
  179277. png_charp PNGAPI
  179278. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  179279. {
  179280. static PNG_CONST char short_months[12][4] =
  179281. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  179282. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  179283. if(png_ptr == NULL) return (NULL);
  179284. if (png_ptr->time_buffer == NULL)
  179285. {
  179286. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  179287. png_sizeof(char)));
  179288. }
  179289. #if defined(_WIN32_WCE)
  179290. {
  179291. wchar_t time_buf[29];
  179292. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  179293. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  179294. ptime->year, ptime->hour % 24, ptime->minute % 60,
  179295. ptime->second % 61);
  179296. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  179297. NULL, NULL);
  179298. }
  179299. #else
  179300. #ifdef USE_FAR_KEYWORD
  179301. {
  179302. char near_time_buf[29];
  179303. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  179304. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  179305. ptime->year, ptime->hour % 24, ptime->minute % 60,
  179306. ptime->second % 61);
  179307. png_memcpy(png_ptr->time_buffer, near_time_buf,
  179308. 29*png_sizeof(char));
  179309. }
  179310. #else
  179311. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  179312. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  179313. ptime->year, ptime->hour % 24, ptime->minute % 60,
  179314. ptime->second % 61);
  179315. #endif
  179316. #endif /* _WIN32_WCE */
  179317. return ((png_charp)png_ptr->time_buffer);
  179318. }
  179319. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  179320. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  179321. png_charp PNGAPI
  179322. png_get_copyright(png_structp png_ptr)
  179323. {
  179324. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  179325. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  179326. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  179327. Copyright (c) 1996-1997 Andreas Dilger\n\
  179328. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  179329. }
  179330. /* The following return the library version as a short string in the
  179331. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  179332. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  179333. * is defined in png.h.
  179334. * Note: now there is no difference between png_get_libpng_ver() and
  179335. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  179336. * it is guaranteed that png.c uses the correct version of png.h.
  179337. */
  179338. png_charp PNGAPI
  179339. png_get_libpng_ver(png_structp png_ptr)
  179340. {
  179341. /* Version of *.c files used when building libpng */
  179342. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  179343. return ((png_charp) PNG_LIBPNG_VER_STRING);
  179344. }
  179345. png_charp PNGAPI
  179346. png_get_header_ver(png_structp png_ptr)
  179347. {
  179348. /* Version of *.h files used when building libpng */
  179349. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  179350. return ((png_charp) PNG_LIBPNG_VER_STRING);
  179351. }
  179352. png_charp PNGAPI
  179353. png_get_header_version(png_structp png_ptr)
  179354. {
  179355. /* Returns longer string containing both version and date */
  179356. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  179357. return ((png_charp) PNG_HEADER_VERSION_STRING
  179358. #ifndef PNG_READ_SUPPORTED
  179359. " (NO READ SUPPORT)"
  179360. #endif
  179361. "\n");
  179362. }
  179363. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179364. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  179365. int PNGAPI
  179366. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  179367. {
  179368. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  179369. int i;
  179370. png_bytep p;
  179371. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  179372. return 0;
  179373. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  179374. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  179375. if (!png_memcmp(chunk_name, p, 4))
  179376. return ((int)*(p+4));
  179377. return 0;
  179378. }
  179379. #endif
  179380. /* This function, added to libpng-1.0.6g, is untested. */
  179381. int PNGAPI
  179382. png_reset_zstream(png_structp png_ptr)
  179383. {
  179384. if (png_ptr == NULL) return Z_STREAM_ERROR;
  179385. return (inflateReset(&png_ptr->zstream));
  179386. }
  179387. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  179388. /* This function was added to libpng-1.0.7 */
  179389. png_uint_32 PNGAPI
  179390. png_access_version_number(void)
  179391. {
  179392. /* Version of *.c files used when building libpng */
  179393. return((png_uint_32) PNG_LIBPNG_VER);
  179394. }
  179395. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  179396. #if !defined(PNG_1_0_X)
  179397. /* this function was added to libpng 1.2.0 */
  179398. int PNGAPI
  179399. png_mmx_support(void)
  179400. {
  179401. /* obsolete, to be removed from libpng-1.4.0 */
  179402. return -1;
  179403. }
  179404. #endif /* PNG_1_0_X */
  179405. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  179406. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179407. #ifdef PNG_SIZE_T
  179408. /* Added at libpng version 1.2.6 */
  179409. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  179410. png_size_t PNGAPI
  179411. png_convert_size(size_t size)
  179412. {
  179413. if (size > (png_size_t)-1)
  179414. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  179415. return ((png_size_t)size);
  179416. }
  179417. #endif /* PNG_SIZE_T */
  179418. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  179419. /********* End of inlined file: png.c *********/
  179420. /********* Start of inlined file: pngerror.c *********/
  179421. /* pngerror.c - stub functions for i/o and memory allocation
  179422. *
  179423. * Last changed in libpng 1.2.20 October 4, 2007
  179424. * For conditions of distribution and use, see copyright notice in png.h
  179425. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179426. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179427. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179428. *
  179429. * This file provides a location for all error handling. Users who
  179430. * need special error handling are expected to write replacement functions
  179431. * and use png_set_error_fn() to use those functions. See the instructions
  179432. * at each function.
  179433. */
  179434. #define PNG_INTERNAL
  179435. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179436. static void /* PRIVATE */
  179437. png_default_error PNGARG((png_structp png_ptr,
  179438. png_const_charp error_message));
  179439. #ifndef PNG_NO_WARNINGS
  179440. static void /* PRIVATE */
  179441. png_default_warning PNGARG((png_structp png_ptr,
  179442. png_const_charp warning_message));
  179443. #endif /* PNG_NO_WARNINGS */
  179444. /* This function is called whenever there is a fatal error. This function
  179445. * should not be changed. If there is a need to handle errors differently,
  179446. * you should supply a replacement error function and use png_set_error_fn()
  179447. * to replace the error function at run-time.
  179448. */
  179449. #ifndef PNG_NO_ERROR_TEXT
  179450. void PNGAPI
  179451. png_error(png_structp png_ptr, png_const_charp error_message)
  179452. {
  179453. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179454. char msg[16];
  179455. if (png_ptr != NULL)
  179456. {
  179457. if (png_ptr->flags&
  179458. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  179459. {
  179460. if (*error_message == '#')
  179461. {
  179462. int offset;
  179463. for (offset=1; offset<15; offset++)
  179464. if (*(error_message+offset) == ' ')
  179465. break;
  179466. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  179467. {
  179468. int i;
  179469. for (i=0; i<offset-1; i++)
  179470. msg[i]=error_message[i+1];
  179471. msg[i]='\0';
  179472. error_message=msg;
  179473. }
  179474. else
  179475. error_message+=offset;
  179476. }
  179477. else
  179478. {
  179479. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  179480. {
  179481. msg[0]='0';
  179482. msg[1]='\0';
  179483. error_message=msg;
  179484. }
  179485. }
  179486. }
  179487. }
  179488. #endif
  179489. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  179490. (*(png_ptr->error_fn))(png_ptr, error_message);
  179491. /* If the custom handler doesn't exist, or if it returns,
  179492. use the default handler, which will not return. */
  179493. png_default_error(png_ptr, error_message);
  179494. }
  179495. #else
  179496. void PNGAPI
  179497. png_err(png_structp png_ptr)
  179498. {
  179499. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  179500. (*(png_ptr->error_fn))(png_ptr, '\0');
  179501. /* If the custom handler doesn't exist, or if it returns,
  179502. use the default handler, which will not return. */
  179503. png_default_error(png_ptr, '\0');
  179504. }
  179505. #endif /* PNG_NO_ERROR_TEXT */
  179506. #ifndef PNG_NO_WARNINGS
  179507. /* This function is called whenever there is a non-fatal error. This function
  179508. * should not be changed. If there is a need to handle warnings differently,
  179509. * you should supply a replacement warning function and use
  179510. * png_set_error_fn() to replace the warning function at run-time.
  179511. */
  179512. void PNGAPI
  179513. png_warning(png_structp png_ptr, png_const_charp warning_message)
  179514. {
  179515. int offset = 0;
  179516. if (png_ptr != NULL)
  179517. {
  179518. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179519. if (png_ptr->flags&
  179520. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  179521. #endif
  179522. {
  179523. if (*warning_message == '#')
  179524. {
  179525. for (offset=1; offset<15; offset++)
  179526. if (*(warning_message+offset) == ' ')
  179527. break;
  179528. }
  179529. }
  179530. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  179531. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  179532. }
  179533. else
  179534. png_default_warning(png_ptr, warning_message+offset);
  179535. }
  179536. #endif /* PNG_NO_WARNINGS */
  179537. /* These utilities are used internally to build an error message that relates
  179538. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  179539. * this is used to prefix the message. The message is limited in length
  179540. * to 63 bytes, the name characters are output as hex digits wrapped in []
  179541. * if the character is invalid.
  179542. */
  179543. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  179544. /*static PNG_CONST char png_digit[16] = {
  179545. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  179546. 'A', 'B', 'C', 'D', 'E', 'F'
  179547. };*/
  179548. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  179549. static void /* PRIVATE */
  179550. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  179551. error_message)
  179552. {
  179553. int iout = 0, iin = 0;
  179554. while (iin < 4)
  179555. {
  179556. int c = png_ptr->chunk_name[iin++];
  179557. if (isnonalpha(c))
  179558. {
  179559. buffer[iout++] = '[';
  179560. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  179561. buffer[iout++] = png_digit[c & 0x0f];
  179562. buffer[iout++] = ']';
  179563. }
  179564. else
  179565. {
  179566. buffer[iout++] = (png_byte)c;
  179567. }
  179568. }
  179569. if (error_message == NULL)
  179570. buffer[iout] = 0;
  179571. else
  179572. {
  179573. buffer[iout++] = ':';
  179574. buffer[iout++] = ' ';
  179575. png_strncpy(buffer+iout, error_message, 63);
  179576. buffer[iout+63] = 0;
  179577. }
  179578. }
  179579. #ifdef PNG_READ_SUPPORTED
  179580. void PNGAPI
  179581. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  179582. {
  179583. char msg[18+64];
  179584. if (png_ptr == NULL)
  179585. png_error(png_ptr, error_message);
  179586. else
  179587. {
  179588. png_format_buffer(png_ptr, msg, error_message);
  179589. png_error(png_ptr, msg);
  179590. }
  179591. }
  179592. #endif /* PNG_READ_SUPPORTED */
  179593. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  179594. #ifndef PNG_NO_WARNINGS
  179595. void PNGAPI
  179596. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  179597. {
  179598. char msg[18+64];
  179599. if (png_ptr == NULL)
  179600. png_warning(png_ptr, warning_message);
  179601. else
  179602. {
  179603. png_format_buffer(png_ptr, msg, warning_message);
  179604. png_warning(png_ptr, msg);
  179605. }
  179606. }
  179607. #endif /* PNG_NO_WARNINGS */
  179608. /* This is the default error handling function. Note that replacements for
  179609. * this function MUST NOT RETURN, or the program will likely crash. This
  179610. * function is used by default, or if the program supplies NULL for the
  179611. * error function pointer in png_set_error_fn().
  179612. */
  179613. static void /* PRIVATE */
  179614. png_default_error(png_structp png_ptr, png_const_charp error_message)
  179615. {
  179616. #ifndef PNG_NO_CONSOLE_IO
  179617. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179618. if (*error_message == '#')
  179619. {
  179620. int offset;
  179621. char error_number[16];
  179622. for (offset=0; offset<15; offset++)
  179623. {
  179624. error_number[offset] = *(error_message+offset+1);
  179625. if (*(error_message+offset) == ' ')
  179626. break;
  179627. }
  179628. if((offset > 1) && (offset < 15))
  179629. {
  179630. error_number[offset-1]='\0';
  179631. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  179632. error_message+offset);
  179633. }
  179634. else
  179635. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  179636. }
  179637. else
  179638. #endif
  179639. fprintf(stderr, "libpng error: %s\n", error_message);
  179640. #endif
  179641. #ifdef PNG_SETJMP_SUPPORTED
  179642. if (png_ptr)
  179643. {
  179644. # ifdef USE_FAR_KEYWORD
  179645. {
  179646. jmp_buf jmpbuf;
  179647. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  179648. longjmp(jmpbuf, 1);
  179649. }
  179650. # else
  179651. longjmp(png_ptr->jmpbuf, 1);
  179652. # endif
  179653. }
  179654. #else
  179655. PNG_ABORT();
  179656. #endif
  179657. #ifdef PNG_NO_CONSOLE_IO
  179658. error_message = error_message; /* make compiler happy */
  179659. #endif
  179660. }
  179661. #ifndef PNG_NO_WARNINGS
  179662. /* This function is called when there is a warning, but the library thinks
  179663. * it can continue anyway. Replacement functions don't have to do anything
  179664. * here if you don't want them to. In the default configuration, png_ptr is
  179665. * not used, but it is passed in case it may be useful.
  179666. */
  179667. static void /* PRIVATE */
  179668. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  179669. {
  179670. #ifndef PNG_NO_CONSOLE_IO
  179671. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179672. if (*warning_message == '#')
  179673. {
  179674. int offset;
  179675. char warning_number[16];
  179676. for (offset=0; offset<15; offset++)
  179677. {
  179678. warning_number[offset]=*(warning_message+offset+1);
  179679. if (*(warning_message+offset) == ' ')
  179680. break;
  179681. }
  179682. if((offset > 1) && (offset < 15))
  179683. {
  179684. warning_number[offset-1]='\0';
  179685. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  179686. warning_message+offset);
  179687. }
  179688. else
  179689. fprintf(stderr, "libpng warning: %s\n", warning_message);
  179690. }
  179691. else
  179692. # endif
  179693. fprintf(stderr, "libpng warning: %s\n", warning_message);
  179694. #else
  179695. warning_message = warning_message; /* make compiler happy */
  179696. #endif
  179697. png_ptr = png_ptr; /* make compiler happy */
  179698. }
  179699. #endif /* PNG_NO_WARNINGS */
  179700. /* This function is called when the application wants to use another method
  179701. * of handling errors and warnings. Note that the error function MUST NOT
  179702. * return to the calling routine or serious problems will occur. The return
  179703. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  179704. */
  179705. void PNGAPI
  179706. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  179707. png_error_ptr error_fn, png_error_ptr warning_fn)
  179708. {
  179709. if (png_ptr == NULL)
  179710. return;
  179711. png_ptr->error_ptr = error_ptr;
  179712. png_ptr->error_fn = error_fn;
  179713. png_ptr->warning_fn = warning_fn;
  179714. }
  179715. /* This function returns a pointer to the error_ptr associated with the user
  179716. * functions. The application should free any memory associated with this
  179717. * pointer before png_write_destroy and png_read_destroy are called.
  179718. */
  179719. png_voidp PNGAPI
  179720. png_get_error_ptr(png_structp png_ptr)
  179721. {
  179722. if (png_ptr == NULL)
  179723. return NULL;
  179724. return ((png_voidp)png_ptr->error_ptr);
  179725. }
  179726. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179727. void PNGAPI
  179728. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  179729. {
  179730. if(png_ptr != NULL)
  179731. {
  179732. png_ptr->flags &=
  179733. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  179734. }
  179735. }
  179736. #endif
  179737. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  179738. /********* End of inlined file: pngerror.c *********/
  179739. /********* Start of inlined file: pngget.c *********/
  179740. /* pngget.c - retrieval of values from info struct
  179741. *
  179742. * Last changed in libpng 1.2.15 January 5, 2007
  179743. * For conditions of distribution and use, see copyright notice in png.h
  179744. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179745. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179746. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179747. */
  179748. #define PNG_INTERNAL
  179749. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179750. png_uint_32 PNGAPI
  179751. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  179752. {
  179753. if (png_ptr != NULL && info_ptr != NULL)
  179754. return(info_ptr->valid & flag);
  179755. else
  179756. return(0);
  179757. }
  179758. png_uint_32 PNGAPI
  179759. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  179760. {
  179761. if (png_ptr != NULL && info_ptr != NULL)
  179762. return(info_ptr->rowbytes);
  179763. else
  179764. return(0);
  179765. }
  179766. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179767. png_bytepp PNGAPI
  179768. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  179769. {
  179770. if (png_ptr != NULL && info_ptr != NULL)
  179771. return(info_ptr->row_pointers);
  179772. else
  179773. return(0);
  179774. }
  179775. #endif
  179776. #ifdef PNG_EASY_ACCESS_SUPPORTED
  179777. /* easy access to info, added in libpng-0.99 */
  179778. png_uint_32 PNGAPI
  179779. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  179780. {
  179781. if (png_ptr != NULL && info_ptr != NULL)
  179782. {
  179783. return info_ptr->width;
  179784. }
  179785. return (0);
  179786. }
  179787. png_uint_32 PNGAPI
  179788. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  179789. {
  179790. if (png_ptr != NULL && info_ptr != NULL)
  179791. {
  179792. return info_ptr->height;
  179793. }
  179794. return (0);
  179795. }
  179796. png_byte PNGAPI
  179797. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  179798. {
  179799. if (png_ptr != NULL && info_ptr != NULL)
  179800. {
  179801. return info_ptr->bit_depth;
  179802. }
  179803. return (0);
  179804. }
  179805. png_byte PNGAPI
  179806. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  179807. {
  179808. if (png_ptr != NULL && info_ptr != NULL)
  179809. {
  179810. return info_ptr->color_type;
  179811. }
  179812. return (0);
  179813. }
  179814. png_byte PNGAPI
  179815. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  179816. {
  179817. if (png_ptr != NULL && info_ptr != NULL)
  179818. {
  179819. return info_ptr->filter_type;
  179820. }
  179821. return (0);
  179822. }
  179823. png_byte PNGAPI
  179824. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  179825. {
  179826. if (png_ptr != NULL && info_ptr != NULL)
  179827. {
  179828. return info_ptr->interlace_type;
  179829. }
  179830. return (0);
  179831. }
  179832. png_byte PNGAPI
  179833. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  179834. {
  179835. if (png_ptr != NULL && info_ptr != NULL)
  179836. {
  179837. return info_ptr->compression_type;
  179838. }
  179839. return (0);
  179840. }
  179841. png_uint_32 PNGAPI
  179842. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  179843. {
  179844. if (png_ptr != NULL && info_ptr != NULL)
  179845. #if defined(PNG_pHYs_SUPPORTED)
  179846. if (info_ptr->valid & PNG_INFO_pHYs)
  179847. {
  179848. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  179849. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  179850. return (0);
  179851. else return (info_ptr->x_pixels_per_unit);
  179852. }
  179853. #else
  179854. return (0);
  179855. #endif
  179856. return (0);
  179857. }
  179858. png_uint_32 PNGAPI
  179859. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  179860. {
  179861. if (png_ptr != NULL && info_ptr != NULL)
  179862. #if defined(PNG_pHYs_SUPPORTED)
  179863. if (info_ptr->valid & PNG_INFO_pHYs)
  179864. {
  179865. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  179866. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  179867. return (0);
  179868. else return (info_ptr->y_pixels_per_unit);
  179869. }
  179870. #else
  179871. return (0);
  179872. #endif
  179873. return (0);
  179874. }
  179875. png_uint_32 PNGAPI
  179876. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  179877. {
  179878. if (png_ptr != NULL && info_ptr != NULL)
  179879. #if defined(PNG_pHYs_SUPPORTED)
  179880. if (info_ptr->valid & PNG_INFO_pHYs)
  179881. {
  179882. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  179883. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  179884. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  179885. return (0);
  179886. else return (info_ptr->x_pixels_per_unit);
  179887. }
  179888. #else
  179889. return (0);
  179890. #endif
  179891. return (0);
  179892. }
  179893. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179894. float PNGAPI
  179895. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  179896. {
  179897. if (png_ptr != NULL && info_ptr != NULL)
  179898. #if defined(PNG_pHYs_SUPPORTED)
  179899. if (info_ptr->valid & PNG_INFO_pHYs)
  179900. {
  179901. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  179902. if (info_ptr->x_pixels_per_unit == 0)
  179903. return ((float)0.0);
  179904. else
  179905. return ((float)((float)info_ptr->y_pixels_per_unit
  179906. /(float)info_ptr->x_pixels_per_unit));
  179907. }
  179908. #else
  179909. return (0.0);
  179910. #endif
  179911. return ((float)0.0);
  179912. }
  179913. #endif
  179914. png_int_32 PNGAPI
  179915. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  179916. {
  179917. if (png_ptr != NULL && info_ptr != NULL)
  179918. #if defined(PNG_oFFs_SUPPORTED)
  179919. if (info_ptr->valid & PNG_INFO_oFFs)
  179920. {
  179921. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  179922. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  179923. return (0);
  179924. else return (info_ptr->x_offset);
  179925. }
  179926. #else
  179927. return (0);
  179928. #endif
  179929. return (0);
  179930. }
  179931. png_int_32 PNGAPI
  179932. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  179933. {
  179934. if (png_ptr != NULL && info_ptr != NULL)
  179935. #if defined(PNG_oFFs_SUPPORTED)
  179936. if (info_ptr->valid & PNG_INFO_oFFs)
  179937. {
  179938. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  179939. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  179940. return (0);
  179941. else return (info_ptr->y_offset);
  179942. }
  179943. #else
  179944. return (0);
  179945. #endif
  179946. return (0);
  179947. }
  179948. png_int_32 PNGAPI
  179949. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  179950. {
  179951. if (png_ptr != NULL && info_ptr != NULL)
  179952. #if defined(PNG_oFFs_SUPPORTED)
  179953. if (info_ptr->valid & PNG_INFO_oFFs)
  179954. {
  179955. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  179956. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  179957. return (0);
  179958. else return (info_ptr->x_offset);
  179959. }
  179960. #else
  179961. return (0);
  179962. #endif
  179963. return (0);
  179964. }
  179965. png_int_32 PNGAPI
  179966. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  179967. {
  179968. if (png_ptr != NULL && info_ptr != NULL)
  179969. #if defined(PNG_oFFs_SUPPORTED)
  179970. if (info_ptr->valid & PNG_INFO_oFFs)
  179971. {
  179972. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  179973. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  179974. return (0);
  179975. else return (info_ptr->y_offset);
  179976. }
  179977. #else
  179978. return (0);
  179979. #endif
  179980. return (0);
  179981. }
  179982. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  179983. png_uint_32 PNGAPI
  179984. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  179985. {
  179986. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  179987. *.0254 +.5));
  179988. }
  179989. png_uint_32 PNGAPI
  179990. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  179991. {
  179992. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  179993. *.0254 +.5));
  179994. }
  179995. png_uint_32 PNGAPI
  179996. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  179997. {
  179998. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  179999. *.0254 +.5));
  180000. }
  180001. float PNGAPI
  180002. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  180003. {
  180004. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  180005. *.00003937);
  180006. }
  180007. float PNGAPI
  180008. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  180009. {
  180010. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  180011. *.00003937);
  180012. }
  180013. #if defined(PNG_pHYs_SUPPORTED)
  180014. png_uint_32 PNGAPI
  180015. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  180016. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  180017. {
  180018. png_uint_32 retval = 0;
  180019. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  180020. {
  180021. png_debug1(1, "in %s retrieval function\n", "pHYs");
  180022. if (res_x != NULL)
  180023. {
  180024. *res_x = info_ptr->x_pixels_per_unit;
  180025. retval |= PNG_INFO_pHYs;
  180026. }
  180027. if (res_y != NULL)
  180028. {
  180029. *res_y = info_ptr->y_pixels_per_unit;
  180030. retval |= PNG_INFO_pHYs;
  180031. }
  180032. if (unit_type != NULL)
  180033. {
  180034. *unit_type = (int)info_ptr->phys_unit_type;
  180035. retval |= PNG_INFO_pHYs;
  180036. if(*unit_type == 1)
  180037. {
  180038. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  180039. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  180040. }
  180041. }
  180042. }
  180043. return (retval);
  180044. }
  180045. #endif /* PNG_pHYs_SUPPORTED */
  180046. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  180047. /* png_get_channels really belongs in here, too, but it's been around longer */
  180048. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  180049. png_byte PNGAPI
  180050. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  180051. {
  180052. if (png_ptr != NULL && info_ptr != NULL)
  180053. return(info_ptr->channels);
  180054. else
  180055. return (0);
  180056. }
  180057. png_bytep PNGAPI
  180058. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  180059. {
  180060. if (png_ptr != NULL && info_ptr != NULL)
  180061. return(info_ptr->signature);
  180062. else
  180063. return (NULL);
  180064. }
  180065. #if defined(PNG_bKGD_SUPPORTED)
  180066. png_uint_32 PNGAPI
  180067. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  180068. png_color_16p *background)
  180069. {
  180070. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  180071. && background != NULL)
  180072. {
  180073. png_debug1(1, "in %s retrieval function\n", "bKGD");
  180074. *background = &(info_ptr->background);
  180075. return (PNG_INFO_bKGD);
  180076. }
  180077. return (0);
  180078. }
  180079. #endif
  180080. #if defined(PNG_cHRM_SUPPORTED)
  180081. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180082. png_uint_32 PNGAPI
  180083. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  180084. double *white_x, double *white_y, double *red_x, double *red_y,
  180085. double *green_x, double *green_y, double *blue_x, double *blue_y)
  180086. {
  180087. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  180088. {
  180089. png_debug1(1, "in %s retrieval function\n", "cHRM");
  180090. if (white_x != NULL)
  180091. *white_x = (double)info_ptr->x_white;
  180092. if (white_y != NULL)
  180093. *white_y = (double)info_ptr->y_white;
  180094. if (red_x != NULL)
  180095. *red_x = (double)info_ptr->x_red;
  180096. if (red_y != NULL)
  180097. *red_y = (double)info_ptr->y_red;
  180098. if (green_x != NULL)
  180099. *green_x = (double)info_ptr->x_green;
  180100. if (green_y != NULL)
  180101. *green_y = (double)info_ptr->y_green;
  180102. if (blue_x != NULL)
  180103. *blue_x = (double)info_ptr->x_blue;
  180104. if (blue_y != NULL)
  180105. *blue_y = (double)info_ptr->y_blue;
  180106. return (PNG_INFO_cHRM);
  180107. }
  180108. return (0);
  180109. }
  180110. #endif
  180111. #ifdef PNG_FIXED_POINT_SUPPORTED
  180112. png_uint_32 PNGAPI
  180113. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  180114. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  180115. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  180116. png_fixed_point *blue_x, png_fixed_point *blue_y)
  180117. {
  180118. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  180119. {
  180120. png_debug1(1, "in %s retrieval function\n", "cHRM");
  180121. if (white_x != NULL)
  180122. *white_x = info_ptr->int_x_white;
  180123. if (white_y != NULL)
  180124. *white_y = info_ptr->int_y_white;
  180125. if (red_x != NULL)
  180126. *red_x = info_ptr->int_x_red;
  180127. if (red_y != NULL)
  180128. *red_y = info_ptr->int_y_red;
  180129. if (green_x != NULL)
  180130. *green_x = info_ptr->int_x_green;
  180131. if (green_y != NULL)
  180132. *green_y = info_ptr->int_y_green;
  180133. if (blue_x != NULL)
  180134. *blue_x = info_ptr->int_x_blue;
  180135. if (blue_y != NULL)
  180136. *blue_y = info_ptr->int_y_blue;
  180137. return (PNG_INFO_cHRM);
  180138. }
  180139. return (0);
  180140. }
  180141. #endif
  180142. #endif
  180143. #if defined(PNG_gAMA_SUPPORTED)
  180144. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180145. png_uint_32 PNGAPI
  180146. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  180147. {
  180148. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  180149. && file_gamma != NULL)
  180150. {
  180151. png_debug1(1, "in %s retrieval function\n", "gAMA");
  180152. *file_gamma = (double)info_ptr->gamma;
  180153. return (PNG_INFO_gAMA);
  180154. }
  180155. return (0);
  180156. }
  180157. #endif
  180158. #ifdef PNG_FIXED_POINT_SUPPORTED
  180159. png_uint_32 PNGAPI
  180160. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  180161. png_fixed_point *int_file_gamma)
  180162. {
  180163. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  180164. && int_file_gamma != NULL)
  180165. {
  180166. png_debug1(1, "in %s retrieval function\n", "gAMA");
  180167. *int_file_gamma = info_ptr->int_gamma;
  180168. return (PNG_INFO_gAMA);
  180169. }
  180170. return (0);
  180171. }
  180172. #endif
  180173. #endif
  180174. #if defined(PNG_sRGB_SUPPORTED)
  180175. png_uint_32 PNGAPI
  180176. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  180177. {
  180178. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  180179. && file_srgb_intent != NULL)
  180180. {
  180181. png_debug1(1, "in %s retrieval function\n", "sRGB");
  180182. *file_srgb_intent = (int)info_ptr->srgb_intent;
  180183. return (PNG_INFO_sRGB);
  180184. }
  180185. return (0);
  180186. }
  180187. #endif
  180188. #if defined(PNG_iCCP_SUPPORTED)
  180189. png_uint_32 PNGAPI
  180190. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  180191. png_charpp name, int *compression_type,
  180192. png_charpp profile, png_uint_32 *proflen)
  180193. {
  180194. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  180195. && name != NULL && profile != NULL && proflen != NULL)
  180196. {
  180197. png_debug1(1, "in %s retrieval function\n", "iCCP");
  180198. *name = info_ptr->iccp_name;
  180199. *profile = info_ptr->iccp_profile;
  180200. /* compression_type is a dummy so the API won't have to change
  180201. if we introduce multiple compression types later. */
  180202. *proflen = (int)info_ptr->iccp_proflen;
  180203. *compression_type = (int)info_ptr->iccp_compression;
  180204. return (PNG_INFO_iCCP);
  180205. }
  180206. return (0);
  180207. }
  180208. #endif
  180209. #if defined(PNG_sPLT_SUPPORTED)
  180210. png_uint_32 PNGAPI
  180211. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  180212. png_sPLT_tpp spalettes)
  180213. {
  180214. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  180215. {
  180216. *spalettes = info_ptr->splt_palettes;
  180217. return ((png_uint_32)info_ptr->splt_palettes_num);
  180218. }
  180219. return (0);
  180220. }
  180221. #endif
  180222. #if defined(PNG_hIST_SUPPORTED)
  180223. png_uint_32 PNGAPI
  180224. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  180225. {
  180226. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  180227. && hist != NULL)
  180228. {
  180229. png_debug1(1, "in %s retrieval function\n", "hIST");
  180230. *hist = info_ptr->hist;
  180231. return (PNG_INFO_hIST);
  180232. }
  180233. return (0);
  180234. }
  180235. #endif
  180236. png_uint_32 PNGAPI
  180237. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  180238. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  180239. int *color_type, int *interlace_type, int *compression_type,
  180240. int *filter_type)
  180241. {
  180242. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  180243. bit_depth != NULL && color_type != NULL)
  180244. {
  180245. png_debug1(1, "in %s retrieval function\n", "IHDR");
  180246. *width = info_ptr->width;
  180247. *height = info_ptr->height;
  180248. *bit_depth = info_ptr->bit_depth;
  180249. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  180250. png_error(png_ptr, "Invalid bit depth");
  180251. *color_type = info_ptr->color_type;
  180252. if (info_ptr->color_type > 6)
  180253. png_error(png_ptr, "Invalid color type");
  180254. if (compression_type != NULL)
  180255. *compression_type = info_ptr->compression_type;
  180256. if (filter_type != NULL)
  180257. *filter_type = info_ptr->filter_type;
  180258. if (interlace_type != NULL)
  180259. *interlace_type = info_ptr->interlace_type;
  180260. /* check for potential overflow of rowbytes */
  180261. if (*width == 0 || *width > PNG_UINT_31_MAX)
  180262. png_error(png_ptr, "Invalid image width");
  180263. if (*height == 0 || *height > PNG_UINT_31_MAX)
  180264. png_error(png_ptr, "Invalid image height");
  180265. if (info_ptr->width > (PNG_UINT_32_MAX
  180266. >> 3) /* 8-byte RGBA pixels */
  180267. - 64 /* bigrowbuf hack */
  180268. - 1 /* filter byte */
  180269. - 7*8 /* rounding of width to multiple of 8 pixels */
  180270. - 8) /* extra max_pixel_depth pad */
  180271. {
  180272. png_warning(png_ptr,
  180273. "Width too large for libpng to process image data.");
  180274. }
  180275. return (1);
  180276. }
  180277. return (0);
  180278. }
  180279. #if defined(PNG_oFFs_SUPPORTED)
  180280. png_uint_32 PNGAPI
  180281. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  180282. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  180283. {
  180284. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  180285. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  180286. {
  180287. png_debug1(1, "in %s retrieval function\n", "oFFs");
  180288. *offset_x = info_ptr->x_offset;
  180289. *offset_y = info_ptr->y_offset;
  180290. *unit_type = (int)info_ptr->offset_unit_type;
  180291. return (PNG_INFO_oFFs);
  180292. }
  180293. return (0);
  180294. }
  180295. #endif
  180296. #if defined(PNG_pCAL_SUPPORTED)
  180297. png_uint_32 PNGAPI
  180298. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  180299. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  180300. png_charp *units, png_charpp *params)
  180301. {
  180302. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  180303. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  180304. nparams != NULL && units != NULL && params != NULL)
  180305. {
  180306. png_debug1(1, "in %s retrieval function\n", "pCAL");
  180307. *purpose = info_ptr->pcal_purpose;
  180308. *X0 = info_ptr->pcal_X0;
  180309. *X1 = info_ptr->pcal_X1;
  180310. *type = (int)info_ptr->pcal_type;
  180311. *nparams = (int)info_ptr->pcal_nparams;
  180312. *units = info_ptr->pcal_units;
  180313. *params = info_ptr->pcal_params;
  180314. return (PNG_INFO_pCAL);
  180315. }
  180316. return (0);
  180317. }
  180318. #endif
  180319. #if defined(PNG_sCAL_SUPPORTED)
  180320. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180321. png_uint_32 PNGAPI
  180322. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  180323. int *unit, double *width, double *height)
  180324. {
  180325. if (png_ptr != NULL && info_ptr != NULL &&
  180326. (info_ptr->valid & PNG_INFO_sCAL))
  180327. {
  180328. *unit = info_ptr->scal_unit;
  180329. *width = info_ptr->scal_pixel_width;
  180330. *height = info_ptr->scal_pixel_height;
  180331. return (PNG_INFO_sCAL);
  180332. }
  180333. return(0);
  180334. }
  180335. #else
  180336. #ifdef PNG_FIXED_POINT_SUPPORTED
  180337. png_uint_32 PNGAPI
  180338. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  180339. int *unit, png_charpp width, png_charpp height)
  180340. {
  180341. if (png_ptr != NULL && info_ptr != NULL &&
  180342. (info_ptr->valid & PNG_INFO_sCAL))
  180343. {
  180344. *unit = info_ptr->scal_unit;
  180345. *width = info_ptr->scal_s_width;
  180346. *height = info_ptr->scal_s_height;
  180347. return (PNG_INFO_sCAL);
  180348. }
  180349. return(0);
  180350. }
  180351. #endif
  180352. #endif
  180353. #endif
  180354. #if defined(PNG_pHYs_SUPPORTED)
  180355. png_uint_32 PNGAPI
  180356. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  180357. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  180358. {
  180359. png_uint_32 retval = 0;
  180360. if (png_ptr != NULL && info_ptr != NULL &&
  180361. (info_ptr->valid & PNG_INFO_pHYs))
  180362. {
  180363. png_debug1(1, "in %s retrieval function\n", "pHYs");
  180364. if (res_x != NULL)
  180365. {
  180366. *res_x = info_ptr->x_pixels_per_unit;
  180367. retval |= PNG_INFO_pHYs;
  180368. }
  180369. if (res_y != NULL)
  180370. {
  180371. *res_y = info_ptr->y_pixels_per_unit;
  180372. retval |= PNG_INFO_pHYs;
  180373. }
  180374. if (unit_type != NULL)
  180375. {
  180376. *unit_type = (int)info_ptr->phys_unit_type;
  180377. retval |= PNG_INFO_pHYs;
  180378. }
  180379. }
  180380. return (retval);
  180381. }
  180382. #endif
  180383. png_uint_32 PNGAPI
  180384. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  180385. int *num_palette)
  180386. {
  180387. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  180388. && palette != NULL)
  180389. {
  180390. png_debug1(1, "in %s retrieval function\n", "PLTE");
  180391. *palette = info_ptr->palette;
  180392. *num_palette = info_ptr->num_palette;
  180393. png_debug1(3, "num_palette = %d\n", *num_palette);
  180394. return (PNG_INFO_PLTE);
  180395. }
  180396. return (0);
  180397. }
  180398. #if defined(PNG_sBIT_SUPPORTED)
  180399. png_uint_32 PNGAPI
  180400. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  180401. {
  180402. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  180403. && sig_bit != NULL)
  180404. {
  180405. png_debug1(1, "in %s retrieval function\n", "sBIT");
  180406. *sig_bit = &(info_ptr->sig_bit);
  180407. return (PNG_INFO_sBIT);
  180408. }
  180409. return (0);
  180410. }
  180411. #endif
  180412. #if defined(PNG_TEXT_SUPPORTED)
  180413. png_uint_32 PNGAPI
  180414. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  180415. int *num_text)
  180416. {
  180417. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  180418. {
  180419. png_debug1(1, "in %s retrieval function\n",
  180420. (png_ptr->chunk_name[0] == '\0' ? "text"
  180421. : (png_const_charp)png_ptr->chunk_name));
  180422. if (text_ptr != NULL)
  180423. *text_ptr = info_ptr->text;
  180424. if (num_text != NULL)
  180425. *num_text = info_ptr->num_text;
  180426. return ((png_uint_32)info_ptr->num_text);
  180427. }
  180428. if (num_text != NULL)
  180429. *num_text = 0;
  180430. return(0);
  180431. }
  180432. #endif
  180433. #if defined(PNG_tIME_SUPPORTED)
  180434. png_uint_32 PNGAPI
  180435. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  180436. {
  180437. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  180438. && mod_time != NULL)
  180439. {
  180440. png_debug1(1, "in %s retrieval function\n", "tIME");
  180441. *mod_time = &(info_ptr->mod_time);
  180442. return (PNG_INFO_tIME);
  180443. }
  180444. return (0);
  180445. }
  180446. #endif
  180447. #if defined(PNG_tRNS_SUPPORTED)
  180448. png_uint_32 PNGAPI
  180449. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  180450. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  180451. {
  180452. png_uint_32 retval = 0;
  180453. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  180454. {
  180455. png_debug1(1, "in %s retrieval function\n", "tRNS");
  180456. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  180457. {
  180458. if (trans != NULL)
  180459. {
  180460. *trans = info_ptr->trans;
  180461. retval |= PNG_INFO_tRNS;
  180462. }
  180463. if (trans_values != NULL)
  180464. *trans_values = &(info_ptr->trans_values);
  180465. }
  180466. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  180467. {
  180468. if (trans_values != NULL)
  180469. {
  180470. *trans_values = &(info_ptr->trans_values);
  180471. retval |= PNG_INFO_tRNS;
  180472. }
  180473. if(trans != NULL)
  180474. *trans = NULL;
  180475. }
  180476. if(num_trans != NULL)
  180477. {
  180478. *num_trans = info_ptr->num_trans;
  180479. retval |= PNG_INFO_tRNS;
  180480. }
  180481. }
  180482. return (retval);
  180483. }
  180484. #endif
  180485. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180486. png_uint_32 PNGAPI
  180487. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  180488. png_unknown_chunkpp unknowns)
  180489. {
  180490. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  180491. {
  180492. *unknowns = info_ptr->unknown_chunks;
  180493. return ((png_uint_32)info_ptr->unknown_chunks_num);
  180494. }
  180495. return (0);
  180496. }
  180497. #endif
  180498. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  180499. png_byte PNGAPI
  180500. png_get_rgb_to_gray_status (png_structp png_ptr)
  180501. {
  180502. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  180503. }
  180504. #endif
  180505. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  180506. png_voidp PNGAPI
  180507. png_get_user_chunk_ptr(png_structp png_ptr)
  180508. {
  180509. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  180510. }
  180511. #endif
  180512. #ifdef PNG_WRITE_SUPPORTED
  180513. png_uint_32 PNGAPI
  180514. png_get_compression_buffer_size(png_structp png_ptr)
  180515. {
  180516. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  180517. }
  180518. #endif
  180519. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  180520. #ifndef PNG_1_0_X
  180521. /* this function was added to libpng 1.2.0 and should exist by default */
  180522. png_uint_32 PNGAPI
  180523. png_get_asm_flags (png_structp png_ptr)
  180524. {
  180525. /* obsolete, to be removed from libpng-1.4.0 */
  180526. return (png_ptr? 0L: 0L);
  180527. }
  180528. /* this function was added to libpng 1.2.0 and should exist by default */
  180529. png_uint_32 PNGAPI
  180530. png_get_asm_flagmask (int flag_select)
  180531. {
  180532. /* obsolete, to be removed from libpng-1.4.0 */
  180533. flag_select=flag_select;
  180534. return 0L;
  180535. }
  180536. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  180537. /* this function was added to libpng 1.2.0 */
  180538. png_uint_32 PNGAPI
  180539. png_get_mmx_flagmask (int flag_select, int *compilerID)
  180540. {
  180541. /* obsolete, to be removed from libpng-1.4.0 */
  180542. flag_select=flag_select;
  180543. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  180544. return 0L;
  180545. }
  180546. /* this function was added to libpng 1.2.0 */
  180547. png_byte PNGAPI
  180548. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  180549. {
  180550. /* obsolete, to be removed from libpng-1.4.0 */
  180551. return (png_ptr? 0: 0);
  180552. }
  180553. /* this function was added to libpng 1.2.0 */
  180554. png_uint_32 PNGAPI
  180555. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  180556. {
  180557. /* obsolete, to be removed from libpng-1.4.0 */
  180558. return (png_ptr? 0L: 0L);
  180559. }
  180560. #endif /* ?PNG_1_0_X */
  180561. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  180562. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  180563. /* these functions were added to libpng 1.2.6 */
  180564. png_uint_32 PNGAPI
  180565. png_get_user_width_max (png_structp png_ptr)
  180566. {
  180567. return (png_ptr? png_ptr->user_width_max : 0);
  180568. }
  180569. png_uint_32 PNGAPI
  180570. png_get_user_height_max (png_structp png_ptr)
  180571. {
  180572. return (png_ptr? png_ptr->user_height_max : 0);
  180573. }
  180574. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  180575. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  180576. /********* End of inlined file: pngget.c *********/
  180577. /********* Start of inlined file: pngmem.c *********/
  180578. /* pngmem.c - stub functions for memory allocation
  180579. *
  180580. * Last changed in libpng 1.2.13 November 13, 2006
  180581. * For conditions of distribution and use, see copyright notice in png.h
  180582. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  180583. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180584. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180585. *
  180586. * This file provides a location for all memory allocation. Users who
  180587. * need special memory handling are expected to supply replacement
  180588. * functions for png_malloc() and png_free(), and to use
  180589. * png_create_read_struct_2() and png_create_write_struct_2() to
  180590. * identify the replacement functions.
  180591. */
  180592. #define PNG_INTERNAL
  180593. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180594. /* Borland DOS special memory handler */
  180595. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  180596. /* if you change this, be sure to change the one in png.h also */
  180597. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  180598. by a single call to calloc() if this is thought to improve performance. */
  180599. png_voidp /* PRIVATE */
  180600. png_create_struct(int type)
  180601. {
  180602. #ifdef PNG_USER_MEM_SUPPORTED
  180603. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  180604. }
  180605. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  180606. png_voidp /* PRIVATE */
  180607. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  180608. {
  180609. #endif /* PNG_USER_MEM_SUPPORTED */
  180610. png_size_t size;
  180611. png_voidp struct_ptr;
  180612. if (type == PNG_STRUCT_INFO)
  180613. size = png_sizeof(png_info);
  180614. else if (type == PNG_STRUCT_PNG)
  180615. size = png_sizeof(png_struct);
  180616. else
  180617. return (png_get_copyright(NULL));
  180618. #ifdef PNG_USER_MEM_SUPPORTED
  180619. if(malloc_fn != NULL)
  180620. {
  180621. png_struct dummy_struct;
  180622. png_structp png_ptr = &dummy_struct;
  180623. png_ptr->mem_ptr=mem_ptr;
  180624. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  180625. }
  180626. else
  180627. #endif /* PNG_USER_MEM_SUPPORTED */
  180628. struct_ptr = (png_voidp)farmalloc(size);
  180629. if (struct_ptr != NULL)
  180630. png_memset(struct_ptr, 0, size);
  180631. return (struct_ptr);
  180632. }
  180633. /* Free memory allocated by a png_create_struct() call */
  180634. void /* PRIVATE */
  180635. png_destroy_struct(png_voidp struct_ptr)
  180636. {
  180637. #ifdef PNG_USER_MEM_SUPPORTED
  180638. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  180639. }
  180640. /* Free memory allocated by a png_create_struct() call */
  180641. void /* PRIVATE */
  180642. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  180643. png_voidp mem_ptr)
  180644. {
  180645. #endif
  180646. if (struct_ptr != NULL)
  180647. {
  180648. #ifdef PNG_USER_MEM_SUPPORTED
  180649. if(free_fn != NULL)
  180650. {
  180651. png_struct dummy_struct;
  180652. png_structp png_ptr = &dummy_struct;
  180653. png_ptr->mem_ptr=mem_ptr;
  180654. (*(free_fn))(png_ptr, struct_ptr);
  180655. return;
  180656. }
  180657. #endif /* PNG_USER_MEM_SUPPORTED */
  180658. farfree (struct_ptr);
  180659. }
  180660. }
  180661. /* Allocate memory. For reasonable files, size should never exceed
  180662. * 64K. However, zlib may allocate more then 64K if you don't tell
  180663. * it not to. See zconf.h and png.h for more information. zlib does
  180664. * need to allocate exactly 64K, so whatever you call here must
  180665. * have the ability to do that.
  180666. *
  180667. * Borland seems to have a problem in DOS mode for exactly 64K.
  180668. * It gives you a segment with an offset of 8 (perhaps to store its
  180669. * memory stuff). zlib doesn't like this at all, so we have to
  180670. * detect and deal with it. This code should not be needed in
  180671. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  180672. * been updated by Alexander Lehmann for version 0.89 to waste less
  180673. * memory.
  180674. *
  180675. * Note that we can't use png_size_t for the "size" declaration,
  180676. * since on some systems a png_size_t is a 16-bit quantity, and as a
  180677. * result, we would be truncating potentially larger memory requests
  180678. * (which should cause a fatal error) and introducing major problems.
  180679. */
  180680. png_voidp PNGAPI
  180681. png_malloc(png_structp png_ptr, png_uint_32 size)
  180682. {
  180683. png_voidp ret;
  180684. if (png_ptr == NULL || size == 0)
  180685. return (NULL);
  180686. #ifdef PNG_USER_MEM_SUPPORTED
  180687. if(png_ptr->malloc_fn != NULL)
  180688. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  180689. else
  180690. ret = (png_malloc_default(png_ptr, size));
  180691. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180692. png_error(png_ptr, "Out of memory!");
  180693. return (ret);
  180694. }
  180695. png_voidp PNGAPI
  180696. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  180697. {
  180698. png_voidp ret;
  180699. #endif /* PNG_USER_MEM_SUPPORTED */
  180700. if (png_ptr == NULL || size == 0)
  180701. return (NULL);
  180702. #ifdef PNG_MAX_MALLOC_64K
  180703. if (size > (png_uint_32)65536L)
  180704. {
  180705. png_warning(png_ptr, "Cannot Allocate > 64K");
  180706. ret = NULL;
  180707. }
  180708. else
  180709. #endif
  180710. if (size != (size_t)size)
  180711. ret = NULL;
  180712. else if (size == (png_uint_32)65536L)
  180713. {
  180714. if (png_ptr->offset_table == NULL)
  180715. {
  180716. /* try to see if we need to do any of this fancy stuff */
  180717. ret = farmalloc(size);
  180718. if (ret == NULL || ((png_size_t)ret & 0xffff))
  180719. {
  180720. int num_blocks;
  180721. png_uint_32 total_size;
  180722. png_bytep table;
  180723. int i;
  180724. png_byte huge * hptr;
  180725. if (ret != NULL)
  180726. {
  180727. farfree(ret);
  180728. ret = NULL;
  180729. }
  180730. if(png_ptr->zlib_window_bits > 14)
  180731. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  180732. else
  180733. num_blocks = 1;
  180734. if (png_ptr->zlib_mem_level >= 7)
  180735. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  180736. else
  180737. num_blocks++;
  180738. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  180739. table = farmalloc(total_size);
  180740. if (table == NULL)
  180741. {
  180742. #ifndef PNG_USER_MEM_SUPPORTED
  180743. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180744. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  180745. else
  180746. png_warning(png_ptr, "Out Of Memory.");
  180747. #endif
  180748. return (NULL);
  180749. }
  180750. if ((png_size_t)table & 0xfff0)
  180751. {
  180752. #ifndef PNG_USER_MEM_SUPPORTED
  180753. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180754. png_error(png_ptr,
  180755. "Farmalloc didn't return normalized pointer");
  180756. else
  180757. png_warning(png_ptr,
  180758. "Farmalloc didn't return normalized pointer");
  180759. #endif
  180760. return (NULL);
  180761. }
  180762. png_ptr->offset_table = table;
  180763. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  180764. png_sizeof (png_bytep));
  180765. if (png_ptr->offset_table_ptr == NULL)
  180766. {
  180767. #ifndef PNG_USER_MEM_SUPPORTED
  180768. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180769. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  180770. else
  180771. png_warning(png_ptr, "Out Of memory.");
  180772. #endif
  180773. return (NULL);
  180774. }
  180775. hptr = (png_byte huge *)table;
  180776. if ((png_size_t)hptr & 0xf)
  180777. {
  180778. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  180779. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  180780. }
  180781. for (i = 0; i < num_blocks; i++)
  180782. {
  180783. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  180784. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  180785. }
  180786. png_ptr->offset_table_number = num_blocks;
  180787. png_ptr->offset_table_count = 0;
  180788. png_ptr->offset_table_count_free = 0;
  180789. }
  180790. }
  180791. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  180792. {
  180793. #ifndef PNG_USER_MEM_SUPPORTED
  180794. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180795. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  180796. else
  180797. png_warning(png_ptr, "Out of Memory.");
  180798. #endif
  180799. return (NULL);
  180800. }
  180801. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  180802. }
  180803. else
  180804. ret = farmalloc(size);
  180805. #ifndef PNG_USER_MEM_SUPPORTED
  180806. if (ret == NULL)
  180807. {
  180808. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180809. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  180810. else
  180811. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  180812. }
  180813. #endif
  180814. return (ret);
  180815. }
  180816. /* free a pointer allocated by png_malloc(). In the default
  180817. configuration, png_ptr is not used, but is passed in case it
  180818. is needed. If ptr is NULL, return without taking any action. */
  180819. void PNGAPI
  180820. png_free(png_structp png_ptr, png_voidp ptr)
  180821. {
  180822. if (png_ptr == NULL || ptr == NULL)
  180823. return;
  180824. #ifdef PNG_USER_MEM_SUPPORTED
  180825. if (png_ptr->free_fn != NULL)
  180826. {
  180827. (*(png_ptr->free_fn))(png_ptr, ptr);
  180828. return;
  180829. }
  180830. else png_free_default(png_ptr, ptr);
  180831. }
  180832. void PNGAPI
  180833. png_free_default(png_structp png_ptr, png_voidp ptr)
  180834. {
  180835. #endif /* PNG_USER_MEM_SUPPORTED */
  180836. if(png_ptr == NULL) return;
  180837. if (png_ptr->offset_table != NULL)
  180838. {
  180839. int i;
  180840. for (i = 0; i < png_ptr->offset_table_count; i++)
  180841. {
  180842. if (ptr == png_ptr->offset_table_ptr[i])
  180843. {
  180844. ptr = NULL;
  180845. png_ptr->offset_table_count_free++;
  180846. break;
  180847. }
  180848. }
  180849. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  180850. {
  180851. farfree(png_ptr->offset_table);
  180852. farfree(png_ptr->offset_table_ptr);
  180853. png_ptr->offset_table = NULL;
  180854. png_ptr->offset_table_ptr = NULL;
  180855. }
  180856. }
  180857. if (ptr != NULL)
  180858. {
  180859. farfree(ptr);
  180860. }
  180861. }
  180862. #else /* Not the Borland DOS special memory handler */
  180863. /* Allocate memory for a png_struct or a png_info. The malloc and
  180864. memset can be replaced by a single call to calloc() if this is thought
  180865. to improve performance noticably. */
  180866. png_voidp /* PRIVATE */
  180867. png_create_struct(int type)
  180868. {
  180869. #ifdef PNG_USER_MEM_SUPPORTED
  180870. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  180871. }
  180872. /* Allocate memory for a png_struct or a png_info. The malloc and
  180873. memset can be replaced by a single call to calloc() if this is thought
  180874. to improve performance noticably. */
  180875. png_voidp /* PRIVATE */
  180876. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  180877. {
  180878. #endif /* PNG_USER_MEM_SUPPORTED */
  180879. png_size_t size;
  180880. png_voidp struct_ptr;
  180881. if (type == PNG_STRUCT_INFO)
  180882. size = png_sizeof(png_info);
  180883. else if (type == PNG_STRUCT_PNG)
  180884. size = png_sizeof(png_struct);
  180885. else
  180886. return (NULL);
  180887. #ifdef PNG_USER_MEM_SUPPORTED
  180888. if(malloc_fn != NULL)
  180889. {
  180890. png_struct dummy_struct;
  180891. png_structp png_ptr = &dummy_struct;
  180892. png_ptr->mem_ptr=mem_ptr;
  180893. struct_ptr = (*(malloc_fn))(png_ptr, size);
  180894. if (struct_ptr != NULL)
  180895. png_memset(struct_ptr, 0, size);
  180896. return (struct_ptr);
  180897. }
  180898. #endif /* PNG_USER_MEM_SUPPORTED */
  180899. #if defined(__TURBOC__) && !defined(__FLAT__)
  180900. struct_ptr = (png_voidp)farmalloc(size);
  180901. #else
  180902. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180903. struct_ptr = (png_voidp)halloc(size,1);
  180904. # else
  180905. struct_ptr = (png_voidp)malloc(size);
  180906. # endif
  180907. #endif
  180908. if (struct_ptr != NULL)
  180909. png_memset(struct_ptr, 0, size);
  180910. return (struct_ptr);
  180911. }
  180912. /* Free memory allocated by a png_create_struct() call */
  180913. void /* PRIVATE */
  180914. png_destroy_struct(png_voidp struct_ptr)
  180915. {
  180916. #ifdef PNG_USER_MEM_SUPPORTED
  180917. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  180918. }
  180919. /* Free memory allocated by a png_create_struct() call */
  180920. void /* PRIVATE */
  180921. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  180922. png_voidp mem_ptr)
  180923. {
  180924. #endif /* PNG_USER_MEM_SUPPORTED */
  180925. if (struct_ptr != NULL)
  180926. {
  180927. #ifdef PNG_USER_MEM_SUPPORTED
  180928. if(free_fn != NULL)
  180929. {
  180930. png_struct dummy_struct;
  180931. png_structp png_ptr = &dummy_struct;
  180932. png_ptr->mem_ptr=mem_ptr;
  180933. (*(free_fn))(png_ptr, struct_ptr);
  180934. return;
  180935. }
  180936. #endif /* PNG_USER_MEM_SUPPORTED */
  180937. #if defined(__TURBOC__) && !defined(__FLAT__)
  180938. farfree(struct_ptr);
  180939. #else
  180940. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180941. hfree(struct_ptr);
  180942. # else
  180943. free(struct_ptr);
  180944. # endif
  180945. #endif
  180946. }
  180947. }
  180948. /* Allocate memory. For reasonable files, size should never exceed
  180949. 64K. However, zlib may allocate more then 64K if you don't tell
  180950. it not to. See zconf.h and png.h for more information. zlib does
  180951. need to allocate exactly 64K, so whatever you call here must
  180952. have the ability to do that. */
  180953. png_voidp PNGAPI
  180954. png_malloc(png_structp png_ptr, png_uint_32 size)
  180955. {
  180956. png_voidp ret;
  180957. #ifdef PNG_USER_MEM_SUPPORTED
  180958. if (png_ptr == NULL || size == 0)
  180959. return (NULL);
  180960. if(png_ptr->malloc_fn != NULL)
  180961. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  180962. else
  180963. ret = (png_malloc_default(png_ptr, size));
  180964. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180965. png_error(png_ptr, "Out of Memory!");
  180966. return (ret);
  180967. }
  180968. png_voidp PNGAPI
  180969. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  180970. {
  180971. png_voidp ret;
  180972. #endif /* PNG_USER_MEM_SUPPORTED */
  180973. if (png_ptr == NULL || size == 0)
  180974. return (NULL);
  180975. #ifdef PNG_MAX_MALLOC_64K
  180976. if (size > (png_uint_32)65536L)
  180977. {
  180978. #ifndef PNG_USER_MEM_SUPPORTED
  180979. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180980. png_error(png_ptr, "Cannot Allocate > 64K");
  180981. else
  180982. #endif
  180983. return NULL;
  180984. }
  180985. #endif
  180986. /* Check for overflow */
  180987. #if defined(__TURBOC__) && !defined(__FLAT__)
  180988. if (size != (unsigned long)size)
  180989. ret = NULL;
  180990. else
  180991. ret = farmalloc(size);
  180992. #else
  180993. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180994. if (size != (unsigned long)size)
  180995. ret = NULL;
  180996. else
  180997. ret = halloc(size, 1);
  180998. # else
  180999. if (size != (size_t)size)
  181000. ret = NULL;
  181001. else
  181002. ret = malloc((size_t)size);
  181003. # endif
  181004. #endif
  181005. #ifndef PNG_USER_MEM_SUPPORTED
  181006. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  181007. png_error(png_ptr, "Out of Memory");
  181008. #endif
  181009. return (ret);
  181010. }
  181011. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  181012. without taking any action. */
  181013. void PNGAPI
  181014. png_free(png_structp png_ptr, png_voidp ptr)
  181015. {
  181016. if (png_ptr == NULL || ptr == NULL)
  181017. return;
  181018. #ifdef PNG_USER_MEM_SUPPORTED
  181019. if (png_ptr->free_fn != NULL)
  181020. {
  181021. (*(png_ptr->free_fn))(png_ptr, ptr);
  181022. return;
  181023. }
  181024. else png_free_default(png_ptr, ptr);
  181025. }
  181026. void PNGAPI
  181027. png_free_default(png_structp png_ptr, png_voidp ptr)
  181028. {
  181029. if (png_ptr == NULL || ptr == NULL)
  181030. return;
  181031. #endif /* PNG_USER_MEM_SUPPORTED */
  181032. #if defined(__TURBOC__) && !defined(__FLAT__)
  181033. farfree(ptr);
  181034. #else
  181035. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  181036. hfree(ptr);
  181037. # else
  181038. free(ptr);
  181039. # endif
  181040. #endif
  181041. }
  181042. #endif /* Not Borland DOS special memory handler */
  181043. #if defined(PNG_1_0_X)
  181044. # define png_malloc_warn png_malloc
  181045. #else
  181046. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  181047. * function will set up png_malloc() to issue a png_warning and return NULL
  181048. * instead of issuing a png_error, if it fails to allocate the requested
  181049. * memory.
  181050. */
  181051. png_voidp PNGAPI
  181052. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  181053. {
  181054. png_voidp ptr;
  181055. png_uint_32 save_flags;
  181056. if(png_ptr == NULL) return (NULL);
  181057. save_flags=png_ptr->flags;
  181058. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  181059. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  181060. png_ptr->flags=save_flags;
  181061. return(ptr);
  181062. }
  181063. #endif
  181064. png_voidp PNGAPI
  181065. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  181066. png_uint_32 length)
  181067. {
  181068. png_size_t size;
  181069. size = (png_size_t)length;
  181070. if ((png_uint_32)size != length)
  181071. png_error(png_ptr,"Overflow in png_memcpy_check.");
  181072. return(png_memcpy (s1, s2, size));
  181073. }
  181074. png_voidp PNGAPI
  181075. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  181076. png_uint_32 length)
  181077. {
  181078. png_size_t size;
  181079. size = (png_size_t)length;
  181080. if ((png_uint_32)size != length)
  181081. png_error(png_ptr,"Overflow in png_memset_check.");
  181082. return (png_memset (s1, value, size));
  181083. }
  181084. #ifdef PNG_USER_MEM_SUPPORTED
  181085. /* This function is called when the application wants to use another method
  181086. * of allocating and freeing memory.
  181087. */
  181088. void PNGAPI
  181089. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  181090. malloc_fn, png_free_ptr free_fn)
  181091. {
  181092. if(png_ptr != NULL) {
  181093. png_ptr->mem_ptr = mem_ptr;
  181094. png_ptr->malloc_fn = malloc_fn;
  181095. png_ptr->free_fn = free_fn;
  181096. }
  181097. }
  181098. /* This function returns a pointer to the mem_ptr associated with the user
  181099. * functions. The application should free any memory associated with this
  181100. * pointer before png_write_destroy and png_read_destroy are called.
  181101. */
  181102. png_voidp PNGAPI
  181103. png_get_mem_ptr(png_structp png_ptr)
  181104. {
  181105. if(png_ptr == NULL) return (NULL);
  181106. return ((png_voidp)png_ptr->mem_ptr);
  181107. }
  181108. #endif /* PNG_USER_MEM_SUPPORTED */
  181109. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  181110. /********* End of inlined file: pngmem.c *********/
  181111. /********* Start of inlined file: pngread.c *********/
  181112. /* pngread.c - read a PNG file
  181113. *
  181114. * Last changed in libpng 1.2.20 September 7, 2007
  181115. * For conditions of distribution and use, see copyright notice in png.h
  181116. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181117. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181118. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181119. *
  181120. * This file contains routines that an application calls directly to
  181121. * read a PNG file or stream.
  181122. */
  181123. #define PNG_INTERNAL
  181124. #if defined(PNG_READ_SUPPORTED)
  181125. /* Create a PNG structure for reading, and allocate any memory needed. */
  181126. png_structp PNGAPI
  181127. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  181128. png_error_ptr error_fn, png_error_ptr warn_fn)
  181129. {
  181130. #ifdef PNG_USER_MEM_SUPPORTED
  181131. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  181132. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  181133. }
  181134. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  181135. png_structp PNGAPI
  181136. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  181137. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  181138. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  181139. {
  181140. #endif /* PNG_USER_MEM_SUPPORTED */
  181141. png_structp png_ptr;
  181142. #ifdef PNG_SETJMP_SUPPORTED
  181143. #ifdef USE_FAR_KEYWORD
  181144. jmp_buf jmpbuf;
  181145. #endif
  181146. #endif
  181147. int i;
  181148. png_debug(1, "in png_create_read_struct\n");
  181149. #ifdef PNG_USER_MEM_SUPPORTED
  181150. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  181151. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  181152. #else
  181153. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  181154. #endif
  181155. if (png_ptr == NULL)
  181156. return (NULL);
  181157. /* added at libpng-1.2.6 */
  181158. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  181159. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  181160. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  181161. #endif
  181162. #ifdef PNG_SETJMP_SUPPORTED
  181163. #ifdef USE_FAR_KEYWORD
  181164. if (setjmp(jmpbuf))
  181165. #else
  181166. if (setjmp(png_ptr->jmpbuf))
  181167. #endif
  181168. {
  181169. png_free(png_ptr, png_ptr->zbuf);
  181170. png_ptr->zbuf=NULL;
  181171. #ifdef PNG_USER_MEM_SUPPORTED
  181172. png_destroy_struct_2((png_voidp)png_ptr,
  181173. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  181174. #else
  181175. png_destroy_struct((png_voidp)png_ptr);
  181176. #endif
  181177. return (NULL);
  181178. }
  181179. #ifdef USE_FAR_KEYWORD
  181180. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  181181. #endif
  181182. #endif
  181183. #ifdef PNG_USER_MEM_SUPPORTED
  181184. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  181185. #endif
  181186. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  181187. i=0;
  181188. do
  181189. {
  181190. if(user_png_ver[i] != png_libpng_ver[i])
  181191. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  181192. } while (png_libpng_ver[i++]);
  181193. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  181194. {
  181195. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  181196. * we must recompile any applications that use any older library version.
  181197. * For versions after libpng 1.0, we will be compatible, so we need
  181198. * only check the first digit.
  181199. */
  181200. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  181201. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  181202. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  181203. {
  181204. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  181205. char msg[80];
  181206. if (user_png_ver)
  181207. {
  181208. png_snprintf(msg, 80,
  181209. "Application was compiled with png.h from libpng-%.20s",
  181210. user_png_ver);
  181211. png_warning(png_ptr, msg);
  181212. }
  181213. png_snprintf(msg, 80,
  181214. "Application is running with png.c from libpng-%.20s",
  181215. png_libpng_ver);
  181216. png_warning(png_ptr, msg);
  181217. #endif
  181218. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181219. png_ptr->flags=0;
  181220. #endif
  181221. png_error(png_ptr,
  181222. "Incompatible libpng version in application and library");
  181223. }
  181224. }
  181225. /* initialize zbuf - compression buffer */
  181226. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  181227. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  181228. (png_uint_32)png_ptr->zbuf_size);
  181229. png_ptr->zstream.zalloc = png_zalloc;
  181230. png_ptr->zstream.zfree = png_zfree;
  181231. png_ptr->zstream.opaque = (voidpf)png_ptr;
  181232. switch (inflateInit(&png_ptr->zstream))
  181233. {
  181234. case Z_OK: /* Do nothing */ break;
  181235. case Z_MEM_ERROR:
  181236. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  181237. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  181238. default: png_error(png_ptr, "Unknown zlib error");
  181239. }
  181240. png_ptr->zstream.next_out = png_ptr->zbuf;
  181241. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  181242. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  181243. #ifdef PNG_SETJMP_SUPPORTED
  181244. /* Applications that neglect to set up their own setjmp() and then encounter
  181245. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  181246. abort instead of returning. */
  181247. #ifdef USE_FAR_KEYWORD
  181248. if (setjmp(jmpbuf))
  181249. PNG_ABORT();
  181250. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  181251. #else
  181252. if (setjmp(png_ptr->jmpbuf))
  181253. PNG_ABORT();
  181254. #endif
  181255. #endif
  181256. return (png_ptr);
  181257. }
  181258. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  181259. /* Initialize PNG structure for reading, and allocate any memory needed.
  181260. This interface is deprecated in favour of the png_create_read_struct(),
  181261. and it will disappear as of libpng-1.3.0. */
  181262. #undef png_read_init
  181263. void PNGAPI
  181264. png_read_init(png_structp png_ptr)
  181265. {
  181266. /* We only come here via pre-1.0.7-compiled applications */
  181267. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  181268. }
  181269. void PNGAPI
  181270. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  181271. png_size_t png_struct_size, png_size_t png_info_size)
  181272. {
  181273. /* We only come here via pre-1.0.12-compiled applications */
  181274. if(png_ptr == NULL) return;
  181275. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  181276. if(png_sizeof(png_struct) > png_struct_size ||
  181277. png_sizeof(png_info) > png_info_size)
  181278. {
  181279. char msg[80];
  181280. png_ptr->warning_fn=NULL;
  181281. if (user_png_ver)
  181282. {
  181283. png_snprintf(msg, 80,
  181284. "Application was compiled with png.h from libpng-%.20s",
  181285. user_png_ver);
  181286. png_warning(png_ptr, msg);
  181287. }
  181288. png_snprintf(msg, 80,
  181289. "Application is running with png.c from libpng-%.20s",
  181290. png_libpng_ver);
  181291. png_warning(png_ptr, msg);
  181292. }
  181293. #endif
  181294. if(png_sizeof(png_struct) > png_struct_size)
  181295. {
  181296. png_ptr->error_fn=NULL;
  181297. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181298. png_ptr->flags=0;
  181299. #endif
  181300. png_error(png_ptr,
  181301. "The png struct allocated by the application for reading is too small.");
  181302. }
  181303. if(png_sizeof(png_info) > png_info_size)
  181304. {
  181305. png_ptr->error_fn=NULL;
  181306. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181307. png_ptr->flags=0;
  181308. #endif
  181309. png_error(png_ptr,
  181310. "The info struct allocated by application for reading is too small.");
  181311. }
  181312. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  181313. }
  181314. #endif /* PNG_1_0_X || PNG_1_2_X */
  181315. void PNGAPI
  181316. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  181317. png_size_t png_struct_size)
  181318. {
  181319. #ifdef PNG_SETJMP_SUPPORTED
  181320. jmp_buf tmp_jmp; /* to save current jump buffer */
  181321. #endif
  181322. int i=0;
  181323. png_structp png_ptr=*ptr_ptr;
  181324. if(png_ptr == NULL) return;
  181325. do
  181326. {
  181327. if(user_png_ver[i] != png_libpng_ver[i])
  181328. {
  181329. #ifdef PNG_LEGACY_SUPPORTED
  181330. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  181331. #else
  181332. png_ptr->warning_fn=NULL;
  181333. png_warning(png_ptr,
  181334. "Application uses deprecated png_read_init() and should be recompiled.");
  181335. break;
  181336. #endif
  181337. }
  181338. } while (png_libpng_ver[i++]);
  181339. png_debug(1, "in png_read_init_3\n");
  181340. #ifdef PNG_SETJMP_SUPPORTED
  181341. /* save jump buffer and error functions */
  181342. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  181343. #endif
  181344. if(png_sizeof(png_struct) > png_struct_size)
  181345. {
  181346. png_destroy_struct(png_ptr);
  181347. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  181348. png_ptr = *ptr_ptr;
  181349. }
  181350. /* reset all variables to 0 */
  181351. png_memset(png_ptr, 0, png_sizeof (png_struct));
  181352. #ifdef PNG_SETJMP_SUPPORTED
  181353. /* restore jump buffer */
  181354. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  181355. #endif
  181356. /* added at libpng-1.2.6 */
  181357. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  181358. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  181359. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  181360. #endif
  181361. /* initialize zbuf - compression buffer */
  181362. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  181363. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  181364. (png_uint_32)png_ptr->zbuf_size);
  181365. png_ptr->zstream.zalloc = png_zalloc;
  181366. png_ptr->zstream.zfree = png_zfree;
  181367. png_ptr->zstream.opaque = (voidpf)png_ptr;
  181368. switch (inflateInit(&png_ptr->zstream))
  181369. {
  181370. case Z_OK: /* Do nothing */ break;
  181371. case Z_MEM_ERROR:
  181372. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  181373. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  181374. default: png_error(png_ptr, "Unknown zlib error");
  181375. }
  181376. png_ptr->zstream.next_out = png_ptr->zbuf;
  181377. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  181378. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  181379. }
  181380. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181381. /* Read the information before the actual image data. This has been
  181382. * changed in v0.90 to allow reading a file that already has the magic
  181383. * bytes read from the stream. You can tell libpng how many bytes have
  181384. * been read from the beginning of the stream (up to the maximum of 8)
  181385. * via png_set_sig_bytes(), and we will only check the remaining bytes
  181386. * here. The application can then have access to the signature bytes we
  181387. * read if it is determined that this isn't a valid PNG file.
  181388. */
  181389. void PNGAPI
  181390. png_read_info(png_structp png_ptr, png_infop info_ptr)
  181391. {
  181392. if(png_ptr == NULL) return;
  181393. png_debug(1, "in png_read_info\n");
  181394. /* If we haven't checked all of the PNG signature bytes, do so now. */
  181395. if (png_ptr->sig_bytes < 8)
  181396. {
  181397. png_size_t num_checked = png_ptr->sig_bytes,
  181398. num_to_check = 8 - num_checked;
  181399. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  181400. png_ptr->sig_bytes = 8;
  181401. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  181402. {
  181403. if (num_checked < 4 &&
  181404. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  181405. png_error(png_ptr, "Not a PNG file");
  181406. else
  181407. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  181408. }
  181409. if (num_checked < 3)
  181410. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  181411. }
  181412. for(;;)
  181413. {
  181414. #ifdef PNG_USE_LOCAL_ARRAYS
  181415. PNG_CONST PNG_IHDR;
  181416. PNG_CONST PNG_IDAT;
  181417. PNG_CONST PNG_IEND;
  181418. PNG_CONST PNG_PLTE;
  181419. #if defined(PNG_READ_bKGD_SUPPORTED)
  181420. PNG_CONST PNG_bKGD;
  181421. #endif
  181422. #if defined(PNG_READ_cHRM_SUPPORTED)
  181423. PNG_CONST PNG_cHRM;
  181424. #endif
  181425. #if defined(PNG_READ_gAMA_SUPPORTED)
  181426. PNG_CONST PNG_gAMA;
  181427. #endif
  181428. #if defined(PNG_READ_hIST_SUPPORTED)
  181429. PNG_CONST PNG_hIST;
  181430. #endif
  181431. #if defined(PNG_READ_iCCP_SUPPORTED)
  181432. PNG_CONST PNG_iCCP;
  181433. #endif
  181434. #if defined(PNG_READ_iTXt_SUPPORTED)
  181435. PNG_CONST PNG_iTXt;
  181436. #endif
  181437. #if defined(PNG_READ_oFFs_SUPPORTED)
  181438. PNG_CONST PNG_oFFs;
  181439. #endif
  181440. #if defined(PNG_READ_pCAL_SUPPORTED)
  181441. PNG_CONST PNG_pCAL;
  181442. #endif
  181443. #if defined(PNG_READ_pHYs_SUPPORTED)
  181444. PNG_CONST PNG_pHYs;
  181445. #endif
  181446. #if defined(PNG_READ_sBIT_SUPPORTED)
  181447. PNG_CONST PNG_sBIT;
  181448. #endif
  181449. #if defined(PNG_READ_sCAL_SUPPORTED)
  181450. PNG_CONST PNG_sCAL;
  181451. #endif
  181452. #if defined(PNG_READ_sPLT_SUPPORTED)
  181453. PNG_CONST PNG_sPLT;
  181454. #endif
  181455. #if defined(PNG_READ_sRGB_SUPPORTED)
  181456. PNG_CONST PNG_sRGB;
  181457. #endif
  181458. #if defined(PNG_READ_tEXt_SUPPORTED)
  181459. PNG_CONST PNG_tEXt;
  181460. #endif
  181461. #if defined(PNG_READ_tIME_SUPPORTED)
  181462. PNG_CONST PNG_tIME;
  181463. #endif
  181464. #if defined(PNG_READ_tRNS_SUPPORTED)
  181465. PNG_CONST PNG_tRNS;
  181466. #endif
  181467. #if defined(PNG_READ_zTXt_SUPPORTED)
  181468. PNG_CONST PNG_zTXt;
  181469. #endif
  181470. #endif /* PNG_USE_LOCAL_ARRAYS */
  181471. png_byte chunk_length[4];
  181472. png_uint_32 length;
  181473. png_read_data(png_ptr, chunk_length, 4);
  181474. length = png_get_uint_31(png_ptr,chunk_length);
  181475. png_reset_crc(png_ptr);
  181476. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  181477. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  181478. length);
  181479. /* This should be a binary subdivision search or a hash for
  181480. * matching the chunk name rather than a linear search.
  181481. */
  181482. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181483. if(png_ptr->mode & PNG_AFTER_IDAT)
  181484. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  181485. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  181486. png_handle_IHDR(png_ptr, info_ptr, length);
  181487. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  181488. png_handle_IEND(png_ptr, info_ptr, length);
  181489. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181490. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  181491. {
  181492. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181493. png_ptr->mode |= PNG_HAVE_IDAT;
  181494. png_handle_unknown(png_ptr, info_ptr, length);
  181495. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181496. png_ptr->mode |= PNG_HAVE_PLTE;
  181497. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181498. {
  181499. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  181500. png_error(png_ptr, "Missing IHDR before IDAT");
  181501. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  181502. !(png_ptr->mode & PNG_HAVE_PLTE))
  181503. png_error(png_ptr, "Missing PLTE before IDAT");
  181504. break;
  181505. }
  181506. }
  181507. #endif
  181508. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181509. png_handle_PLTE(png_ptr, info_ptr, length);
  181510. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181511. {
  181512. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  181513. png_error(png_ptr, "Missing IHDR before IDAT");
  181514. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  181515. !(png_ptr->mode & PNG_HAVE_PLTE))
  181516. png_error(png_ptr, "Missing PLTE before IDAT");
  181517. png_ptr->idat_size = length;
  181518. png_ptr->mode |= PNG_HAVE_IDAT;
  181519. break;
  181520. }
  181521. #if defined(PNG_READ_bKGD_SUPPORTED)
  181522. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  181523. png_handle_bKGD(png_ptr, info_ptr, length);
  181524. #endif
  181525. #if defined(PNG_READ_cHRM_SUPPORTED)
  181526. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  181527. png_handle_cHRM(png_ptr, info_ptr, length);
  181528. #endif
  181529. #if defined(PNG_READ_gAMA_SUPPORTED)
  181530. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  181531. png_handle_gAMA(png_ptr, info_ptr, length);
  181532. #endif
  181533. #if defined(PNG_READ_hIST_SUPPORTED)
  181534. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  181535. png_handle_hIST(png_ptr, info_ptr, length);
  181536. #endif
  181537. #if defined(PNG_READ_oFFs_SUPPORTED)
  181538. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  181539. png_handle_oFFs(png_ptr, info_ptr, length);
  181540. #endif
  181541. #if defined(PNG_READ_pCAL_SUPPORTED)
  181542. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  181543. png_handle_pCAL(png_ptr, info_ptr, length);
  181544. #endif
  181545. #if defined(PNG_READ_sCAL_SUPPORTED)
  181546. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  181547. png_handle_sCAL(png_ptr, info_ptr, length);
  181548. #endif
  181549. #if defined(PNG_READ_pHYs_SUPPORTED)
  181550. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  181551. png_handle_pHYs(png_ptr, info_ptr, length);
  181552. #endif
  181553. #if defined(PNG_READ_sBIT_SUPPORTED)
  181554. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  181555. png_handle_sBIT(png_ptr, info_ptr, length);
  181556. #endif
  181557. #if defined(PNG_READ_sRGB_SUPPORTED)
  181558. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  181559. png_handle_sRGB(png_ptr, info_ptr, length);
  181560. #endif
  181561. #if defined(PNG_READ_iCCP_SUPPORTED)
  181562. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  181563. png_handle_iCCP(png_ptr, info_ptr, length);
  181564. #endif
  181565. #if defined(PNG_READ_sPLT_SUPPORTED)
  181566. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  181567. png_handle_sPLT(png_ptr, info_ptr, length);
  181568. #endif
  181569. #if defined(PNG_READ_tEXt_SUPPORTED)
  181570. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  181571. png_handle_tEXt(png_ptr, info_ptr, length);
  181572. #endif
  181573. #if defined(PNG_READ_tIME_SUPPORTED)
  181574. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  181575. png_handle_tIME(png_ptr, info_ptr, length);
  181576. #endif
  181577. #if defined(PNG_READ_tRNS_SUPPORTED)
  181578. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  181579. png_handle_tRNS(png_ptr, info_ptr, length);
  181580. #endif
  181581. #if defined(PNG_READ_zTXt_SUPPORTED)
  181582. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  181583. png_handle_zTXt(png_ptr, info_ptr, length);
  181584. #endif
  181585. #if defined(PNG_READ_iTXt_SUPPORTED)
  181586. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  181587. png_handle_iTXt(png_ptr, info_ptr, length);
  181588. #endif
  181589. else
  181590. png_handle_unknown(png_ptr, info_ptr, length);
  181591. }
  181592. }
  181593. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181594. /* optional call to update the users info_ptr structure */
  181595. void PNGAPI
  181596. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  181597. {
  181598. png_debug(1, "in png_read_update_info\n");
  181599. if(png_ptr == NULL) return;
  181600. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  181601. png_read_start_row(png_ptr);
  181602. else
  181603. png_warning(png_ptr,
  181604. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  181605. png_read_transform_info(png_ptr, info_ptr);
  181606. }
  181607. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181608. /* Initialize palette, background, etc, after transformations
  181609. * are set, but before any reading takes place. This allows
  181610. * the user to obtain a gamma-corrected palette, for example.
  181611. * If the user doesn't call this, we will do it ourselves.
  181612. */
  181613. void PNGAPI
  181614. png_start_read_image(png_structp png_ptr)
  181615. {
  181616. png_debug(1, "in png_start_read_image\n");
  181617. if(png_ptr == NULL) return;
  181618. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  181619. png_read_start_row(png_ptr);
  181620. }
  181621. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181622. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181623. void PNGAPI
  181624. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  181625. {
  181626. #ifdef PNG_USE_LOCAL_ARRAYS
  181627. PNG_CONST PNG_IDAT;
  181628. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  181629. 0xff};
  181630. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  181631. #endif
  181632. int ret;
  181633. if(png_ptr == NULL) return;
  181634. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  181635. png_ptr->row_number, png_ptr->pass);
  181636. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  181637. png_read_start_row(png_ptr);
  181638. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  181639. {
  181640. /* check for transforms that have been set but were defined out */
  181641. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  181642. if (png_ptr->transformations & PNG_INVERT_MONO)
  181643. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  181644. #endif
  181645. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  181646. if (png_ptr->transformations & PNG_FILLER)
  181647. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  181648. #endif
  181649. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  181650. if (png_ptr->transformations & PNG_PACKSWAP)
  181651. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  181652. #endif
  181653. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  181654. if (png_ptr->transformations & PNG_PACK)
  181655. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  181656. #endif
  181657. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  181658. if (png_ptr->transformations & PNG_SHIFT)
  181659. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  181660. #endif
  181661. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  181662. if (png_ptr->transformations & PNG_BGR)
  181663. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  181664. #endif
  181665. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  181666. if (png_ptr->transformations & PNG_SWAP_BYTES)
  181667. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  181668. #endif
  181669. }
  181670. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  181671. /* if interlaced and we do not need a new row, combine row and return */
  181672. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  181673. {
  181674. switch (png_ptr->pass)
  181675. {
  181676. case 0:
  181677. if (png_ptr->row_number & 0x07)
  181678. {
  181679. if (dsp_row != NULL)
  181680. png_combine_row(png_ptr, dsp_row,
  181681. png_pass_dsp_mask[png_ptr->pass]);
  181682. png_read_finish_row(png_ptr);
  181683. return;
  181684. }
  181685. break;
  181686. case 1:
  181687. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  181688. {
  181689. if (dsp_row != NULL)
  181690. png_combine_row(png_ptr, dsp_row,
  181691. png_pass_dsp_mask[png_ptr->pass]);
  181692. png_read_finish_row(png_ptr);
  181693. return;
  181694. }
  181695. break;
  181696. case 2:
  181697. if ((png_ptr->row_number & 0x07) != 4)
  181698. {
  181699. if (dsp_row != NULL && (png_ptr->row_number & 4))
  181700. png_combine_row(png_ptr, dsp_row,
  181701. png_pass_dsp_mask[png_ptr->pass]);
  181702. png_read_finish_row(png_ptr);
  181703. return;
  181704. }
  181705. break;
  181706. case 3:
  181707. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  181708. {
  181709. if (dsp_row != NULL)
  181710. png_combine_row(png_ptr, dsp_row,
  181711. png_pass_dsp_mask[png_ptr->pass]);
  181712. png_read_finish_row(png_ptr);
  181713. return;
  181714. }
  181715. break;
  181716. case 4:
  181717. if ((png_ptr->row_number & 3) != 2)
  181718. {
  181719. if (dsp_row != NULL && (png_ptr->row_number & 2))
  181720. png_combine_row(png_ptr, dsp_row,
  181721. png_pass_dsp_mask[png_ptr->pass]);
  181722. png_read_finish_row(png_ptr);
  181723. return;
  181724. }
  181725. break;
  181726. case 5:
  181727. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  181728. {
  181729. if (dsp_row != NULL)
  181730. png_combine_row(png_ptr, dsp_row,
  181731. png_pass_dsp_mask[png_ptr->pass]);
  181732. png_read_finish_row(png_ptr);
  181733. return;
  181734. }
  181735. break;
  181736. case 6:
  181737. if (!(png_ptr->row_number & 1))
  181738. {
  181739. png_read_finish_row(png_ptr);
  181740. return;
  181741. }
  181742. break;
  181743. }
  181744. }
  181745. #endif
  181746. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  181747. png_error(png_ptr, "Invalid attempt to read row data");
  181748. png_ptr->zstream.next_out = png_ptr->row_buf;
  181749. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  181750. do
  181751. {
  181752. if (!(png_ptr->zstream.avail_in))
  181753. {
  181754. while (!png_ptr->idat_size)
  181755. {
  181756. png_byte chunk_length[4];
  181757. png_crc_finish(png_ptr, 0);
  181758. png_read_data(png_ptr, chunk_length, 4);
  181759. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  181760. png_reset_crc(png_ptr);
  181761. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  181762. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181763. png_error(png_ptr, "Not enough image data");
  181764. }
  181765. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  181766. png_ptr->zstream.next_in = png_ptr->zbuf;
  181767. if (png_ptr->zbuf_size > png_ptr->idat_size)
  181768. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  181769. png_crc_read(png_ptr, png_ptr->zbuf,
  181770. (png_size_t)png_ptr->zstream.avail_in);
  181771. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  181772. }
  181773. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  181774. if (ret == Z_STREAM_END)
  181775. {
  181776. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  181777. png_ptr->idat_size)
  181778. png_error(png_ptr, "Extra compressed data");
  181779. png_ptr->mode |= PNG_AFTER_IDAT;
  181780. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  181781. break;
  181782. }
  181783. if (ret != Z_OK)
  181784. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  181785. "Decompression error");
  181786. } while (png_ptr->zstream.avail_out);
  181787. png_ptr->row_info.color_type = png_ptr->color_type;
  181788. png_ptr->row_info.width = png_ptr->iwidth;
  181789. png_ptr->row_info.channels = png_ptr->channels;
  181790. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  181791. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  181792. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  181793. png_ptr->row_info.width);
  181794. if(png_ptr->row_buf[0])
  181795. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  181796. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  181797. (int)(png_ptr->row_buf[0]));
  181798. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  181799. png_ptr->rowbytes + 1);
  181800. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  181801. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  181802. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  181803. {
  181804. /* Intrapixel differencing */
  181805. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  181806. }
  181807. #endif
  181808. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  181809. png_do_read_transformations(png_ptr);
  181810. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  181811. /* blow up interlaced rows to full size */
  181812. if (png_ptr->interlaced &&
  181813. (png_ptr->transformations & PNG_INTERLACE))
  181814. {
  181815. if (png_ptr->pass < 6)
  181816. /* old interface (pre-1.0.9):
  181817. png_do_read_interlace(&(png_ptr->row_info),
  181818. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  181819. */
  181820. png_do_read_interlace(png_ptr);
  181821. if (dsp_row != NULL)
  181822. png_combine_row(png_ptr, dsp_row,
  181823. png_pass_dsp_mask[png_ptr->pass]);
  181824. if (row != NULL)
  181825. png_combine_row(png_ptr, row,
  181826. png_pass_mask[png_ptr->pass]);
  181827. }
  181828. else
  181829. #endif
  181830. {
  181831. if (row != NULL)
  181832. png_combine_row(png_ptr, row, 0xff);
  181833. if (dsp_row != NULL)
  181834. png_combine_row(png_ptr, dsp_row, 0xff);
  181835. }
  181836. png_read_finish_row(png_ptr);
  181837. if (png_ptr->read_row_fn != NULL)
  181838. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  181839. }
  181840. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181841. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181842. /* Read one or more rows of image data. If the image is interlaced,
  181843. * and png_set_interlace_handling() has been called, the rows need to
  181844. * contain the contents of the rows from the previous pass. If the
  181845. * image has alpha or transparency, and png_handle_alpha()[*] has been
  181846. * called, the rows contents must be initialized to the contents of the
  181847. * screen.
  181848. *
  181849. * "row" holds the actual image, and pixels are placed in it
  181850. * as they arrive. If the image is displayed after each pass, it will
  181851. * appear to "sparkle" in. "display_row" can be used to display a
  181852. * "chunky" progressive image, with finer detail added as it becomes
  181853. * available. If you do not want this "chunky" display, you may pass
  181854. * NULL for display_row. If you do not want the sparkle display, and
  181855. * you have not called png_handle_alpha(), you may pass NULL for rows.
  181856. * If you have called png_handle_alpha(), and the image has either an
  181857. * alpha channel or a transparency chunk, you must provide a buffer for
  181858. * rows. In this case, you do not have to provide a display_row buffer
  181859. * also, but you may. If the image is not interlaced, or if you have
  181860. * not called png_set_interlace_handling(), the display_row buffer will
  181861. * be ignored, so pass NULL to it.
  181862. *
  181863. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  181864. */
  181865. void PNGAPI
  181866. png_read_rows(png_structp png_ptr, png_bytepp row,
  181867. png_bytepp display_row, png_uint_32 num_rows)
  181868. {
  181869. png_uint_32 i;
  181870. png_bytepp rp;
  181871. png_bytepp dp;
  181872. png_debug(1, "in png_read_rows\n");
  181873. if(png_ptr == NULL) return;
  181874. rp = row;
  181875. dp = display_row;
  181876. if (rp != NULL && dp != NULL)
  181877. for (i = 0; i < num_rows; i++)
  181878. {
  181879. png_bytep rptr = *rp++;
  181880. png_bytep dptr = *dp++;
  181881. png_read_row(png_ptr, rptr, dptr);
  181882. }
  181883. else if(rp != NULL)
  181884. for (i = 0; i < num_rows; i++)
  181885. {
  181886. png_bytep rptr = *rp;
  181887. png_read_row(png_ptr, rptr, png_bytep_NULL);
  181888. rp++;
  181889. }
  181890. else if(dp != NULL)
  181891. for (i = 0; i < num_rows; i++)
  181892. {
  181893. png_bytep dptr = *dp;
  181894. png_read_row(png_ptr, png_bytep_NULL, dptr);
  181895. dp++;
  181896. }
  181897. }
  181898. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181899. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181900. /* Read the entire image. If the image has an alpha channel or a tRNS
  181901. * chunk, and you have called png_handle_alpha()[*], you will need to
  181902. * initialize the image to the current image that PNG will be overlaying.
  181903. * We set the num_rows again here, in case it was incorrectly set in
  181904. * png_read_start_row() by a call to png_read_update_info() or
  181905. * png_start_read_image() if png_set_interlace_handling() wasn't called
  181906. * prior to either of these functions like it should have been. You can
  181907. * only call this function once. If you desire to have an image for
  181908. * each pass of a interlaced image, use png_read_rows() instead.
  181909. *
  181910. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  181911. */
  181912. void PNGAPI
  181913. png_read_image(png_structp png_ptr, png_bytepp image)
  181914. {
  181915. png_uint_32 i,image_height;
  181916. int pass, j;
  181917. png_bytepp rp;
  181918. png_debug(1, "in png_read_image\n");
  181919. if(png_ptr == NULL) return;
  181920. #ifdef PNG_READ_INTERLACING_SUPPORTED
  181921. pass = png_set_interlace_handling(png_ptr);
  181922. #else
  181923. if (png_ptr->interlaced)
  181924. png_error(png_ptr,
  181925. "Cannot read interlaced image -- interlace handler disabled.");
  181926. pass = 1;
  181927. #endif
  181928. image_height=png_ptr->height;
  181929. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  181930. for (j = 0; j < pass; j++)
  181931. {
  181932. rp = image;
  181933. for (i = 0; i < image_height; i++)
  181934. {
  181935. png_read_row(png_ptr, *rp, png_bytep_NULL);
  181936. rp++;
  181937. }
  181938. }
  181939. }
  181940. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181941. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181942. /* Read the end of the PNG file. Will not read past the end of the
  181943. * file, will verify the end is accurate, and will read any comments
  181944. * or time information at the end of the file, if info is not NULL.
  181945. */
  181946. void PNGAPI
  181947. png_read_end(png_structp png_ptr, png_infop info_ptr)
  181948. {
  181949. png_byte chunk_length[4];
  181950. png_uint_32 length;
  181951. png_debug(1, "in png_read_end\n");
  181952. if(png_ptr == NULL) return;
  181953. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  181954. do
  181955. {
  181956. #ifdef PNG_USE_LOCAL_ARRAYS
  181957. PNG_CONST PNG_IHDR;
  181958. PNG_CONST PNG_IDAT;
  181959. PNG_CONST PNG_IEND;
  181960. PNG_CONST PNG_PLTE;
  181961. #if defined(PNG_READ_bKGD_SUPPORTED)
  181962. PNG_CONST PNG_bKGD;
  181963. #endif
  181964. #if defined(PNG_READ_cHRM_SUPPORTED)
  181965. PNG_CONST PNG_cHRM;
  181966. #endif
  181967. #if defined(PNG_READ_gAMA_SUPPORTED)
  181968. PNG_CONST PNG_gAMA;
  181969. #endif
  181970. #if defined(PNG_READ_hIST_SUPPORTED)
  181971. PNG_CONST PNG_hIST;
  181972. #endif
  181973. #if defined(PNG_READ_iCCP_SUPPORTED)
  181974. PNG_CONST PNG_iCCP;
  181975. #endif
  181976. #if defined(PNG_READ_iTXt_SUPPORTED)
  181977. PNG_CONST PNG_iTXt;
  181978. #endif
  181979. #if defined(PNG_READ_oFFs_SUPPORTED)
  181980. PNG_CONST PNG_oFFs;
  181981. #endif
  181982. #if defined(PNG_READ_pCAL_SUPPORTED)
  181983. PNG_CONST PNG_pCAL;
  181984. #endif
  181985. #if defined(PNG_READ_pHYs_SUPPORTED)
  181986. PNG_CONST PNG_pHYs;
  181987. #endif
  181988. #if defined(PNG_READ_sBIT_SUPPORTED)
  181989. PNG_CONST PNG_sBIT;
  181990. #endif
  181991. #if defined(PNG_READ_sCAL_SUPPORTED)
  181992. PNG_CONST PNG_sCAL;
  181993. #endif
  181994. #if defined(PNG_READ_sPLT_SUPPORTED)
  181995. PNG_CONST PNG_sPLT;
  181996. #endif
  181997. #if defined(PNG_READ_sRGB_SUPPORTED)
  181998. PNG_CONST PNG_sRGB;
  181999. #endif
  182000. #if defined(PNG_READ_tEXt_SUPPORTED)
  182001. PNG_CONST PNG_tEXt;
  182002. #endif
  182003. #if defined(PNG_READ_tIME_SUPPORTED)
  182004. PNG_CONST PNG_tIME;
  182005. #endif
  182006. #if defined(PNG_READ_tRNS_SUPPORTED)
  182007. PNG_CONST PNG_tRNS;
  182008. #endif
  182009. #if defined(PNG_READ_zTXt_SUPPORTED)
  182010. PNG_CONST PNG_zTXt;
  182011. #endif
  182012. #endif /* PNG_USE_LOCAL_ARRAYS */
  182013. png_read_data(png_ptr, chunk_length, 4);
  182014. length = png_get_uint_31(png_ptr,chunk_length);
  182015. png_reset_crc(png_ptr);
  182016. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  182017. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  182018. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  182019. png_handle_IHDR(png_ptr, info_ptr, length);
  182020. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  182021. png_handle_IEND(png_ptr, info_ptr, length);
  182022. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182023. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  182024. {
  182025. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182026. {
  182027. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  182028. png_error(png_ptr, "Too many IDAT's found");
  182029. }
  182030. png_handle_unknown(png_ptr, info_ptr, length);
  182031. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182032. png_ptr->mode |= PNG_HAVE_PLTE;
  182033. }
  182034. #endif
  182035. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182036. {
  182037. /* Zero length IDATs are legal after the last IDAT has been
  182038. * read, but not after other chunks have been read.
  182039. */
  182040. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  182041. png_error(png_ptr, "Too many IDAT's found");
  182042. png_crc_finish(png_ptr, length);
  182043. }
  182044. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182045. png_handle_PLTE(png_ptr, info_ptr, length);
  182046. #if defined(PNG_READ_bKGD_SUPPORTED)
  182047. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  182048. png_handle_bKGD(png_ptr, info_ptr, length);
  182049. #endif
  182050. #if defined(PNG_READ_cHRM_SUPPORTED)
  182051. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  182052. png_handle_cHRM(png_ptr, info_ptr, length);
  182053. #endif
  182054. #if defined(PNG_READ_gAMA_SUPPORTED)
  182055. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  182056. png_handle_gAMA(png_ptr, info_ptr, length);
  182057. #endif
  182058. #if defined(PNG_READ_hIST_SUPPORTED)
  182059. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  182060. png_handle_hIST(png_ptr, info_ptr, length);
  182061. #endif
  182062. #if defined(PNG_READ_oFFs_SUPPORTED)
  182063. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  182064. png_handle_oFFs(png_ptr, info_ptr, length);
  182065. #endif
  182066. #if defined(PNG_READ_pCAL_SUPPORTED)
  182067. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  182068. png_handle_pCAL(png_ptr, info_ptr, length);
  182069. #endif
  182070. #if defined(PNG_READ_sCAL_SUPPORTED)
  182071. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  182072. png_handle_sCAL(png_ptr, info_ptr, length);
  182073. #endif
  182074. #if defined(PNG_READ_pHYs_SUPPORTED)
  182075. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  182076. png_handle_pHYs(png_ptr, info_ptr, length);
  182077. #endif
  182078. #if defined(PNG_READ_sBIT_SUPPORTED)
  182079. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  182080. png_handle_sBIT(png_ptr, info_ptr, length);
  182081. #endif
  182082. #if defined(PNG_READ_sRGB_SUPPORTED)
  182083. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  182084. png_handle_sRGB(png_ptr, info_ptr, length);
  182085. #endif
  182086. #if defined(PNG_READ_iCCP_SUPPORTED)
  182087. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  182088. png_handle_iCCP(png_ptr, info_ptr, length);
  182089. #endif
  182090. #if defined(PNG_READ_sPLT_SUPPORTED)
  182091. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  182092. png_handle_sPLT(png_ptr, info_ptr, length);
  182093. #endif
  182094. #if defined(PNG_READ_tEXt_SUPPORTED)
  182095. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  182096. png_handle_tEXt(png_ptr, info_ptr, length);
  182097. #endif
  182098. #if defined(PNG_READ_tIME_SUPPORTED)
  182099. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  182100. png_handle_tIME(png_ptr, info_ptr, length);
  182101. #endif
  182102. #if defined(PNG_READ_tRNS_SUPPORTED)
  182103. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  182104. png_handle_tRNS(png_ptr, info_ptr, length);
  182105. #endif
  182106. #if defined(PNG_READ_zTXt_SUPPORTED)
  182107. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  182108. png_handle_zTXt(png_ptr, info_ptr, length);
  182109. #endif
  182110. #if defined(PNG_READ_iTXt_SUPPORTED)
  182111. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  182112. png_handle_iTXt(png_ptr, info_ptr, length);
  182113. #endif
  182114. else
  182115. png_handle_unknown(png_ptr, info_ptr, length);
  182116. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  182117. }
  182118. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182119. /* free all memory used by the read */
  182120. void PNGAPI
  182121. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  182122. png_infopp end_info_ptr_ptr)
  182123. {
  182124. png_structp png_ptr = NULL;
  182125. png_infop info_ptr = NULL, end_info_ptr = NULL;
  182126. #ifdef PNG_USER_MEM_SUPPORTED
  182127. png_free_ptr free_fn;
  182128. png_voidp mem_ptr;
  182129. #endif
  182130. png_debug(1, "in png_destroy_read_struct\n");
  182131. if (png_ptr_ptr != NULL)
  182132. png_ptr = *png_ptr_ptr;
  182133. if (info_ptr_ptr != NULL)
  182134. info_ptr = *info_ptr_ptr;
  182135. if (end_info_ptr_ptr != NULL)
  182136. end_info_ptr = *end_info_ptr_ptr;
  182137. #ifdef PNG_USER_MEM_SUPPORTED
  182138. free_fn = png_ptr->free_fn;
  182139. mem_ptr = png_ptr->mem_ptr;
  182140. #endif
  182141. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  182142. if (info_ptr != NULL)
  182143. {
  182144. #if defined(PNG_TEXT_SUPPORTED)
  182145. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  182146. #endif
  182147. #ifdef PNG_USER_MEM_SUPPORTED
  182148. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  182149. (png_voidp)mem_ptr);
  182150. #else
  182151. png_destroy_struct((png_voidp)info_ptr);
  182152. #endif
  182153. *info_ptr_ptr = NULL;
  182154. }
  182155. if (end_info_ptr != NULL)
  182156. {
  182157. #if defined(PNG_READ_TEXT_SUPPORTED)
  182158. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  182159. #endif
  182160. #ifdef PNG_USER_MEM_SUPPORTED
  182161. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  182162. (png_voidp)mem_ptr);
  182163. #else
  182164. png_destroy_struct((png_voidp)end_info_ptr);
  182165. #endif
  182166. *end_info_ptr_ptr = NULL;
  182167. }
  182168. if (png_ptr != NULL)
  182169. {
  182170. #ifdef PNG_USER_MEM_SUPPORTED
  182171. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  182172. (png_voidp)mem_ptr);
  182173. #else
  182174. png_destroy_struct((png_voidp)png_ptr);
  182175. #endif
  182176. *png_ptr_ptr = NULL;
  182177. }
  182178. }
  182179. /* free all memory used by the read (old method) */
  182180. void /* PRIVATE */
  182181. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  182182. {
  182183. #ifdef PNG_SETJMP_SUPPORTED
  182184. jmp_buf tmp_jmp;
  182185. #endif
  182186. png_error_ptr error_fn;
  182187. png_error_ptr warning_fn;
  182188. png_voidp error_ptr;
  182189. #ifdef PNG_USER_MEM_SUPPORTED
  182190. png_free_ptr free_fn;
  182191. #endif
  182192. png_debug(1, "in png_read_destroy\n");
  182193. if (info_ptr != NULL)
  182194. png_info_destroy(png_ptr, info_ptr);
  182195. if (end_info_ptr != NULL)
  182196. png_info_destroy(png_ptr, end_info_ptr);
  182197. png_free(png_ptr, png_ptr->zbuf);
  182198. png_free(png_ptr, png_ptr->big_row_buf);
  182199. png_free(png_ptr, png_ptr->prev_row);
  182200. #if defined(PNG_READ_DITHER_SUPPORTED)
  182201. png_free(png_ptr, png_ptr->palette_lookup);
  182202. png_free(png_ptr, png_ptr->dither_index);
  182203. #endif
  182204. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182205. png_free(png_ptr, png_ptr->gamma_table);
  182206. #endif
  182207. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182208. png_free(png_ptr, png_ptr->gamma_from_1);
  182209. png_free(png_ptr, png_ptr->gamma_to_1);
  182210. #endif
  182211. #ifdef PNG_FREE_ME_SUPPORTED
  182212. if (png_ptr->free_me & PNG_FREE_PLTE)
  182213. png_zfree(png_ptr, png_ptr->palette);
  182214. png_ptr->free_me &= ~PNG_FREE_PLTE;
  182215. #else
  182216. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  182217. png_zfree(png_ptr, png_ptr->palette);
  182218. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  182219. #endif
  182220. #if defined(PNG_tRNS_SUPPORTED) || \
  182221. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182222. #ifdef PNG_FREE_ME_SUPPORTED
  182223. if (png_ptr->free_me & PNG_FREE_TRNS)
  182224. png_free(png_ptr, png_ptr->trans);
  182225. png_ptr->free_me &= ~PNG_FREE_TRNS;
  182226. #else
  182227. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  182228. png_free(png_ptr, png_ptr->trans);
  182229. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  182230. #endif
  182231. #endif
  182232. #if defined(PNG_READ_hIST_SUPPORTED)
  182233. #ifdef PNG_FREE_ME_SUPPORTED
  182234. if (png_ptr->free_me & PNG_FREE_HIST)
  182235. png_free(png_ptr, png_ptr->hist);
  182236. png_ptr->free_me &= ~PNG_FREE_HIST;
  182237. #else
  182238. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  182239. png_free(png_ptr, png_ptr->hist);
  182240. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  182241. #endif
  182242. #endif
  182243. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182244. if (png_ptr->gamma_16_table != NULL)
  182245. {
  182246. int i;
  182247. int istop = (1 << (8 - png_ptr->gamma_shift));
  182248. for (i = 0; i < istop; i++)
  182249. {
  182250. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  182251. }
  182252. png_free(png_ptr, png_ptr->gamma_16_table);
  182253. }
  182254. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182255. if (png_ptr->gamma_16_from_1 != NULL)
  182256. {
  182257. int i;
  182258. int istop = (1 << (8 - png_ptr->gamma_shift));
  182259. for (i = 0; i < istop; i++)
  182260. {
  182261. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  182262. }
  182263. png_free(png_ptr, png_ptr->gamma_16_from_1);
  182264. }
  182265. if (png_ptr->gamma_16_to_1 != NULL)
  182266. {
  182267. int i;
  182268. int istop = (1 << (8 - png_ptr->gamma_shift));
  182269. for (i = 0; i < istop; i++)
  182270. {
  182271. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  182272. }
  182273. png_free(png_ptr, png_ptr->gamma_16_to_1);
  182274. }
  182275. #endif
  182276. #endif
  182277. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182278. png_free(png_ptr, png_ptr->time_buffer);
  182279. #endif
  182280. inflateEnd(&png_ptr->zstream);
  182281. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182282. png_free(png_ptr, png_ptr->save_buffer);
  182283. #endif
  182284. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182285. #ifdef PNG_TEXT_SUPPORTED
  182286. png_free(png_ptr, png_ptr->current_text);
  182287. #endif /* PNG_TEXT_SUPPORTED */
  182288. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182289. /* Save the important info out of the png_struct, in case it is
  182290. * being used again.
  182291. */
  182292. #ifdef PNG_SETJMP_SUPPORTED
  182293. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  182294. #endif
  182295. error_fn = png_ptr->error_fn;
  182296. warning_fn = png_ptr->warning_fn;
  182297. error_ptr = png_ptr->error_ptr;
  182298. #ifdef PNG_USER_MEM_SUPPORTED
  182299. free_fn = png_ptr->free_fn;
  182300. #endif
  182301. png_memset(png_ptr, 0, png_sizeof (png_struct));
  182302. png_ptr->error_fn = error_fn;
  182303. png_ptr->warning_fn = warning_fn;
  182304. png_ptr->error_ptr = error_ptr;
  182305. #ifdef PNG_USER_MEM_SUPPORTED
  182306. png_ptr->free_fn = free_fn;
  182307. #endif
  182308. #ifdef PNG_SETJMP_SUPPORTED
  182309. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  182310. #endif
  182311. }
  182312. void PNGAPI
  182313. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  182314. {
  182315. if(png_ptr == NULL) return;
  182316. png_ptr->read_row_fn = read_row_fn;
  182317. }
  182318. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182319. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182320. void PNGAPI
  182321. png_read_png(png_structp png_ptr, png_infop info_ptr,
  182322. int transforms,
  182323. voidp params)
  182324. {
  182325. int row;
  182326. if(png_ptr == NULL) return;
  182327. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  182328. /* invert the alpha channel from opacity to transparency
  182329. */
  182330. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  182331. png_set_invert_alpha(png_ptr);
  182332. #endif
  182333. /* png_read_info() gives us all of the information from the
  182334. * PNG file before the first IDAT (image data chunk).
  182335. */
  182336. png_read_info(png_ptr, info_ptr);
  182337. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  182338. png_error(png_ptr,"Image is too high to process with png_read_png()");
  182339. /* -------------- image transformations start here ------------------- */
  182340. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182341. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  182342. */
  182343. if (transforms & PNG_TRANSFORM_STRIP_16)
  182344. png_set_strip_16(png_ptr);
  182345. #endif
  182346. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182347. /* Strip alpha bytes from the input data without combining with
  182348. * the background (not recommended).
  182349. */
  182350. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  182351. png_set_strip_alpha(png_ptr);
  182352. #endif
  182353. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  182354. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  182355. * byte into separate bytes (useful for paletted and grayscale images).
  182356. */
  182357. if (transforms & PNG_TRANSFORM_PACKING)
  182358. png_set_packing(png_ptr);
  182359. #endif
  182360. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  182361. /* Change the order of packed pixels to least significant bit first
  182362. * (not useful if you are using png_set_packing).
  182363. */
  182364. if (transforms & PNG_TRANSFORM_PACKSWAP)
  182365. png_set_packswap(png_ptr);
  182366. #endif
  182367. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182368. /* Expand paletted colors into true RGB triplets
  182369. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  182370. * Expand paletted or RGB images with transparency to full alpha
  182371. * channels so the data will be available as RGBA quartets.
  182372. */
  182373. if (transforms & PNG_TRANSFORM_EXPAND)
  182374. if ((png_ptr->bit_depth < 8) ||
  182375. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  182376. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  182377. png_set_expand(png_ptr);
  182378. #endif
  182379. /* We don't handle background color or gamma transformation or dithering.
  182380. */
  182381. #if defined(PNG_READ_INVERT_SUPPORTED)
  182382. /* invert monochrome files to have 0 as white and 1 as black
  182383. */
  182384. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  182385. png_set_invert_mono(png_ptr);
  182386. #endif
  182387. #if defined(PNG_READ_SHIFT_SUPPORTED)
  182388. /* If you want to shift the pixel values from the range [0,255] or
  182389. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  182390. * colors were originally in:
  182391. */
  182392. if ((transforms & PNG_TRANSFORM_SHIFT)
  182393. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  182394. {
  182395. png_color_8p sig_bit;
  182396. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  182397. png_set_shift(png_ptr, sig_bit);
  182398. }
  182399. #endif
  182400. #if defined(PNG_READ_BGR_SUPPORTED)
  182401. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  182402. */
  182403. if (transforms & PNG_TRANSFORM_BGR)
  182404. png_set_bgr(png_ptr);
  182405. #endif
  182406. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  182407. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  182408. */
  182409. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  182410. png_set_swap_alpha(png_ptr);
  182411. #endif
  182412. #if defined(PNG_READ_SWAP_SUPPORTED)
  182413. /* swap bytes of 16 bit files to least significant byte first
  182414. */
  182415. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  182416. png_set_swap(png_ptr);
  182417. #endif
  182418. /* We don't handle adding filler bytes */
  182419. /* Optional call to gamma correct and add the background to the palette
  182420. * and update info structure. REQUIRED if you are expecting libpng to
  182421. * update the palette for you (i.e., you selected such a transform above).
  182422. */
  182423. png_read_update_info(png_ptr, info_ptr);
  182424. /* -------------- image transformations end here ------------------- */
  182425. #ifdef PNG_FREE_ME_SUPPORTED
  182426. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  182427. #endif
  182428. if(info_ptr->row_pointers == NULL)
  182429. {
  182430. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  182431. info_ptr->height * png_sizeof(png_bytep));
  182432. #ifdef PNG_FREE_ME_SUPPORTED
  182433. info_ptr->free_me |= PNG_FREE_ROWS;
  182434. #endif
  182435. for (row = 0; row < (int)info_ptr->height; row++)
  182436. {
  182437. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  182438. png_get_rowbytes(png_ptr, info_ptr));
  182439. }
  182440. }
  182441. png_read_image(png_ptr, info_ptr->row_pointers);
  182442. info_ptr->valid |= PNG_INFO_IDAT;
  182443. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  182444. png_read_end(png_ptr, info_ptr);
  182445. transforms = transforms; /* quiet compiler warnings */
  182446. params = params;
  182447. }
  182448. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  182449. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  182450. #endif /* PNG_READ_SUPPORTED */
  182451. /********* End of inlined file: pngread.c *********/
  182452. /********* Start of inlined file: pngpread.c *********/
  182453. /* pngpread.c - read a png file in push mode
  182454. *
  182455. * Last changed in libpng 1.2.21 October 4, 2007
  182456. * For conditions of distribution and use, see copyright notice in png.h
  182457. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  182458. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182459. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182460. */
  182461. #define PNG_INTERNAL
  182462. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182463. /* push model modes */
  182464. #define PNG_READ_SIG_MODE 0
  182465. #define PNG_READ_CHUNK_MODE 1
  182466. #define PNG_READ_IDAT_MODE 2
  182467. #define PNG_SKIP_MODE 3
  182468. #define PNG_READ_tEXt_MODE 4
  182469. #define PNG_READ_zTXt_MODE 5
  182470. #define PNG_READ_DONE_MODE 6
  182471. #define PNG_READ_iTXt_MODE 7
  182472. #define PNG_ERROR_MODE 8
  182473. void PNGAPI
  182474. png_process_data(png_structp png_ptr, png_infop info_ptr,
  182475. png_bytep buffer, png_size_t buffer_size)
  182476. {
  182477. if(png_ptr == NULL) return;
  182478. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  182479. while (png_ptr->buffer_size)
  182480. {
  182481. png_process_some_data(png_ptr, info_ptr);
  182482. }
  182483. }
  182484. /* What we do with the incoming data depends on what we were previously
  182485. * doing before we ran out of data...
  182486. */
  182487. void /* PRIVATE */
  182488. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  182489. {
  182490. if(png_ptr == NULL) return;
  182491. switch (png_ptr->process_mode)
  182492. {
  182493. case PNG_READ_SIG_MODE:
  182494. {
  182495. png_push_read_sig(png_ptr, info_ptr);
  182496. break;
  182497. }
  182498. case PNG_READ_CHUNK_MODE:
  182499. {
  182500. png_push_read_chunk(png_ptr, info_ptr);
  182501. break;
  182502. }
  182503. case PNG_READ_IDAT_MODE:
  182504. {
  182505. png_push_read_IDAT(png_ptr);
  182506. break;
  182507. }
  182508. #if defined(PNG_READ_tEXt_SUPPORTED)
  182509. case PNG_READ_tEXt_MODE:
  182510. {
  182511. png_push_read_tEXt(png_ptr, info_ptr);
  182512. break;
  182513. }
  182514. #endif
  182515. #if defined(PNG_READ_zTXt_SUPPORTED)
  182516. case PNG_READ_zTXt_MODE:
  182517. {
  182518. png_push_read_zTXt(png_ptr, info_ptr);
  182519. break;
  182520. }
  182521. #endif
  182522. #if defined(PNG_READ_iTXt_SUPPORTED)
  182523. case PNG_READ_iTXt_MODE:
  182524. {
  182525. png_push_read_iTXt(png_ptr, info_ptr);
  182526. break;
  182527. }
  182528. #endif
  182529. case PNG_SKIP_MODE:
  182530. {
  182531. png_push_crc_finish(png_ptr);
  182532. break;
  182533. }
  182534. default:
  182535. {
  182536. png_ptr->buffer_size = 0;
  182537. break;
  182538. }
  182539. }
  182540. }
  182541. /* Read any remaining signature bytes from the stream and compare them with
  182542. * the correct PNG signature. It is possible that this routine is called
  182543. * with bytes already read from the signature, either because they have been
  182544. * checked by the calling application, or because of multiple calls to this
  182545. * routine.
  182546. */
  182547. void /* PRIVATE */
  182548. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  182549. {
  182550. png_size_t num_checked = png_ptr->sig_bytes,
  182551. num_to_check = 8 - num_checked;
  182552. if (png_ptr->buffer_size < num_to_check)
  182553. {
  182554. num_to_check = png_ptr->buffer_size;
  182555. }
  182556. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  182557. num_to_check);
  182558. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  182559. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  182560. {
  182561. if (num_checked < 4 &&
  182562. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  182563. png_error(png_ptr, "Not a PNG file");
  182564. else
  182565. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  182566. }
  182567. else
  182568. {
  182569. if (png_ptr->sig_bytes >= 8)
  182570. {
  182571. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  182572. }
  182573. }
  182574. }
  182575. void /* PRIVATE */
  182576. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  182577. {
  182578. #ifdef PNG_USE_LOCAL_ARRAYS
  182579. PNG_CONST PNG_IHDR;
  182580. PNG_CONST PNG_IDAT;
  182581. PNG_CONST PNG_IEND;
  182582. PNG_CONST PNG_PLTE;
  182583. #if defined(PNG_READ_bKGD_SUPPORTED)
  182584. PNG_CONST PNG_bKGD;
  182585. #endif
  182586. #if defined(PNG_READ_cHRM_SUPPORTED)
  182587. PNG_CONST PNG_cHRM;
  182588. #endif
  182589. #if defined(PNG_READ_gAMA_SUPPORTED)
  182590. PNG_CONST PNG_gAMA;
  182591. #endif
  182592. #if defined(PNG_READ_hIST_SUPPORTED)
  182593. PNG_CONST PNG_hIST;
  182594. #endif
  182595. #if defined(PNG_READ_iCCP_SUPPORTED)
  182596. PNG_CONST PNG_iCCP;
  182597. #endif
  182598. #if defined(PNG_READ_iTXt_SUPPORTED)
  182599. PNG_CONST PNG_iTXt;
  182600. #endif
  182601. #if defined(PNG_READ_oFFs_SUPPORTED)
  182602. PNG_CONST PNG_oFFs;
  182603. #endif
  182604. #if defined(PNG_READ_pCAL_SUPPORTED)
  182605. PNG_CONST PNG_pCAL;
  182606. #endif
  182607. #if defined(PNG_READ_pHYs_SUPPORTED)
  182608. PNG_CONST PNG_pHYs;
  182609. #endif
  182610. #if defined(PNG_READ_sBIT_SUPPORTED)
  182611. PNG_CONST PNG_sBIT;
  182612. #endif
  182613. #if defined(PNG_READ_sCAL_SUPPORTED)
  182614. PNG_CONST PNG_sCAL;
  182615. #endif
  182616. #if defined(PNG_READ_sRGB_SUPPORTED)
  182617. PNG_CONST PNG_sRGB;
  182618. #endif
  182619. #if defined(PNG_READ_sPLT_SUPPORTED)
  182620. PNG_CONST PNG_sPLT;
  182621. #endif
  182622. #if defined(PNG_READ_tEXt_SUPPORTED)
  182623. PNG_CONST PNG_tEXt;
  182624. #endif
  182625. #if defined(PNG_READ_tIME_SUPPORTED)
  182626. PNG_CONST PNG_tIME;
  182627. #endif
  182628. #if defined(PNG_READ_tRNS_SUPPORTED)
  182629. PNG_CONST PNG_tRNS;
  182630. #endif
  182631. #if defined(PNG_READ_zTXt_SUPPORTED)
  182632. PNG_CONST PNG_zTXt;
  182633. #endif
  182634. #endif /* PNG_USE_LOCAL_ARRAYS */
  182635. /* First we make sure we have enough data for the 4 byte chunk name
  182636. * and the 4 byte chunk length before proceeding with decoding the
  182637. * chunk data. To fully decode each of these chunks, we also make
  182638. * sure we have enough data in the buffer for the 4 byte CRC at the
  182639. * end of every chunk (except IDAT, which is handled separately).
  182640. */
  182641. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  182642. {
  182643. png_byte chunk_length[4];
  182644. if (png_ptr->buffer_size < 8)
  182645. {
  182646. png_push_save_buffer(png_ptr);
  182647. return;
  182648. }
  182649. png_push_fill_buffer(png_ptr, chunk_length, 4);
  182650. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  182651. png_reset_crc(png_ptr);
  182652. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  182653. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  182654. }
  182655. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182656. if(png_ptr->mode & PNG_AFTER_IDAT)
  182657. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  182658. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  182659. {
  182660. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182661. {
  182662. png_push_save_buffer(png_ptr);
  182663. return;
  182664. }
  182665. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  182666. }
  182667. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  182668. {
  182669. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182670. {
  182671. png_push_save_buffer(png_ptr);
  182672. return;
  182673. }
  182674. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  182675. png_ptr->process_mode = PNG_READ_DONE_MODE;
  182676. png_push_have_end(png_ptr, info_ptr);
  182677. }
  182678. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182679. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  182680. {
  182681. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182682. {
  182683. png_push_save_buffer(png_ptr);
  182684. return;
  182685. }
  182686. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182687. png_ptr->mode |= PNG_HAVE_IDAT;
  182688. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  182689. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182690. png_ptr->mode |= PNG_HAVE_PLTE;
  182691. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182692. {
  182693. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  182694. png_error(png_ptr, "Missing IHDR before IDAT");
  182695. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  182696. !(png_ptr->mode & PNG_HAVE_PLTE))
  182697. png_error(png_ptr, "Missing PLTE before IDAT");
  182698. }
  182699. }
  182700. #endif
  182701. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182702. {
  182703. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182704. {
  182705. png_push_save_buffer(png_ptr);
  182706. return;
  182707. }
  182708. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  182709. }
  182710. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182711. {
  182712. /* If we reach an IDAT chunk, this means we have read all of the
  182713. * header chunks, and we can start reading the image (or if this
  182714. * is called after the image has been read - we have an error).
  182715. */
  182716. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  182717. png_error(png_ptr, "Missing IHDR before IDAT");
  182718. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  182719. !(png_ptr->mode & PNG_HAVE_PLTE))
  182720. png_error(png_ptr, "Missing PLTE before IDAT");
  182721. if (png_ptr->mode & PNG_HAVE_IDAT)
  182722. {
  182723. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  182724. if (png_ptr->push_length == 0)
  182725. return;
  182726. if (png_ptr->mode & PNG_AFTER_IDAT)
  182727. png_error(png_ptr, "Too many IDAT's found");
  182728. }
  182729. png_ptr->idat_size = png_ptr->push_length;
  182730. png_ptr->mode |= PNG_HAVE_IDAT;
  182731. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  182732. png_push_have_info(png_ptr, info_ptr);
  182733. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  182734. png_ptr->zstream.next_out = png_ptr->row_buf;
  182735. return;
  182736. }
  182737. #if defined(PNG_READ_gAMA_SUPPORTED)
  182738. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  182739. {
  182740. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182741. {
  182742. png_push_save_buffer(png_ptr);
  182743. return;
  182744. }
  182745. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  182746. }
  182747. #endif
  182748. #if defined(PNG_READ_sBIT_SUPPORTED)
  182749. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  182750. {
  182751. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182752. {
  182753. png_push_save_buffer(png_ptr);
  182754. return;
  182755. }
  182756. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  182757. }
  182758. #endif
  182759. #if defined(PNG_READ_cHRM_SUPPORTED)
  182760. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  182761. {
  182762. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182763. {
  182764. png_push_save_buffer(png_ptr);
  182765. return;
  182766. }
  182767. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  182768. }
  182769. #endif
  182770. #if defined(PNG_READ_sRGB_SUPPORTED)
  182771. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  182772. {
  182773. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182774. {
  182775. png_push_save_buffer(png_ptr);
  182776. return;
  182777. }
  182778. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  182779. }
  182780. #endif
  182781. #if defined(PNG_READ_iCCP_SUPPORTED)
  182782. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  182783. {
  182784. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182785. {
  182786. png_push_save_buffer(png_ptr);
  182787. return;
  182788. }
  182789. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  182790. }
  182791. #endif
  182792. #if defined(PNG_READ_sPLT_SUPPORTED)
  182793. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  182794. {
  182795. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182796. {
  182797. png_push_save_buffer(png_ptr);
  182798. return;
  182799. }
  182800. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  182801. }
  182802. #endif
  182803. #if defined(PNG_READ_tRNS_SUPPORTED)
  182804. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  182805. {
  182806. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182807. {
  182808. png_push_save_buffer(png_ptr);
  182809. return;
  182810. }
  182811. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  182812. }
  182813. #endif
  182814. #if defined(PNG_READ_bKGD_SUPPORTED)
  182815. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  182816. {
  182817. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182818. {
  182819. png_push_save_buffer(png_ptr);
  182820. return;
  182821. }
  182822. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  182823. }
  182824. #endif
  182825. #if defined(PNG_READ_hIST_SUPPORTED)
  182826. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  182827. {
  182828. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182829. {
  182830. png_push_save_buffer(png_ptr);
  182831. return;
  182832. }
  182833. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  182834. }
  182835. #endif
  182836. #if defined(PNG_READ_pHYs_SUPPORTED)
  182837. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  182838. {
  182839. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182840. {
  182841. png_push_save_buffer(png_ptr);
  182842. return;
  182843. }
  182844. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  182845. }
  182846. #endif
  182847. #if defined(PNG_READ_oFFs_SUPPORTED)
  182848. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  182849. {
  182850. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182851. {
  182852. png_push_save_buffer(png_ptr);
  182853. return;
  182854. }
  182855. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  182856. }
  182857. #endif
  182858. #if defined(PNG_READ_pCAL_SUPPORTED)
  182859. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  182860. {
  182861. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182862. {
  182863. png_push_save_buffer(png_ptr);
  182864. return;
  182865. }
  182866. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  182867. }
  182868. #endif
  182869. #if defined(PNG_READ_sCAL_SUPPORTED)
  182870. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  182871. {
  182872. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182873. {
  182874. png_push_save_buffer(png_ptr);
  182875. return;
  182876. }
  182877. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  182878. }
  182879. #endif
  182880. #if defined(PNG_READ_tIME_SUPPORTED)
  182881. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  182882. {
  182883. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182884. {
  182885. png_push_save_buffer(png_ptr);
  182886. return;
  182887. }
  182888. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  182889. }
  182890. #endif
  182891. #if defined(PNG_READ_tEXt_SUPPORTED)
  182892. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  182893. {
  182894. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182895. {
  182896. png_push_save_buffer(png_ptr);
  182897. return;
  182898. }
  182899. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  182900. }
  182901. #endif
  182902. #if defined(PNG_READ_zTXt_SUPPORTED)
  182903. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  182904. {
  182905. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182906. {
  182907. png_push_save_buffer(png_ptr);
  182908. return;
  182909. }
  182910. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  182911. }
  182912. #endif
  182913. #if defined(PNG_READ_iTXt_SUPPORTED)
  182914. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  182915. {
  182916. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182917. {
  182918. png_push_save_buffer(png_ptr);
  182919. return;
  182920. }
  182921. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  182922. }
  182923. #endif
  182924. else
  182925. {
  182926. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182927. {
  182928. png_push_save_buffer(png_ptr);
  182929. return;
  182930. }
  182931. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  182932. }
  182933. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  182934. }
  182935. void /* PRIVATE */
  182936. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  182937. {
  182938. png_ptr->process_mode = PNG_SKIP_MODE;
  182939. png_ptr->skip_length = skip;
  182940. }
  182941. void /* PRIVATE */
  182942. png_push_crc_finish(png_structp png_ptr)
  182943. {
  182944. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  182945. {
  182946. png_size_t save_size;
  182947. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  182948. save_size = (png_size_t)png_ptr->skip_length;
  182949. else
  182950. save_size = png_ptr->save_buffer_size;
  182951. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  182952. png_ptr->skip_length -= save_size;
  182953. png_ptr->buffer_size -= save_size;
  182954. png_ptr->save_buffer_size -= save_size;
  182955. png_ptr->save_buffer_ptr += save_size;
  182956. }
  182957. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  182958. {
  182959. png_size_t save_size;
  182960. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  182961. save_size = (png_size_t)png_ptr->skip_length;
  182962. else
  182963. save_size = png_ptr->current_buffer_size;
  182964. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  182965. png_ptr->skip_length -= save_size;
  182966. png_ptr->buffer_size -= save_size;
  182967. png_ptr->current_buffer_size -= save_size;
  182968. png_ptr->current_buffer_ptr += save_size;
  182969. }
  182970. if (!png_ptr->skip_length)
  182971. {
  182972. if (png_ptr->buffer_size < 4)
  182973. {
  182974. png_push_save_buffer(png_ptr);
  182975. return;
  182976. }
  182977. png_crc_finish(png_ptr, 0);
  182978. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  182979. }
  182980. }
  182981. void PNGAPI
  182982. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  182983. {
  182984. png_bytep ptr;
  182985. if(png_ptr == NULL) return;
  182986. ptr = buffer;
  182987. if (png_ptr->save_buffer_size)
  182988. {
  182989. png_size_t save_size;
  182990. if (length < png_ptr->save_buffer_size)
  182991. save_size = length;
  182992. else
  182993. save_size = png_ptr->save_buffer_size;
  182994. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  182995. length -= save_size;
  182996. ptr += save_size;
  182997. png_ptr->buffer_size -= save_size;
  182998. png_ptr->save_buffer_size -= save_size;
  182999. png_ptr->save_buffer_ptr += save_size;
  183000. }
  183001. if (length && png_ptr->current_buffer_size)
  183002. {
  183003. png_size_t save_size;
  183004. if (length < png_ptr->current_buffer_size)
  183005. save_size = length;
  183006. else
  183007. save_size = png_ptr->current_buffer_size;
  183008. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  183009. png_ptr->buffer_size -= save_size;
  183010. png_ptr->current_buffer_size -= save_size;
  183011. png_ptr->current_buffer_ptr += save_size;
  183012. }
  183013. }
  183014. void /* PRIVATE */
  183015. png_push_save_buffer(png_structp png_ptr)
  183016. {
  183017. if (png_ptr->save_buffer_size)
  183018. {
  183019. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  183020. {
  183021. png_size_t i,istop;
  183022. png_bytep sp;
  183023. png_bytep dp;
  183024. istop = png_ptr->save_buffer_size;
  183025. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  183026. i < istop; i++, sp++, dp++)
  183027. {
  183028. *dp = *sp;
  183029. }
  183030. }
  183031. }
  183032. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  183033. png_ptr->save_buffer_max)
  183034. {
  183035. png_size_t new_max;
  183036. png_bytep old_buffer;
  183037. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  183038. (png_ptr->current_buffer_size + 256))
  183039. {
  183040. png_error(png_ptr, "Potential overflow of save_buffer");
  183041. }
  183042. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  183043. old_buffer = png_ptr->save_buffer;
  183044. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  183045. (png_uint_32)new_max);
  183046. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  183047. png_free(png_ptr, old_buffer);
  183048. png_ptr->save_buffer_max = new_max;
  183049. }
  183050. if (png_ptr->current_buffer_size)
  183051. {
  183052. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  183053. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  183054. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  183055. png_ptr->current_buffer_size = 0;
  183056. }
  183057. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  183058. png_ptr->buffer_size = 0;
  183059. }
  183060. void /* PRIVATE */
  183061. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  183062. png_size_t buffer_length)
  183063. {
  183064. png_ptr->current_buffer = buffer;
  183065. png_ptr->current_buffer_size = buffer_length;
  183066. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  183067. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  183068. }
  183069. void /* PRIVATE */
  183070. png_push_read_IDAT(png_structp png_ptr)
  183071. {
  183072. #ifdef PNG_USE_LOCAL_ARRAYS
  183073. PNG_CONST PNG_IDAT;
  183074. #endif
  183075. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  183076. {
  183077. png_byte chunk_length[4];
  183078. if (png_ptr->buffer_size < 8)
  183079. {
  183080. png_push_save_buffer(png_ptr);
  183081. return;
  183082. }
  183083. png_push_fill_buffer(png_ptr, chunk_length, 4);
  183084. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  183085. png_reset_crc(png_ptr);
  183086. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183087. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  183088. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183089. {
  183090. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  183091. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  183092. png_error(png_ptr, "Not enough compressed data");
  183093. return;
  183094. }
  183095. png_ptr->idat_size = png_ptr->push_length;
  183096. }
  183097. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  183098. {
  183099. png_size_t save_size;
  183100. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  183101. {
  183102. save_size = (png_size_t)png_ptr->idat_size;
  183103. /* check for overflow */
  183104. if((png_uint_32)save_size != png_ptr->idat_size)
  183105. png_error(png_ptr, "save_size overflowed in pngpread");
  183106. }
  183107. else
  183108. save_size = png_ptr->save_buffer_size;
  183109. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  183110. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  183111. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  183112. png_ptr->idat_size -= save_size;
  183113. png_ptr->buffer_size -= save_size;
  183114. png_ptr->save_buffer_size -= save_size;
  183115. png_ptr->save_buffer_ptr += save_size;
  183116. }
  183117. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  183118. {
  183119. png_size_t save_size;
  183120. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  183121. {
  183122. save_size = (png_size_t)png_ptr->idat_size;
  183123. /* check for overflow */
  183124. if((png_uint_32)save_size != png_ptr->idat_size)
  183125. png_error(png_ptr, "save_size overflowed in pngpread");
  183126. }
  183127. else
  183128. save_size = png_ptr->current_buffer_size;
  183129. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  183130. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  183131. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  183132. png_ptr->idat_size -= save_size;
  183133. png_ptr->buffer_size -= save_size;
  183134. png_ptr->current_buffer_size -= save_size;
  183135. png_ptr->current_buffer_ptr += save_size;
  183136. }
  183137. if (!png_ptr->idat_size)
  183138. {
  183139. if (png_ptr->buffer_size < 4)
  183140. {
  183141. png_push_save_buffer(png_ptr);
  183142. return;
  183143. }
  183144. png_crc_finish(png_ptr, 0);
  183145. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  183146. png_ptr->mode |= PNG_AFTER_IDAT;
  183147. }
  183148. }
  183149. void /* PRIVATE */
  183150. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  183151. png_size_t buffer_length)
  183152. {
  183153. int ret;
  183154. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  183155. png_error(png_ptr, "Extra compression data");
  183156. png_ptr->zstream.next_in = buffer;
  183157. png_ptr->zstream.avail_in = (uInt)buffer_length;
  183158. for(;;)
  183159. {
  183160. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  183161. if (ret != Z_OK)
  183162. {
  183163. if (ret == Z_STREAM_END)
  183164. {
  183165. if (png_ptr->zstream.avail_in)
  183166. png_error(png_ptr, "Extra compressed data");
  183167. if (!(png_ptr->zstream.avail_out))
  183168. {
  183169. png_push_process_row(png_ptr);
  183170. }
  183171. png_ptr->mode |= PNG_AFTER_IDAT;
  183172. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  183173. break;
  183174. }
  183175. else if (ret == Z_BUF_ERROR)
  183176. break;
  183177. else
  183178. png_error(png_ptr, "Decompression Error");
  183179. }
  183180. if (!(png_ptr->zstream.avail_out))
  183181. {
  183182. if ((
  183183. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183184. png_ptr->interlaced && png_ptr->pass > 6) ||
  183185. (!png_ptr->interlaced &&
  183186. #endif
  183187. png_ptr->row_number == png_ptr->num_rows))
  183188. {
  183189. if (png_ptr->zstream.avail_in)
  183190. {
  183191. png_warning(png_ptr, "Too much data in IDAT chunks");
  183192. }
  183193. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  183194. break;
  183195. }
  183196. png_push_process_row(png_ptr);
  183197. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  183198. png_ptr->zstream.next_out = png_ptr->row_buf;
  183199. }
  183200. else
  183201. break;
  183202. }
  183203. }
  183204. void /* PRIVATE */
  183205. png_push_process_row(png_structp png_ptr)
  183206. {
  183207. png_ptr->row_info.color_type = png_ptr->color_type;
  183208. png_ptr->row_info.width = png_ptr->iwidth;
  183209. png_ptr->row_info.channels = png_ptr->channels;
  183210. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  183211. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  183212. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  183213. png_ptr->row_info.width);
  183214. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  183215. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  183216. (int)(png_ptr->row_buf[0]));
  183217. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  183218. png_ptr->rowbytes + 1);
  183219. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  183220. png_do_read_transformations(png_ptr);
  183221. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183222. /* blow up interlaced rows to full size */
  183223. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  183224. {
  183225. if (png_ptr->pass < 6)
  183226. /* old interface (pre-1.0.9):
  183227. png_do_read_interlace(&(png_ptr->row_info),
  183228. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  183229. */
  183230. png_do_read_interlace(png_ptr);
  183231. switch (png_ptr->pass)
  183232. {
  183233. case 0:
  183234. {
  183235. int i;
  183236. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  183237. {
  183238. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183239. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  183240. }
  183241. if (png_ptr->pass == 2) /* pass 1 might be empty */
  183242. {
  183243. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  183244. {
  183245. png_push_have_row(png_ptr, png_bytep_NULL);
  183246. png_read_push_finish_row(png_ptr);
  183247. }
  183248. }
  183249. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  183250. {
  183251. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  183252. {
  183253. png_push_have_row(png_ptr, png_bytep_NULL);
  183254. png_read_push_finish_row(png_ptr);
  183255. }
  183256. }
  183257. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  183258. {
  183259. png_push_have_row(png_ptr, png_bytep_NULL);
  183260. png_read_push_finish_row(png_ptr);
  183261. }
  183262. break;
  183263. }
  183264. case 1:
  183265. {
  183266. int i;
  183267. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  183268. {
  183269. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183270. png_read_push_finish_row(png_ptr);
  183271. }
  183272. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  183273. {
  183274. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  183275. {
  183276. png_push_have_row(png_ptr, png_bytep_NULL);
  183277. png_read_push_finish_row(png_ptr);
  183278. }
  183279. }
  183280. break;
  183281. }
  183282. case 2:
  183283. {
  183284. int i;
  183285. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  183286. {
  183287. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183288. png_read_push_finish_row(png_ptr);
  183289. }
  183290. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  183291. {
  183292. png_push_have_row(png_ptr, png_bytep_NULL);
  183293. png_read_push_finish_row(png_ptr);
  183294. }
  183295. if (png_ptr->pass == 4) /* pass 3 might be empty */
  183296. {
  183297. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  183298. {
  183299. png_push_have_row(png_ptr, png_bytep_NULL);
  183300. png_read_push_finish_row(png_ptr);
  183301. }
  183302. }
  183303. break;
  183304. }
  183305. case 3:
  183306. {
  183307. int i;
  183308. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  183309. {
  183310. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183311. png_read_push_finish_row(png_ptr);
  183312. }
  183313. if (png_ptr->pass == 4) /* skip top two generated rows */
  183314. {
  183315. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  183316. {
  183317. png_push_have_row(png_ptr, png_bytep_NULL);
  183318. png_read_push_finish_row(png_ptr);
  183319. }
  183320. }
  183321. break;
  183322. }
  183323. case 4:
  183324. {
  183325. int i;
  183326. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  183327. {
  183328. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183329. png_read_push_finish_row(png_ptr);
  183330. }
  183331. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  183332. {
  183333. png_push_have_row(png_ptr, png_bytep_NULL);
  183334. png_read_push_finish_row(png_ptr);
  183335. }
  183336. if (png_ptr->pass == 6) /* pass 5 might be empty */
  183337. {
  183338. png_push_have_row(png_ptr, png_bytep_NULL);
  183339. png_read_push_finish_row(png_ptr);
  183340. }
  183341. break;
  183342. }
  183343. case 5:
  183344. {
  183345. int i;
  183346. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  183347. {
  183348. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183349. png_read_push_finish_row(png_ptr);
  183350. }
  183351. if (png_ptr->pass == 6) /* skip top generated row */
  183352. {
  183353. png_push_have_row(png_ptr, png_bytep_NULL);
  183354. png_read_push_finish_row(png_ptr);
  183355. }
  183356. break;
  183357. }
  183358. case 6:
  183359. {
  183360. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183361. png_read_push_finish_row(png_ptr);
  183362. if (png_ptr->pass != 6)
  183363. break;
  183364. png_push_have_row(png_ptr, png_bytep_NULL);
  183365. png_read_push_finish_row(png_ptr);
  183366. }
  183367. }
  183368. }
  183369. else
  183370. #endif
  183371. {
  183372. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  183373. png_read_push_finish_row(png_ptr);
  183374. }
  183375. }
  183376. void /* PRIVATE */
  183377. png_read_push_finish_row(png_structp png_ptr)
  183378. {
  183379. #ifdef PNG_USE_LOCAL_ARRAYS
  183380. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  183381. /* start of interlace block */
  183382. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  183383. /* offset to next interlace block */
  183384. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  183385. /* start of interlace block in the y direction */
  183386. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  183387. /* offset to next interlace block in the y direction */
  183388. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  183389. /* Height of interlace block. This is not currently used - if you need
  183390. * it, uncomment it here and in png.h
  183391. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  183392. */
  183393. #endif
  183394. png_ptr->row_number++;
  183395. if (png_ptr->row_number < png_ptr->num_rows)
  183396. return;
  183397. if (png_ptr->interlaced)
  183398. {
  183399. png_ptr->row_number = 0;
  183400. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  183401. png_ptr->rowbytes + 1);
  183402. do
  183403. {
  183404. png_ptr->pass++;
  183405. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  183406. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  183407. (png_ptr->pass == 5 && png_ptr->width < 2))
  183408. png_ptr->pass++;
  183409. if (png_ptr->pass > 7)
  183410. png_ptr->pass--;
  183411. if (png_ptr->pass >= 7)
  183412. break;
  183413. png_ptr->iwidth = (png_ptr->width +
  183414. png_pass_inc[png_ptr->pass] - 1 -
  183415. png_pass_start[png_ptr->pass]) /
  183416. png_pass_inc[png_ptr->pass];
  183417. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  183418. png_ptr->iwidth) + 1;
  183419. if (png_ptr->transformations & PNG_INTERLACE)
  183420. break;
  183421. png_ptr->num_rows = (png_ptr->height +
  183422. png_pass_yinc[png_ptr->pass] - 1 -
  183423. png_pass_ystart[png_ptr->pass]) /
  183424. png_pass_yinc[png_ptr->pass];
  183425. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  183426. }
  183427. }
  183428. #if defined(PNG_READ_tEXt_SUPPORTED)
  183429. void /* PRIVATE */
  183430. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  183431. length)
  183432. {
  183433. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  183434. {
  183435. png_error(png_ptr, "Out of place tEXt");
  183436. info_ptr = info_ptr; /* to quiet some compiler warnings */
  183437. }
  183438. #ifdef PNG_MAX_MALLOC_64K
  183439. png_ptr->skip_length = 0; /* This may not be necessary */
  183440. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  183441. {
  183442. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  183443. png_ptr->skip_length = length - (png_uint_32)65535L;
  183444. length = (png_uint_32)65535L;
  183445. }
  183446. #endif
  183447. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  183448. (png_uint_32)(length+1));
  183449. png_ptr->current_text[length] = '\0';
  183450. png_ptr->current_text_ptr = png_ptr->current_text;
  183451. png_ptr->current_text_size = (png_size_t)length;
  183452. png_ptr->current_text_left = (png_size_t)length;
  183453. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  183454. }
  183455. void /* PRIVATE */
  183456. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  183457. {
  183458. if (png_ptr->buffer_size && png_ptr->current_text_left)
  183459. {
  183460. png_size_t text_size;
  183461. if (png_ptr->buffer_size < png_ptr->current_text_left)
  183462. text_size = png_ptr->buffer_size;
  183463. else
  183464. text_size = png_ptr->current_text_left;
  183465. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  183466. png_ptr->current_text_left -= text_size;
  183467. png_ptr->current_text_ptr += text_size;
  183468. }
  183469. if (!(png_ptr->current_text_left))
  183470. {
  183471. png_textp text_ptr;
  183472. png_charp text;
  183473. png_charp key;
  183474. int ret;
  183475. if (png_ptr->buffer_size < 4)
  183476. {
  183477. png_push_save_buffer(png_ptr);
  183478. return;
  183479. }
  183480. png_push_crc_finish(png_ptr);
  183481. #if defined(PNG_MAX_MALLOC_64K)
  183482. if (png_ptr->skip_length)
  183483. return;
  183484. #endif
  183485. key = png_ptr->current_text;
  183486. for (text = key; *text; text++)
  183487. /* empty loop */ ;
  183488. if (text < key + png_ptr->current_text_size)
  183489. text++;
  183490. text_ptr = (png_textp)png_malloc(png_ptr,
  183491. (png_uint_32)png_sizeof(png_text));
  183492. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  183493. text_ptr->key = key;
  183494. #ifdef PNG_iTXt_SUPPORTED
  183495. text_ptr->lang = NULL;
  183496. text_ptr->lang_key = NULL;
  183497. #endif
  183498. text_ptr->text = text;
  183499. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  183500. png_free(png_ptr, key);
  183501. png_free(png_ptr, text_ptr);
  183502. png_ptr->current_text = NULL;
  183503. if (ret)
  183504. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  183505. }
  183506. }
  183507. #endif
  183508. #if defined(PNG_READ_zTXt_SUPPORTED)
  183509. void /* PRIVATE */
  183510. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  183511. length)
  183512. {
  183513. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  183514. {
  183515. png_error(png_ptr, "Out of place zTXt");
  183516. info_ptr = info_ptr; /* to quiet some compiler warnings */
  183517. }
  183518. #ifdef PNG_MAX_MALLOC_64K
  183519. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  183520. * to be able to store the uncompressed data. Actually, the threshold
  183521. * is probably around 32K, but it isn't as definite as 64K is.
  183522. */
  183523. if (length > (png_uint_32)65535L)
  183524. {
  183525. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  183526. png_push_crc_skip(png_ptr, length);
  183527. return;
  183528. }
  183529. #endif
  183530. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  183531. (png_uint_32)(length+1));
  183532. png_ptr->current_text[length] = '\0';
  183533. png_ptr->current_text_ptr = png_ptr->current_text;
  183534. png_ptr->current_text_size = (png_size_t)length;
  183535. png_ptr->current_text_left = (png_size_t)length;
  183536. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  183537. }
  183538. void /* PRIVATE */
  183539. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  183540. {
  183541. if (png_ptr->buffer_size && png_ptr->current_text_left)
  183542. {
  183543. png_size_t text_size;
  183544. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  183545. text_size = png_ptr->buffer_size;
  183546. else
  183547. text_size = png_ptr->current_text_left;
  183548. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  183549. png_ptr->current_text_left -= text_size;
  183550. png_ptr->current_text_ptr += text_size;
  183551. }
  183552. if (!(png_ptr->current_text_left))
  183553. {
  183554. png_textp text_ptr;
  183555. png_charp text;
  183556. png_charp key;
  183557. int ret;
  183558. png_size_t text_size, key_size;
  183559. if (png_ptr->buffer_size < 4)
  183560. {
  183561. png_push_save_buffer(png_ptr);
  183562. return;
  183563. }
  183564. png_push_crc_finish(png_ptr);
  183565. key = png_ptr->current_text;
  183566. for (text = key; *text; text++)
  183567. /* empty loop */ ;
  183568. /* zTXt can't have zero text */
  183569. if (text >= key + png_ptr->current_text_size)
  183570. {
  183571. png_ptr->current_text = NULL;
  183572. png_free(png_ptr, key);
  183573. return;
  183574. }
  183575. text++;
  183576. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  183577. {
  183578. png_ptr->current_text = NULL;
  183579. png_free(png_ptr, key);
  183580. return;
  183581. }
  183582. text++;
  183583. png_ptr->zstream.next_in = (png_bytep )text;
  183584. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  183585. (text - key));
  183586. png_ptr->zstream.next_out = png_ptr->zbuf;
  183587. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  183588. key_size = text - key;
  183589. text_size = 0;
  183590. text = NULL;
  183591. ret = Z_STREAM_END;
  183592. while (png_ptr->zstream.avail_in)
  183593. {
  183594. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  183595. if (ret != Z_OK && ret != Z_STREAM_END)
  183596. {
  183597. inflateReset(&png_ptr->zstream);
  183598. png_ptr->zstream.avail_in = 0;
  183599. png_ptr->current_text = NULL;
  183600. png_free(png_ptr, key);
  183601. png_free(png_ptr, text);
  183602. return;
  183603. }
  183604. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  183605. {
  183606. if (text == NULL)
  183607. {
  183608. text = (png_charp)png_malloc(png_ptr,
  183609. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  183610. + key_size + 1));
  183611. png_memcpy(text + key_size, png_ptr->zbuf,
  183612. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  183613. png_memcpy(text, key, key_size);
  183614. text_size = key_size + png_ptr->zbuf_size -
  183615. png_ptr->zstream.avail_out;
  183616. *(text + text_size) = '\0';
  183617. }
  183618. else
  183619. {
  183620. png_charp tmp;
  183621. tmp = text;
  183622. text = (png_charp)png_malloc(png_ptr, text_size +
  183623. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  183624. + 1));
  183625. png_memcpy(text, tmp, text_size);
  183626. png_free(png_ptr, tmp);
  183627. png_memcpy(text + text_size, png_ptr->zbuf,
  183628. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  183629. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  183630. *(text + text_size) = '\0';
  183631. }
  183632. if (ret != Z_STREAM_END)
  183633. {
  183634. png_ptr->zstream.next_out = png_ptr->zbuf;
  183635. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  183636. }
  183637. }
  183638. else
  183639. {
  183640. break;
  183641. }
  183642. if (ret == Z_STREAM_END)
  183643. break;
  183644. }
  183645. inflateReset(&png_ptr->zstream);
  183646. png_ptr->zstream.avail_in = 0;
  183647. if (ret != Z_STREAM_END)
  183648. {
  183649. png_ptr->current_text = NULL;
  183650. png_free(png_ptr, key);
  183651. png_free(png_ptr, text);
  183652. return;
  183653. }
  183654. png_ptr->current_text = NULL;
  183655. png_free(png_ptr, key);
  183656. key = text;
  183657. text += key_size;
  183658. text_ptr = (png_textp)png_malloc(png_ptr,
  183659. (png_uint_32)png_sizeof(png_text));
  183660. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  183661. text_ptr->key = key;
  183662. #ifdef PNG_iTXt_SUPPORTED
  183663. text_ptr->lang = NULL;
  183664. text_ptr->lang_key = NULL;
  183665. #endif
  183666. text_ptr->text = text;
  183667. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  183668. png_free(png_ptr, key);
  183669. png_free(png_ptr, text_ptr);
  183670. if (ret)
  183671. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  183672. }
  183673. }
  183674. #endif
  183675. #if defined(PNG_READ_iTXt_SUPPORTED)
  183676. void /* PRIVATE */
  183677. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  183678. length)
  183679. {
  183680. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  183681. {
  183682. png_error(png_ptr, "Out of place iTXt");
  183683. info_ptr = info_ptr; /* to quiet some compiler warnings */
  183684. }
  183685. #ifdef PNG_MAX_MALLOC_64K
  183686. png_ptr->skip_length = 0; /* This may not be necessary */
  183687. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  183688. {
  183689. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  183690. png_ptr->skip_length = length - (png_uint_32)65535L;
  183691. length = (png_uint_32)65535L;
  183692. }
  183693. #endif
  183694. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  183695. (png_uint_32)(length+1));
  183696. png_ptr->current_text[length] = '\0';
  183697. png_ptr->current_text_ptr = png_ptr->current_text;
  183698. png_ptr->current_text_size = (png_size_t)length;
  183699. png_ptr->current_text_left = (png_size_t)length;
  183700. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  183701. }
  183702. void /* PRIVATE */
  183703. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  183704. {
  183705. if (png_ptr->buffer_size && png_ptr->current_text_left)
  183706. {
  183707. png_size_t text_size;
  183708. if (png_ptr->buffer_size < png_ptr->current_text_left)
  183709. text_size = png_ptr->buffer_size;
  183710. else
  183711. text_size = png_ptr->current_text_left;
  183712. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  183713. png_ptr->current_text_left -= text_size;
  183714. png_ptr->current_text_ptr += text_size;
  183715. }
  183716. if (!(png_ptr->current_text_left))
  183717. {
  183718. png_textp text_ptr;
  183719. png_charp key;
  183720. int comp_flag;
  183721. png_charp lang;
  183722. png_charp lang_key;
  183723. png_charp text;
  183724. int ret;
  183725. if (png_ptr->buffer_size < 4)
  183726. {
  183727. png_push_save_buffer(png_ptr);
  183728. return;
  183729. }
  183730. png_push_crc_finish(png_ptr);
  183731. #if defined(PNG_MAX_MALLOC_64K)
  183732. if (png_ptr->skip_length)
  183733. return;
  183734. #endif
  183735. key = png_ptr->current_text;
  183736. for (lang = key; *lang; lang++)
  183737. /* empty loop */ ;
  183738. if (lang < key + png_ptr->current_text_size - 3)
  183739. lang++;
  183740. comp_flag = *lang++;
  183741. lang++; /* skip comp_type, always zero */
  183742. for (lang_key = lang; *lang_key; lang_key++)
  183743. /* empty loop */ ;
  183744. lang_key++; /* skip NUL separator */
  183745. text=lang_key;
  183746. if (lang_key < key + png_ptr->current_text_size - 1)
  183747. {
  183748. for (; *text; text++)
  183749. /* empty loop */ ;
  183750. }
  183751. if (text < key + png_ptr->current_text_size)
  183752. text++;
  183753. text_ptr = (png_textp)png_malloc(png_ptr,
  183754. (png_uint_32)png_sizeof(png_text));
  183755. text_ptr->compression = comp_flag + 2;
  183756. text_ptr->key = key;
  183757. text_ptr->lang = lang;
  183758. text_ptr->lang_key = lang_key;
  183759. text_ptr->text = text;
  183760. text_ptr->text_length = 0;
  183761. text_ptr->itxt_length = png_strlen(text);
  183762. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  183763. png_ptr->current_text = NULL;
  183764. png_free(png_ptr, text_ptr);
  183765. if (ret)
  183766. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  183767. }
  183768. }
  183769. #endif
  183770. /* This function is called when we haven't found a handler for this
  183771. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  183772. * name or a critical chunk), the chunk is (currently) silently ignored.
  183773. */
  183774. void /* PRIVATE */
  183775. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  183776. length)
  183777. {
  183778. png_uint_32 skip=0;
  183779. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  183780. if (!(png_ptr->chunk_name[0] & 0x20))
  183781. {
  183782. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  183783. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  183784. PNG_HANDLE_CHUNK_ALWAYS
  183785. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  183786. && png_ptr->read_user_chunk_fn == NULL
  183787. #endif
  183788. )
  183789. #endif
  183790. png_chunk_error(png_ptr, "unknown critical chunk");
  183791. info_ptr = info_ptr; /* to quiet some compiler warnings */
  183792. }
  183793. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  183794. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  183795. {
  183796. #ifdef PNG_MAX_MALLOC_64K
  183797. if (length > (png_uint_32)65535L)
  183798. {
  183799. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  183800. skip = length - (png_uint_32)65535L;
  183801. length = (png_uint_32)65535L;
  183802. }
  183803. #endif
  183804. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  183805. (png_charp)png_ptr->chunk_name, 5);
  183806. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  183807. png_ptr->unknown_chunk.size = (png_size_t)length;
  183808. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  183809. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  183810. if(png_ptr->read_user_chunk_fn != NULL)
  183811. {
  183812. /* callback to user unknown chunk handler */
  183813. int ret;
  183814. ret = (*(png_ptr->read_user_chunk_fn))
  183815. (png_ptr, &png_ptr->unknown_chunk);
  183816. if (ret < 0)
  183817. png_chunk_error(png_ptr, "error in user chunk");
  183818. if (ret == 0)
  183819. {
  183820. if (!(png_ptr->chunk_name[0] & 0x20))
  183821. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  183822. PNG_HANDLE_CHUNK_ALWAYS)
  183823. png_chunk_error(png_ptr, "unknown critical chunk");
  183824. png_set_unknown_chunks(png_ptr, info_ptr,
  183825. &png_ptr->unknown_chunk, 1);
  183826. }
  183827. }
  183828. #else
  183829. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  183830. #endif
  183831. png_free(png_ptr, png_ptr->unknown_chunk.data);
  183832. png_ptr->unknown_chunk.data = NULL;
  183833. }
  183834. else
  183835. #endif
  183836. skip=length;
  183837. png_push_crc_skip(png_ptr, skip);
  183838. }
  183839. void /* PRIVATE */
  183840. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  183841. {
  183842. if (png_ptr->info_fn != NULL)
  183843. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  183844. }
  183845. void /* PRIVATE */
  183846. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  183847. {
  183848. if (png_ptr->end_fn != NULL)
  183849. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  183850. }
  183851. void /* PRIVATE */
  183852. png_push_have_row(png_structp png_ptr, png_bytep row)
  183853. {
  183854. if (png_ptr->row_fn != NULL)
  183855. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  183856. (int)png_ptr->pass);
  183857. }
  183858. void PNGAPI
  183859. png_progressive_combine_row (png_structp png_ptr,
  183860. png_bytep old_row, png_bytep new_row)
  183861. {
  183862. #ifdef PNG_USE_LOCAL_ARRAYS
  183863. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  183864. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  183865. #endif
  183866. if(png_ptr == NULL) return;
  183867. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  183868. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  183869. }
  183870. void PNGAPI
  183871. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  183872. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183873. png_progressive_end_ptr end_fn)
  183874. {
  183875. if(png_ptr == NULL) return;
  183876. png_ptr->info_fn = info_fn;
  183877. png_ptr->row_fn = row_fn;
  183878. png_ptr->end_fn = end_fn;
  183879. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  183880. }
  183881. png_voidp PNGAPI
  183882. png_get_progressive_ptr(png_structp png_ptr)
  183883. {
  183884. if(png_ptr == NULL) return (NULL);
  183885. return png_ptr->io_ptr;
  183886. }
  183887. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183888. /********* End of inlined file: pngpread.c *********/
  183889. /********* Start of inlined file: pngrio.c *********/
  183890. /* pngrio.c - functions for data input
  183891. *
  183892. * Last changed in libpng 1.2.13 November 13, 2006
  183893. * For conditions of distribution and use, see copyright notice in png.h
  183894. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  183895. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183896. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183897. *
  183898. * This file provides a location for all input. Users who need
  183899. * special handling are expected to write a function that has the same
  183900. * arguments as this and performs a similar function, but that possibly
  183901. * has a different input method. Note that you shouldn't change this
  183902. * function, but rather write a replacement function and then make
  183903. * libpng use it at run time with png_set_read_fn(...).
  183904. */
  183905. #define PNG_INTERNAL
  183906. #if defined(PNG_READ_SUPPORTED)
  183907. /* Read the data from whatever input you are using. The default routine
  183908. reads from a file pointer. Note that this routine sometimes gets called
  183909. with very small lengths, so you should implement some kind of simple
  183910. buffering if you are using unbuffered reads. This should never be asked
  183911. to read more then 64K on a 16 bit machine. */
  183912. void /* PRIVATE */
  183913. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  183914. {
  183915. png_debug1(4,"reading %d bytes\n", (int)length);
  183916. if (png_ptr->read_data_fn != NULL)
  183917. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  183918. else
  183919. png_error(png_ptr, "Call to NULL read function");
  183920. }
  183921. #if !defined(PNG_NO_STDIO)
  183922. /* This is the function that does the actual reading of data. If you are
  183923. not reading from a standard C stream, you should create a replacement
  183924. read_data function and use it at run time with png_set_read_fn(), rather
  183925. than changing the library. */
  183926. #ifndef USE_FAR_KEYWORD
  183927. void PNGAPI
  183928. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  183929. {
  183930. png_size_t check;
  183931. if(png_ptr == NULL) return;
  183932. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  183933. * instead of an int, which is what fread() actually returns.
  183934. */
  183935. #if defined(_WIN32_WCE)
  183936. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  183937. check = 0;
  183938. #else
  183939. check = (png_size_t)fread(data, (png_size_t)1, length,
  183940. (png_FILE_p)png_ptr->io_ptr);
  183941. #endif
  183942. if (check != length)
  183943. png_error(png_ptr, "Read Error");
  183944. }
  183945. #else
  183946. /* this is the model-independent version. Since the standard I/O library
  183947. can't handle far buffers in the medium and small models, we have to copy
  183948. the data.
  183949. */
  183950. #define NEAR_BUF_SIZE 1024
  183951. #define MIN(a,b) (a <= b ? a : b)
  183952. static void PNGAPI
  183953. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  183954. {
  183955. int check;
  183956. png_byte *n_data;
  183957. png_FILE_p io_ptr;
  183958. if(png_ptr == NULL) return;
  183959. /* Check if data really is near. If so, use usual code. */
  183960. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  183961. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  183962. if ((png_bytep)n_data == data)
  183963. {
  183964. #if defined(_WIN32_WCE)
  183965. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  183966. check = 0;
  183967. #else
  183968. check = fread(n_data, 1, length, io_ptr);
  183969. #endif
  183970. }
  183971. else
  183972. {
  183973. png_byte buf[NEAR_BUF_SIZE];
  183974. png_size_t read, remaining, err;
  183975. check = 0;
  183976. remaining = length;
  183977. do
  183978. {
  183979. read = MIN(NEAR_BUF_SIZE, remaining);
  183980. #if defined(_WIN32_WCE)
  183981. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  183982. err = 0;
  183983. #else
  183984. err = fread(buf, (png_size_t)1, read, io_ptr);
  183985. #endif
  183986. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  183987. if(err != read)
  183988. break;
  183989. else
  183990. check += err;
  183991. data += read;
  183992. remaining -= read;
  183993. }
  183994. while (remaining != 0);
  183995. }
  183996. if ((png_uint_32)check != (png_uint_32)length)
  183997. png_error(png_ptr, "read Error");
  183998. }
  183999. #endif
  184000. #endif
  184001. /* This function allows the application to supply a new input function
  184002. for libpng if standard C streams aren't being used.
  184003. This function takes as its arguments:
  184004. png_ptr - pointer to a png input data structure
  184005. io_ptr - pointer to user supplied structure containing info about
  184006. the input functions. May be NULL.
  184007. read_data_fn - pointer to a new input function that takes as its
  184008. arguments a pointer to a png_struct, a pointer to
  184009. a location where input data can be stored, and a 32-bit
  184010. unsigned int that is the number of bytes to be read.
  184011. To exit and output any fatal error messages the new write
  184012. function should call png_error(png_ptr, "Error msg"). */
  184013. void PNGAPI
  184014. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  184015. png_rw_ptr read_data_fn)
  184016. {
  184017. if(png_ptr == NULL) return;
  184018. png_ptr->io_ptr = io_ptr;
  184019. #if !defined(PNG_NO_STDIO)
  184020. if (read_data_fn != NULL)
  184021. png_ptr->read_data_fn = read_data_fn;
  184022. else
  184023. png_ptr->read_data_fn = png_default_read_data;
  184024. #else
  184025. png_ptr->read_data_fn = read_data_fn;
  184026. #endif
  184027. /* It is an error to write to a read device */
  184028. if (png_ptr->write_data_fn != NULL)
  184029. {
  184030. png_ptr->write_data_fn = NULL;
  184031. png_warning(png_ptr,
  184032. "It's an error to set both read_data_fn and write_data_fn in the ");
  184033. png_warning(png_ptr,
  184034. "same structure. Resetting write_data_fn to NULL.");
  184035. }
  184036. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184037. png_ptr->output_flush_fn = NULL;
  184038. #endif
  184039. }
  184040. #endif /* PNG_READ_SUPPORTED */
  184041. /********* End of inlined file: pngrio.c *********/
  184042. /********* Start of inlined file: pngrtran.c *********/
  184043. /* pngrtran.c - transforms the data in a row for PNG readers
  184044. *
  184045. * Last changed in libpng 1.2.21 [October 4, 2007]
  184046. * For conditions of distribution and use, see copyright notice in png.h
  184047. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184048. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184049. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184050. *
  184051. * This file contains functions optionally called by an application
  184052. * in order to tell libpng how to handle data when reading a PNG.
  184053. * Transformations that are used in both reading and writing are
  184054. * in pngtrans.c.
  184055. */
  184056. #define PNG_INTERNAL
  184057. #if defined(PNG_READ_SUPPORTED)
  184058. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  184059. void PNGAPI
  184060. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  184061. {
  184062. png_debug(1, "in png_set_crc_action\n");
  184063. /* Tell libpng how we react to CRC errors in critical chunks */
  184064. if(png_ptr == NULL) return;
  184065. switch (crit_action)
  184066. {
  184067. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  184068. break;
  184069. case PNG_CRC_WARN_USE: /* warn/use data */
  184070. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  184071. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  184072. break;
  184073. case PNG_CRC_QUIET_USE: /* quiet/use data */
  184074. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  184075. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  184076. PNG_FLAG_CRC_CRITICAL_IGNORE;
  184077. break;
  184078. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  184079. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  184080. case PNG_CRC_ERROR_QUIT: /* error/quit */
  184081. case PNG_CRC_DEFAULT:
  184082. default:
  184083. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  184084. break;
  184085. }
  184086. switch (ancil_action)
  184087. {
  184088. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  184089. break;
  184090. case PNG_CRC_WARN_USE: /* warn/use data */
  184091. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  184092. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  184093. break;
  184094. case PNG_CRC_QUIET_USE: /* quiet/use data */
  184095. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  184096. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  184097. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  184098. break;
  184099. case PNG_CRC_ERROR_QUIT: /* error/quit */
  184100. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  184101. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  184102. break;
  184103. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  184104. case PNG_CRC_DEFAULT:
  184105. default:
  184106. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  184107. break;
  184108. }
  184109. }
  184110. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  184111. defined(PNG_FLOATING_POINT_SUPPORTED)
  184112. /* handle alpha and tRNS via a background color */
  184113. void PNGAPI
  184114. png_set_background(png_structp png_ptr,
  184115. png_color_16p background_color, int background_gamma_code,
  184116. int need_expand, double background_gamma)
  184117. {
  184118. png_debug(1, "in png_set_background\n");
  184119. if(png_ptr == NULL) return;
  184120. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  184121. {
  184122. png_warning(png_ptr, "Application must supply a known background gamma");
  184123. return;
  184124. }
  184125. png_ptr->transformations |= PNG_BACKGROUND;
  184126. png_memcpy(&(png_ptr->background), background_color,
  184127. png_sizeof(png_color_16));
  184128. png_ptr->background_gamma = (float)background_gamma;
  184129. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  184130. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  184131. }
  184132. #endif
  184133. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184134. /* strip 16 bit depth files to 8 bit depth */
  184135. void PNGAPI
  184136. png_set_strip_16(png_structp png_ptr)
  184137. {
  184138. png_debug(1, "in png_set_strip_16\n");
  184139. if(png_ptr == NULL) return;
  184140. png_ptr->transformations |= PNG_16_TO_8;
  184141. }
  184142. #endif
  184143. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184144. void PNGAPI
  184145. png_set_strip_alpha(png_structp png_ptr)
  184146. {
  184147. png_debug(1, "in png_set_strip_alpha\n");
  184148. if(png_ptr == NULL) return;
  184149. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  184150. }
  184151. #endif
  184152. #if defined(PNG_READ_DITHER_SUPPORTED)
  184153. /* Dither file to 8 bit. Supply a palette, the current number
  184154. * of elements in the palette, the maximum number of elements
  184155. * allowed, and a histogram if possible. If the current number
  184156. * of colors is greater then the maximum number, the palette will be
  184157. * modified to fit in the maximum number. "full_dither" indicates
  184158. * whether we need a dithering cube set up for RGB images, or if we
  184159. * simply are reducing the number of colors in a paletted image.
  184160. */
  184161. typedef struct png_dsort_struct
  184162. {
  184163. struct png_dsort_struct FAR * next;
  184164. png_byte left;
  184165. png_byte right;
  184166. } png_dsort;
  184167. typedef png_dsort FAR * png_dsortp;
  184168. typedef png_dsort FAR * FAR * png_dsortpp;
  184169. void PNGAPI
  184170. png_set_dither(png_structp png_ptr, png_colorp palette,
  184171. int num_palette, int maximum_colors, png_uint_16p histogram,
  184172. int full_dither)
  184173. {
  184174. png_debug(1, "in png_set_dither\n");
  184175. if(png_ptr == NULL) return;
  184176. png_ptr->transformations |= PNG_DITHER;
  184177. if (!full_dither)
  184178. {
  184179. int i;
  184180. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  184181. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  184182. for (i = 0; i < num_palette; i++)
  184183. png_ptr->dither_index[i] = (png_byte)i;
  184184. }
  184185. if (num_palette > maximum_colors)
  184186. {
  184187. if (histogram != NULL)
  184188. {
  184189. /* This is easy enough, just throw out the least used colors.
  184190. Perhaps not the best solution, but good enough. */
  184191. int i;
  184192. /* initialize an array to sort colors */
  184193. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  184194. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  184195. /* initialize the dither_sort array */
  184196. for (i = 0; i < num_palette; i++)
  184197. png_ptr->dither_sort[i] = (png_byte)i;
  184198. /* Find the least used palette entries by starting a
  184199. bubble sort, and running it until we have sorted
  184200. out enough colors. Note that we don't care about
  184201. sorting all the colors, just finding which are
  184202. least used. */
  184203. for (i = num_palette - 1; i >= maximum_colors; i--)
  184204. {
  184205. int done; /* to stop early if the list is pre-sorted */
  184206. int j;
  184207. done = 1;
  184208. for (j = 0; j < i; j++)
  184209. {
  184210. if (histogram[png_ptr->dither_sort[j]]
  184211. < histogram[png_ptr->dither_sort[j + 1]])
  184212. {
  184213. png_byte t;
  184214. t = png_ptr->dither_sort[j];
  184215. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  184216. png_ptr->dither_sort[j + 1] = t;
  184217. done = 0;
  184218. }
  184219. }
  184220. if (done)
  184221. break;
  184222. }
  184223. /* swap the palette around, and set up a table, if necessary */
  184224. if (full_dither)
  184225. {
  184226. int j = num_palette;
  184227. /* put all the useful colors within the max, but don't
  184228. move the others */
  184229. for (i = 0; i < maximum_colors; i++)
  184230. {
  184231. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  184232. {
  184233. do
  184234. j--;
  184235. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  184236. palette[i] = palette[j];
  184237. }
  184238. }
  184239. }
  184240. else
  184241. {
  184242. int j = num_palette;
  184243. /* move all the used colors inside the max limit, and
  184244. develop a translation table */
  184245. for (i = 0; i < maximum_colors; i++)
  184246. {
  184247. /* only move the colors we need to */
  184248. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  184249. {
  184250. png_color tmp_color;
  184251. do
  184252. j--;
  184253. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  184254. tmp_color = palette[j];
  184255. palette[j] = palette[i];
  184256. palette[i] = tmp_color;
  184257. /* indicate where the color went */
  184258. png_ptr->dither_index[j] = (png_byte)i;
  184259. png_ptr->dither_index[i] = (png_byte)j;
  184260. }
  184261. }
  184262. /* find closest color for those colors we are not using */
  184263. for (i = 0; i < num_palette; i++)
  184264. {
  184265. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  184266. {
  184267. int min_d, k, min_k, d_index;
  184268. /* find the closest color to one we threw out */
  184269. d_index = png_ptr->dither_index[i];
  184270. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  184271. for (k = 1, min_k = 0; k < maximum_colors; k++)
  184272. {
  184273. int d;
  184274. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  184275. if (d < min_d)
  184276. {
  184277. min_d = d;
  184278. min_k = k;
  184279. }
  184280. }
  184281. /* point to closest color */
  184282. png_ptr->dither_index[i] = (png_byte)min_k;
  184283. }
  184284. }
  184285. }
  184286. png_free(png_ptr, png_ptr->dither_sort);
  184287. png_ptr->dither_sort=NULL;
  184288. }
  184289. else
  184290. {
  184291. /* This is much harder to do simply (and quickly). Perhaps
  184292. we need to go through a median cut routine, but those
  184293. don't always behave themselves with only a few colors
  184294. as input. So we will just find the closest two colors,
  184295. and throw out one of them (chosen somewhat randomly).
  184296. [We don't understand this at all, so if someone wants to
  184297. work on improving it, be our guest - AED, GRP]
  184298. */
  184299. int i;
  184300. int max_d;
  184301. int num_new_palette;
  184302. png_dsortp t;
  184303. png_dsortpp hash;
  184304. t=NULL;
  184305. /* initialize palette index arrays */
  184306. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  184307. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  184308. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  184309. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  184310. /* initialize the sort array */
  184311. for (i = 0; i < num_palette; i++)
  184312. {
  184313. png_ptr->index_to_palette[i] = (png_byte)i;
  184314. png_ptr->palette_to_index[i] = (png_byte)i;
  184315. }
  184316. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  184317. png_sizeof (png_dsortp)));
  184318. for (i = 0; i < 769; i++)
  184319. hash[i] = NULL;
  184320. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  184321. num_new_palette = num_palette;
  184322. /* initial wild guess at how far apart the farthest pixel
  184323. pair we will be eliminating will be. Larger
  184324. numbers mean more areas will be allocated, Smaller
  184325. numbers run the risk of not saving enough data, and
  184326. having to do this all over again.
  184327. I have not done extensive checking on this number.
  184328. */
  184329. max_d = 96;
  184330. while (num_new_palette > maximum_colors)
  184331. {
  184332. for (i = 0; i < num_new_palette - 1; i++)
  184333. {
  184334. int j;
  184335. for (j = i + 1; j < num_new_palette; j++)
  184336. {
  184337. int d;
  184338. d = PNG_COLOR_DIST(palette[i], palette[j]);
  184339. if (d <= max_d)
  184340. {
  184341. t = (png_dsortp)png_malloc_warn(png_ptr,
  184342. (png_uint_32)(png_sizeof(png_dsort)));
  184343. if (t == NULL)
  184344. break;
  184345. t->next = hash[d];
  184346. t->left = (png_byte)i;
  184347. t->right = (png_byte)j;
  184348. hash[d] = t;
  184349. }
  184350. }
  184351. if (t == NULL)
  184352. break;
  184353. }
  184354. if (t != NULL)
  184355. for (i = 0; i <= max_d; i++)
  184356. {
  184357. if (hash[i] != NULL)
  184358. {
  184359. png_dsortp p;
  184360. for (p = hash[i]; p; p = p->next)
  184361. {
  184362. if ((int)png_ptr->index_to_palette[p->left]
  184363. < num_new_palette &&
  184364. (int)png_ptr->index_to_palette[p->right]
  184365. < num_new_palette)
  184366. {
  184367. int j, next_j;
  184368. if (num_new_palette & 0x01)
  184369. {
  184370. j = p->left;
  184371. next_j = p->right;
  184372. }
  184373. else
  184374. {
  184375. j = p->right;
  184376. next_j = p->left;
  184377. }
  184378. num_new_palette--;
  184379. palette[png_ptr->index_to_palette[j]]
  184380. = palette[num_new_palette];
  184381. if (!full_dither)
  184382. {
  184383. int k;
  184384. for (k = 0; k < num_palette; k++)
  184385. {
  184386. if (png_ptr->dither_index[k] ==
  184387. png_ptr->index_to_palette[j])
  184388. png_ptr->dither_index[k] =
  184389. png_ptr->index_to_palette[next_j];
  184390. if ((int)png_ptr->dither_index[k] ==
  184391. num_new_palette)
  184392. png_ptr->dither_index[k] =
  184393. png_ptr->index_to_palette[j];
  184394. }
  184395. }
  184396. png_ptr->index_to_palette[png_ptr->palette_to_index
  184397. [num_new_palette]] = png_ptr->index_to_palette[j];
  184398. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  184399. = png_ptr->palette_to_index[num_new_palette];
  184400. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  184401. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  184402. }
  184403. if (num_new_palette <= maximum_colors)
  184404. break;
  184405. }
  184406. if (num_new_palette <= maximum_colors)
  184407. break;
  184408. }
  184409. }
  184410. for (i = 0; i < 769; i++)
  184411. {
  184412. if (hash[i] != NULL)
  184413. {
  184414. png_dsortp p = hash[i];
  184415. while (p)
  184416. {
  184417. t = p->next;
  184418. png_free(png_ptr, p);
  184419. p = t;
  184420. }
  184421. }
  184422. hash[i] = 0;
  184423. }
  184424. max_d += 96;
  184425. }
  184426. png_free(png_ptr, hash);
  184427. png_free(png_ptr, png_ptr->palette_to_index);
  184428. png_free(png_ptr, png_ptr->index_to_palette);
  184429. png_ptr->palette_to_index=NULL;
  184430. png_ptr->index_to_palette=NULL;
  184431. }
  184432. num_palette = maximum_colors;
  184433. }
  184434. if (png_ptr->palette == NULL)
  184435. {
  184436. png_ptr->palette = palette;
  184437. }
  184438. png_ptr->num_palette = (png_uint_16)num_palette;
  184439. if (full_dither)
  184440. {
  184441. int i;
  184442. png_bytep distance;
  184443. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  184444. PNG_DITHER_BLUE_BITS;
  184445. int num_red = (1 << PNG_DITHER_RED_BITS);
  184446. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  184447. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  184448. png_size_t num_entries = ((png_size_t)1 << total_bits);
  184449. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  184450. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  184451. png_memset(png_ptr->palette_lookup, 0, num_entries *
  184452. png_sizeof (png_byte));
  184453. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  184454. png_sizeof(png_byte)));
  184455. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  184456. for (i = 0; i < num_palette; i++)
  184457. {
  184458. int ir, ig, ib;
  184459. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  184460. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  184461. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  184462. for (ir = 0; ir < num_red; ir++)
  184463. {
  184464. /* int dr = abs(ir - r); */
  184465. int dr = ((ir > r) ? ir - r : r - ir);
  184466. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  184467. for (ig = 0; ig < num_green; ig++)
  184468. {
  184469. /* int dg = abs(ig - g); */
  184470. int dg = ((ig > g) ? ig - g : g - ig);
  184471. int dt = dr + dg;
  184472. int dm = ((dr > dg) ? dr : dg);
  184473. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  184474. for (ib = 0; ib < num_blue; ib++)
  184475. {
  184476. int d_index = index_g | ib;
  184477. /* int db = abs(ib - b); */
  184478. int db = ((ib > b) ? ib - b : b - ib);
  184479. int dmax = ((dm > db) ? dm : db);
  184480. int d = dmax + dt + db;
  184481. if (d < (int)distance[d_index])
  184482. {
  184483. distance[d_index] = (png_byte)d;
  184484. png_ptr->palette_lookup[d_index] = (png_byte)i;
  184485. }
  184486. }
  184487. }
  184488. }
  184489. }
  184490. png_free(png_ptr, distance);
  184491. }
  184492. }
  184493. #endif
  184494. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184495. /* Transform the image from the file_gamma to the screen_gamma. We
  184496. * only do transformations on images where the file_gamma and screen_gamma
  184497. * are not close reciprocals, otherwise it slows things down slightly, and
  184498. * also needlessly introduces small errors.
  184499. *
  184500. * We will turn off gamma transformation later if no semitransparent entries
  184501. * are present in the tRNS array for palette images. We can't do it here
  184502. * because we don't necessarily have the tRNS chunk yet.
  184503. */
  184504. void PNGAPI
  184505. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  184506. {
  184507. png_debug(1, "in png_set_gamma\n");
  184508. if(png_ptr == NULL) return;
  184509. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  184510. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  184511. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  184512. png_ptr->transformations |= PNG_GAMMA;
  184513. png_ptr->gamma = (float)file_gamma;
  184514. png_ptr->screen_gamma = (float)scrn_gamma;
  184515. }
  184516. #endif
  184517. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184518. /* Expand paletted images to RGB, expand grayscale images of
  184519. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  184520. * to alpha channels.
  184521. */
  184522. void PNGAPI
  184523. png_set_expand(png_structp png_ptr)
  184524. {
  184525. png_debug(1, "in png_set_expand\n");
  184526. if(png_ptr == NULL) return;
  184527. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  184528. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184529. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  184530. #endif
  184531. }
  184532. /* GRR 19990627: the following three functions currently are identical
  184533. * to png_set_expand(). However, it is entirely reasonable that someone
  184534. * might wish to expand an indexed image to RGB but *not* expand a single,
  184535. * fully transparent palette entry to a full alpha channel--perhaps instead
  184536. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  184537. * the transparent color with a particular RGB value, or drop tRNS entirely.
  184538. * IOW, a future version of the library may make the transformations flag
  184539. * a bit more fine-grained, with separate bits for each of these three
  184540. * functions.
  184541. *
  184542. * More to the point, these functions make it obvious what libpng will be
  184543. * doing, whereas "expand" can (and does) mean any number of things.
  184544. *
  184545. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  184546. * to expand only the sample depth but not to expand the tRNS to alpha.
  184547. */
  184548. /* Expand paletted images to RGB. */
  184549. void PNGAPI
  184550. png_set_palette_to_rgb(png_structp png_ptr)
  184551. {
  184552. png_debug(1, "in png_set_palette_to_rgb\n");
  184553. if(png_ptr == NULL) return;
  184554. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  184555. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184556. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  184557. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  184558. #endif
  184559. }
  184560. #if !defined(PNG_1_0_X)
  184561. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  184562. void PNGAPI
  184563. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  184564. {
  184565. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  184566. if(png_ptr == NULL) return;
  184567. png_ptr->transformations |= PNG_EXPAND;
  184568. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184569. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  184570. #endif
  184571. }
  184572. #endif
  184573. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184574. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  184575. /* Deprecated as of libpng-1.2.9 */
  184576. void PNGAPI
  184577. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  184578. {
  184579. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  184580. if(png_ptr == NULL) return;
  184581. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  184582. }
  184583. #endif
  184584. /* Expand tRNS chunks to alpha channels. */
  184585. void PNGAPI
  184586. png_set_tRNS_to_alpha(png_structp png_ptr)
  184587. {
  184588. png_debug(1, "in png_set_tRNS_to_alpha\n");
  184589. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  184590. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184591. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  184592. #endif
  184593. }
  184594. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  184595. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184596. void PNGAPI
  184597. png_set_gray_to_rgb(png_structp png_ptr)
  184598. {
  184599. png_debug(1, "in png_set_gray_to_rgb\n");
  184600. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  184601. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184602. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  184603. #endif
  184604. }
  184605. #endif
  184606. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184607. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  184608. /* Convert a RGB image to a grayscale of the same width. This allows us,
  184609. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  184610. */
  184611. void PNGAPI
  184612. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  184613. double green)
  184614. {
  184615. int red_fixed = (int)((float)red*100000.0 + 0.5);
  184616. int green_fixed = (int)((float)green*100000.0 + 0.5);
  184617. if(png_ptr == NULL) return;
  184618. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  184619. }
  184620. #endif
  184621. void PNGAPI
  184622. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  184623. png_fixed_point red, png_fixed_point green)
  184624. {
  184625. png_debug(1, "in png_set_rgb_to_gray\n");
  184626. if(png_ptr == NULL) return;
  184627. switch(error_action)
  184628. {
  184629. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  184630. break;
  184631. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  184632. break;
  184633. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  184634. }
  184635. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  184636. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184637. png_ptr->transformations |= PNG_EXPAND;
  184638. #else
  184639. {
  184640. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  184641. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  184642. }
  184643. #endif
  184644. {
  184645. png_uint_16 red_int, green_int;
  184646. if(red < 0 || green < 0)
  184647. {
  184648. red_int = 6968; /* .212671 * 32768 + .5 */
  184649. green_int = 23434; /* .715160 * 32768 + .5 */
  184650. }
  184651. else if(red + green < 100000L)
  184652. {
  184653. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  184654. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  184655. }
  184656. else
  184657. {
  184658. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  184659. red_int = 6968;
  184660. green_int = 23434;
  184661. }
  184662. png_ptr->rgb_to_gray_red_coeff = red_int;
  184663. png_ptr->rgb_to_gray_green_coeff = green_int;
  184664. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  184665. }
  184666. }
  184667. #endif
  184668. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  184669. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  184670. defined(PNG_LEGACY_SUPPORTED)
  184671. void PNGAPI
  184672. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  184673. read_user_transform_fn)
  184674. {
  184675. png_debug(1, "in png_set_read_user_transform_fn\n");
  184676. if(png_ptr == NULL) return;
  184677. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  184678. png_ptr->transformations |= PNG_USER_TRANSFORM;
  184679. png_ptr->read_user_transform_fn = read_user_transform_fn;
  184680. #endif
  184681. #ifdef PNG_LEGACY_SUPPORTED
  184682. if(read_user_transform_fn)
  184683. png_warning(png_ptr,
  184684. "This version of libpng does not support user transforms");
  184685. #endif
  184686. }
  184687. #endif
  184688. /* Initialize everything needed for the read. This includes modifying
  184689. * the palette.
  184690. */
  184691. void /* PRIVATE */
  184692. png_init_read_transformations(png_structp png_ptr)
  184693. {
  184694. png_debug(1, "in png_init_read_transformations\n");
  184695. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  184696. if(png_ptr != NULL)
  184697. #endif
  184698. {
  184699. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  184700. || defined(PNG_READ_GAMMA_SUPPORTED)
  184701. int color_type = png_ptr->color_type;
  184702. #endif
  184703. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  184704. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184705. /* Detect gray background and attempt to enable optimization
  184706. * for gray --> RGB case */
  184707. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  184708. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  184709. * background color might actually be gray yet not be flagged as such.
  184710. * This is not a problem for the current code, which uses
  184711. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  184712. * png_do_gray_to_rgb() transformation.
  184713. */
  184714. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  184715. !(color_type & PNG_COLOR_MASK_COLOR))
  184716. {
  184717. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  184718. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  184719. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  184720. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  184721. png_ptr->background.red == png_ptr->background.green &&
  184722. png_ptr->background.red == png_ptr->background.blue)
  184723. {
  184724. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  184725. png_ptr->background.gray = png_ptr->background.red;
  184726. }
  184727. #endif
  184728. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  184729. (png_ptr->transformations & PNG_EXPAND))
  184730. {
  184731. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  184732. {
  184733. /* expand background and tRNS chunks */
  184734. switch (png_ptr->bit_depth)
  184735. {
  184736. case 1:
  184737. png_ptr->background.gray *= (png_uint_16)0xff;
  184738. png_ptr->background.red = png_ptr->background.green
  184739. = png_ptr->background.blue = png_ptr->background.gray;
  184740. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  184741. {
  184742. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  184743. png_ptr->trans_values.red = png_ptr->trans_values.green
  184744. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  184745. }
  184746. break;
  184747. case 2:
  184748. png_ptr->background.gray *= (png_uint_16)0x55;
  184749. png_ptr->background.red = png_ptr->background.green
  184750. = png_ptr->background.blue = png_ptr->background.gray;
  184751. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  184752. {
  184753. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  184754. png_ptr->trans_values.red = png_ptr->trans_values.green
  184755. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  184756. }
  184757. break;
  184758. case 4:
  184759. png_ptr->background.gray *= (png_uint_16)0x11;
  184760. png_ptr->background.red = png_ptr->background.green
  184761. = png_ptr->background.blue = png_ptr->background.gray;
  184762. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  184763. {
  184764. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  184765. png_ptr->trans_values.red = png_ptr->trans_values.green
  184766. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  184767. }
  184768. break;
  184769. case 8:
  184770. case 16:
  184771. png_ptr->background.red = png_ptr->background.green
  184772. = png_ptr->background.blue = png_ptr->background.gray;
  184773. break;
  184774. }
  184775. }
  184776. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  184777. {
  184778. png_ptr->background.red =
  184779. png_ptr->palette[png_ptr->background.index].red;
  184780. png_ptr->background.green =
  184781. png_ptr->palette[png_ptr->background.index].green;
  184782. png_ptr->background.blue =
  184783. png_ptr->palette[png_ptr->background.index].blue;
  184784. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184785. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  184786. {
  184787. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184788. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  184789. #endif
  184790. {
  184791. /* invert the alpha channel (in tRNS) unless the pixels are
  184792. going to be expanded, in which case leave it for later */
  184793. int i,istop;
  184794. istop=(int)png_ptr->num_trans;
  184795. for (i=0; i<istop; i++)
  184796. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  184797. }
  184798. }
  184799. #endif
  184800. }
  184801. }
  184802. #endif
  184803. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  184804. png_ptr->background_1 = png_ptr->background;
  184805. #endif
  184806. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184807. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  184808. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  184809. < PNG_GAMMA_THRESHOLD))
  184810. {
  184811. int i,k;
  184812. k=0;
  184813. for (i=0; i<png_ptr->num_trans; i++)
  184814. {
  184815. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  184816. k=1; /* partial transparency is present */
  184817. }
  184818. if (k == 0)
  184819. png_ptr->transformations &= (~PNG_GAMMA);
  184820. }
  184821. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  184822. png_ptr->gamma != 0.0)
  184823. {
  184824. png_build_gamma_table(png_ptr);
  184825. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184826. if (png_ptr->transformations & PNG_BACKGROUND)
  184827. {
  184828. if (color_type == PNG_COLOR_TYPE_PALETTE)
  184829. {
  184830. /* could skip if no transparency and
  184831. */
  184832. png_color back, back_1;
  184833. png_colorp palette = png_ptr->palette;
  184834. int num_palette = png_ptr->num_palette;
  184835. int i;
  184836. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  184837. {
  184838. back.red = png_ptr->gamma_table[png_ptr->background.red];
  184839. back.green = png_ptr->gamma_table[png_ptr->background.green];
  184840. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  184841. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  184842. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  184843. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  184844. }
  184845. else
  184846. {
  184847. double g, gs;
  184848. switch (png_ptr->background_gamma_type)
  184849. {
  184850. case PNG_BACKGROUND_GAMMA_SCREEN:
  184851. g = (png_ptr->screen_gamma);
  184852. gs = 1.0;
  184853. break;
  184854. case PNG_BACKGROUND_GAMMA_FILE:
  184855. g = 1.0 / (png_ptr->gamma);
  184856. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  184857. break;
  184858. case PNG_BACKGROUND_GAMMA_UNIQUE:
  184859. g = 1.0 / (png_ptr->background_gamma);
  184860. gs = 1.0 / (png_ptr->background_gamma *
  184861. png_ptr->screen_gamma);
  184862. break;
  184863. default:
  184864. g = 1.0; /* back_1 */
  184865. gs = 1.0; /* back */
  184866. }
  184867. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  184868. {
  184869. back.red = (png_byte)png_ptr->background.red;
  184870. back.green = (png_byte)png_ptr->background.green;
  184871. back.blue = (png_byte)png_ptr->background.blue;
  184872. }
  184873. else
  184874. {
  184875. back.red = (png_byte)(pow(
  184876. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  184877. back.green = (png_byte)(pow(
  184878. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  184879. back.blue = (png_byte)(pow(
  184880. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  184881. }
  184882. back_1.red = (png_byte)(pow(
  184883. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  184884. back_1.green = (png_byte)(pow(
  184885. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  184886. back_1.blue = (png_byte)(pow(
  184887. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  184888. }
  184889. for (i = 0; i < num_palette; i++)
  184890. {
  184891. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  184892. {
  184893. if (png_ptr->trans[i] == 0)
  184894. {
  184895. palette[i] = back;
  184896. }
  184897. else /* if (png_ptr->trans[i] != 0xff) */
  184898. {
  184899. png_byte v, w;
  184900. v = png_ptr->gamma_to_1[palette[i].red];
  184901. png_composite(w, v, png_ptr->trans[i], back_1.red);
  184902. palette[i].red = png_ptr->gamma_from_1[w];
  184903. v = png_ptr->gamma_to_1[palette[i].green];
  184904. png_composite(w, v, png_ptr->trans[i], back_1.green);
  184905. palette[i].green = png_ptr->gamma_from_1[w];
  184906. v = png_ptr->gamma_to_1[palette[i].blue];
  184907. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  184908. palette[i].blue = png_ptr->gamma_from_1[w];
  184909. }
  184910. }
  184911. else
  184912. {
  184913. palette[i].red = png_ptr->gamma_table[palette[i].red];
  184914. palette[i].green = png_ptr->gamma_table[palette[i].green];
  184915. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  184916. }
  184917. }
  184918. }
  184919. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  184920. else
  184921. /* color_type != PNG_COLOR_TYPE_PALETTE */
  184922. {
  184923. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  184924. double g = 1.0;
  184925. double gs = 1.0;
  184926. switch (png_ptr->background_gamma_type)
  184927. {
  184928. case PNG_BACKGROUND_GAMMA_SCREEN:
  184929. g = (png_ptr->screen_gamma);
  184930. gs = 1.0;
  184931. break;
  184932. case PNG_BACKGROUND_GAMMA_FILE:
  184933. g = 1.0 / (png_ptr->gamma);
  184934. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  184935. break;
  184936. case PNG_BACKGROUND_GAMMA_UNIQUE:
  184937. g = 1.0 / (png_ptr->background_gamma);
  184938. gs = 1.0 / (png_ptr->background_gamma *
  184939. png_ptr->screen_gamma);
  184940. break;
  184941. }
  184942. png_ptr->background_1.gray = (png_uint_16)(pow(
  184943. (double)png_ptr->background.gray / m, g) * m + .5);
  184944. png_ptr->background.gray = (png_uint_16)(pow(
  184945. (double)png_ptr->background.gray / m, gs) * m + .5);
  184946. if ((png_ptr->background.red != png_ptr->background.green) ||
  184947. (png_ptr->background.red != png_ptr->background.blue) ||
  184948. (png_ptr->background.red != png_ptr->background.gray))
  184949. {
  184950. /* RGB or RGBA with color background */
  184951. png_ptr->background_1.red = (png_uint_16)(pow(
  184952. (double)png_ptr->background.red / m, g) * m + .5);
  184953. png_ptr->background_1.green = (png_uint_16)(pow(
  184954. (double)png_ptr->background.green / m, g) * m + .5);
  184955. png_ptr->background_1.blue = (png_uint_16)(pow(
  184956. (double)png_ptr->background.blue / m, g) * m + .5);
  184957. png_ptr->background.red = (png_uint_16)(pow(
  184958. (double)png_ptr->background.red / m, gs) * m + .5);
  184959. png_ptr->background.green = (png_uint_16)(pow(
  184960. (double)png_ptr->background.green / m, gs) * m + .5);
  184961. png_ptr->background.blue = (png_uint_16)(pow(
  184962. (double)png_ptr->background.blue / m, gs) * m + .5);
  184963. }
  184964. else
  184965. {
  184966. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  184967. png_ptr->background_1.red = png_ptr->background_1.green
  184968. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  184969. png_ptr->background.red = png_ptr->background.green
  184970. = png_ptr->background.blue = png_ptr->background.gray;
  184971. }
  184972. }
  184973. }
  184974. else
  184975. /* transformation does not include PNG_BACKGROUND */
  184976. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  184977. if (color_type == PNG_COLOR_TYPE_PALETTE)
  184978. {
  184979. png_colorp palette = png_ptr->palette;
  184980. int num_palette = png_ptr->num_palette;
  184981. int i;
  184982. for (i = 0; i < num_palette; i++)
  184983. {
  184984. palette[i].red = png_ptr->gamma_table[palette[i].red];
  184985. palette[i].green = png_ptr->gamma_table[palette[i].green];
  184986. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  184987. }
  184988. }
  184989. }
  184990. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184991. else
  184992. #endif
  184993. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  184994. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184995. /* No GAMMA transformation */
  184996. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  184997. (color_type == PNG_COLOR_TYPE_PALETTE))
  184998. {
  184999. int i;
  185000. int istop = (int)png_ptr->num_trans;
  185001. png_color back;
  185002. png_colorp palette = png_ptr->palette;
  185003. back.red = (png_byte)png_ptr->background.red;
  185004. back.green = (png_byte)png_ptr->background.green;
  185005. back.blue = (png_byte)png_ptr->background.blue;
  185006. for (i = 0; i < istop; i++)
  185007. {
  185008. if (png_ptr->trans[i] == 0)
  185009. {
  185010. palette[i] = back;
  185011. }
  185012. else if (png_ptr->trans[i] != 0xff)
  185013. {
  185014. /* The png_composite() macro is defined in png.h */
  185015. png_composite(palette[i].red, palette[i].red,
  185016. png_ptr->trans[i], back.red);
  185017. png_composite(palette[i].green, palette[i].green,
  185018. png_ptr->trans[i], back.green);
  185019. png_composite(palette[i].blue, palette[i].blue,
  185020. png_ptr->trans[i], back.blue);
  185021. }
  185022. }
  185023. }
  185024. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  185025. #if defined(PNG_READ_SHIFT_SUPPORTED)
  185026. if ((png_ptr->transformations & PNG_SHIFT) &&
  185027. (color_type == PNG_COLOR_TYPE_PALETTE))
  185028. {
  185029. png_uint_16 i;
  185030. png_uint_16 istop = png_ptr->num_palette;
  185031. int sr = 8 - png_ptr->sig_bit.red;
  185032. int sg = 8 - png_ptr->sig_bit.green;
  185033. int sb = 8 - png_ptr->sig_bit.blue;
  185034. if (sr < 0 || sr > 8)
  185035. sr = 0;
  185036. if (sg < 0 || sg > 8)
  185037. sg = 0;
  185038. if (sb < 0 || sb > 8)
  185039. sb = 0;
  185040. for (i = 0; i < istop; i++)
  185041. {
  185042. png_ptr->palette[i].red >>= sr;
  185043. png_ptr->palette[i].green >>= sg;
  185044. png_ptr->palette[i].blue >>= sb;
  185045. }
  185046. }
  185047. #endif /* PNG_READ_SHIFT_SUPPORTED */
  185048. }
  185049. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  185050. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  185051. if(png_ptr)
  185052. return;
  185053. #endif
  185054. }
  185055. /* Modify the info structure to reflect the transformations. The
  185056. * info should be updated so a PNG file could be written with it,
  185057. * assuming the transformations result in valid PNG data.
  185058. */
  185059. void /* PRIVATE */
  185060. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  185061. {
  185062. png_debug(1, "in png_read_transform_info\n");
  185063. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185064. if (png_ptr->transformations & PNG_EXPAND)
  185065. {
  185066. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185067. {
  185068. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  185069. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  185070. else
  185071. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  185072. info_ptr->bit_depth = 8;
  185073. info_ptr->num_trans = 0;
  185074. }
  185075. else
  185076. {
  185077. if (png_ptr->num_trans)
  185078. {
  185079. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  185080. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  185081. else
  185082. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  185083. }
  185084. if (info_ptr->bit_depth < 8)
  185085. info_ptr->bit_depth = 8;
  185086. info_ptr->num_trans = 0;
  185087. }
  185088. }
  185089. #endif
  185090. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185091. if (png_ptr->transformations & PNG_BACKGROUND)
  185092. {
  185093. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  185094. info_ptr->num_trans = 0;
  185095. info_ptr->background = png_ptr->background;
  185096. }
  185097. #endif
  185098. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185099. if (png_ptr->transformations & PNG_GAMMA)
  185100. {
  185101. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185102. info_ptr->gamma = png_ptr->gamma;
  185103. #endif
  185104. #ifdef PNG_FIXED_POINT_SUPPORTED
  185105. info_ptr->int_gamma = png_ptr->int_gamma;
  185106. #endif
  185107. }
  185108. #endif
  185109. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185110. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  185111. info_ptr->bit_depth = 8;
  185112. #endif
  185113. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185114. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  185115. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  185116. #endif
  185117. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185118. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  185119. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  185120. #endif
  185121. #if defined(PNG_READ_DITHER_SUPPORTED)
  185122. if (png_ptr->transformations & PNG_DITHER)
  185123. {
  185124. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  185125. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  185126. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  185127. {
  185128. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  185129. }
  185130. }
  185131. #endif
  185132. #if defined(PNG_READ_PACK_SUPPORTED)
  185133. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  185134. info_ptr->bit_depth = 8;
  185135. #endif
  185136. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185137. info_ptr->channels = 1;
  185138. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  185139. info_ptr->channels = 3;
  185140. else
  185141. info_ptr->channels = 1;
  185142. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  185143. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  185144. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  185145. #endif
  185146. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  185147. info_ptr->channels++;
  185148. #if defined(PNG_READ_FILLER_SUPPORTED)
  185149. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  185150. if ((png_ptr->transformations & PNG_FILLER) &&
  185151. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  185152. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  185153. {
  185154. info_ptr->channels++;
  185155. /* if adding a true alpha channel not just filler */
  185156. #if !defined(PNG_1_0_X)
  185157. if (png_ptr->transformations & PNG_ADD_ALPHA)
  185158. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  185159. #endif
  185160. }
  185161. #endif
  185162. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  185163. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  185164. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  185165. {
  185166. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  185167. info_ptr->bit_depth = png_ptr->user_transform_depth;
  185168. if(info_ptr->channels < png_ptr->user_transform_channels)
  185169. info_ptr->channels = png_ptr->user_transform_channels;
  185170. }
  185171. #endif
  185172. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  185173. info_ptr->bit_depth);
  185174. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  185175. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  185176. if(png_ptr)
  185177. return;
  185178. #endif
  185179. }
  185180. /* Transform the row. The order of transformations is significant,
  185181. * and is very touchy. If you add a transformation, take care to
  185182. * decide how it fits in with the other transformations here.
  185183. */
  185184. void /* PRIVATE */
  185185. png_do_read_transformations(png_structp png_ptr)
  185186. {
  185187. png_debug(1, "in png_do_read_transformations\n");
  185188. if (png_ptr->row_buf == NULL)
  185189. {
  185190. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  185191. char msg[50];
  185192. png_snprintf2(msg, 50,
  185193. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  185194. png_ptr->pass);
  185195. png_error(png_ptr, msg);
  185196. #else
  185197. png_error(png_ptr, "NULL row buffer");
  185198. #endif
  185199. }
  185200. #ifdef PNG_WARN_UNINITIALIZED_ROW
  185201. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  185202. /* Application has failed to call either png_read_start_image()
  185203. * or png_read_update_info() after setting transforms that expand
  185204. * pixels. This check added to libpng-1.2.19 */
  185205. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  185206. png_error(png_ptr, "Uninitialized row");
  185207. #else
  185208. png_warning(png_ptr, "Uninitialized row");
  185209. #endif
  185210. #endif
  185211. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185212. if (png_ptr->transformations & PNG_EXPAND)
  185213. {
  185214. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  185215. {
  185216. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185217. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  185218. }
  185219. else
  185220. {
  185221. if (png_ptr->num_trans &&
  185222. (png_ptr->transformations & PNG_EXPAND_tRNS))
  185223. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185224. &(png_ptr->trans_values));
  185225. else
  185226. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185227. NULL);
  185228. }
  185229. }
  185230. #endif
  185231. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  185232. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  185233. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185234. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  185235. #endif
  185236. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185237. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  185238. {
  185239. int rgb_error =
  185240. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  185241. if(rgb_error)
  185242. {
  185243. png_ptr->rgb_to_gray_status=1;
  185244. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  185245. PNG_RGB_TO_GRAY_WARN)
  185246. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  185247. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  185248. PNG_RGB_TO_GRAY_ERR)
  185249. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  185250. }
  185251. }
  185252. #endif
  185253. /*
  185254. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  185255. In most cases, the "simple transparency" should be done prior to doing
  185256. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  185257. pixel is transparent. You would also need to make sure that the
  185258. transparency information is upgraded to RGB.
  185259. To summarize, the current flow is:
  185260. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  185261. with background "in place" if transparent,
  185262. convert to RGB if necessary
  185263. - Gray + alpha -> composite with gray background and remove alpha bytes,
  185264. convert to RGB if necessary
  185265. To support RGB backgrounds for gray images we need:
  185266. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  185267. 3 or 6 bytes and composite with background
  185268. "in place" if transparent (3x compare/pixel
  185269. compared to doing composite with gray bkgrnd)
  185270. - Gray + alpha -> convert to RGB + alpha, composite with background and
  185271. remove alpha bytes (3x float operations/pixel
  185272. compared with composite on gray background)
  185273. Greg's change will do this. The reason it wasn't done before is for
  185274. performance, as this increases the per-pixel operations. If we would check
  185275. in advance if the background was gray or RGB, and position the gray-to-RGB
  185276. transform appropriately, then it would save a lot of work/time.
  185277. */
  185278. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185279. /* if gray -> RGB, do so now only if background is non-gray; else do later
  185280. * for performance reasons */
  185281. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  185282. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  185283. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185284. #endif
  185285. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185286. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  185287. ((png_ptr->num_trans != 0 ) ||
  185288. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  185289. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185290. &(png_ptr->trans_values), &(png_ptr->background)
  185291. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185292. , &(png_ptr->background_1),
  185293. png_ptr->gamma_table, png_ptr->gamma_from_1,
  185294. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  185295. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  185296. png_ptr->gamma_shift
  185297. #endif
  185298. );
  185299. #endif
  185300. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185301. if ((png_ptr->transformations & PNG_GAMMA) &&
  185302. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185303. !((png_ptr->transformations & PNG_BACKGROUND) &&
  185304. ((png_ptr->num_trans != 0) ||
  185305. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  185306. #endif
  185307. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  185308. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185309. png_ptr->gamma_table, png_ptr->gamma_16_table,
  185310. png_ptr->gamma_shift);
  185311. #endif
  185312. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185313. if (png_ptr->transformations & PNG_16_TO_8)
  185314. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185315. #endif
  185316. #if defined(PNG_READ_DITHER_SUPPORTED)
  185317. if (png_ptr->transformations & PNG_DITHER)
  185318. {
  185319. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  185320. png_ptr->palette_lookup, png_ptr->dither_index);
  185321. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  185322. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  185323. }
  185324. #endif
  185325. #if defined(PNG_READ_INVERT_SUPPORTED)
  185326. if (png_ptr->transformations & PNG_INVERT_MONO)
  185327. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185328. #endif
  185329. #if defined(PNG_READ_SHIFT_SUPPORTED)
  185330. if (png_ptr->transformations & PNG_SHIFT)
  185331. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185332. &(png_ptr->shift));
  185333. #endif
  185334. #if defined(PNG_READ_PACK_SUPPORTED)
  185335. if (png_ptr->transformations & PNG_PACK)
  185336. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185337. #endif
  185338. #if defined(PNG_READ_BGR_SUPPORTED)
  185339. if (png_ptr->transformations & PNG_BGR)
  185340. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185341. #endif
  185342. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  185343. if (png_ptr->transformations & PNG_PACKSWAP)
  185344. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185345. #endif
  185346. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185347. /* if gray -> RGB, do so now only if we did not do so above */
  185348. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  185349. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  185350. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185351. #endif
  185352. #if defined(PNG_READ_FILLER_SUPPORTED)
  185353. if (png_ptr->transformations & PNG_FILLER)
  185354. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  185355. (png_uint_32)png_ptr->filler, png_ptr->flags);
  185356. #endif
  185357. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  185358. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  185359. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185360. #endif
  185361. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  185362. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  185363. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185364. #endif
  185365. #if defined(PNG_READ_SWAP_SUPPORTED)
  185366. if (png_ptr->transformations & PNG_SWAP_BYTES)
  185367. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  185368. #endif
  185369. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  185370. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  185371. {
  185372. if(png_ptr->read_user_transform_fn != NULL)
  185373. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  185374. (png_ptr, /* png_ptr */
  185375. &(png_ptr->row_info), /* row_info: */
  185376. /* png_uint_32 width; width of row */
  185377. /* png_uint_32 rowbytes; number of bytes in row */
  185378. /* png_byte color_type; color type of pixels */
  185379. /* png_byte bit_depth; bit depth of samples */
  185380. /* png_byte channels; number of channels (1-4) */
  185381. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  185382. png_ptr->row_buf + 1); /* start of pixel data for row */
  185383. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  185384. if(png_ptr->user_transform_depth)
  185385. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  185386. if(png_ptr->user_transform_channels)
  185387. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  185388. #endif
  185389. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  185390. png_ptr->row_info.channels);
  185391. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  185392. png_ptr->row_info.width);
  185393. }
  185394. #endif
  185395. }
  185396. #if defined(PNG_READ_PACK_SUPPORTED)
  185397. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  185398. * without changing the actual values. Thus, if you had a row with
  185399. * a bit depth of 1, you would end up with bytes that only contained
  185400. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  185401. * png_do_shift() after this.
  185402. */
  185403. void /* PRIVATE */
  185404. png_do_unpack(png_row_infop row_info, png_bytep row)
  185405. {
  185406. png_debug(1, "in png_do_unpack\n");
  185407. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185408. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  185409. #else
  185410. if (row_info->bit_depth < 8)
  185411. #endif
  185412. {
  185413. png_uint_32 i;
  185414. png_uint_32 row_width=row_info->width;
  185415. switch (row_info->bit_depth)
  185416. {
  185417. case 1:
  185418. {
  185419. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  185420. png_bytep dp = row + (png_size_t)row_width - 1;
  185421. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  185422. for (i = 0; i < row_width; i++)
  185423. {
  185424. *dp = (png_byte)((*sp >> shift) & 0x01);
  185425. if (shift == 7)
  185426. {
  185427. shift = 0;
  185428. sp--;
  185429. }
  185430. else
  185431. shift++;
  185432. dp--;
  185433. }
  185434. break;
  185435. }
  185436. case 2:
  185437. {
  185438. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  185439. png_bytep dp = row + (png_size_t)row_width - 1;
  185440. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  185441. for (i = 0; i < row_width; i++)
  185442. {
  185443. *dp = (png_byte)((*sp >> shift) & 0x03);
  185444. if (shift == 6)
  185445. {
  185446. shift = 0;
  185447. sp--;
  185448. }
  185449. else
  185450. shift += 2;
  185451. dp--;
  185452. }
  185453. break;
  185454. }
  185455. case 4:
  185456. {
  185457. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  185458. png_bytep dp = row + (png_size_t)row_width - 1;
  185459. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  185460. for (i = 0; i < row_width; i++)
  185461. {
  185462. *dp = (png_byte)((*sp >> shift) & 0x0f);
  185463. if (shift == 4)
  185464. {
  185465. shift = 0;
  185466. sp--;
  185467. }
  185468. else
  185469. shift = 4;
  185470. dp--;
  185471. }
  185472. break;
  185473. }
  185474. }
  185475. row_info->bit_depth = 8;
  185476. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  185477. row_info->rowbytes = row_width * row_info->channels;
  185478. }
  185479. }
  185480. #endif
  185481. #if defined(PNG_READ_SHIFT_SUPPORTED)
  185482. /* Reverse the effects of png_do_shift. This routine merely shifts the
  185483. * pixels back to their significant bits values. Thus, if you have
  185484. * a row of bit depth 8, but only 5 are significant, this will shift
  185485. * the values back to 0 through 31.
  185486. */
  185487. void /* PRIVATE */
  185488. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  185489. {
  185490. png_debug(1, "in png_do_unshift\n");
  185491. if (
  185492. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185493. row != NULL && row_info != NULL && sig_bits != NULL &&
  185494. #endif
  185495. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  185496. {
  185497. int shift[4];
  185498. int channels = 0;
  185499. int c;
  185500. png_uint_16 value = 0;
  185501. png_uint_32 row_width = row_info->width;
  185502. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  185503. {
  185504. shift[channels++] = row_info->bit_depth - sig_bits->red;
  185505. shift[channels++] = row_info->bit_depth - sig_bits->green;
  185506. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  185507. }
  185508. else
  185509. {
  185510. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  185511. }
  185512. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  185513. {
  185514. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  185515. }
  185516. for (c = 0; c < channels; c++)
  185517. {
  185518. if (shift[c] <= 0)
  185519. shift[c] = 0;
  185520. else
  185521. value = 1;
  185522. }
  185523. if (!value)
  185524. return;
  185525. switch (row_info->bit_depth)
  185526. {
  185527. case 2:
  185528. {
  185529. png_bytep bp;
  185530. png_uint_32 i;
  185531. png_uint_32 istop = row_info->rowbytes;
  185532. for (bp = row, i = 0; i < istop; i++)
  185533. {
  185534. *bp >>= 1;
  185535. *bp++ &= 0x55;
  185536. }
  185537. break;
  185538. }
  185539. case 4:
  185540. {
  185541. png_bytep bp = row;
  185542. png_uint_32 i;
  185543. png_uint_32 istop = row_info->rowbytes;
  185544. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  185545. (png_byte)((int)0xf >> shift[0]));
  185546. for (i = 0; i < istop; i++)
  185547. {
  185548. *bp >>= shift[0];
  185549. *bp++ &= mask;
  185550. }
  185551. break;
  185552. }
  185553. case 8:
  185554. {
  185555. png_bytep bp = row;
  185556. png_uint_32 i;
  185557. png_uint_32 istop = row_width * channels;
  185558. for (i = 0; i < istop; i++)
  185559. {
  185560. *bp++ >>= shift[i%channels];
  185561. }
  185562. break;
  185563. }
  185564. case 16:
  185565. {
  185566. png_bytep bp = row;
  185567. png_uint_32 i;
  185568. png_uint_32 istop = channels * row_width;
  185569. for (i = 0; i < istop; i++)
  185570. {
  185571. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  185572. value >>= shift[i%channels];
  185573. *bp++ = (png_byte)(value >> 8);
  185574. *bp++ = (png_byte)(value & 0xff);
  185575. }
  185576. break;
  185577. }
  185578. }
  185579. }
  185580. }
  185581. #endif
  185582. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185583. /* chop rows of bit depth 16 down to 8 */
  185584. void /* PRIVATE */
  185585. png_do_chop(png_row_infop row_info, png_bytep row)
  185586. {
  185587. png_debug(1, "in png_do_chop\n");
  185588. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185589. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  185590. #else
  185591. if (row_info->bit_depth == 16)
  185592. #endif
  185593. {
  185594. png_bytep sp = row;
  185595. png_bytep dp = row;
  185596. png_uint_32 i;
  185597. png_uint_32 istop = row_info->width * row_info->channels;
  185598. for (i = 0; i<istop; i++, sp += 2, dp++)
  185599. {
  185600. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  185601. /* This does a more accurate scaling of the 16-bit color
  185602. * value, rather than a simple low-byte truncation.
  185603. *
  185604. * What the ideal calculation should be:
  185605. * *dp = (((((png_uint_32)(*sp) << 8) |
  185606. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  185607. *
  185608. * GRR: no, I think this is what it really should be:
  185609. * *dp = (((((png_uint_32)(*sp) << 8) |
  185610. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  185611. *
  185612. * GRR: here's the exact calculation with shifts:
  185613. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  185614. * *dp = (temp - (temp >> 8)) >> 8;
  185615. *
  185616. * Approximate calculation with shift/add instead of multiply/divide:
  185617. * *dp = ((((png_uint_32)(*sp) << 8) |
  185618. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  185619. *
  185620. * What we actually do to avoid extra shifting and conversion:
  185621. */
  185622. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  185623. #else
  185624. /* Simply discard the low order byte */
  185625. *dp = *sp;
  185626. #endif
  185627. }
  185628. row_info->bit_depth = 8;
  185629. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  185630. row_info->rowbytes = row_info->width * row_info->channels;
  185631. }
  185632. }
  185633. #endif
  185634. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  185635. void /* PRIVATE */
  185636. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  185637. {
  185638. png_debug(1, "in png_do_read_swap_alpha\n");
  185639. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185640. if (row != NULL && row_info != NULL)
  185641. #endif
  185642. {
  185643. png_uint_32 row_width = row_info->width;
  185644. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  185645. {
  185646. /* This converts from RGBA to ARGB */
  185647. if (row_info->bit_depth == 8)
  185648. {
  185649. png_bytep sp = row + row_info->rowbytes;
  185650. png_bytep dp = sp;
  185651. png_byte save;
  185652. png_uint_32 i;
  185653. for (i = 0; i < row_width; i++)
  185654. {
  185655. save = *(--sp);
  185656. *(--dp) = *(--sp);
  185657. *(--dp) = *(--sp);
  185658. *(--dp) = *(--sp);
  185659. *(--dp) = save;
  185660. }
  185661. }
  185662. /* This converts from RRGGBBAA to AARRGGBB */
  185663. else
  185664. {
  185665. png_bytep sp = row + row_info->rowbytes;
  185666. png_bytep dp = sp;
  185667. png_byte save[2];
  185668. png_uint_32 i;
  185669. for (i = 0; i < row_width; i++)
  185670. {
  185671. save[0] = *(--sp);
  185672. save[1] = *(--sp);
  185673. *(--dp) = *(--sp);
  185674. *(--dp) = *(--sp);
  185675. *(--dp) = *(--sp);
  185676. *(--dp) = *(--sp);
  185677. *(--dp) = *(--sp);
  185678. *(--dp) = *(--sp);
  185679. *(--dp) = save[0];
  185680. *(--dp) = save[1];
  185681. }
  185682. }
  185683. }
  185684. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  185685. {
  185686. /* This converts from GA to AG */
  185687. if (row_info->bit_depth == 8)
  185688. {
  185689. png_bytep sp = row + row_info->rowbytes;
  185690. png_bytep dp = sp;
  185691. png_byte save;
  185692. png_uint_32 i;
  185693. for (i = 0; i < row_width; i++)
  185694. {
  185695. save = *(--sp);
  185696. *(--dp) = *(--sp);
  185697. *(--dp) = save;
  185698. }
  185699. }
  185700. /* This converts from GGAA to AAGG */
  185701. else
  185702. {
  185703. png_bytep sp = row + row_info->rowbytes;
  185704. png_bytep dp = sp;
  185705. png_byte save[2];
  185706. png_uint_32 i;
  185707. for (i = 0; i < row_width; i++)
  185708. {
  185709. save[0] = *(--sp);
  185710. save[1] = *(--sp);
  185711. *(--dp) = *(--sp);
  185712. *(--dp) = *(--sp);
  185713. *(--dp) = save[0];
  185714. *(--dp) = save[1];
  185715. }
  185716. }
  185717. }
  185718. }
  185719. }
  185720. #endif
  185721. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  185722. void /* PRIVATE */
  185723. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  185724. {
  185725. png_debug(1, "in png_do_read_invert_alpha\n");
  185726. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185727. if (row != NULL && row_info != NULL)
  185728. #endif
  185729. {
  185730. png_uint_32 row_width = row_info->width;
  185731. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  185732. {
  185733. /* This inverts the alpha channel in RGBA */
  185734. if (row_info->bit_depth == 8)
  185735. {
  185736. png_bytep sp = row + row_info->rowbytes;
  185737. png_bytep dp = sp;
  185738. png_uint_32 i;
  185739. for (i = 0; i < row_width; i++)
  185740. {
  185741. *(--dp) = (png_byte)(255 - *(--sp));
  185742. /* This does nothing:
  185743. *(--dp) = *(--sp);
  185744. *(--dp) = *(--sp);
  185745. *(--dp) = *(--sp);
  185746. We can replace it with:
  185747. */
  185748. sp-=3;
  185749. dp=sp;
  185750. }
  185751. }
  185752. /* This inverts the alpha channel in RRGGBBAA */
  185753. else
  185754. {
  185755. png_bytep sp = row + row_info->rowbytes;
  185756. png_bytep dp = sp;
  185757. png_uint_32 i;
  185758. for (i = 0; i < row_width; i++)
  185759. {
  185760. *(--dp) = (png_byte)(255 - *(--sp));
  185761. *(--dp) = (png_byte)(255 - *(--sp));
  185762. /* This does nothing:
  185763. *(--dp) = *(--sp);
  185764. *(--dp) = *(--sp);
  185765. *(--dp) = *(--sp);
  185766. *(--dp) = *(--sp);
  185767. *(--dp) = *(--sp);
  185768. *(--dp) = *(--sp);
  185769. We can replace it with:
  185770. */
  185771. sp-=6;
  185772. dp=sp;
  185773. }
  185774. }
  185775. }
  185776. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  185777. {
  185778. /* This inverts the alpha channel in GA */
  185779. if (row_info->bit_depth == 8)
  185780. {
  185781. png_bytep sp = row + row_info->rowbytes;
  185782. png_bytep dp = sp;
  185783. png_uint_32 i;
  185784. for (i = 0; i < row_width; i++)
  185785. {
  185786. *(--dp) = (png_byte)(255 - *(--sp));
  185787. *(--dp) = *(--sp);
  185788. }
  185789. }
  185790. /* This inverts the alpha channel in GGAA */
  185791. else
  185792. {
  185793. png_bytep sp = row + row_info->rowbytes;
  185794. png_bytep dp = sp;
  185795. png_uint_32 i;
  185796. for (i = 0; i < row_width; i++)
  185797. {
  185798. *(--dp) = (png_byte)(255 - *(--sp));
  185799. *(--dp) = (png_byte)(255 - *(--sp));
  185800. /*
  185801. *(--dp) = *(--sp);
  185802. *(--dp) = *(--sp);
  185803. */
  185804. sp-=2;
  185805. dp=sp;
  185806. }
  185807. }
  185808. }
  185809. }
  185810. }
  185811. #endif
  185812. #if defined(PNG_READ_FILLER_SUPPORTED)
  185813. /* Add filler channel if we have RGB color */
  185814. void /* PRIVATE */
  185815. png_do_read_filler(png_row_infop row_info, png_bytep row,
  185816. png_uint_32 filler, png_uint_32 flags)
  185817. {
  185818. png_uint_32 i;
  185819. png_uint_32 row_width = row_info->width;
  185820. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  185821. png_byte lo_filler = (png_byte)(filler & 0xff);
  185822. png_debug(1, "in png_do_read_filler\n");
  185823. if (
  185824. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185825. row != NULL && row_info != NULL &&
  185826. #endif
  185827. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  185828. {
  185829. if(row_info->bit_depth == 8)
  185830. {
  185831. /* This changes the data from G to GX */
  185832. if (flags & PNG_FLAG_FILLER_AFTER)
  185833. {
  185834. png_bytep sp = row + (png_size_t)row_width;
  185835. png_bytep dp = sp + (png_size_t)row_width;
  185836. for (i = 1; i < row_width; i++)
  185837. {
  185838. *(--dp) = lo_filler;
  185839. *(--dp) = *(--sp);
  185840. }
  185841. *(--dp) = lo_filler;
  185842. row_info->channels = 2;
  185843. row_info->pixel_depth = 16;
  185844. row_info->rowbytes = row_width * 2;
  185845. }
  185846. /* This changes the data from G to XG */
  185847. else
  185848. {
  185849. png_bytep sp = row + (png_size_t)row_width;
  185850. png_bytep dp = sp + (png_size_t)row_width;
  185851. for (i = 0; i < row_width; i++)
  185852. {
  185853. *(--dp) = *(--sp);
  185854. *(--dp) = lo_filler;
  185855. }
  185856. row_info->channels = 2;
  185857. row_info->pixel_depth = 16;
  185858. row_info->rowbytes = row_width * 2;
  185859. }
  185860. }
  185861. else if(row_info->bit_depth == 16)
  185862. {
  185863. /* This changes the data from GG to GGXX */
  185864. if (flags & PNG_FLAG_FILLER_AFTER)
  185865. {
  185866. png_bytep sp = row + (png_size_t)row_width * 2;
  185867. png_bytep dp = sp + (png_size_t)row_width * 2;
  185868. for (i = 1; i < row_width; i++)
  185869. {
  185870. *(--dp) = hi_filler;
  185871. *(--dp) = lo_filler;
  185872. *(--dp) = *(--sp);
  185873. *(--dp) = *(--sp);
  185874. }
  185875. *(--dp) = hi_filler;
  185876. *(--dp) = lo_filler;
  185877. row_info->channels = 2;
  185878. row_info->pixel_depth = 32;
  185879. row_info->rowbytes = row_width * 4;
  185880. }
  185881. /* This changes the data from GG to XXGG */
  185882. else
  185883. {
  185884. png_bytep sp = row + (png_size_t)row_width * 2;
  185885. png_bytep dp = sp + (png_size_t)row_width * 2;
  185886. for (i = 0; i < row_width; i++)
  185887. {
  185888. *(--dp) = *(--sp);
  185889. *(--dp) = *(--sp);
  185890. *(--dp) = hi_filler;
  185891. *(--dp) = lo_filler;
  185892. }
  185893. row_info->channels = 2;
  185894. row_info->pixel_depth = 32;
  185895. row_info->rowbytes = row_width * 4;
  185896. }
  185897. }
  185898. } /* COLOR_TYPE == GRAY */
  185899. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  185900. {
  185901. if(row_info->bit_depth == 8)
  185902. {
  185903. /* This changes the data from RGB to RGBX */
  185904. if (flags & PNG_FLAG_FILLER_AFTER)
  185905. {
  185906. png_bytep sp = row + (png_size_t)row_width * 3;
  185907. png_bytep dp = sp + (png_size_t)row_width;
  185908. for (i = 1; i < row_width; i++)
  185909. {
  185910. *(--dp) = lo_filler;
  185911. *(--dp) = *(--sp);
  185912. *(--dp) = *(--sp);
  185913. *(--dp) = *(--sp);
  185914. }
  185915. *(--dp) = lo_filler;
  185916. row_info->channels = 4;
  185917. row_info->pixel_depth = 32;
  185918. row_info->rowbytes = row_width * 4;
  185919. }
  185920. /* This changes the data from RGB to XRGB */
  185921. else
  185922. {
  185923. png_bytep sp = row + (png_size_t)row_width * 3;
  185924. png_bytep dp = sp + (png_size_t)row_width;
  185925. for (i = 0; i < row_width; i++)
  185926. {
  185927. *(--dp) = *(--sp);
  185928. *(--dp) = *(--sp);
  185929. *(--dp) = *(--sp);
  185930. *(--dp) = lo_filler;
  185931. }
  185932. row_info->channels = 4;
  185933. row_info->pixel_depth = 32;
  185934. row_info->rowbytes = row_width * 4;
  185935. }
  185936. }
  185937. else if(row_info->bit_depth == 16)
  185938. {
  185939. /* This changes the data from RRGGBB to RRGGBBXX */
  185940. if (flags & PNG_FLAG_FILLER_AFTER)
  185941. {
  185942. png_bytep sp = row + (png_size_t)row_width * 6;
  185943. png_bytep dp = sp + (png_size_t)row_width * 2;
  185944. for (i = 1; i < row_width; i++)
  185945. {
  185946. *(--dp) = hi_filler;
  185947. *(--dp) = lo_filler;
  185948. *(--dp) = *(--sp);
  185949. *(--dp) = *(--sp);
  185950. *(--dp) = *(--sp);
  185951. *(--dp) = *(--sp);
  185952. *(--dp) = *(--sp);
  185953. *(--dp) = *(--sp);
  185954. }
  185955. *(--dp) = hi_filler;
  185956. *(--dp) = lo_filler;
  185957. row_info->channels = 4;
  185958. row_info->pixel_depth = 64;
  185959. row_info->rowbytes = row_width * 8;
  185960. }
  185961. /* This changes the data from RRGGBB to XXRRGGBB */
  185962. else
  185963. {
  185964. png_bytep sp = row + (png_size_t)row_width * 6;
  185965. png_bytep dp = sp + (png_size_t)row_width * 2;
  185966. for (i = 0; i < row_width; i++)
  185967. {
  185968. *(--dp) = *(--sp);
  185969. *(--dp) = *(--sp);
  185970. *(--dp) = *(--sp);
  185971. *(--dp) = *(--sp);
  185972. *(--dp) = *(--sp);
  185973. *(--dp) = *(--sp);
  185974. *(--dp) = hi_filler;
  185975. *(--dp) = lo_filler;
  185976. }
  185977. row_info->channels = 4;
  185978. row_info->pixel_depth = 64;
  185979. row_info->rowbytes = row_width * 8;
  185980. }
  185981. }
  185982. } /* COLOR_TYPE == RGB */
  185983. }
  185984. #endif
  185985. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185986. /* expand grayscale files to RGB, with or without alpha */
  185987. void /* PRIVATE */
  185988. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  185989. {
  185990. png_uint_32 i;
  185991. png_uint_32 row_width = row_info->width;
  185992. png_debug(1, "in png_do_gray_to_rgb\n");
  185993. if (row_info->bit_depth >= 8 &&
  185994. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185995. row != NULL && row_info != NULL &&
  185996. #endif
  185997. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  185998. {
  185999. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  186000. {
  186001. if (row_info->bit_depth == 8)
  186002. {
  186003. png_bytep sp = row + (png_size_t)row_width - 1;
  186004. png_bytep dp = sp + (png_size_t)row_width * 2;
  186005. for (i = 0; i < row_width; i++)
  186006. {
  186007. *(dp--) = *sp;
  186008. *(dp--) = *sp;
  186009. *(dp--) = *(sp--);
  186010. }
  186011. }
  186012. else
  186013. {
  186014. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  186015. png_bytep dp = sp + (png_size_t)row_width * 4;
  186016. for (i = 0; i < row_width; i++)
  186017. {
  186018. *(dp--) = *sp;
  186019. *(dp--) = *(sp - 1);
  186020. *(dp--) = *sp;
  186021. *(dp--) = *(sp - 1);
  186022. *(dp--) = *(sp--);
  186023. *(dp--) = *(sp--);
  186024. }
  186025. }
  186026. }
  186027. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  186028. {
  186029. if (row_info->bit_depth == 8)
  186030. {
  186031. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  186032. png_bytep dp = sp + (png_size_t)row_width * 2;
  186033. for (i = 0; i < row_width; i++)
  186034. {
  186035. *(dp--) = *(sp--);
  186036. *(dp--) = *sp;
  186037. *(dp--) = *sp;
  186038. *(dp--) = *(sp--);
  186039. }
  186040. }
  186041. else
  186042. {
  186043. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  186044. png_bytep dp = sp + (png_size_t)row_width * 4;
  186045. for (i = 0; i < row_width; i++)
  186046. {
  186047. *(dp--) = *(sp--);
  186048. *(dp--) = *(sp--);
  186049. *(dp--) = *sp;
  186050. *(dp--) = *(sp - 1);
  186051. *(dp--) = *sp;
  186052. *(dp--) = *(sp - 1);
  186053. *(dp--) = *(sp--);
  186054. *(dp--) = *(sp--);
  186055. }
  186056. }
  186057. }
  186058. row_info->channels += (png_byte)2;
  186059. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  186060. row_info->pixel_depth = (png_byte)(row_info->channels *
  186061. row_info->bit_depth);
  186062. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  186063. }
  186064. }
  186065. #endif
  186066. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186067. /* reduce RGB files to grayscale, with or without alpha
  186068. * using the equation given in Poynton's ColorFAQ at
  186069. * <http://www.inforamp.net/~poynton/>
  186070. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  186071. *
  186072. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  186073. *
  186074. * We approximate this with
  186075. *
  186076. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  186077. *
  186078. * which can be expressed with integers as
  186079. *
  186080. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  186081. *
  186082. * The calculation is to be done in a linear colorspace.
  186083. *
  186084. * Other integer coefficents can be used via png_set_rgb_to_gray().
  186085. */
  186086. int /* PRIVATE */
  186087. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  186088. {
  186089. png_uint_32 i;
  186090. png_uint_32 row_width = row_info->width;
  186091. int rgb_error = 0;
  186092. png_debug(1, "in png_do_rgb_to_gray\n");
  186093. if (
  186094. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186095. row != NULL && row_info != NULL &&
  186096. #endif
  186097. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  186098. {
  186099. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  186100. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  186101. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  186102. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  186103. {
  186104. if (row_info->bit_depth == 8)
  186105. {
  186106. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  186107. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  186108. {
  186109. png_bytep sp = row;
  186110. png_bytep dp = row;
  186111. for (i = 0; i < row_width; i++)
  186112. {
  186113. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  186114. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  186115. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  186116. if(red != green || red != blue)
  186117. {
  186118. rgb_error |= 1;
  186119. *(dp++) = png_ptr->gamma_from_1[
  186120. (rc*red+gc*green+bc*blue)>>15];
  186121. }
  186122. else
  186123. *(dp++) = *(sp-1);
  186124. }
  186125. }
  186126. else
  186127. #endif
  186128. {
  186129. png_bytep sp = row;
  186130. png_bytep dp = row;
  186131. for (i = 0; i < row_width; i++)
  186132. {
  186133. png_byte red = *(sp++);
  186134. png_byte green = *(sp++);
  186135. png_byte blue = *(sp++);
  186136. if(red != green || red != blue)
  186137. {
  186138. rgb_error |= 1;
  186139. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  186140. }
  186141. else
  186142. *(dp++) = *(sp-1);
  186143. }
  186144. }
  186145. }
  186146. else /* RGB bit_depth == 16 */
  186147. {
  186148. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  186149. if (png_ptr->gamma_16_to_1 != NULL &&
  186150. png_ptr->gamma_16_from_1 != NULL)
  186151. {
  186152. png_bytep sp = row;
  186153. png_bytep dp = row;
  186154. for (i = 0; i < row_width; i++)
  186155. {
  186156. png_uint_16 red, green, blue, w;
  186157. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186158. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186159. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186160. if(red == green && red == blue)
  186161. w = red;
  186162. else
  186163. {
  186164. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  186165. png_ptr->gamma_shift][red>>8];
  186166. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  186167. png_ptr->gamma_shift][green>>8];
  186168. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  186169. png_ptr->gamma_shift][blue>>8];
  186170. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  186171. + bc*blue_1)>>15);
  186172. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  186173. png_ptr->gamma_shift][gray16 >> 8];
  186174. rgb_error |= 1;
  186175. }
  186176. *(dp++) = (png_byte)((w>>8) & 0xff);
  186177. *(dp++) = (png_byte)(w & 0xff);
  186178. }
  186179. }
  186180. else
  186181. #endif
  186182. {
  186183. png_bytep sp = row;
  186184. png_bytep dp = row;
  186185. for (i = 0; i < row_width; i++)
  186186. {
  186187. png_uint_16 red, green, blue, gray16;
  186188. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186189. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186190. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186191. if(red != green || red != blue)
  186192. rgb_error |= 1;
  186193. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  186194. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  186195. *(dp++) = (png_byte)(gray16 & 0xff);
  186196. }
  186197. }
  186198. }
  186199. }
  186200. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  186201. {
  186202. if (row_info->bit_depth == 8)
  186203. {
  186204. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  186205. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  186206. {
  186207. png_bytep sp = row;
  186208. png_bytep dp = row;
  186209. for (i = 0; i < row_width; i++)
  186210. {
  186211. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  186212. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  186213. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  186214. if(red != green || red != blue)
  186215. rgb_error |= 1;
  186216. *(dp++) = png_ptr->gamma_from_1
  186217. [(rc*red + gc*green + bc*blue)>>15];
  186218. *(dp++) = *(sp++); /* alpha */
  186219. }
  186220. }
  186221. else
  186222. #endif
  186223. {
  186224. png_bytep sp = row;
  186225. png_bytep dp = row;
  186226. for (i = 0; i < row_width; i++)
  186227. {
  186228. png_byte red = *(sp++);
  186229. png_byte green = *(sp++);
  186230. png_byte blue = *(sp++);
  186231. if(red != green || red != blue)
  186232. rgb_error |= 1;
  186233. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  186234. *(dp++) = *(sp++); /* alpha */
  186235. }
  186236. }
  186237. }
  186238. else /* RGBA bit_depth == 16 */
  186239. {
  186240. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  186241. if (png_ptr->gamma_16_to_1 != NULL &&
  186242. png_ptr->gamma_16_from_1 != NULL)
  186243. {
  186244. png_bytep sp = row;
  186245. png_bytep dp = row;
  186246. for (i = 0; i < row_width; i++)
  186247. {
  186248. png_uint_16 red, green, blue, w;
  186249. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186250. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186251. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  186252. if(red == green && red == blue)
  186253. w = red;
  186254. else
  186255. {
  186256. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  186257. png_ptr->gamma_shift][red>>8];
  186258. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  186259. png_ptr->gamma_shift][green>>8];
  186260. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  186261. png_ptr->gamma_shift][blue>>8];
  186262. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  186263. + gc * green_1 + bc * blue_1)>>15);
  186264. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  186265. png_ptr->gamma_shift][gray16 >> 8];
  186266. rgb_error |= 1;
  186267. }
  186268. *(dp++) = (png_byte)((w>>8) & 0xff);
  186269. *(dp++) = (png_byte)(w & 0xff);
  186270. *(dp++) = *(sp++); /* alpha */
  186271. *(dp++) = *(sp++);
  186272. }
  186273. }
  186274. else
  186275. #endif
  186276. {
  186277. png_bytep sp = row;
  186278. png_bytep dp = row;
  186279. for (i = 0; i < row_width; i++)
  186280. {
  186281. png_uint_16 red, green, blue, gray16;
  186282. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  186283. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  186284. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  186285. if(red != green || red != blue)
  186286. rgb_error |= 1;
  186287. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  186288. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  186289. *(dp++) = (png_byte)(gray16 & 0xff);
  186290. *(dp++) = *(sp++); /* alpha */
  186291. *(dp++) = *(sp++);
  186292. }
  186293. }
  186294. }
  186295. }
  186296. row_info->channels -= (png_byte)2;
  186297. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  186298. row_info->pixel_depth = (png_byte)(row_info->channels *
  186299. row_info->bit_depth);
  186300. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  186301. }
  186302. return rgb_error;
  186303. }
  186304. #endif
  186305. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  186306. * large of png_color. This lets grayscale images be treated as
  186307. * paletted. Most useful for gamma correction and simplification
  186308. * of code.
  186309. */
  186310. void PNGAPI
  186311. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  186312. {
  186313. int num_palette;
  186314. int color_inc;
  186315. int i;
  186316. int v;
  186317. png_debug(1, "in png_do_build_grayscale_palette\n");
  186318. if (palette == NULL)
  186319. return;
  186320. switch (bit_depth)
  186321. {
  186322. case 1:
  186323. num_palette = 2;
  186324. color_inc = 0xff;
  186325. break;
  186326. case 2:
  186327. num_palette = 4;
  186328. color_inc = 0x55;
  186329. break;
  186330. case 4:
  186331. num_palette = 16;
  186332. color_inc = 0x11;
  186333. break;
  186334. case 8:
  186335. num_palette = 256;
  186336. color_inc = 1;
  186337. break;
  186338. default:
  186339. num_palette = 0;
  186340. color_inc = 0;
  186341. break;
  186342. }
  186343. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  186344. {
  186345. palette[i].red = (png_byte)v;
  186346. palette[i].green = (png_byte)v;
  186347. palette[i].blue = (png_byte)v;
  186348. }
  186349. }
  186350. /* This function is currently unused. Do we really need it? */
  186351. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  186352. void /* PRIVATE */
  186353. png_correct_palette(png_structp png_ptr, png_colorp palette,
  186354. int num_palette)
  186355. {
  186356. png_debug(1, "in png_correct_palette\n");
  186357. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  186358. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186359. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  186360. {
  186361. png_color back, back_1;
  186362. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  186363. {
  186364. back.red = png_ptr->gamma_table[png_ptr->background.red];
  186365. back.green = png_ptr->gamma_table[png_ptr->background.green];
  186366. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  186367. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  186368. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  186369. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  186370. }
  186371. else
  186372. {
  186373. double g;
  186374. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  186375. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  186376. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  186377. {
  186378. back.red = png_ptr->background.red;
  186379. back.green = png_ptr->background.green;
  186380. back.blue = png_ptr->background.blue;
  186381. }
  186382. else
  186383. {
  186384. back.red =
  186385. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  186386. 255.0 + 0.5);
  186387. back.green =
  186388. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  186389. 255.0 + 0.5);
  186390. back.blue =
  186391. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  186392. 255.0 + 0.5);
  186393. }
  186394. g = 1.0 / png_ptr->background_gamma;
  186395. back_1.red =
  186396. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  186397. 255.0 + 0.5);
  186398. back_1.green =
  186399. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  186400. 255.0 + 0.5);
  186401. back_1.blue =
  186402. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  186403. 255.0 + 0.5);
  186404. }
  186405. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186406. {
  186407. png_uint_32 i;
  186408. for (i = 0; i < (png_uint_32)num_palette; i++)
  186409. {
  186410. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  186411. {
  186412. palette[i] = back;
  186413. }
  186414. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  186415. {
  186416. png_byte v, w;
  186417. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  186418. png_composite(w, v, png_ptr->trans[i], back_1.red);
  186419. palette[i].red = png_ptr->gamma_from_1[w];
  186420. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  186421. png_composite(w, v, png_ptr->trans[i], back_1.green);
  186422. palette[i].green = png_ptr->gamma_from_1[w];
  186423. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  186424. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  186425. palette[i].blue = png_ptr->gamma_from_1[w];
  186426. }
  186427. else
  186428. {
  186429. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186430. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186431. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186432. }
  186433. }
  186434. }
  186435. else
  186436. {
  186437. int i;
  186438. for (i = 0; i < num_palette; i++)
  186439. {
  186440. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  186441. {
  186442. palette[i] = back;
  186443. }
  186444. else
  186445. {
  186446. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186447. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186448. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186449. }
  186450. }
  186451. }
  186452. }
  186453. else
  186454. #endif
  186455. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186456. if (png_ptr->transformations & PNG_GAMMA)
  186457. {
  186458. int i;
  186459. for (i = 0; i < num_palette; i++)
  186460. {
  186461. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186462. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186463. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186464. }
  186465. }
  186466. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186467. else
  186468. #endif
  186469. #endif
  186470. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186471. if (png_ptr->transformations & PNG_BACKGROUND)
  186472. {
  186473. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186474. {
  186475. png_color back;
  186476. back.red = (png_byte)png_ptr->background.red;
  186477. back.green = (png_byte)png_ptr->background.green;
  186478. back.blue = (png_byte)png_ptr->background.blue;
  186479. for (i = 0; i < (int)png_ptr->num_trans; i++)
  186480. {
  186481. if (png_ptr->trans[i] == 0)
  186482. {
  186483. palette[i].red = back.red;
  186484. palette[i].green = back.green;
  186485. palette[i].blue = back.blue;
  186486. }
  186487. else if (png_ptr->trans[i] != 0xff)
  186488. {
  186489. png_composite(palette[i].red, png_ptr->palette[i].red,
  186490. png_ptr->trans[i], back.red);
  186491. png_composite(palette[i].green, png_ptr->palette[i].green,
  186492. png_ptr->trans[i], back.green);
  186493. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  186494. png_ptr->trans[i], back.blue);
  186495. }
  186496. }
  186497. }
  186498. else /* assume grayscale palette (what else could it be?) */
  186499. {
  186500. int i;
  186501. for (i = 0; i < num_palette; i++)
  186502. {
  186503. if (i == (png_byte)png_ptr->trans_values.gray)
  186504. {
  186505. palette[i].red = (png_byte)png_ptr->background.red;
  186506. palette[i].green = (png_byte)png_ptr->background.green;
  186507. palette[i].blue = (png_byte)png_ptr->background.blue;
  186508. }
  186509. }
  186510. }
  186511. }
  186512. #endif
  186513. }
  186514. #endif
  186515. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186516. /* Replace any alpha or transparency with the supplied background color.
  186517. * "background" is already in the screen gamma, while "background_1" is
  186518. * at a gamma of 1.0. Paletted files have already been taken care of.
  186519. */
  186520. void /* PRIVATE */
  186521. png_do_background(png_row_infop row_info, png_bytep row,
  186522. png_color_16p trans_values, png_color_16p background
  186523. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186524. , png_color_16p background_1,
  186525. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  186526. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  186527. png_uint_16pp gamma_16_to_1, int gamma_shift
  186528. #endif
  186529. )
  186530. {
  186531. png_bytep sp, dp;
  186532. png_uint_32 i;
  186533. png_uint_32 row_width=row_info->width;
  186534. int shift;
  186535. png_debug(1, "in png_do_background\n");
  186536. if (background != NULL &&
  186537. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186538. row != NULL && row_info != NULL &&
  186539. #endif
  186540. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  186541. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  186542. {
  186543. switch (row_info->color_type)
  186544. {
  186545. case PNG_COLOR_TYPE_GRAY:
  186546. {
  186547. switch (row_info->bit_depth)
  186548. {
  186549. case 1:
  186550. {
  186551. sp = row;
  186552. shift = 7;
  186553. for (i = 0; i < row_width; i++)
  186554. {
  186555. if ((png_uint_16)((*sp >> shift) & 0x01)
  186556. == trans_values->gray)
  186557. {
  186558. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  186559. *sp |= (png_byte)(background->gray << shift);
  186560. }
  186561. if (!shift)
  186562. {
  186563. shift = 7;
  186564. sp++;
  186565. }
  186566. else
  186567. shift--;
  186568. }
  186569. break;
  186570. }
  186571. case 2:
  186572. {
  186573. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186574. if (gamma_table != NULL)
  186575. {
  186576. sp = row;
  186577. shift = 6;
  186578. for (i = 0; i < row_width; i++)
  186579. {
  186580. if ((png_uint_16)((*sp >> shift) & 0x03)
  186581. == trans_values->gray)
  186582. {
  186583. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  186584. *sp |= (png_byte)(background->gray << shift);
  186585. }
  186586. else
  186587. {
  186588. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  186589. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  186590. (p << 4) | (p << 6)] >> 6) & 0x03);
  186591. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  186592. *sp |= (png_byte)(g << shift);
  186593. }
  186594. if (!shift)
  186595. {
  186596. shift = 6;
  186597. sp++;
  186598. }
  186599. else
  186600. shift -= 2;
  186601. }
  186602. }
  186603. else
  186604. #endif
  186605. {
  186606. sp = row;
  186607. shift = 6;
  186608. for (i = 0; i < row_width; i++)
  186609. {
  186610. if ((png_uint_16)((*sp >> shift) & 0x03)
  186611. == trans_values->gray)
  186612. {
  186613. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  186614. *sp |= (png_byte)(background->gray << shift);
  186615. }
  186616. if (!shift)
  186617. {
  186618. shift = 6;
  186619. sp++;
  186620. }
  186621. else
  186622. shift -= 2;
  186623. }
  186624. }
  186625. break;
  186626. }
  186627. case 4:
  186628. {
  186629. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186630. if (gamma_table != NULL)
  186631. {
  186632. sp = row;
  186633. shift = 4;
  186634. for (i = 0; i < row_width; i++)
  186635. {
  186636. if ((png_uint_16)((*sp >> shift) & 0x0f)
  186637. == trans_values->gray)
  186638. {
  186639. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  186640. *sp |= (png_byte)(background->gray << shift);
  186641. }
  186642. else
  186643. {
  186644. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  186645. png_byte g = (png_byte)((gamma_table[p |
  186646. (p << 4)] >> 4) & 0x0f);
  186647. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  186648. *sp |= (png_byte)(g << shift);
  186649. }
  186650. if (!shift)
  186651. {
  186652. shift = 4;
  186653. sp++;
  186654. }
  186655. else
  186656. shift -= 4;
  186657. }
  186658. }
  186659. else
  186660. #endif
  186661. {
  186662. sp = row;
  186663. shift = 4;
  186664. for (i = 0; i < row_width; i++)
  186665. {
  186666. if ((png_uint_16)((*sp >> shift) & 0x0f)
  186667. == trans_values->gray)
  186668. {
  186669. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  186670. *sp |= (png_byte)(background->gray << shift);
  186671. }
  186672. if (!shift)
  186673. {
  186674. shift = 4;
  186675. sp++;
  186676. }
  186677. else
  186678. shift -= 4;
  186679. }
  186680. }
  186681. break;
  186682. }
  186683. case 8:
  186684. {
  186685. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186686. if (gamma_table != NULL)
  186687. {
  186688. sp = row;
  186689. for (i = 0; i < row_width; i++, sp++)
  186690. {
  186691. if (*sp == trans_values->gray)
  186692. {
  186693. *sp = (png_byte)background->gray;
  186694. }
  186695. else
  186696. {
  186697. *sp = gamma_table[*sp];
  186698. }
  186699. }
  186700. }
  186701. else
  186702. #endif
  186703. {
  186704. sp = row;
  186705. for (i = 0; i < row_width; i++, sp++)
  186706. {
  186707. if (*sp == trans_values->gray)
  186708. {
  186709. *sp = (png_byte)background->gray;
  186710. }
  186711. }
  186712. }
  186713. break;
  186714. }
  186715. case 16:
  186716. {
  186717. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186718. if (gamma_16 != NULL)
  186719. {
  186720. sp = row;
  186721. for (i = 0; i < row_width; i++, sp += 2)
  186722. {
  186723. png_uint_16 v;
  186724. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186725. if (v == trans_values->gray)
  186726. {
  186727. /* background is already in screen gamma */
  186728. *sp = (png_byte)((background->gray >> 8) & 0xff);
  186729. *(sp + 1) = (png_byte)(background->gray & 0xff);
  186730. }
  186731. else
  186732. {
  186733. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  186734. *sp = (png_byte)((v >> 8) & 0xff);
  186735. *(sp + 1) = (png_byte)(v & 0xff);
  186736. }
  186737. }
  186738. }
  186739. else
  186740. #endif
  186741. {
  186742. sp = row;
  186743. for (i = 0; i < row_width; i++, sp += 2)
  186744. {
  186745. png_uint_16 v;
  186746. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186747. if (v == trans_values->gray)
  186748. {
  186749. *sp = (png_byte)((background->gray >> 8) & 0xff);
  186750. *(sp + 1) = (png_byte)(background->gray & 0xff);
  186751. }
  186752. }
  186753. }
  186754. break;
  186755. }
  186756. }
  186757. break;
  186758. }
  186759. case PNG_COLOR_TYPE_RGB:
  186760. {
  186761. if (row_info->bit_depth == 8)
  186762. {
  186763. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186764. if (gamma_table != NULL)
  186765. {
  186766. sp = row;
  186767. for (i = 0; i < row_width; i++, sp += 3)
  186768. {
  186769. if (*sp == trans_values->red &&
  186770. *(sp + 1) == trans_values->green &&
  186771. *(sp + 2) == trans_values->blue)
  186772. {
  186773. *sp = (png_byte)background->red;
  186774. *(sp + 1) = (png_byte)background->green;
  186775. *(sp + 2) = (png_byte)background->blue;
  186776. }
  186777. else
  186778. {
  186779. *sp = gamma_table[*sp];
  186780. *(sp + 1) = gamma_table[*(sp + 1)];
  186781. *(sp + 2) = gamma_table[*(sp + 2)];
  186782. }
  186783. }
  186784. }
  186785. else
  186786. #endif
  186787. {
  186788. sp = row;
  186789. for (i = 0; i < row_width; i++, sp += 3)
  186790. {
  186791. if (*sp == trans_values->red &&
  186792. *(sp + 1) == trans_values->green &&
  186793. *(sp + 2) == trans_values->blue)
  186794. {
  186795. *sp = (png_byte)background->red;
  186796. *(sp + 1) = (png_byte)background->green;
  186797. *(sp + 2) = (png_byte)background->blue;
  186798. }
  186799. }
  186800. }
  186801. }
  186802. else /* if (row_info->bit_depth == 16) */
  186803. {
  186804. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186805. if (gamma_16 != NULL)
  186806. {
  186807. sp = row;
  186808. for (i = 0; i < row_width; i++, sp += 6)
  186809. {
  186810. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186811. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186812. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  186813. if (r == trans_values->red && g == trans_values->green &&
  186814. b == trans_values->blue)
  186815. {
  186816. /* background is already in screen gamma */
  186817. *sp = (png_byte)((background->red >> 8) & 0xff);
  186818. *(sp + 1) = (png_byte)(background->red & 0xff);
  186819. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  186820. *(sp + 3) = (png_byte)(background->green & 0xff);
  186821. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  186822. *(sp + 5) = (png_byte)(background->blue & 0xff);
  186823. }
  186824. else
  186825. {
  186826. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  186827. *sp = (png_byte)((v >> 8) & 0xff);
  186828. *(sp + 1) = (png_byte)(v & 0xff);
  186829. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  186830. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  186831. *(sp + 3) = (png_byte)(v & 0xff);
  186832. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  186833. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  186834. *(sp + 5) = (png_byte)(v & 0xff);
  186835. }
  186836. }
  186837. }
  186838. else
  186839. #endif
  186840. {
  186841. sp = row;
  186842. for (i = 0; i < row_width; i++, sp += 6)
  186843. {
  186844. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  186845. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186846. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  186847. if (r == trans_values->red && g == trans_values->green &&
  186848. b == trans_values->blue)
  186849. {
  186850. *sp = (png_byte)((background->red >> 8) & 0xff);
  186851. *(sp + 1) = (png_byte)(background->red & 0xff);
  186852. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  186853. *(sp + 3) = (png_byte)(background->green & 0xff);
  186854. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  186855. *(sp + 5) = (png_byte)(background->blue & 0xff);
  186856. }
  186857. }
  186858. }
  186859. }
  186860. break;
  186861. }
  186862. case PNG_COLOR_TYPE_GRAY_ALPHA:
  186863. {
  186864. if (row_info->bit_depth == 8)
  186865. {
  186866. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186867. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  186868. gamma_table != NULL)
  186869. {
  186870. sp = row;
  186871. dp = row;
  186872. for (i = 0; i < row_width; i++, sp += 2, dp++)
  186873. {
  186874. png_uint_16 a = *(sp + 1);
  186875. if (a == 0xff)
  186876. {
  186877. *dp = gamma_table[*sp];
  186878. }
  186879. else if (a == 0)
  186880. {
  186881. /* background is already in screen gamma */
  186882. *dp = (png_byte)background->gray;
  186883. }
  186884. else
  186885. {
  186886. png_byte v, w;
  186887. v = gamma_to_1[*sp];
  186888. png_composite(w, v, a, background_1->gray);
  186889. *dp = gamma_from_1[w];
  186890. }
  186891. }
  186892. }
  186893. else
  186894. #endif
  186895. {
  186896. sp = row;
  186897. dp = row;
  186898. for (i = 0; i < row_width; i++, sp += 2, dp++)
  186899. {
  186900. png_byte a = *(sp + 1);
  186901. if (a == 0xff)
  186902. {
  186903. *dp = *sp;
  186904. }
  186905. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186906. else if (a == 0)
  186907. {
  186908. *dp = (png_byte)background->gray;
  186909. }
  186910. else
  186911. {
  186912. png_composite(*dp, *sp, a, background_1->gray);
  186913. }
  186914. #else
  186915. *dp = (png_byte)background->gray;
  186916. #endif
  186917. }
  186918. }
  186919. }
  186920. else /* if (png_ptr->bit_depth == 16) */
  186921. {
  186922. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186923. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  186924. gamma_16_to_1 != NULL)
  186925. {
  186926. sp = row;
  186927. dp = row;
  186928. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  186929. {
  186930. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186931. if (a == (png_uint_16)0xffff)
  186932. {
  186933. png_uint_16 v;
  186934. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  186935. *dp = (png_byte)((v >> 8) & 0xff);
  186936. *(dp + 1) = (png_byte)(v & 0xff);
  186937. }
  186938. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186939. else if (a == 0)
  186940. #else
  186941. else
  186942. #endif
  186943. {
  186944. /* background is already in screen gamma */
  186945. *dp = (png_byte)((background->gray >> 8) & 0xff);
  186946. *(dp + 1) = (png_byte)(background->gray & 0xff);
  186947. }
  186948. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186949. else
  186950. {
  186951. png_uint_16 g, v, w;
  186952. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  186953. png_composite_16(v, g, a, background_1->gray);
  186954. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  186955. *dp = (png_byte)((w >> 8) & 0xff);
  186956. *(dp + 1) = (png_byte)(w & 0xff);
  186957. }
  186958. #endif
  186959. }
  186960. }
  186961. else
  186962. #endif
  186963. {
  186964. sp = row;
  186965. dp = row;
  186966. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  186967. {
  186968. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186969. if (a == (png_uint_16)0xffff)
  186970. {
  186971. png_memcpy(dp, sp, 2);
  186972. }
  186973. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186974. else if (a == 0)
  186975. #else
  186976. else
  186977. #endif
  186978. {
  186979. *dp = (png_byte)((background->gray >> 8) & 0xff);
  186980. *(dp + 1) = (png_byte)(background->gray & 0xff);
  186981. }
  186982. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186983. else
  186984. {
  186985. png_uint_16 g, v;
  186986. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186987. png_composite_16(v, g, a, background_1->gray);
  186988. *dp = (png_byte)((v >> 8) & 0xff);
  186989. *(dp + 1) = (png_byte)(v & 0xff);
  186990. }
  186991. #endif
  186992. }
  186993. }
  186994. }
  186995. break;
  186996. }
  186997. case PNG_COLOR_TYPE_RGB_ALPHA:
  186998. {
  186999. if (row_info->bit_depth == 8)
  187000. {
  187001. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187002. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  187003. gamma_table != NULL)
  187004. {
  187005. sp = row;
  187006. dp = row;
  187007. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  187008. {
  187009. png_byte a = *(sp + 3);
  187010. if (a == 0xff)
  187011. {
  187012. *dp = gamma_table[*sp];
  187013. *(dp + 1) = gamma_table[*(sp + 1)];
  187014. *(dp + 2) = gamma_table[*(sp + 2)];
  187015. }
  187016. else if (a == 0)
  187017. {
  187018. /* background is already in screen gamma */
  187019. *dp = (png_byte)background->red;
  187020. *(dp + 1) = (png_byte)background->green;
  187021. *(dp + 2) = (png_byte)background->blue;
  187022. }
  187023. else
  187024. {
  187025. png_byte v, w;
  187026. v = gamma_to_1[*sp];
  187027. png_composite(w, v, a, background_1->red);
  187028. *dp = gamma_from_1[w];
  187029. v = gamma_to_1[*(sp + 1)];
  187030. png_composite(w, v, a, background_1->green);
  187031. *(dp + 1) = gamma_from_1[w];
  187032. v = gamma_to_1[*(sp + 2)];
  187033. png_composite(w, v, a, background_1->blue);
  187034. *(dp + 2) = gamma_from_1[w];
  187035. }
  187036. }
  187037. }
  187038. else
  187039. #endif
  187040. {
  187041. sp = row;
  187042. dp = row;
  187043. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  187044. {
  187045. png_byte a = *(sp + 3);
  187046. if (a == 0xff)
  187047. {
  187048. *dp = *sp;
  187049. *(dp + 1) = *(sp + 1);
  187050. *(dp + 2) = *(sp + 2);
  187051. }
  187052. else if (a == 0)
  187053. {
  187054. *dp = (png_byte)background->red;
  187055. *(dp + 1) = (png_byte)background->green;
  187056. *(dp + 2) = (png_byte)background->blue;
  187057. }
  187058. else
  187059. {
  187060. png_composite(*dp, *sp, a, background->red);
  187061. png_composite(*(dp + 1), *(sp + 1), a,
  187062. background->green);
  187063. png_composite(*(dp + 2), *(sp + 2), a,
  187064. background->blue);
  187065. }
  187066. }
  187067. }
  187068. }
  187069. else /* if (row_info->bit_depth == 16) */
  187070. {
  187071. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187072. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  187073. gamma_16_to_1 != NULL)
  187074. {
  187075. sp = row;
  187076. dp = row;
  187077. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  187078. {
  187079. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  187080. << 8) + (png_uint_16)(*(sp + 7)));
  187081. if (a == (png_uint_16)0xffff)
  187082. {
  187083. png_uint_16 v;
  187084. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  187085. *dp = (png_byte)((v >> 8) & 0xff);
  187086. *(dp + 1) = (png_byte)(v & 0xff);
  187087. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  187088. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  187089. *(dp + 3) = (png_byte)(v & 0xff);
  187090. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  187091. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  187092. *(dp + 5) = (png_byte)(v & 0xff);
  187093. }
  187094. else if (a == 0)
  187095. {
  187096. /* background is already in screen gamma */
  187097. *dp = (png_byte)((background->red >> 8) & 0xff);
  187098. *(dp + 1) = (png_byte)(background->red & 0xff);
  187099. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  187100. *(dp + 3) = (png_byte)(background->green & 0xff);
  187101. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  187102. *(dp + 5) = (png_byte)(background->blue & 0xff);
  187103. }
  187104. else
  187105. {
  187106. png_uint_16 v, w, x;
  187107. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  187108. png_composite_16(w, v, a, background_1->red);
  187109. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  187110. *dp = (png_byte)((x >> 8) & 0xff);
  187111. *(dp + 1) = (png_byte)(x & 0xff);
  187112. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  187113. png_composite_16(w, v, a, background_1->green);
  187114. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  187115. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  187116. *(dp + 3) = (png_byte)(x & 0xff);
  187117. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  187118. png_composite_16(w, v, a, background_1->blue);
  187119. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  187120. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  187121. *(dp + 5) = (png_byte)(x & 0xff);
  187122. }
  187123. }
  187124. }
  187125. else
  187126. #endif
  187127. {
  187128. sp = row;
  187129. dp = row;
  187130. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  187131. {
  187132. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  187133. << 8) + (png_uint_16)(*(sp + 7)));
  187134. if (a == (png_uint_16)0xffff)
  187135. {
  187136. png_memcpy(dp, sp, 6);
  187137. }
  187138. else if (a == 0)
  187139. {
  187140. *dp = (png_byte)((background->red >> 8) & 0xff);
  187141. *(dp + 1) = (png_byte)(background->red & 0xff);
  187142. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  187143. *(dp + 3) = (png_byte)(background->green & 0xff);
  187144. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  187145. *(dp + 5) = (png_byte)(background->blue & 0xff);
  187146. }
  187147. else
  187148. {
  187149. png_uint_16 v;
  187150. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  187151. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  187152. + *(sp + 3));
  187153. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  187154. + *(sp + 5));
  187155. png_composite_16(v, r, a, background->red);
  187156. *dp = (png_byte)((v >> 8) & 0xff);
  187157. *(dp + 1) = (png_byte)(v & 0xff);
  187158. png_composite_16(v, g, a, background->green);
  187159. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  187160. *(dp + 3) = (png_byte)(v & 0xff);
  187161. png_composite_16(v, b, a, background->blue);
  187162. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  187163. *(dp + 5) = (png_byte)(v & 0xff);
  187164. }
  187165. }
  187166. }
  187167. }
  187168. break;
  187169. }
  187170. }
  187171. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  187172. {
  187173. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  187174. row_info->channels--;
  187175. row_info->pixel_depth = (png_byte)(row_info->channels *
  187176. row_info->bit_depth);
  187177. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187178. }
  187179. }
  187180. }
  187181. #endif
  187182. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187183. /* Gamma correct the image, avoiding the alpha channel. Make sure
  187184. * you do this after you deal with the transparency issue on grayscale
  187185. * or RGB images. If your bit depth is 8, use gamma_table, if it
  187186. * is 16, use gamma_16_table and gamma_shift. Build these with
  187187. * build_gamma_table().
  187188. */
  187189. void /* PRIVATE */
  187190. png_do_gamma(png_row_infop row_info, png_bytep row,
  187191. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  187192. int gamma_shift)
  187193. {
  187194. png_bytep sp;
  187195. png_uint_32 i;
  187196. png_uint_32 row_width=row_info->width;
  187197. png_debug(1, "in png_do_gamma\n");
  187198. if (
  187199. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187200. row != NULL && row_info != NULL &&
  187201. #endif
  187202. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  187203. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  187204. {
  187205. switch (row_info->color_type)
  187206. {
  187207. case PNG_COLOR_TYPE_RGB:
  187208. {
  187209. if (row_info->bit_depth == 8)
  187210. {
  187211. sp = row;
  187212. for (i = 0; i < row_width; i++)
  187213. {
  187214. *sp = gamma_table[*sp];
  187215. sp++;
  187216. *sp = gamma_table[*sp];
  187217. sp++;
  187218. *sp = gamma_table[*sp];
  187219. sp++;
  187220. }
  187221. }
  187222. else /* if (row_info->bit_depth == 16) */
  187223. {
  187224. sp = row;
  187225. for (i = 0; i < row_width; i++)
  187226. {
  187227. png_uint_16 v;
  187228. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187229. *sp = (png_byte)((v >> 8) & 0xff);
  187230. *(sp + 1) = (png_byte)(v & 0xff);
  187231. sp += 2;
  187232. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187233. *sp = (png_byte)((v >> 8) & 0xff);
  187234. *(sp + 1) = (png_byte)(v & 0xff);
  187235. sp += 2;
  187236. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187237. *sp = (png_byte)((v >> 8) & 0xff);
  187238. *(sp + 1) = (png_byte)(v & 0xff);
  187239. sp += 2;
  187240. }
  187241. }
  187242. break;
  187243. }
  187244. case PNG_COLOR_TYPE_RGB_ALPHA:
  187245. {
  187246. if (row_info->bit_depth == 8)
  187247. {
  187248. sp = row;
  187249. for (i = 0; i < row_width; i++)
  187250. {
  187251. *sp = gamma_table[*sp];
  187252. sp++;
  187253. *sp = gamma_table[*sp];
  187254. sp++;
  187255. *sp = gamma_table[*sp];
  187256. sp++;
  187257. sp++;
  187258. }
  187259. }
  187260. else /* if (row_info->bit_depth == 16) */
  187261. {
  187262. sp = row;
  187263. for (i = 0; i < row_width; i++)
  187264. {
  187265. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187266. *sp = (png_byte)((v >> 8) & 0xff);
  187267. *(sp + 1) = (png_byte)(v & 0xff);
  187268. sp += 2;
  187269. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187270. *sp = (png_byte)((v >> 8) & 0xff);
  187271. *(sp + 1) = (png_byte)(v & 0xff);
  187272. sp += 2;
  187273. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187274. *sp = (png_byte)((v >> 8) & 0xff);
  187275. *(sp + 1) = (png_byte)(v & 0xff);
  187276. sp += 4;
  187277. }
  187278. }
  187279. break;
  187280. }
  187281. case PNG_COLOR_TYPE_GRAY_ALPHA:
  187282. {
  187283. if (row_info->bit_depth == 8)
  187284. {
  187285. sp = row;
  187286. for (i = 0; i < row_width; i++)
  187287. {
  187288. *sp = gamma_table[*sp];
  187289. sp += 2;
  187290. }
  187291. }
  187292. else /* if (row_info->bit_depth == 16) */
  187293. {
  187294. sp = row;
  187295. for (i = 0; i < row_width; i++)
  187296. {
  187297. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187298. *sp = (png_byte)((v >> 8) & 0xff);
  187299. *(sp + 1) = (png_byte)(v & 0xff);
  187300. sp += 4;
  187301. }
  187302. }
  187303. break;
  187304. }
  187305. case PNG_COLOR_TYPE_GRAY:
  187306. {
  187307. if (row_info->bit_depth == 2)
  187308. {
  187309. sp = row;
  187310. for (i = 0; i < row_width; i += 4)
  187311. {
  187312. int a = *sp & 0xc0;
  187313. int b = *sp & 0x30;
  187314. int c = *sp & 0x0c;
  187315. int d = *sp & 0x03;
  187316. *sp = (png_byte)(
  187317. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  187318. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  187319. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  187320. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  187321. sp++;
  187322. }
  187323. }
  187324. if (row_info->bit_depth == 4)
  187325. {
  187326. sp = row;
  187327. for (i = 0; i < row_width; i += 2)
  187328. {
  187329. int msb = *sp & 0xf0;
  187330. int lsb = *sp & 0x0f;
  187331. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  187332. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  187333. sp++;
  187334. }
  187335. }
  187336. else if (row_info->bit_depth == 8)
  187337. {
  187338. sp = row;
  187339. for (i = 0; i < row_width; i++)
  187340. {
  187341. *sp = gamma_table[*sp];
  187342. sp++;
  187343. }
  187344. }
  187345. else if (row_info->bit_depth == 16)
  187346. {
  187347. sp = row;
  187348. for (i = 0; i < row_width; i++)
  187349. {
  187350. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  187351. *sp = (png_byte)((v >> 8) & 0xff);
  187352. *(sp + 1) = (png_byte)(v & 0xff);
  187353. sp += 2;
  187354. }
  187355. }
  187356. break;
  187357. }
  187358. }
  187359. }
  187360. }
  187361. #endif
  187362. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187363. /* Expands a palette row to an RGB or RGBA row depending
  187364. * upon whether you supply trans and num_trans.
  187365. */
  187366. void /* PRIVATE */
  187367. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  187368. png_colorp palette, png_bytep trans, int num_trans)
  187369. {
  187370. int shift, value;
  187371. png_bytep sp, dp;
  187372. png_uint_32 i;
  187373. png_uint_32 row_width=row_info->width;
  187374. png_debug(1, "in png_do_expand_palette\n");
  187375. if (
  187376. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187377. row != NULL && row_info != NULL &&
  187378. #endif
  187379. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  187380. {
  187381. if (row_info->bit_depth < 8)
  187382. {
  187383. switch (row_info->bit_depth)
  187384. {
  187385. case 1:
  187386. {
  187387. sp = row + (png_size_t)((row_width - 1) >> 3);
  187388. dp = row + (png_size_t)row_width - 1;
  187389. shift = 7 - (int)((row_width + 7) & 0x07);
  187390. for (i = 0; i < row_width; i++)
  187391. {
  187392. if ((*sp >> shift) & 0x01)
  187393. *dp = 1;
  187394. else
  187395. *dp = 0;
  187396. if (shift == 7)
  187397. {
  187398. shift = 0;
  187399. sp--;
  187400. }
  187401. else
  187402. shift++;
  187403. dp--;
  187404. }
  187405. break;
  187406. }
  187407. case 2:
  187408. {
  187409. sp = row + (png_size_t)((row_width - 1) >> 2);
  187410. dp = row + (png_size_t)row_width - 1;
  187411. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  187412. for (i = 0; i < row_width; i++)
  187413. {
  187414. value = (*sp >> shift) & 0x03;
  187415. *dp = (png_byte)value;
  187416. if (shift == 6)
  187417. {
  187418. shift = 0;
  187419. sp--;
  187420. }
  187421. else
  187422. shift += 2;
  187423. dp--;
  187424. }
  187425. break;
  187426. }
  187427. case 4:
  187428. {
  187429. sp = row + (png_size_t)((row_width - 1) >> 1);
  187430. dp = row + (png_size_t)row_width - 1;
  187431. shift = (int)((row_width & 0x01) << 2);
  187432. for (i = 0; i < row_width; i++)
  187433. {
  187434. value = (*sp >> shift) & 0x0f;
  187435. *dp = (png_byte)value;
  187436. if (shift == 4)
  187437. {
  187438. shift = 0;
  187439. sp--;
  187440. }
  187441. else
  187442. shift += 4;
  187443. dp--;
  187444. }
  187445. break;
  187446. }
  187447. }
  187448. row_info->bit_depth = 8;
  187449. row_info->pixel_depth = 8;
  187450. row_info->rowbytes = row_width;
  187451. }
  187452. switch (row_info->bit_depth)
  187453. {
  187454. case 8:
  187455. {
  187456. if (trans != NULL)
  187457. {
  187458. sp = row + (png_size_t)row_width - 1;
  187459. dp = row + (png_size_t)(row_width << 2) - 1;
  187460. for (i = 0; i < row_width; i++)
  187461. {
  187462. if ((int)(*sp) >= num_trans)
  187463. *dp-- = 0xff;
  187464. else
  187465. *dp-- = trans[*sp];
  187466. *dp-- = palette[*sp].blue;
  187467. *dp-- = palette[*sp].green;
  187468. *dp-- = palette[*sp].red;
  187469. sp--;
  187470. }
  187471. row_info->bit_depth = 8;
  187472. row_info->pixel_depth = 32;
  187473. row_info->rowbytes = row_width * 4;
  187474. row_info->color_type = 6;
  187475. row_info->channels = 4;
  187476. }
  187477. else
  187478. {
  187479. sp = row + (png_size_t)row_width - 1;
  187480. dp = row + (png_size_t)(row_width * 3) - 1;
  187481. for (i = 0; i < row_width; i++)
  187482. {
  187483. *dp-- = palette[*sp].blue;
  187484. *dp-- = palette[*sp].green;
  187485. *dp-- = palette[*sp].red;
  187486. sp--;
  187487. }
  187488. row_info->bit_depth = 8;
  187489. row_info->pixel_depth = 24;
  187490. row_info->rowbytes = row_width * 3;
  187491. row_info->color_type = 2;
  187492. row_info->channels = 3;
  187493. }
  187494. break;
  187495. }
  187496. }
  187497. }
  187498. }
  187499. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  187500. * expanded transparency value is supplied, an alpha channel is built.
  187501. */
  187502. void /* PRIVATE */
  187503. png_do_expand(png_row_infop row_info, png_bytep row,
  187504. png_color_16p trans_value)
  187505. {
  187506. int shift, value;
  187507. png_bytep sp, dp;
  187508. png_uint_32 i;
  187509. png_uint_32 row_width=row_info->width;
  187510. png_debug(1, "in png_do_expand\n");
  187511. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187512. if (row != NULL && row_info != NULL)
  187513. #endif
  187514. {
  187515. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  187516. {
  187517. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  187518. if (row_info->bit_depth < 8)
  187519. {
  187520. switch (row_info->bit_depth)
  187521. {
  187522. case 1:
  187523. {
  187524. gray = (png_uint_16)((gray&0x01)*0xff);
  187525. sp = row + (png_size_t)((row_width - 1) >> 3);
  187526. dp = row + (png_size_t)row_width - 1;
  187527. shift = 7 - (int)((row_width + 7) & 0x07);
  187528. for (i = 0; i < row_width; i++)
  187529. {
  187530. if ((*sp >> shift) & 0x01)
  187531. *dp = 0xff;
  187532. else
  187533. *dp = 0;
  187534. if (shift == 7)
  187535. {
  187536. shift = 0;
  187537. sp--;
  187538. }
  187539. else
  187540. shift++;
  187541. dp--;
  187542. }
  187543. break;
  187544. }
  187545. case 2:
  187546. {
  187547. gray = (png_uint_16)((gray&0x03)*0x55);
  187548. sp = row + (png_size_t)((row_width - 1) >> 2);
  187549. dp = row + (png_size_t)row_width - 1;
  187550. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  187551. for (i = 0; i < row_width; i++)
  187552. {
  187553. value = (*sp >> shift) & 0x03;
  187554. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  187555. (value << 6));
  187556. if (shift == 6)
  187557. {
  187558. shift = 0;
  187559. sp--;
  187560. }
  187561. else
  187562. shift += 2;
  187563. dp--;
  187564. }
  187565. break;
  187566. }
  187567. case 4:
  187568. {
  187569. gray = (png_uint_16)((gray&0x0f)*0x11);
  187570. sp = row + (png_size_t)((row_width - 1) >> 1);
  187571. dp = row + (png_size_t)row_width - 1;
  187572. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  187573. for (i = 0; i < row_width; i++)
  187574. {
  187575. value = (*sp >> shift) & 0x0f;
  187576. *dp = (png_byte)(value | (value << 4));
  187577. if (shift == 4)
  187578. {
  187579. shift = 0;
  187580. sp--;
  187581. }
  187582. else
  187583. shift = 4;
  187584. dp--;
  187585. }
  187586. break;
  187587. }
  187588. }
  187589. row_info->bit_depth = 8;
  187590. row_info->pixel_depth = 8;
  187591. row_info->rowbytes = row_width;
  187592. }
  187593. if (trans_value != NULL)
  187594. {
  187595. if (row_info->bit_depth == 8)
  187596. {
  187597. gray = gray & 0xff;
  187598. sp = row + (png_size_t)row_width - 1;
  187599. dp = row + (png_size_t)(row_width << 1) - 1;
  187600. for (i = 0; i < row_width; i++)
  187601. {
  187602. if (*sp == gray)
  187603. *dp-- = 0;
  187604. else
  187605. *dp-- = 0xff;
  187606. *dp-- = *sp--;
  187607. }
  187608. }
  187609. else if (row_info->bit_depth == 16)
  187610. {
  187611. png_byte gray_high = (gray >> 8) & 0xff;
  187612. png_byte gray_low = gray & 0xff;
  187613. sp = row + row_info->rowbytes - 1;
  187614. dp = row + (row_info->rowbytes << 1) - 1;
  187615. for (i = 0; i < row_width; i++)
  187616. {
  187617. if (*(sp-1) == gray_high && *(sp) == gray_low)
  187618. {
  187619. *dp-- = 0;
  187620. *dp-- = 0;
  187621. }
  187622. else
  187623. {
  187624. *dp-- = 0xff;
  187625. *dp-- = 0xff;
  187626. }
  187627. *dp-- = *sp--;
  187628. *dp-- = *sp--;
  187629. }
  187630. }
  187631. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  187632. row_info->channels = 2;
  187633. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  187634. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  187635. row_width);
  187636. }
  187637. }
  187638. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  187639. {
  187640. if (row_info->bit_depth == 8)
  187641. {
  187642. png_byte red = trans_value->red & 0xff;
  187643. png_byte green = trans_value->green & 0xff;
  187644. png_byte blue = trans_value->blue & 0xff;
  187645. sp = row + (png_size_t)row_info->rowbytes - 1;
  187646. dp = row + (png_size_t)(row_width << 2) - 1;
  187647. for (i = 0; i < row_width; i++)
  187648. {
  187649. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  187650. *dp-- = 0;
  187651. else
  187652. *dp-- = 0xff;
  187653. *dp-- = *sp--;
  187654. *dp-- = *sp--;
  187655. *dp-- = *sp--;
  187656. }
  187657. }
  187658. else if (row_info->bit_depth == 16)
  187659. {
  187660. png_byte red_high = (trans_value->red >> 8) & 0xff;
  187661. png_byte green_high = (trans_value->green >> 8) & 0xff;
  187662. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  187663. png_byte red_low = trans_value->red & 0xff;
  187664. png_byte green_low = trans_value->green & 0xff;
  187665. png_byte blue_low = trans_value->blue & 0xff;
  187666. sp = row + row_info->rowbytes - 1;
  187667. dp = row + (png_size_t)(row_width << 3) - 1;
  187668. for (i = 0; i < row_width; i++)
  187669. {
  187670. if (*(sp - 5) == red_high &&
  187671. *(sp - 4) == red_low &&
  187672. *(sp - 3) == green_high &&
  187673. *(sp - 2) == green_low &&
  187674. *(sp - 1) == blue_high &&
  187675. *(sp ) == blue_low)
  187676. {
  187677. *dp-- = 0;
  187678. *dp-- = 0;
  187679. }
  187680. else
  187681. {
  187682. *dp-- = 0xff;
  187683. *dp-- = 0xff;
  187684. }
  187685. *dp-- = *sp--;
  187686. *dp-- = *sp--;
  187687. *dp-- = *sp--;
  187688. *dp-- = *sp--;
  187689. *dp-- = *sp--;
  187690. *dp-- = *sp--;
  187691. }
  187692. }
  187693. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  187694. row_info->channels = 4;
  187695. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  187696. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187697. }
  187698. }
  187699. }
  187700. #endif
  187701. #if defined(PNG_READ_DITHER_SUPPORTED)
  187702. void /* PRIVATE */
  187703. png_do_dither(png_row_infop row_info, png_bytep row,
  187704. png_bytep palette_lookup, png_bytep dither_lookup)
  187705. {
  187706. png_bytep sp, dp;
  187707. png_uint_32 i;
  187708. png_uint_32 row_width=row_info->width;
  187709. png_debug(1, "in png_do_dither\n");
  187710. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187711. if (row != NULL && row_info != NULL)
  187712. #endif
  187713. {
  187714. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  187715. palette_lookup && row_info->bit_depth == 8)
  187716. {
  187717. int r, g, b, p;
  187718. sp = row;
  187719. dp = row;
  187720. for (i = 0; i < row_width; i++)
  187721. {
  187722. r = *sp++;
  187723. g = *sp++;
  187724. b = *sp++;
  187725. /* this looks real messy, but the compiler will reduce
  187726. it down to a reasonable formula. For example, with
  187727. 5 bits per color, we get:
  187728. p = (((r >> 3) & 0x1f) << 10) |
  187729. (((g >> 3) & 0x1f) << 5) |
  187730. ((b >> 3) & 0x1f);
  187731. */
  187732. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  187733. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  187734. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  187735. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  187736. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  187737. (PNG_DITHER_BLUE_BITS)) |
  187738. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  187739. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  187740. *dp++ = palette_lookup[p];
  187741. }
  187742. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  187743. row_info->channels = 1;
  187744. row_info->pixel_depth = row_info->bit_depth;
  187745. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187746. }
  187747. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  187748. palette_lookup != NULL && row_info->bit_depth == 8)
  187749. {
  187750. int r, g, b, p;
  187751. sp = row;
  187752. dp = row;
  187753. for (i = 0; i < row_width; i++)
  187754. {
  187755. r = *sp++;
  187756. g = *sp++;
  187757. b = *sp++;
  187758. sp++;
  187759. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  187760. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  187761. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  187762. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  187763. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  187764. (PNG_DITHER_BLUE_BITS)) |
  187765. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  187766. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  187767. *dp++ = palette_lookup[p];
  187768. }
  187769. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  187770. row_info->channels = 1;
  187771. row_info->pixel_depth = row_info->bit_depth;
  187772. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187773. }
  187774. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  187775. dither_lookup && row_info->bit_depth == 8)
  187776. {
  187777. sp = row;
  187778. for (i = 0; i < row_width; i++, sp++)
  187779. {
  187780. *sp = dither_lookup[*sp];
  187781. }
  187782. }
  187783. }
  187784. }
  187785. #endif
  187786. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187787. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187788. static PNG_CONST int png_gamma_shift[] =
  187789. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  187790. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  187791. * tables, we don't make a full table if we are reducing to 8-bit in
  187792. * the future. Note also how the gamma_16 tables are segmented so that
  187793. * we don't need to allocate > 64K chunks for a full 16-bit table.
  187794. */
  187795. void /* PRIVATE */
  187796. png_build_gamma_table(png_structp png_ptr)
  187797. {
  187798. png_debug(1, "in png_build_gamma_table\n");
  187799. if (png_ptr->bit_depth <= 8)
  187800. {
  187801. int i;
  187802. double g;
  187803. if (png_ptr->screen_gamma > .000001)
  187804. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187805. else
  187806. g = 1.0;
  187807. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  187808. (png_uint_32)256);
  187809. for (i = 0; i < 256; i++)
  187810. {
  187811. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  187812. g) * 255.0 + .5);
  187813. }
  187814. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  187815. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187816. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  187817. {
  187818. g = 1.0 / (png_ptr->gamma);
  187819. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  187820. (png_uint_32)256);
  187821. for (i = 0; i < 256; i++)
  187822. {
  187823. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  187824. g) * 255.0 + .5);
  187825. }
  187826. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  187827. (png_uint_32)256);
  187828. if(png_ptr->screen_gamma > 0.000001)
  187829. g = 1.0 / png_ptr->screen_gamma;
  187830. else
  187831. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  187832. for (i = 0; i < 256; i++)
  187833. {
  187834. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  187835. g) * 255.0 + .5);
  187836. }
  187837. }
  187838. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  187839. }
  187840. else
  187841. {
  187842. double g;
  187843. int i, j, shift, num;
  187844. int sig_bit;
  187845. png_uint_32 ig;
  187846. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  187847. {
  187848. sig_bit = (int)png_ptr->sig_bit.red;
  187849. if ((int)png_ptr->sig_bit.green > sig_bit)
  187850. sig_bit = png_ptr->sig_bit.green;
  187851. if ((int)png_ptr->sig_bit.blue > sig_bit)
  187852. sig_bit = png_ptr->sig_bit.blue;
  187853. }
  187854. else
  187855. {
  187856. sig_bit = (int)png_ptr->sig_bit.gray;
  187857. }
  187858. if (sig_bit > 0)
  187859. shift = 16 - sig_bit;
  187860. else
  187861. shift = 0;
  187862. if (png_ptr->transformations & PNG_16_TO_8)
  187863. {
  187864. if (shift < (16 - PNG_MAX_GAMMA_8))
  187865. shift = (16 - PNG_MAX_GAMMA_8);
  187866. }
  187867. if (shift > 8)
  187868. shift = 8;
  187869. if (shift < 0)
  187870. shift = 0;
  187871. png_ptr->gamma_shift = (png_byte)shift;
  187872. num = (1 << (8 - shift));
  187873. if (png_ptr->screen_gamma > .000001)
  187874. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187875. else
  187876. g = 1.0;
  187877. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  187878. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  187879. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  187880. {
  187881. double fin, fout;
  187882. png_uint_32 last, max;
  187883. for (i = 0; i < num; i++)
  187884. {
  187885. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  187886. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187887. }
  187888. g = 1.0 / g;
  187889. last = 0;
  187890. for (i = 0; i < 256; i++)
  187891. {
  187892. fout = ((double)i + 0.5) / 256.0;
  187893. fin = pow(fout, g);
  187894. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  187895. while (last <= max)
  187896. {
  187897. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  187898. [(int)(last >> (8 - shift))] = (png_uint_16)(
  187899. (png_uint_16)i | ((png_uint_16)i << 8));
  187900. last++;
  187901. }
  187902. }
  187903. while (last < ((png_uint_32)num << 8))
  187904. {
  187905. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  187906. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  187907. last++;
  187908. }
  187909. }
  187910. else
  187911. {
  187912. for (i = 0; i < num; i++)
  187913. {
  187914. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  187915. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187916. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  187917. for (j = 0; j < 256; j++)
  187918. {
  187919. png_ptr->gamma_16_table[i][j] =
  187920. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  187921. 65535.0, g) * 65535.0 + .5);
  187922. }
  187923. }
  187924. }
  187925. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  187926. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187927. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  187928. {
  187929. g = 1.0 / (png_ptr->gamma);
  187930. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  187931. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  187932. for (i = 0; i < num; i++)
  187933. {
  187934. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  187935. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187936. ig = (((png_uint_32)i *
  187937. (png_uint_32)png_gamma_shift[shift]) >> 4);
  187938. for (j = 0; j < 256; j++)
  187939. {
  187940. png_ptr->gamma_16_to_1[i][j] =
  187941. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  187942. 65535.0, g) * 65535.0 + .5);
  187943. }
  187944. }
  187945. if(png_ptr->screen_gamma > 0.000001)
  187946. g = 1.0 / png_ptr->screen_gamma;
  187947. else
  187948. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  187949. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  187950. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  187951. for (i = 0; i < num; i++)
  187952. {
  187953. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  187954. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187955. ig = (((png_uint_32)i *
  187956. (png_uint_32)png_gamma_shift[shift]) >> 4);
  187957. for (j = 0; j < 256; j++)
  187958. {
  187959. png_ptr->gamma_16_from_1[i][j] =
  187960. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  187961. 65535.0, g) * 65535.0 + .5);
  187962. }
  187963. }
  187964. }
  187965. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  187966. }
  187967. }
  187968. #endif
  187969. /* To do: install integer version of png_build_gamma_table here */
  187970. #endif
  187971. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187972. /* undoes intrapixel differencing */
  187973. void /* PRIVATE */
  187974. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  187975. {
  187976. png_debug(1, "in png_do_read_intrapixel\n");
  187977. if (
  187978. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187979. row != NULL && row_info != NULL &&
  187980. #endif
  187981. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  187982. {
  187983. int bytes_per_pixel;
  187984. png_uint_32 row_width = row_info->width;
  187985. if (row_info->bit_depth == 8)
  187986. {
  187987. png_bytep rp;
  187988. png_uint_32 i;
  187989. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187990. bytes_per_pixel = 3;
  187991. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187992. bytes_per_pixel = 4;
  187993. else
  187994. return;
  187995. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  187996. {
  187997. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  187998. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  187999. }
  188000. }
  188001. else if (row_info->bit_depth == 16)
  188002. {
  188003. png_bytep rp;
  188004. png_uint_32 i;
  188005. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  188006. bytes_per_pixel = 6;
  188007. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  188008. bytes_per_pixel = 8;
  188009. else
  188010. return;
  188011. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  188012. {
  188013. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  188014. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  188015. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  188016. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  188017. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  188018. *(rp ) = (png_byte)((red >> 8) & 0xff);
  188019. *(rp+1) = (png_byte)(red & 0xff);
  188020. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  188021. *(rp+5) = (png_byte)(blue & 0xff);
  188022. }
  188023. }
  188024. }
  188025. }
  188026. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  188027. #endif /* PNG_READ_SUPPORTED */
  188028. /********* End of inlined file: pngrtran.c *********/
  188029. /********* Start of inlined file: pngrutil.c *********/
  188030. /* pngrutil.c - utilities to read a PNG file
  188031. *
  188032. * Last changed in libpng 1.2.21 [October 4, 2007]
  188033. * For conditions of distribution and use, see copyright notice in png.h
  188034. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188035. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188036. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188037. *
  188038. * This file contains routines that are only called from within
  188039. * libpng itself during the course of reading an image.
  188040. */
  188041. #define PNG_INTERNAL
  188042. #if defined(PNG_READ_SUPPORTED)
  188043. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  188044. # define WIN32_WCE_OLD
  188045. #endif
  188046. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188047. # if defined(WIN32_WCE_OLD)
  188048. /* strtod() function is not supported on WindowsCE */
  188049. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  188050. {
  188051. double result = 0;
  188052. int len;
  188053. wchar_t *str, *end;
  188054. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  188055. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  188056. if ( NULL != str )
  188057. {
  188058. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  188059. result = wcstod(str, &end);
  188060. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  188061. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  188062. png_free(png_ptr, str);
  188063. }
  188064. return result;
  188065. }
  188066. # else
  188067. # define png_strtod(p,a,b) strtod(a,b)
  188068. # endif
  188069. #endif
  188070. png_uint_32 PNGAPI
  188071. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  188072. {
  188073. png_uint_32 i = png_get_uint_32(buf);
  188074. if (i > PNG_UINT_31_MAX)
  188075. png_error(png_ptr, "PNG unsigned integer out of range.");
  188076. return (i);
  188077. }
  188078. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  188079. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  188080. png_uint_32 PNGAPI
  188081. png_get_uint_32(png_bytep buf)
  188082. {
  188083. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  188084. ((png_uint_32)(*(buf + 1)) << 16) +
  188085. ((png_uint_32)(*(buf + 2)) << 8) +
  188086. (png_uint_32)(*(buf + 3));
  188087. return (i);
  188088. }
  188089. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  188090. * data is stored in the PNG file in two's complement format, and it is
  188091. * assumed that the machine format for signed integers is the same. */
  188092. png_int_32 PNGAPI
  188093. png_get_int_32(png_bytep buf)
  188094. {
  188095. png_int_32 i = ((png_int_32)(*buf) << 24) +
  188096. ((png_int_32)(*(buf + 1)) << 16) +
  188097. ((png_int_32)(*(buf + 2)) << 8) +
  188098. (png_int_32)(*(buf + 3));
  188099. return (i);
  188100. }
  188101. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  188102. png_uint_16 PNGAPI
  188103. png_get_uint_16(png_bytep buf)
  188104. {
  188105. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  188106. (png_uint_16)(*(buf + 1)));
  188107. return (i);
  188108. }
  188109. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  188110. /* Read data, and (optionally) run it through the CRC. */
  188111. void /* PRIVATE */
  188112. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  188113. {
  188114. if(png_ptr == NULL) return;
  188115. png_read_data(png_ptr, buf, length);
  188116. png_calculate_crc(png_ptr, buf, length);
  188117. }
  188118. /* Optionally skip data and then check the CRC. Depending on whether we
  188119. are reading a ancillary or critical chunk, and how the program has set
  188120. things up, we may calculate the CRC on the data and print a message.
  188121. Returns '1' if there was a CRC error, '0' otherwise. */
  188122. int /* PRIVATE */
  188123. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  188124. {
  188125. png_size_t i;
  188126. png_size_t istop = png_ptr->zbuf_size;
  188127. for (i = (png_size_t)skip; i > istop; i -= istop)
  188128. {
  188129. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  188130. }
  188131. if (i)
  188132. {
  188133. png_crc_read(png_ptr, png_ptr->zbuf, i);
  188134. }
  188135. if (png_crc_error(png_ptr))
  188136. {
  188137. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  188138. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  188139. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  188140. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  188141. {
  188142. png_chunk_warning(png_ptr, "CRC error");
  188143. }
  188144. else
  188145. {
  188146. png_chunk_error(png_ptr, "CRC error");
  188147. }
  188148. return (1);
  188149. }
  188150. return (0);
  188151. }
  188152. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  188153. the data it has read thus far. */
  188154. int /* PRIVATE */
  188155. png_crc_error(png_structp png_ptr)
  188156. {
  188157. png_byte crc_bytes[4];
  188158. png_uint_32 crc;
  188159. int need_crc = 1;
  188160. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  188161. {
  188162. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  188163. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  188164. need_crc = 0;
  188165. }
  188166. else /* critical */
  188167. {
  188168. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  188169. need_crc = 0;
  188170. }
  188171. png_read_data(png_ptr, crc_bytes, 4);
  188172. if (need_crc)
  188173. {
  188174. crc = png_get_uint_32(crc_bytes);
  188175. return ((int)(crc != png_ptr->crc));
  188176. }
  188177. else
  188178. return (0);
  188179. }
  188180. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  188181. defined(PNG_READ_iCCP_SUPPORTED)
  188182. /*
  188183. * Decompress trailing data in a chunk. The assumption is that chunkdata
  188184. * points at an allocated area holding the contents of a chunk with a
  188185. * trailing compressed part. What we get back is an allocated area
  188186. * holding the original prefix part and an uncompressed version of the
  188187. * trailing part (the malloc area passed in is freed).
  188188. */
  188189. png_charp /* PRIVATE */
  188190. png_decompress_chunk(png_structp png_ptr, int comp_type,
  188191. png_charp chunkdata, png_size_t chunklength,
  188192. png_size_t prefix_size, png_size_t *newlength)
  188193. {
  188194. static PNG_CONST char msg[] = "Error decoding compressed text";
  188195. png_charp text;
  188196. png_size_t text_size;
  188197. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  188198. {
  188199. int ret = Z_OK;
  188200. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  188201. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  188202. png_ptr->zstream.next_out = png_ptr->zbuf;
  188203. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188204. text_size = 0;
  188205. text = NULL;
  188206. while (png_ptr->zstream.avail_in)
  188207. {
  188208. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188209. if (ret != Z_OK && ret != Z_STREAM_END)
  188210. {
  188211. if (png_ptr->zstream.msg != NULL)
  188212. png_warning(png_ptr, png_ptr->zstream.msg);
  188213. else
  188214. png_warning(png_ptr, msg);
  188215. inflateReset(&png_ptr->zstream);
  188216. png_ptr->zstream.avail_in = 0;
  188217. if (text == NULL)
  188218. {
  188219. text_size = prefix_size + png_sizeof(msg) + 1;
  188220. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  188221. if (text == NULL)
  188222. {
  188223. png_free(png_ptr,chunkdata);
  188224. png_error(png_ptr,"Not enough memory to decompress chunk");
  188225. }
  188226. png_memcpy(text, chunkdata, prefix_size);
  188227. }
  188228. text[text_size - 1] = 0x00;
  188229. /* Copy what we can of the error message into the text chunk */
  188230. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  188231. text_size = png_sizeof(msg) > text_size ? text_size :
  188232. png_sizeof(msg);
  188233. png_memcpy(text + prefix_size, msg, text_size + 1);
  188234. break;
  188235. }
  188236. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  188237. {
  188238. if (text == NULL)
  188239. {
  188240. text_size = prefix_size +
  188241. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  188242. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  188243. if (text == NULL)
  188244. {
  188245. png_free(png_ptr,chunkdata);
  188246. png_error(png_ptr,"Not enough memory to decompress chunk.");
  188247. }
  188248. png_memcpy(text + prefix_size, png_ptr->zbuf,
  188249. text_size - prefix_size);
  188250. png_memcpy(text, chunkdata, prefix_size);
  188251. *(text + text_size) = 0x00;
  188252. }
  188253. else
  188254. {
  188255. png_charp tmp;
  188256. tmp = text;
  188257. text = (png_charp)png_malloc_warn(png_ptr,
  188258. (png_uint_32)(text_size +
  188259. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  188260. if (text == NULL)
  188261. {
  188262. png_free(png_ptr, tmp);
  188263. png_free(png_ptr, chunkdata);
  188264. png_error(png_ptr,"Not enough memory to decompress chunk..");
  188265. }
  188266. png_memcpy(text, tmp, text_size);
  188267. png_free(png_ptr, tmp);
  188268. png_memcpy(text + text_size, png_ptr->zbuf,
  188269. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  188270. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  188271. *(text + text_size) = 0x00;
  188272. }
  188273. if (ret == Z_STREAM_END)
  188274. break;
  188275. else
  188276. {
  188277. png_ptr->zstream.next_out = png_ptr->zbuf;
  188278. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188279. }
  188280. }
  188281. }
  188282. if (ret != Z_STREAM_END)
  188283. {
  188284. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  188285. char umsg[52];
  188286. if (ret == Z_BUF_ERROR)
  188287. png_snprintf(umsg, 52,
  188288. "Buffer error in compressed datastream in %s chunk",
  188289. png_ptr->chunk_name);
  188290. else if (ret == Z_DATA_ERROR)
  188291. png_snprintf(umsg, 52,
  188292. "Data error in compressed datastream in %s chunk",
  188293. png_ptr->chunk_name);
  188294. else
  188295. png_snprintf(umsg, 52,
  188296. "Incomplete compressed datastream in %s chunk",
  188297. png_ptr->chunk_name);
  188298. png_warning(png_ptr, umsg);
  188299. #else
  188300. png_warning(png_ptr,
  188301. "Incomplete compressed datastream in chunk other than IDAT");
  188302. #endif
  188303. text_size=prefix_size;
  188304. if (text == NULL)
  188305. {
  188306. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  188307. if (text == NULL)
  188308. {
  188309. png_free(png_ptr, chunkdata);
  188310. png_error(png_ptr,"Not enough memory for text.");
  188311. }
  188312. png_memcpy(text, chunkdata, prefix_size);
  188313. }
  188314. *(text + text_size) = 0x00;
  188315. }
  188316. inflateReset(&png_ptr->zstream);
  188317. png_ptr->zstream.avail_in = 0;
  188318. png_free(png_ptr, chunkdata);
  188319. chunkdata = text;
  188320. *newlength=text_size;
  188321. }
  188322. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  188323. {
  188324. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  188325. char umsg[50];
  188326. png_snprintf(umsg, 50,
  188327. "Unknown zTXt compression type %d", comp_type);
  188328. png_warning(png_ptr, umsg);
  188329. #else
  188330. png_warning(png_ptr, "Unknown zTXt compression type");
  188331. #endif
  188332. *(chunkdata + prefix_size) = 0x00;
  188333. *newlength=prefix_size;
  188334. }
  188335. return chunkdata;
  188336. }
  188337. #endif
  188338. /* read and check the IDHR chunk */
  188339. void /* PRIVATE */
  188340. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188341. {
  188342. png_byte buf[13];
  188343. png_uint_32 width, height;
  188344. int bit_depth, color_type, compression_type, filter_type;
  188345. int interlace_type;
  188346. png_debug(1, "in png_handle_IHDR\n");
  188347. if (png_ptr->mode & PNG_HAVE_IHDR)
  188348. png_error(png_ptr, "Out of place IHDR");
  188349. /* check the length */
  188350. if (length != 13)
  188351. png_error(png_ptr, "Invalid IHDR chunk");
  188352. png_ptr->mode |= PNG_HAVE_IHDR;
  188353. png_crc_read(png_ptr, buf, 13);
  188354. png_crc_finish(png_ptr, 0);
  188355. width = png_get_uint_31(png_ptr, buf);
  188356. height = png_get_uint_31(png_ptr, buf + 4);
  188357. bit_depth = buf[8];
  188358. color_type = buf[9];
  188359. compression_type = buf[10];
  188360. filter_type = buf[11];
  188361. interlace_type = buf[12];
  188362. /* set internal variables */
  188363. png_ptr->width = width;
  188364. png_ptr->height = height;
  188365. png_ptr->bit_depth = (png_byte)bit_depth;
  188366. png_ptr->interlaced = (png_byte)interlace_type;
  188367. png_ptr->color_type = (png_byte)color_type;
  188368. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  188369. png_ptr->filter_type = (png_byte)filter_type;
  188370. #endif
  188371. png_ptr->compression_type = (png_byte)compression_type;
  188372. /* find number of channels */
  188373. switch (png_ptr->color_type)
  188374. {
  188375. case PNG_COLOR_TYPE_GRAY:
  188376. case PNG_COLOR_TYPE_PALETTE:
  188377. png_ptr->channels = 1;
  188378. break;
  188379. case PNG_COLOR_TYPE_RGB:
  188380. png_ptr->channels = 3;
  188381. break;
  188382. case PNG_COLOR_TYPE_GRAY_ALPHA:
  188383. png_ptr->channels = 2;
  188384. break;
  188385. case PNG_COLOR_TYPE_RGB_ALPHA:
  188386. png_ptr->channels = 4;
  188387. break;
  188388. }
  188389. /* set up other useful info */
  188390. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  188391. png_ptr->channels);
  188392. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  188393. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  188394. png_debug1(3,"channels = %d\n", png_ptr->channels);
  188395. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  188396. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  188397. color_type, interlace_type, compression_type, filter_type);
  188398. }
  188399. /* read and check the palette */
  188400. void /* PRIVATE */
  188401. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188402. {
  188403. png_color palette[PNG_MAX_PALETTE_LENGTH];
  188404. int num, i;
  188405. #ifndef PNG_NO_POINTER_INDEXING
  188406. png_colorp pal_ptr;
  188407. #endif
  188408. png_debug(1, "in png_handle_PLTE\n");
  188409. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188410. png_error(png_ptr, "Missing IHDR before PLTE");
  188411. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188412. {
  188413. png_warning(png_ptr, "Invalid PLTE after IDAT");
  188414. png_crc_finish(png_ptr, length);
  188415. return;
  188416. }
  188417. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188418. png_error(png_ptr, "Duplicate PLTE chunk");
  188419. png_ptr->mode |= PNG_HAVE_PLTE;
  188420. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  188421. {
  188422. png_warning(png_ptr,
  188423. "Ignoring PLTE chunk in grayscale PNG");
  188424. png_crc_finish(png_ptr, length);
  188425. return;
  188426. }
  188427. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  188428. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  188429. {
  188430. png_crc_finish(png_ptr, length);
  188431. return;
  188432. }
  188433. #endif
  188434. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  188435. {
  188436. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  188437. {
  188438. png_warning(png_ptr, "Invalid palette chunk");
  188439. png_crc_finish(png_ptr, length);
  188440. return;
  188441. }
  188442. else
  188443. {
  188444. png_error(png_ptr, "Invalid palette chunk");
  188445. }
  188446. }
  188447. num = (int)length / 3;
  188448. #ifndef PNG_NO_POINTER_INDEXING
  188449. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  188450. {
  188451. png_byte buf[3];
  188452. png_crc_read(png_ptr, buf, 3);
  188453. pal_ptr->red = buf[0];
  188454. pal_ptr->green = buf[1];
  188455. pal_ptr->blue = buf[2];
  188456. }
  188457. #else
  188458. for (i = 0; i < num; i++)
  188459. {
  188460. png_byte buf[3];
  188461. png_crc_read(png_ptr, buf, 3);
  188462. /* don't depend upon png_color being any order */
  188463. palette[i].red = buf[0];
  188464. palette[i].green = buf[1];
  188465. palette[i].blue = buf[2];
  188466. }
  188467. #endif
  188468. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  188469. whatever the normal CRC configuration tells us. However, if we
  188470. have an RGB image, the PLTE can be considered ancillary, so
  188471. we will act as though it is. */
  188472. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  188473. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188474. #endif
  188475. {
  188476. png_crc_finish(png_ptr, 0);
  188477. }
  188478. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  188479. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  188480. {
  188481. /* If we don't want to use the data from an ancillary chunk,
  188482. we have two options: an error abort, or a warning and we
  188483. ignore the data in this chunk (which should be OK, since
  188484. it's considered ancillary for a RGB or RGBA image). */
  188485. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  188486. {
  188487. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  188488. {
  188489. png_chunk_error(png_ptr, "CRC error");
  188490. }
  188491. else
  188492. {
  188493. png_chunk_warning(png_ptr, "CRC error");
  188494. return;
  188495. }
  188496. }
  188497. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  188498. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  188499. {
  188500. png_chunk_warning(png_ptr, "CRC error");
  188501. }
  188502. }
  188503. #endif
  188504. png_set_PLTE(png_ptr, info_ptr, palette, num);
  188505. #if defined(PNG_READ_tRNS_SUPPORTED)
  188506. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188507. {
  188508. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  188509. {
  188510. if (png_ptr->num_trans > (png_uint_16)num)
  188511. {
  188512. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  188513. png_ptr->num_trans = (png_uint_16)num;
  188514. }
  188515. if (info_ptr->num_trans > (png_uint_16)num)
  188516. {
  188517. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  188518. info_ptr->num_trans = (png_uint_16)num;
  188519. }
  188520. }
  188521. }
  188522. #endif
  188523. }
  188524. void /* PRIVATE */
  188525. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188526. {
  188527. png_debug(1, "in png_handle_IEND\n");
  188528. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  188529. {
  188530. png_error(png_ptr, "No image in file");
  188531. }
  188532. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  188533. if (length != 0)
  188534. {
  188535. png_warning(png_ptr, "Incorrect IEND chunk length");
  188536. }
  188537. png_crc_finish(png_ptr, length);
  188538. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  188539. }
  188540. #if defined(PNG_READ_gAMA_SUPPORTED)
  188541. void /* PRIVATE */
  188542. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188543. {
  188544. png_fixed_point igamma;
  188545. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188546. float file_gamma;
  188547. #endif
  188548. png_byte buf[4];
  188549. png_debug(1, "in png_handle_gAMA\n");
  188550. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188551. png_error(png_ptr, "Missing IHDR before gAMA");
  188552. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188553. {
  188554. png_warning(png_ptr, "Invalid gAMA after IDAT");
  188555. png_crc_finish(png_ptr, length);
  188556. return;
  188557. }
  188558. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188559. /* Should be an error, but we can cope with it */
  188560. png_warning(png_ptr, "Out of place gAMA chunk");
  188561. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  188562. #if defined(PNG_READ_sRGB_SUPPORTED)
  188563. && !(info_ptr->valid & PNG_INFO_sRGB)
  188564. #endif
  188565. )
  188566. {
  188567. png_warning(png_ptr, "Duplicate gAMA chunk");
  188568. png_crc_finish(png_ptr, length);
  188569. return;
  188570. }
  188571. if (length != 4)
  188572. {
  188573. png_warning(png_ptr, "Incorrect gAMA chunk length");
  188574. png_crc_finish(png_ptr, length);
  188575. return;
  188576. }
  188577. png_crc_read(png_ptr, buf, 4);
  188578. if (png_crc_finish(png_ptr, 0))
  188579. return;
  188580. igamma = (png_fixed_point)png_get_uint_32(buf);
  188581. /* check for zero gamma */
  188582. if (igamma == 0)
  188583. {
  188584. png_warning(png_ptr,
  188585. "Ignoring gAMA chunk with gamma=0");
  188586. return;
  188587. }
  188588. #if defined(PNG_READ_sRGB_SUPPORTED)
  188589. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  188590. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  188591. {
  188592. png_warning(png_ptr,
  188593. "Ignoring incorrect gAMA value when sRGB is also present");
  188594. #ifndef PNG_NO_CONSOLE_IO
  188595. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  188596. #endif
  188597. return;
  188598. }
  188599. #endif /* PNG_READ_sRGB_SUPPORTED */
  188600. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188601. file_gamma = (float)igamma / (float)100000.0;
  188602. # ifdef PNG_READ_GAMMA_SUPPORTED
  188603. png_ptr->gamma = file_gamma;
  188604. # endif
  188605. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  188606. #endif
  188607. #ifdef PNG_FIXED_POINT_SUPPORTED
  188608. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  188609. #endif
  188610. }
  188611. #endif
  188612. #if defined(PNG_READ_sBIT_SUPPORTED)
  188613. void /* PRIVATE */
  188614. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188615. {
  188616. png_size_t truelen;
  188617. png_byte buf[4];
  188618. png_debug(1, "in png_handle_sBIT\n");
  188619. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  188620. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188621. png_error(png_ptr, "Missing IHDR before sBIT");
  188622. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188623. {
  188624. png_warning(png_ptr, "Invalid sBIT after IDAT");
  188625. png_crc_finish(png_ptr, length);
  188626. return;
  188627. }
  188628. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188629. {
  188630. /* Should be an error, but we can cope with it */
  188631. png_warning(png_ptr, "Out of place sBIT chunk");
  188632. }
  188633. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  188634. {
  188635. png_warning(png_ptr, "Duplicate sBIT chunk");
  188636. png_crc_finish(png_ptr, length);
  188637. return;
  188638. }
  188639. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188640. truelen = 3;
  188641. else
  188642. truelen = (png_size_t)png_ptr->channels;
  188643. if (length != truelen || length > 4)
  188644. {
  188645. png_warning(png_ptr, "Incorrect sBIT chunk length");
  188646. png_crc_finish(png_ptr, length);
  188647. return;
  188648. }
  188649. png_crc_read(png_ptr, buf, truelen);
  188650. if (png_crc_finish(png_ptr, 0))
  188651. return;
  188652. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  188653. {
  188654. png_ptr->sig_bit.red = buf[0];
  188655. png_ptr->sig_bit.green = buf[1];
  188656. png_ptr->sig_bit.blue = buf[2];
  188657. png_ptr->sig_bit.alpha = buf[3];
  188658. }
  188659. else
  188660. {
  188661. png_ptr->sig_bit.gray = buf[0];
  188662. png_ptr->sig_bit.red = buf[0];
  188663. png_ptr->sig_bit.green = buf[0];
  188664. png_ptr->sig_bit.blue = buf[0];
  188665. png_ptr->sig_bit.alpha = buf[1];
  188666. }
  188667. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  188668. }
  188669. #endif
  188670. #if defined(PNG_READ_cHRM_SUPPORTED)
  188671. void /* PRIVATE */
  188672. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188673. {
  188674. png_byte buf[4];
  188675. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188676. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  188677. #endif
  188678. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  188679. int_y_green, int_x_blue, int_y_blue;
  188680. png_uint_32 uint_x, uint_y;
  188681. png_debug(1, "in png_handle_cHRM\n");
  188682. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188683. png_error(png_ptr, "Missing IHDR before cHRM");
  188684. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188685. {
  188686. png_warning(png_ptr, "Invalid cHRM after IDAT");
  188687. png_crc_finish(png_ptr, length);
  188688. return;
  188689. }
  188690. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188691. /* Should be an error, but we can cope with it */
  188692. png_warning(png_ptr, "Missing PLTE before cHRM");
  188693. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  188694. #if defined(PNG_READ_sRGB_SUPPORTED)
  188695. && !(info_ptr->valid & PNG_INFO_sRGB)
  188696. #endif
  188697. )
  188698. {
  188699. png_warning(png_ptr, "Duplicate cHRM chunk");
  188700. png_crc_finish(png_ptr, length);
  188701. return;
  188702. }
  188703. if (length != 32)
  188704. {
  188705. png_warning(png_ptr, "Incorrect cHRM chunk length");
  188706. png_crc_finish(png_ptr, length);
  188707. return;
  188708. }
  188709. png_crc_read(png_ptr, buf, 4);
  188710. uint_x = png_get_uint_32(buf);
  188711. png_crc_read(png_ptr, buf, 4);
  188712. uint_y = png_get_uint_32(buf);
  188713. if (uint_x > 80000L || uint_y > 80000L ||
  188714. uint_x + uint_y > 100000L)
  188715. {
  188716. png_warning(png_ptr, "Invalid cHRM white point");
  188717. png_crc_finish(png_ptr, 24);
  188718. return;
  188719. }
  188720. int_x_white = (png_fixed_point)uint_x;
  188721. int_y_white = (png_fixed_point)uint_y;
  188722. png_crc_read(png_ptr, buf, 4);
  188723. uint_x = png_get_uint_32(buf);
  188724. png_crc_read(png_ptr, buf, 4);
  188725. uint_y = png_get_uint_32(buf);
  188726. if (uint_x + uint_y > 100000L)
  188727. {
  188728. png_warning(png_ptr, "Invalid cHRM red point");
  188729. png_crc_finish(png_ptr, 16);
  188730. return;
  188731. }
  188732. int_x_red = (png_fixed_point)uint_x;
  188733. int_y_red = (png_fixed_point)uint_y;
  188734. png_crc_read(png_ptr, buf, 4);
  188735. uint_x = png_get_uint_32(buf);
  188736. png_crc_read(png_ptr, buf, 4);
  188737. uint_y = png_get_uint_32(buf);
  188738. if (uint_x + uint_y > 100000L)
  188739. {
  188740. png_warning(png_ptr, "Invalid cHRM green point");
  188741. png_crc_finish(png_ptr, 8);
  188742. return;
  188743. }
  188744. int_x_green = (png_fixed_point)uint_x;
  188745. int_y_green = (png_fixed_point)uint_y;
  188746. png_crc_read(png_ptr, buf, 4);
  188747. uint_x = png_get_uint_32(buf);
  188748. png_crc_read(png_ptr, buf, 4);
  188749. uint_y = png_get_uint_32(buf);
  188750. if (uint_x + uint_y > 100000L)
  188751. {
  188752. png_warning(png_ptr, "Invalid cHRM blue point");
  188753. png_crc_finish(png_ptr, 0);
  188754. return;
  188755. }
  188756. int_x_blue = (png_fixed_point)uint_x;
  188757. int_y_blue = (png_fixed_point)uint_y;
  188758. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188759. white_x = (float)int_x_white / (float)100000.0;
  188760. white_y = (float)int_y_white / (float)100000.0;
  188761. red_x = (float)int_x_red / (float)100000.0;
  188762. red_y = (float)int_y_red / (float)100000.0;
  188763. green_x = (float)int_x_green / (float)100000.0;
  188764. green_y = (float)int_y_green / (float)100000.0;
  188765. blue_x = (float)int_x_blue / (float)100000.0;
  188766. blue_y = (float)int_y_blue / (float)100000.0;
  188767. #endif
  188768. #if defined(PNG_READ_sRGB_SUPPORTED)
  188769. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  188770. {
  188771. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  188772. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  188773. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  188774. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  188775. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  188776. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  188777. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  188778. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  188779. {
  188780. png_warning(png_ptr,
  188781. "Ignoring incorrect cHRM value when sRGB is also present");
  188782. #ifndef PNG_NO_CONSOLE_IO
  188783. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188784. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  188785. white_x, white_y, red_x, red_y);
  188786. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  188787. green_x, green_y, blue_x, blue_y);
  188788. #else
  188789. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  188790. int_x_white, int_y_white, int_x_red, int_y_red);
  188791. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  188792. int_x_green, int_y_green, int_x_blue, int_y_blue);
  188793. #endif
  188794. #endif /* PNG_NO_CONSOLE_IO */
  188795. }
  188796. png_crc_finish(png_ptr, 0);
  188797. return;
  188798. }
  188799. #endif /* PNG_READ_sRGB_SUPPORTED */
  188800. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188801. png_set_cHRM(png_ptr, info_ptr,
  188802. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  188803. #endif
  188804. #ifdef PNG_FIXED_POINT_SUPPORTED
  188805. png_set_cHRM_fixed(png_ptr, info_ptr,
  188806. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  188807. int_y_green, int_x_blue, int_y_blue);
  188808. #endif
  188809. if (png_crc_finish(png_ptr, 0))
  188810. return;
  188811. }
  188812. #endif
  188813. #if defined(PNG_READ_sRGB_SUPPORTED)
  188814. void /* PRIVATE */
  188815. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188816. {
  188817. int intent;
  188818. png_byte buf[1];
  188819. png_debug(1, "in png_handle_sRGB\n");
  188820. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188821. png_error(png_ptr, "Missing IHDR before sRGB");
  188822. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188823. {
  188824. png_warning(png_ptr, "Invalid sRGB after IDAT");
  188825. png_crc_finish(png_ptr, length);
  188826. return;
  188827. }
  188828. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188829. /* Should be an error, but we can cope with it */
  188830. png_warning(png_ptr, "Out of place sRGB chunk");
  188831. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  188832. {
  188833. png_warning(png_ptr, "Duplicate sRGB chunk");
  188834. png_crc_finish(png_ptr, length);
  188835. return;
  188836. }
  188837. if (length != 1)
  188838. {
  188839. png_warning(png_ptr, "Incorrect sRGB chunk length");
  188840. png_crc_finish(png_ptr, length);
  188841. return;
  188842. }
  188843. png_crc_read(png_ptr, buf, 1);
  188844. if (png_crc_finish(png_ptr, 0))
  188845. return;
  188846. intent = buf[0];
  188847. /* check for bad intent */
  188848. if (intent >= PNG_sRGB_INTENT_LAST)
  188849. {
  188850. png_warning(png_ptr, "Unknown sRGB intent");
  188851. return;
  188852. }
  188853. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  188854. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  188855. {
  188856. png_fixed_point igamma;
  188857. #ifdef PNG_FIXED_POINT_SUPPORTED
  188858. igamma=info_ptr->int_gamma;
  188859. #else
  188860. # ifdef PNG_FLOATING_POINT_SUPPORTED
  188861. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  188862. # endif
  188863. #endif
  188864. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  188865. {
  188866. png_warning(png_ptr,
  188867. "Ignoring incorrect gAMA value when sRGB is also present");
  188868. #ifndef PNG_NO_CONSOLE_IO
  188869. # ifdef PNG_FIXED_POINT_SUPPORTED
  188870. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  188871. # else
  188872. # ifdef PNG_FLOATING_POINT_SUPPORTED
  188873. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  188874. # endif
  188875. # endif
  188876. #endif
  188877. }
  188878. }
  188879. #endif /* PNG_READ_gAMA_SUPPORTED */
  188880. #ifdef PNG_READ_cHRM_SUPPORTED
  188881. #ifdef PNG_FIXED_POINT_SUPPORTED
  188882. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  188883. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  188884. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  188885. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  188886. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  188887. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  188888. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  188889. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  188890. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  188891. {
  188892. png_warning(png_ptr,
  188893. "Ignoring incorrect cHRM value when sRGB is also present");
  188894. }
  188895. #endif /* PNG_FIXED_POINT_SUPPORTED */
  188896. #endif /* PNG_READ_cHRM_SUPPORTED */
  188897. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  188898. }
  188899. #endif /* PNG_READ_sRGB_SUPPORTED */
  188900. #if defined(PNG_READ_iCCP_SUPPORTED)
  188901. void /* PRIVATE */
  188902. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188903. /* Note: this does not properly handle chunks that are > 64K under DOS */
  188904. {
  188905. png_charp chunkdata;
  188906. png_byte compression_type;
  188907. png_bytep pC;
  188908. png_charp profile;
  188909. png_uint_32 skip = 0;
  188910. png_uint_32 profile_size, profile_length;
  188911. png_size_t slength, prefix_length, data_length;
  188912. png_debug(1, "in png_handle_iCCP\n");
  188913. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188914. png_error(png_ptr, "Missing IHDR before iCCP");
  188915. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188916. {
  188917. png_warning(png_ptr, "Invalid iCCP after IDAT");
  188918. png_crc_finish(png_ptr, length);
  188919. return;
  188920. }
  188921. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188922. /* Should be an error, but we can cope with it */
  188923. png_warning(png_ptr, "Out of place iCCP chunk");
  188924. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  188925. {
  188926. png_warning(png_ptr, "Duplicate iCCP chunk");
  188927. png_crc_finish(png_ptr, length);
  188928. return;
  188929. }
  188930. #ifdef PNG_MAX_MALLOC_64K
  188931. if (length > (png_uint_32)65535L)
  188932. {
  188933. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  188934. skip = length - (png_uint_32)65535L;
  188935. length = (png_uint_32)65535L;
  188936. }
  188937. #endif
  188938. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  188939. slength = (png_size_t)length;
  188940. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  188941. if (png_crc_finish(png_ptr, skip))
  188942. {
  188943. png_free(png_ptr, chunkdata);
  188944. return;
  188945. }
  188946. chunkdata[slength] = 0x00;
  188947. for (profile = chunkdata; *profile; profile++)
  188948. /* empty loop to find end of name */ ;
  188949. ++profile;
  188950. /* there should be at least one zero (the compression type byte)
  188951. following the separator, and we should be on it */
  188952. if ( profile >= chunkdata + slength - 1)
  188953. {
  188954. png_free(png_ptr, chunkdata);
  188955. png_warning(png_ptr, "Malformed iCCP chunk");
  188956. return;
  188957. }
  188958. /* compression_type should always be zero */
  188959. compression_type = *profile++;
  188960. if (compression_type)
  188961. {
  188962. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  188963. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  188964. wrote nonzero) */
  188965. }
  188966. prefix_length = profile - chunkdata;
  188967. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  188968. slength, prefix_length, &data_length);
  188969. profile_length = data_length - prefix_length;
  188970. if ( prefix_length > data_length || profile_length < 4)
  188971. {
  188972. png_free(png_ptr, chunkdata);
  188973. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  188974. return;
  188975. }
  188976. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  188977. pC = (png_bytep)(chunkdata+prefix_length);
  188978. profile_size = ((*(pC ))<<24) |
  188979. ((*(pC+1))<<16) |
  188980. ((*(pC+2))<< 8) |
  188981. ((*(pC+3)) );
  188982. if(profile_size < profile_length)
  188983. profile_length = profile_size;
  188984. if(profile_size > profile_length)
  188985. {
  188986. png_free(png_ptr, chunkdata);
  188987. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  188988. return;
  188989. }
  188990. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  188991. chunkdata + prefix_length, profile_length);
  188992. png_free(png_ptr, chunkdata);
  188993. }
  188994. #endif /* PNG_READ_iCCP_SUPPORTED */
  188995. #if defined(PNG_READ_sPLT_SUPPORTED)
  188996. void /* PRIVATE */
  188997. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188998. /* Note: this does not properly handle chunks that are > 64K under DOS */
  188999. {
  189000. png_bytep chunkdata;
  189001. png_bytep entry_start;
  189002. png_sPLT_t new_palette;
  189003. #ifdef PNG_NO_POINTER_INDEXING
  189004. png_sPLT_entryp pp;
  189005. #endif
  189006. int data_length, entry_size, i;
  189007. png_uint_32 skip = 0;
  189008. png_size_t slength;
  189009. png_debug(1, "in png_handle_sPLT\n");
  189010. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189011. png_error(png_ptr, "Missing IHDR before sPLT");
  189012. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189013. {
  189014. png_warning(png_ptr, "Invalid sPLT after IDAT");
  189015. png_crc_finish(png_ptr, length);
  189016. return;
  189017. }
  189018. #ifdef PNG_MAX_MALLOC_64K
  189019. if (length > (png_uint_32)65535L)
  189020. {
  189021. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  189022. skip = length - (png_uint_32)65535L;
  189023. length = (png_uint_32)65535L;
  189024. }
  189025. #endif
  189026. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  189027. slength = (png_size_t)length;
  189028. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  189029. if (png_crc_finish(png_ptr, skip))
  189030. {
  189031. png_free(png_ptr, chunkdata);
  189032. return;
  189033. }
  189034. chunkdata[slength] = 0x00;
  189035. for (entry_start = chunkdata; *entry_start; entry_start++)
  189036. /* empty loop to find end of name */ ;
  189037. ++entry_start;
  189038. /* a sample depth should follow the separator, and we should be on it */
  189039. if (entry_start > chunkdata + slength - 2)
  189040. {
  189041. png_free(png_ptr, chunkdata);
  189042. png_warning(png_ptr, "malformed sPLT chunk");
  189043. return;
  189044. }
  189045. new_palette.depth = *entry_start++;
  189046. entry_size = (new_palette.depth == 8 ? 6 : 10);
  189047. data_length = (slength - (entry_start - chunkdata));
  189048. /* integrity-check the data length */
  189049. if (data_length % entry_size)
  189050. {
  189051. png_free(png_ptr, chunkdata);
  189052. png_warning(png_ptr, "sPLT chunk has bad length");
  189053. return;
  189054. }
  189055. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  189056. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  189057. png_sizeof(png_sPLT_entry)))
  189058. {
  189059. png_warning(png_ptr, "sPLT chunk too long");
  189060. return;
  189061. }
  189062. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  189063. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  189064. if (new_palette.entries == NULL)
  189065. {
  189066. png_warning(png_ptr, "sPLT chunk requires too much memory");
  189067. return;
  189068. }
  189069. #ifndef PNG_NO_POINTER_INDEXING
  189070. for (i = 0; i < new_palette.nentries; i++)
  189071. {
  189072. png_sPLT_entryp pp = new_palette.entries + i;
  189073. if (new_palette.depth == 8)
  189074. {
  189075. pp->red = *entry_start++;
  189076. pp->green = *entry_start++;
  189077. pp->blue = *entry_start++;
  189078. pp->alpha = *entry_start++;
  189079. }
  189080. else
  189081. {
  189082. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  189083. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  189084. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  189085. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  189086. }
  189087. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  189088. }
  189089. #else
  189090. pp = new_palette.entries;
  189091. for (i = 0; i < new_palette.nentries; i++)
  189092. {
  189093. if (new_palette.depth == 8)
  189094. {
  189095. pp[i].red = *entry_start++;
  189096. pp[i].green = *entry_start++;
  189097. pp[i].blue = *entry_start++;
  189098. pp[i].alpha = *entry_start++;
  189099. }
  189100. else
  189101. {
  189102. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  189103. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  189104. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  189105. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  189106. }
  189107. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  189108. }
  189109. #endif
  189110. /* discard all chunk data except the name and stash that */
  189111. new_palette.name = (png_charp)chunkdata;
  189112. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  189113. png_free(png_ptr, chunkdata);
  189114. png_free(png_ptr, new_palette.entries);
  189115. }
  189116. #endif /* PNG_READ_sPLT_SUPPORTED */
  189117. #if defined(PNG_READ_tRNS_SUPPORTED)
  189118. void /* PRIVATE */
  189119. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189120. {
  189121. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  189122. int bit_mask;
  189123. png_debug(1, "in png_handle_tRNS\n");
  189124. /* For non-indexed color, mask off any bits in the tRNS value that
  189125. * exceed the bit depth. Some creators were writing extra bits there.
  189126. * This is not needed for indexed color. */
  189127. bit_mask = (1 << png_ptr->bit_depth) - 1;
  189128. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189129. png_error(png_ptr, "Missing IHDR before tRNS");
  189130. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189131. {
  189132. png_warning(png_ptr, "Invalid tRNS after IDAT");
  189133. png_crc_finish(png_ptr, length);
  189134. return;
  189135. }
  189136. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  189137. {
  189138. png_warning(png_ptr, "Duplicate tRNS chunk");
  189139. png_crc_finish(png_ptr, length);
  189140. return;
  189141. }
  189142. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  189143. {
  189144. png_byte buf[2];
  189145. if (length != 2)
  189146. {
  189147. png_warning(png_ptr, "Incorrect tRNS chunk length");
  189148. png_crc_finish(png_ptr, length);
  189149. return;
  189150. }
  189151. png_crc_read(png_ptr, buf, 2);
  189152. png_ptr->num_trans = 1;
  189153. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  189154. }
  189155. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  189156. {
  189157. png_byte buf[6];
  189158. if (length != 6)
  189159. {
  189160. png_warning(png_ptr, "Incorrect tRNS chunk length");
  189161. png_crc_finish(png_ptr, length);
  189162. return;
  189163. }
  189164. png_crc_read(png_ptr, buf, (png_size_t)length);
  189165. png_ptr->num_trans = 1;
  189166. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  189167. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  189168. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  189169. }
  189170. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189171. {
  189172. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  189173. {
  189174. /* Should be an error, but we can cope with it. */
  189175. png_warning(png_ptr, "Missing PLTE before tRNS");
  189176. }
  189177. if (length > (png_uint_32)png_ptr->num_palette ||
  189178. length > PNG_MAX_PALETTE_LENGTH)
  189179. {
  189180. png_warning(png_ptr, "Incorrect tRNS chunk length");
  189181. png_crc_finish(png_ptr, length);
  189182. return;
  189183. }
  189184. if (length == 0)
  189185. {
  189186. png_warning(png_ptr, "Zero length tRNS chunk");
  189187. png_crc_finish(png_ptr, length);
  189188. return;
  189189. }
  189190. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  189191. png_ptr->num_trans = (png_uint_16)length;
  189192. }
  189193. else
  189194. {
  189195. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  189196. png_crc_finish(png_ptr, length);
  189197. return;
  189198. }
  189199. if (png_crc_finish(png_ptr, 0))
  189200. {
  189201. png_ptr->num_trans = 0;
  189202. return;
  189203. }
  189204. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  189205. &(png_ptr->trans_values));
  189206. }
  189207. #endif
  189208. #if defined(PNG_READ_bKGD_SUPPORTED)
  189209. void /* PRIVATE */
  189210. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189211. {
  189212. png_size_t truelen;
  189213. png_byte buf[6];
  189214. png_debug(1, "in png_handle_bKGD\n");
  189215. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189216. png_error(png_ptr, "Missing IHDR before bKGD");
  189217. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189218. {
  189219. png_warning(png_ptr, "Invalid bKGD after IDAT");
  189220. png_crc_finish(png_ptr, length);
  189221. return;
  189222. }
  189223. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  189224. !(png_ptr->mode & PNG_HAVE_PLTE))
  189225. {
  189226. png_warning(png_ptr, "Missing PLTE before bKGD");
  189227. png_crc_finish(png_ptr, length);
  189228. return;
  189229. }
  189230. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  189231. {
  189232. png_warning(png_ptr, "Duplicate bKGD chunk");
  189233. png_crc_finish(png_ptr, length);
  189234. return;
  189235. }
  189236. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189237. truelen = 1;
  189238. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  189239. truelen = 6;
  189240. else
  189241. truelen = 2;
  189242. if (length != truelen)
  189243. {
  189244. png_warning(png_ptr, "Incorrect bKGD chunk length");
  189245. png_crc_finish(png_ptr, length);
  189246. return;
  189247. }
  189248. png_crc_read(png_ptr, buf, truelen);
  189249. if (png_crc_finish(png_ptr, 0))
  189250. return;
  189251. /* We convert the index value into RGB components so that we can allow
  189252. * arbitrary RGB values for background when we have transparency, and
  189253. * so it is easy to determine the RGB values of the background color
  189254. * from the info_ptr struct. */
  189255. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189256. {
  189257. png_ptr->background.index = buf[0];
  189258. if(info_ptr->num_palette)
  189259. {
  189260. if(buf[0] > info_ptr->num_palette)
  189261. {
  189262. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  189263. return;
  189264. }
  189265. png_ptr->background.red =
  189266. (png_uint_16)png_ptr->palette[buf[0]].red;
  189267. png_ptr->background.green =
  189268. (png_uint_16)png_ptr->palette[buf[0]].green;
  189269. png_ptr->background.blue =
  189270. (png_uint_16)png_ptr->palette[buf[0]].blue;
  189271. }
  189272. }
  189273. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  189274. {
  189275. png_ptr->background.red =
  189276. png_ptr->background.green =
  189277. png_ptr->background.blue =
  189278. png_ptr->background.gray = png_get_uint_16(buf);
  189279. }
  189280. else
  189281. {
  189282. png_ptr->background.red = png_get_uint_16(buf);
  189283. png_ptr->background.green = png_get_uint_16(buf + 2);
  189284. png_ptr->background.blue = png_get_uint_16(buf + 4);
  189285. }
  189286. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  189287. }
  189288. #endif
  189289. #if defined(PNG_READ_hIST_SUPPORTED)
  189290. void /* PRIVATE */
  189291. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189292. {
  189293. unsigned int num, i;
  189294. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  189295. png_debug(1, "in png_handle_hIST\n");
  189296. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189297. png_error(png_ptr, "Missing IHDR before hIST");
  189298. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189299. {
  189300. png_warning(png_ptr, "Invalid hIST after IDAT");
  189301. png_crc_finish(png_ptr, length);
  189302. return;
  189303. }
  189304. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  189305. {
  189306. png_warning(png_ptr, "Missing PLTE before hIST");
  189307. png_crc_finish(png_ptr, length);
  189308. return;
  189309. }
  189310. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  189311. {
  189312. png_warning(png_ptr, "Duplicate hIST chunk");
  189313. png_crc_finish(png_ptr, length);
  189314. return;
  189315. }
  189316. num = length / 2 ;
  189317. if (num != (unsigned int) png_ptr->num_palette || num >
  189318. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  189319. {
  189320. png_warning(png_ptr, "Incorrect hIST chunk length");
  189321. png_crc_finish(png_ptr, length);
  189322. return;
  189323. }
  189324. for (i = 0; i < num; i++)
  189325. {
  189326. png_byte buf[2];
  189327. png_crc_read(png_ptr, buf, 2);
  189328. readbuf[i] = png_get_uint_16(buf);
  189329. }
  189330. if (png_crc_finish(png_ptr, 0))
  189331. return;
  189332. png_set_hIST(png_ptr, info_ptr, readbuf);
  189333. }
  189334. #endif
  189335. #if defined(PNG_READ_pHYs_SUPPORTED)
  189336. void /* PRIVATE */
  189337. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189338. {
  189339. png_byte buf[9];
  189340. png_uint_32 res_x, res_y;
  189341. int unit_type;
  189342. png_debug(1, "in png_handle_pHYs\n");
  189343. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189344. png_error(png_ptr, "Missing IHDR before pHYs");
  189345. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189346. {
  189347. png_warning(png_ptr, "Invalid pHYs after IDAT");
  189348. png_crc_finish(png_ptr, length);
  189349. return;
  189350. }
  189351. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  189352. {
  189353. png_warning(png_ptr, "Duplicate pHYs chunk");
  189354. png_crc_finish(png_ptr, length);
  189355. return;
  189356. }
  189357. if (length != 9)
  189358. {
  189359. png_warning(png_ptr, "Incorrect pHYs chunk length");
  189360. png_crc_finish(png_ptr, length);
  189361. return;
  189362. }
  189363. png_crc_read(png_ptr, buf, 9);
  189364. if (png_crc_finish(png_ptr, 0))
  189365. return;
  189366. res_x = png_get_uint_32(buf);
  189367. res_y = png_get_uint_32(buf + 4);
  189368. unit_type = buf[8];
  189369. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  189370. }
  189371. #endif
  189372. #if defined(PNG_READ_oFFs_SUPPORTED)
  189373. void /* PRIVATE */
  189374. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189375. {
  189376. png_byte buf[9];
  189377. png_int_32 offset_x, offset_y;
  189378. int unit_type;
  189379. png_debug(1, "in png_handle_oFFs\n");
  189380. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189381. png_error(png_ptr, "Missing IHDR before oFFs");
  189382. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189383. {
  189384. png_warning(png_ptr, "Invalid oFFs after IDAT");
  189385. png_crc_finish(png_ptr, length);
  189386. return;
  189387. }
  189388. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  189389. {
  189390. png_warning(png_ptr, "Duplicate oFFs chunk");
  189391. png_crc_finish(png_ptr, length);
  189392. return;
  189393. }
  189394. if (length != 9)
  189395. {
  189396. png_warning(png_ptr, "Incorrect oFFs chunk length");
  189397. png_crc_finish(png_ptr, length);
  189398. return;
  189399. }
  189400. png_crc_read(png_ptr, buf, 9);
  189401. if (png_crc_finish(png_ptr, 0))
  189402. return;
  189403. offset_x = png_get_int_32(buf);
  189404. offset_y = png_get_int_32(buf + 4);
  189405. unit_type = buf[8];
  189406. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  189407. }
  189408. #endif
  189409. #if defined(PNG_READ_pCAL_SUPPORTED)
  189410. /* read the pCAL chunk (described in the PNG Extensions document) */
  189411. void /* PRIVATE */
  189412. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189413. {
  189414. png_charp purpose;
  189415. png_int_32 X0, X1;
  189416. png_byte type, nparams;
  189417. png_charp buf, units, endptr;
  189418. png_charpp params;
  189419. png_size_t slength;
  189420. int i;
  189421. png_debug(1, "in png_handle_pCAL\n");
  189422. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189423. png_error(png_ptr, "Missing IHDR before pCAL");
  189424. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189425. {
  189426. png_warning(png_ptr, "Invalid pCAL after IDAT");
  189427. png_crc_finish(png_ptr, length);
  189428. return;
  189429. }
  189430. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  189431. {
  189432. png_warning(png_ptr, "Duplicate pCAL chunk");
  189433. png_crc_finish(png_ptr, length);
  189434. return;
  189435. }
  189436. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  189437. length + 1);
  189438. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189439. if (purpose == NULL)
  189440. {
  189441. png_warning(png_ptr, "No memory for pCAL purpose.");
  189442. return;
  189443. }
  189444. slength = (png_size_t)length;
  189445. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  189446. if (png_crc_finish(png_ptr, 0))
  189447. {
  189448. png_free(png_ptr, purpose);
  189449. return;
  189450. }
  189451. purpose[slength] = 0x00; /* null terminate the last string */
  189452. png_debug(3, "Finding end of pCAL purpose string\n");
  189453. for (buf = purpose; *buf; buf++)
  189454. /* empty loop */ ;
  189455. endptr = purpose + slength;
  189456. /* We need to have at least 12 bytes after the purpose string
  189457. in order to get the parameter information. */
  189458. if (endptr <= buf + 12)
  189459. {
  189460. png_warning(png_ptr, "Invalid pCAL data");
  189461. png_free(png_ptr, purpose);
  189462. return;
  189463. }
  189464. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  189465. X0 = png_get_int_32((png_bytep)buf+1);
  189466. X1 = png_get_int_32((png_bytep)buf+5);
  189467. type = buf[9];
  189468. nparams = buf[10];
  189469. units = buf + 11;
  189470. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  189471. /* Check that we have the right number of parameters for known
  189472. equation types. */
  189473. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  189474. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  189475. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  189476. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  189477. {
  189478. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  189479. png_free(png_ptr, purpose);
  189480. return;
  189481. }
  189482. else if (type >= PNG_EQUATION_LAST)
  189483. {
  189484. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  189485. }
  189486. for (buf = units; *buf; buf++)
  189487. /* Empty loop to move past the units string. */ ;
  189488. png_debug(3, "Allocating pCAL parameters array\n");
  189489. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  189490. *png_sizeof(png_charp))) ;
  189491. if (params == NULL)
  189492. {
  189493. png_free(png_ptr, purpose);
  189494. png_warning(png_ptr, "No memory for pCAL params.");
  189495. return;
  189496. }
  189497. /* Get pointers to the start of each parameter string. */
  189498. for (i = 0; i < (int)nparams; i++)
  189499. {
  189500. buf++; /* Skip the null string terminator from previous parameter. */
  189501. png_debug1(3, "Reading pCAL parameter %d\n", i);
  189502. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  189503. /* Empty loop to move past each parameter string */ ;
  189504. /* Make sure we haven't run out of data yet */
  189505. if (buf > endptr)
  189506. {
  189507. png_warning(png_ptr, "Invalid pCAL data");
  189508. png_free(png_ptr, purpose);
  189509. png_free(png_ptr, params);
  189510. return;
  189511. }
  189512. }
  189513. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  189514. units, params);
  189515. png_free(png_ptr, purpose);
  189516. png_free(png_ptr, params);
  189517. }
  189518. #endif
  189519. #if defined(PNG_READ_sCAL_SUPPORTED)
  189520. /* read the sCAL chunk */
  189521. void /* PRIVATE */
  189522. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189523. {
  189524. png_charp buffer, ep;
  189525. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189526. double width, height;
  189527. png_charp vp;
  189528. #else
  189529. #ifdef PNG_FIXED_POINT_SUPPORTED
  189530. png_charp swidth, sheight;
  189531. #endif
  189532. #endif
  189533. png_size_t slength;
  189534. png_debug(1, "in png_handle_sCAL\n");
  189535. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189536. png_error(png_ptr, "Missing IHDR before sCAL");
  189537. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189538. {
  189539. png_warning(png_ptr, "Invalid sCAL after IDAT");
  189540. png_crc_finish(png_ptr, length);
  189541. return;
  189542. }
  189543. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  189544. {
  189545. png_warning(png_ptr, "Duplicate sCAL chunk");
  189546. png_crc_finish(png_ptr, length);
  189547. return;
  189548. }
  189549. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  189550. length + 1);
  189551. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189552. if (buffer == NULL)
  189553. {
  189554. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  189555. return;
  189556. }
  189557. slength = (png_size_t)length;
  189558. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  189559. if (png_crc_finish(png_ptr, 0))
  189560. {
  189561. png_free(png_ptr, buffer);
  189562. return;
  189563. }
  189564. buffer[slength] = 0x00; /* null terminate the last string */
  189565. ep = buffer + 1; /* skip unit byte */
  189566. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189567. width = png_strtod(png_ptr, ep, &vp);
  189568. if (*vp)
  189569. {
  189570. png_warning(png_ptr, "malformed width string in sCAL chunk");
  189571. return;
  189572. }
  189573. #else
  189574. #ifdef PNG_FIXED_POINT_SUPPORTED
  189575. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  189576. if (swidth == NULL)
  189577. {
  189578. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  189579. return;
  189580. }
  189581. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  189582. #endif
  189583. #endif
  189584. for (ep = buffer; *ep; ep++)
  189585. /* empty loop */ ;
  189586. ep++;
  189587. if (buffer + slength < ep)
  189588. {
  189589. png_warning(png_ptr, "Truncated sCAL chunk");
  189590. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  189591. !defined(PNG_FLOATING_POINT_SUPPORTED)
  189592. png_free(png_ptr, swidth);
  189593. #endif
  189594. png_free(png_ptr, buffer);
  189595. return;
  189596. }
  189597. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189598. height = png_strtod(png_ptr, ep, &vp);
  189599. if (*vp)
  189600. {
  189601. png_warning(png_ptr, "malformed height string in sCAL chunk");
  189602. return;
  189603. }
  189604. #else
  189605. #ifdef PNG_FIXED_POINT_SUPPORTED
  189606. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  189607. if (swidth == NULL)
  189608. {
  189609. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  189610. return;
  189611. }
  189612. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  189613. #endif
  189614. #endif
  189615. if (buffer + slength < ep
  189616. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189617. || width <= 0. || height <= 0.
  189618. #endif
  189619. )
  189620. {
  189621. png_warning(png_ptr, "Invalid sCAL data");
  189622. png_free(png_ptr, buffer);
  189623. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  189624. png_free(png_ptr, swidth);
  189625. png_free(png_ptr, sheight);
  189626. #endif
  189627. return;
  189628. }
  189629. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189630. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  189631. #else
  189632. #ifdef PNG_FIXED_POINT_SUPPORTED
  189633. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  189634. #endif
  189635. #endif
  189636. png_free(png_ptr, buffer);
  189637. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  189638. png_free(png_ptr, swidth);
  189639. png_free(png_ptr, sheight);
  189640. #endif
  189641. }
  189642. #endif
  189643. #if defined(PNG_READ_tIME_SUPPORTED)
  189644. void /* PRIVATE */
  189645. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189646. {
  189647. png_byte buf[7];
  189648. png_time mod_time;
  189649. png_debug(1, "in png_handle_tIME\n");
  189650. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189651. png_error(png_ptr, "Out of place tIME chunk");
  189652. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  189653. {
  189654. png_warning(png_ptr, "Duplicate tIME chunk");
  189655. png_crc_finish(png_ptr, length);
  189656. return;
  189657. }
  189658. if (png_ptr->mode & PNG_HAVE_IDAT)
  189659. png_ptr->mode |= PNG_AFTER_IDAT;
  189660. if (length != 7)
  189661. {
  189662. png_warning(png_ptr, "Incorrect tIME chunk length");
  189663. png_crc_finish(png_ptr, length);
  189664. return;
  189665. }
  189666. png_crc_read(png_ptr, buf, 7);
  189667. if (png_crc_finish(png_ptr, 0))
  189668. return;
  189669. mod_time.second = buf[6];
  189670. mod_time.minute = buf[5];
  189671. mod_time.hour = buf[4];
  189672. mod_time.day = buf[3];
  189673. mod_time.month = buf[2];
  189674. mod_time.year = png_get_uint_16(buf);
  189675. png_set_tIME(png_ptr, info_ptr, &mod_time);
  189676. }
  189677. #endif
  189678. #if defined(PNG_READ_tEXt_SUPPORTED)
  189679. /* Note: this does not properly handle chunks that are > 64K under DOS */
  189680. void /* PRIVATE */
  189681. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189682. {
  189683. png_textp text_ptr;
  189684. png_charp key;
  189685. png_charp text;
  189686. png_uint_32 skip = 0;
  189687. png_size_t slength;
  189688. int ret;
  189689. png_debug(1, "in png_handle_tEXt\n");
  189690. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189691. png_error(png_ptr, "Missing IHDR before tEXt");
  189692. if (png_ptr->mode & PNG_HAVE_IDAT)
  189693. png_ptr->mode |= PNG_AFTER_IDAT;
  189694. #ifdef PNG_MAX_MALLOC_64K
  189695. if (length > (png_uint_32)65535L)
  189696. {
  189697. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189698. skip = length - (png_uint_32)65535L;
  189699. length = (png_uint_32)65535L;
  189700. }
  189701. #endif
  189702. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189703. if (key == NULL)
  189704. {
  189705. png_warning(png_ptr, "No memory to process text chunk.");
  189706. return;
  189707. }
  189708. slength = (png_size_t)length;
  189709. png_crc_read(png_ptr, (png_bytep)key, slength);
  189710. if (png_crc_finish(png_ptr, skip))
  189711. {
  189712. png_free(png_ptr, key);
  189713. return;
  189714. }
  189715. key[slength] = 0x00;
  189716. for (text = key; *text; text++)
  189717. /* empty loop to find end of key */ ;
  189718. if (text != key + slength)
  189719. text++;
  189720. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  189721. (png_uint_32)png_sizeof(png_text));
  189722. if (text_ptr == NULL)
  189723. {
  189724. png_warning(png_ptr, "Not enough memory to process text chunk.");
  189725. png_free(png_ptr, key);
  189726. return;
  189727. }
  189728. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189729. text_ptr->key = key;
  189730. #ifdef PNG_iTXt_SUPPORTED
  189731. text_ptr->lang = NULL;
  189732. text_ptr->lang_key = NULL;
  189733. text_ptr->itxt_length = 0;
  189734. #endif
  189735. text_ptr->text = text;
  189736. text_ptr->text_length = png_strlen(text);
  189737. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189738. png_free(png_ptr, key);
  189739. png_free(png_ptr, text_ptr);
  189740. if (ret)
  189741. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  189742. }
  189743. #endif
  189744. #if defined(PNG_READ_zTXt_SUPPORTED)
  189745. /* note: this does not correctly handle chunks that are > 64K under DOS */
  189746. void /* PRIVATE */
  189747. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189748. {
  189749. png_textp text_ptr;
  189750. png_charp chunkdata;
  189751. png_charp text;
  189752. int comp_type;
  189753. int ret;
  189754. png_size_t slength, prefix_len, data_len;
  189755. png_debug(1, "in png_handle_zTXt\n");
  189756. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189757. png_error(png_ptr, "Missing IHDR before zTXt");
  189758. if (png_ptr->mode & PNG_HAVE_IDAT)
  189759. png_ptr->mode |= PNG_AFTER_IDAT;
  189760. #ifdef PNG_MAX_MALLOC_64K
  189761. /* We will no doubt have problems with chunks even half this size, but
  189762. there is no hard and fast rule to tell us where to stop. */
  189763. if (length > (png_uint_32)65535L)
  189764. {
  189765. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  189766. png_crc_finish(png_ptr, length);
  189767. return;
  189768. }
  189769. #endif
  189770. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189771. if (chunkdata == NULL)
  189772. {
  189773. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  189774. return;
  189775. }
  189776. slength = (png_size_t)length;
  189777. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  189778. if (png_crc_finish(png_ptr, 0))
  189779. {
  189780. png_free(png_ptr, chunkdata);
  189781. return;
  189782. }
  189783. chunkdata[slength] = 0x00;
  189784. for (text = chunkdata; *text; text++)
  189785. /* empty loop */ ;
  189786. /* zTXt must have some text after the chunkdataword */
  189787. if (text >= chunkdata + slength - 2)
  189788. {
  189789. png_warning(png_ptr, "Truncated zTXt chunk");
  189790. png_free(png_ptr, chunkdata);
  189791. return;
  189792. }
  189793. else
  189794. {
  189795. comp_type = *(++text);
  189796. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  189797. {
  189798. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  189799. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  189800. }
  189801. text++; /* skip the compression_method byte */
  189802. }
  189803. prefix_len = text - chunkdata;
  189804. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  189805. (png_size_t)length, prefix_len, &data_len);
  189806. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  189807. (png_uint_32)png_sizeof(png_text));
  189808. if (text_ptr == NULL)
  189809. {
  189810. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  189811. png_free(png_ptr, chunkdata);
  189812. return;
  189813. }
  189814. text_ptr->compression = comp_type;
  189815. text_ptr->key = chunkdata;
  189816. #ifdef PNG_iTXt_SUPPORTED
  189817. text_ptr->lang = NULL;
  189818. text_ptr->lang_key = NULL;
  189819. text_ptr->itxt_length = 0;
  189820. #endif
  189821. text_ptr->text = chunkdata + prefix_len;
  189822. text_ptr->text_length = data_len;
  189823. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189824. png_free(png_ptr, text_ptr);
  189825. png_free(png_ptr, chunkdata);
  189826. if (ret)
  189827. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  189828. }
  189829. #endif
  189830. #if defined(PNG_READ_iTXt_SUPPORTED)
  189831. /* note: this does not correctly handle chunks that are > 64K under DOS */
  189832. void /* PRIVATE */
  189833. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189834. {
  189835. png_textp text_ptr;
  189836. png_charp chunkdata;
  189837. png_charp key, lang, text, lang_key;
  189838. int comp_flag;
  189839. int comp_type = 0;
  189840. int ret;
  189841. png_size_t slength, prefix_len, data_len;
  189842. png_debug(1, "in png_handle_iTXt\n");
  189843. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189844. png_error(png_ptr, "Missing IHDR before iTXt");
  189845. if (png_ptr->mode & PNG_HAVE_IDAT)
  189846. png_ptr->mode |= PNG_AFTER_IDAT;
  189847. #ifdef PNG_MAX_MALLOC_64K
  189848. /* We will no doubt have problems with chunks even half this size, but
  189849. there is no hard and fast rule to tell us where to stop. */
  189850. if (length > (png_uint_32)65535L)
  189851. {
  189852. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  189853. png_crc_finish(png_ptr, length);
  189854. return;
  189855. }
  189856. #endif
  189857. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189858. if (chunkdata == NULL)
  189859. {
  189860. png_warning(png_ptr, "No memory to process iTXt chunk.");
  189861. return;
  189862. }
  189863. slength = (png_size_t)length;
  189864. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  189865. if (png_crc_finish(png_ptr, 0))
  189866. {
  189867. png_free(png_ptr, chunkdata);
  189868. return;
  189869. }
  189870. chunkdata[slength] = 0x00;
  189871. for (lang = chunkdata; *lang; lang++)
  189872. /* empty loop */ ;
  189873. lang++; /* skip NUL separator */
  189874. /* iTXt must have a language tag (possibly empty), two compression bytes,
  189875. translated keyword (possibly empty), and possibly some text after the
  189876. keyword */
  189877. if (lang >= chunkdata + slength - 3)
  189878. {
  189879. png_warning(png_ptr, "Truncated iTXt chunk");
  189880. png_free(png_ptr, chunkdata);
  189881. return;
  189882. }
  189883. else
  189884. {
  189885. comp_flag = *lang++;
  189886. comp_type = *lang++;
  189887. }
  189888. for (lang_key = lang; *lang_key; lang_key++)
  189889. /* empty loop */ ;
  189890. lang_key++; /* skip NUL separator */
  189891. if (lang_key >= chunkdata + slength)
  189892. {
  189893. png_warning(png_ptr, "Truncated iTXt chunk");
  189894. png_free(png_ptr, chunkdata);
  189895. return;
  189896. }
  189897. for (text = lang_key; *text; text++)
  189898. /* empty loop */ ;
  189899. text++; /* skip NUL separator */
  189900. if (text >= chunkdata + slength)
  189901. {
  189902. png_warning(png_ptr, "Malformed iTXt chunk");
  189903. png_free(png_ptr, chunkdata);
  189904. return;
  189905. }
  189906. prefix_len = text - chunkdata;
  189907. key=chunkdata;
  189908. if (comp_flag)
  189909. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  189910. (size_t)length, prefix_len, &data_len);
  189911. else
  189912. data_len=png_strlen(chunkdata + prefix_len);
  189913. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  189914. (png_uint_32)png_sizeof(png_text));
  189915. if (text_ptr == NULL)
  189916. {
  189917. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  189918. png_free(png_ptr, chunkdata);
  189919. return;
  189920. }
  189921. text_ptr->compression = (int)comp_flag + 1;
  189922. text_ptr->lang_key = chunkdata+(lang_key-key);
  189923. text_ptr->lang = chunkdata+(lang-key);
  189924. text_ptr->itxt_length = data_len;
  189925. text_ptr->text_length = 0;
  189926. text_ptr->key = chunkdata;
  189927. text_ptr->text = chunkdata + prefix_len;
  189928. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189929. png_free(png_ptr, text_ptr);
  189930. png_free(png_ptr, chunkdata);
  189931. if (ret)
  189932. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  189933. }
  189934. #endif
  189935. /* This function is called when we haven't found a handler for a
  189936. chunk. If there isn't a problem with the chunk itself (ie bad
  189937. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  189938. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  189939. case it will be saved away to be written out later. */
  189940. void /* PRIVATE */
  189941. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189942. {
  189943. png_uint_32 skip = 0;
  189944. png_debug(1, "in png_handle_unknown\n");
  189945. if (png_ptr->mode & PNG_HAVE_IDAT)
  189946. {
  189947. #ifdef PNG_USE_LOCAL_ARRAYS
  189948. PNG_CONST PNG_IDAT;
  189949. #endif
  189950. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  189951. png_ptr->mode |= PNG_AFTER_IDAT;
  189952. }
  189953. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189954. if (!(png_ptr->chunk_name[0] & 0x20))
  189955. {
  189956. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189957. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189958. PNG_HANDLE_CHUNK_ALWAYS
  189959. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189960. && png_ptr->read_user_chunk_fn == NULL
  189961. #endif
  189962. )
  189963. #endif
  189964. png_chunk_error(png_ptr, "unknown critical chunk");
  189965. }
  189966. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189967. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  189968. (png_ptr->read_user_chunk_fn != NULL))
  189969. {
  189970. #ifdef PNG_MAX_MALLOC_64K
  189971. if (length > (png_uint_32)65535L)
  189972. {
  189973. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189974. skip = length - (png_uint_32)65535L;
  189975. length = (png_uint_32)65535L;
  189976. }
  189977. #endif
  189978. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189979. (png_charp)png_ptr->chunk_name, 5);
  189980. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189981. png_ptr->unknown_chunk.size = (png_size_t)length;
  189982. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189983. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189984. if(png_ptr->read_user_chunk_fn != NULL)
  189985. {
  189986. /* callback to user unknown chunk handler */
  189987. int ret;
  189988. ret = (*(png_ptr->read_user_chunk_fn))
  189989. (png_ptr, &png_ptr->unknown_chunk);
  189990. if (ret < 0)
  189991. png_chunk_error(png_ptr, "error in user chunk");
  189992. if (ret == 0)
  189993. {
  189994. if (!(png_ptr->chunk_name[0] & 0x20))
  189995. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189996. PNG_HANDLE_CHUNK_ALWAYS)
  189997. png_chunk_error(png_ptr, "unknown critical chunk");
  189998. png_set_unknown_chunks(png_ptr, info_ptr,
  189999. &png_ptr->unknown_chunk, 1);
  190000. }
  190001. }
  190002. #else
  190003. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  190004. #endif
  190005. png_free(png_ptr, png_ptr->unknown_chunk.data);
  190006. png_ptr->unknown_chunk.data = NULL;
  190007. }
  190008. else
  190009. #endif
  190010. skip = length;
  190011. png_crc_finish(png_ptr, skip);
  190012. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  190013. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  190014. #endif
  190015. }
  190016. /* This function is called to verify that a chunk name is valid.
  190017. This function can't have the "critical chunk check" incorporated
  190018. into it, since in the future we will need to be able to call user
  190019. functions to handle unknown critical chunks after we check that
  190020. the chunk name itself is valid. */
  190021. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  190022. void /* PRIVATE */
  190023. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  190024. {
  190025. png_debug(1, "in png_check_chunk_name\n");
  190026. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  190027. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  190028. {
  190029. png_chunk_error(png_ptr, "invalid chunk type");
  190030. }
  190031. }
  190032. /* Combines the row recently read in with the existing pixels in the
  190033. row. This routine takes care of alpha and transparency if requested.
  190034. This routine also handles the two methods of progressive display
  190035. of interlaced images, depending on the mask value.
  190036. The mask value describes which pixels are to be combined with
  190037. the row. The pattern always repeats every 8 pixels, so just 8
  190038. bits are needed. A one indicates the pixel is to be combined,
  190039. a zero indicates the pixel is to be skipped. This is in addition
  190040. to any alpha or transparency value associated with the pixel. If
  190041. you want all pixels to be combined, pass 0xff (255) in mask. */
  190042. void /* PRIVATE */
  190043. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  190044. {
  190045. png_debug(1,"in png_combine_row\n");
  190046. if (mask == 0xff)
  190047. {
  190048. png_memcpy(row, png_ptr->row_buf + 1,
  190049. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  190050. }
  190051. else
  190052. {
  190053. switch (png_ptr->row_info.pixel_depth)
  190054. {
  190055. case 1:
  190056. {
  190057. png_bytep sp = png_ptr->row_buf + 1;
  190058. png_bytep dp = row;
  190059. int s_inc, s_start, s_end;
  190060. int m = 0x80;
  190061. int shift;
  190062. png_uint_32 i;
  190063. png_uint_32 row_width = png_ptr->width;
  190064. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190065. if (png_ptr->transformations & PNG_PACKSWAP)
  190066. {
  190067. s_start = 0;
  190068. s_end = 7;
  190069. s_inc = 1;
  190070. }
  190071. else
  190072. #endif
  190073. {
  190074. s_start = 7;
  190075. s_end = 0;
  190076. s_inc = -1;
  190077. }
  190078. shift = s_start;
  190079. for (i = 0; i < row_width; i++)
  190080. {
  190081. if (m & mask)
  190082. {
  190083. int value;
  190084. value = (*sp >> shift) & 0x01;
  190085. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  190086. *dp |= (png_byte)(value << shift);
  190087. }
  190088. if (shift == s_end)
  190089. {
  190090. shift = s_start;
  190091. sp++;
  190092. dp++;
  190093. }
  190094. else
  190095. shift += s_inc;
  190096. if (m == 1)
  190097. m = 0x80;
  190098. else
  190099. m >>= 1;
  190100. }
  190101. break;
  190102. }
  190103. case 2:
  190104. {
  190105. png_bytep sp = png_ptr->row_buf + 1;
  190106. png_bytep dp = row;
  190107. int s_start, s_end, s_inc;
  190108. int m = 0x80;
  190109. int shift;
  190110. png_uint_32 i;
  190111. png_uint_32 row_width = png_ptr->width;
  190112. int value;
  190113. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190114. if (png_ptr->transformations & PNG_PACKSWAP)
  190115. {
  190116. s_start = 0;
  190117. s_end = 6;
  190118. s_inc = 2;
  190119. }
  190120. else
  190121. #endif
  190122. {
  190123. s_start = 6;
  190124. s_end = 0;
  190125. s_inc = -2;
  190126. }
  190127. shift = s_start;
  190128. for (i = 0; i < row_width; i++)
  190129. {
  190130. if (m & mask)
  190131. {
  190132. value = (*sp >> shift) & 0x03;
  190133. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  190134. *dp |= (png_byte)(value << shift);
  190135. }
  190136. if (shift == s_end)
  190137. {
  190138. shift = s_start;
  190139. sp++;
  190140. dp++;
  190141. }
  190142. else
  190143. shift += s_inc;
  190144. if (m == 1)
  190145. m = 0x80;
  190146. else
  190147. m >>= 1;
  190148. }
  190149. break;
  190150. }
  190151. case 4:
  190152. {
  190153. png_bytep sp = png_ptr->row_buf + 1;
  190154. png_bytep dp = row;
  190155. int s_start, s_end, s_inc;
  190156. int m = 0x80;
  190157. int shift;
  190158. png_uint_32 i;
  190159. png_uint_32 row_width = png_ptr->width;
  190160. int value;
  190161. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190162. if (png_ptr->transformations & PNG_PACKSWAP)
  190163. {
  190164. s_start = 0;
  190165. s_end = 4;
  190166. s_inc = 4;
  190167. }
  190168. else
  190169. #endif
  190170. {
  190171. s_start = 4;
  190172. s_end = 0;
  190173. s_inc = -4;
  190174. }
  190175. shift = s_start;
  190176. for (i = 0; i < row_width; i++)
  190177. {
  190178. if (m & mask)
  190179. {
  190180. value = (*sp >> shift) & 0xf;
  190181. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  190182. *dp |= (png_byte)(value << shift);
  190183. }
  190184. if (shift == s_end)
  190185. {
  190186. shift = s_start;
  190187. sp++;
  190188. dp++;
  190189. }
  190190. else
  190191. shift += s_inc;
  190192. if (m == 1)
  190193. m = 0x80;
  190194. else
  190195. m >>= 1;
  190196. }
  190197. break;
  190198. }
  190199. default:
  190200. {
  190201. png_bytep sp = png_ptr->row_buf + 1;
  190202. png_bytep dp = row;
  190203. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  190204. png_uint_32 i;
  190205. png_uint_32 row_width = png_ptr->width;
  190206. png_byte m = 0x80;
  190207. for (i = 0; i < row_width; i++)
  190208. {
  190209. if (m & mask)
  190210. {
  190211. png_memcpy(dp, sp, pixel_bytes);
  190212. }
  190213. sp += pixel_bytes;
  190214. dp += pixel_bytes;
  190215. if (m == 1)
  190216. m = 0x80;
  190217. else
  190218. m >>= 1;
  190219. }
  190220. break;
  190221. }
  190222. }
  190223. }
  190224. }
  190225. #ifdef PNG_READ_INTERLACING_SUPPORTED
  190226. /* OLD pre-1.0.9 interface:
  190227. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  190228. png_uint_32 transformations)
  190229. */
  190230. void /* PRIVATE */
  190231. png_do_read_interlace(png_structp png_ptr)
  190232. {
  190233. png_row_infop row_info = &(png_ptr->row_info);
  190234. png_bytep row = png_ptr->row_buf + 1;
  190235. int pass = png_ptr->pass;
  190236. png_uint_32 transformations = png_ptr->transformations;
  190237. #ifdef PNG_USE_LOCAL_ARRAYS
  190238. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  190239. /* offset to next interlace block */
  190240. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  190241. #endif
  190242. png_debug(1,"in png_do_read_interlace\n");
  190243. if (row != NULL && row_info != NULL)
  190244. {
  190245. png_uint_32 final_width;
  190246. final_width = row_info->width * png_pass_inc[pass];
  190247. switch (row_info->pixel_depth)
  190248. {
  190249. case 1:
  190250. {
  190251. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  190252. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  190253. int sshift, dshift;
  190254. int s_start, s_end, s_inc;
  190255. int jstop = png_pass_inc[pass];
  190256. png_byte v;
  190257. png_uint_32 i;
  190258. int j;
  190259. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190260. if (transformations & PNG_PACKSWAP)
  190261. {
  190262. sshift = (int)((row_info->width + 7) & 0x07);
  190263. dshift = (int)((final_width + 7) & 0x07);
  190264. s_start = 7;
  190265. s_end = 0;
  190266. s_inc = -1;
  190267. }
  190268. else
  190269. #endif
  190270. {
  190271. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  190272. dshift = 7 - (int)((final_width + 7) & 0x07);
  190273. s_start = 0;
  190274. s_end = 7;
  190275. s_inc = 1;
  190276. }
  190277. for (i = 0; i < row_info->width; i++)
  190278. {
  190279. v = (png_byte)((*sp >> sshift) & 0x01);
  190280. for (j = 0; j < jstop; j++)
  190281. {
  190282. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  190283. *dp |= (png_byte)(v << dshift);
  190284. if (dshift == s_end)
  190285. {
  190286. dshift = s_start;
  190287. dp--;
  190288. }
  190289. else
  190290. dshift += s_inc;
  190291. }
  190292. if (sshift == s_end)
  190293. {
  190294. sshift = s_start;
  190295. sp--;
  190296. }
  190297. else
  190298. sshift += s_inc;
  190299. }
  190300. break;
  190301. }
  190302. case 2:
  190303. {
  190304. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  190305. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  190306. int sshift, dshift;
  190307. int s_start, s_end, s_inc;
  190308. int jstop = png_pass_inc[pass];
  190309. png_uint_32 i;
  190310. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190311. if (transformations & PNG_PACKSWAP)
  190312. {
  190313. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  190314. dshift = (int)(((final_width + 3) & 0x03) << 1);
  190315. s_start = 6;
  190316. s_end = 0;
  190317. s_inc = -2;
  190318. }
  190319. else
  190320. #endif
  190321. {
  190322. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  190323. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  190324. s_start = 0;
  190325. s_end = 6;
  190326. s_inc = 2;
  190327. }
  190328. for (i = 0; i < row_info->width; i++)
  190329. {
  190330. png_byte v;
  190331. int j;
  190332. v = (png_byte)((*sp >> sshift) & 0x03);
  190333. for (j = 0; j < jstop; j++)
  190334. {
  190335. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  190336. *dp |= (png_byte)(v << dshift);
  190337. if (dshift == s_end)
  190338. {
  190339. dshift = s_start;
  190340. dp--;
  190341. }
  190342. else
  190343. dshift += s_inc;
  190344. }
  190345. if (sshift == s_end)
  190346. {
  190347. sshift = s_start;
  190348. sp--;
  190349. }
  190350. else
  190351. sshift += s_inc;
  190352. }
  190353. break;
  190354. }
  190355. case 4:
  190356. {
  190357. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  190358. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  190359. int sshift, dshift;
  190360. int s_start, s_end, s_inc;
  190361. png_uint_32 i;
  190362. int jstop = png_pass_inc[pass];
  190363. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190364. if (transformations & PNG_PACKSWAP)
  190365. {
  190366. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  190367. dshift = (int)(((final_width + 1) & 0x01) << 2);
  190368. s_start = 4;
  190369. s_end = 0;
  190370. s_inc = -4;
  190371. }
  190372. else
  190373. #endif
  190374. {
  190375. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  190376. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  190377. s_start = 0;
  190378. s_end = 4;
  190379. s_inc = 4;
  190380. }
  190381. for (i = 0; i < row_info->width; i++)
  190382. {
  190383. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  190384. int j;
  190385. for (j = 0; j < jstop; j++)
  190386. {
  190387. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  190388. *dp |= (png_byte)(v << dshift);
  190389. if (dshift == s_end)
  190390. {
  190391. dshift = s_start;
  190392. dp--;
  190393. }
  190394. else
  190395. dshift += s_inc;
  190396. }
  190397. if (sshift == s_end)
  190398. {
  190399. sshift = s_start;
  190400. sp--;
  190401. }
  190402. else
  190403. sshift += s_inc;
  190404. }
  190405. break;
  190406. }
  190407. default:
  190408. {
  190409. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  190410. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  190411. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  190412. int jstop = png_pass_inc[pass];
  190413. png_uint_32 i;
  190414. for (i = 0; i < row_info->width; i++)
  190415. {
  190416. png_byte v[8];
  190417. int j;
  190418. png_memcpy(v, sp, pixel_bytes);
  190419. for (j = 0; j < jstop; j++)
  190420. {
  190421. png_memcpy(dp, v, pixel_bytes);
  190422. dp -= pixel_bytes;
  190423. }
  190424. sp -= pixel_bytes;
  190425. }
  190426. break;
  190427. }
  190428. }
  190429. row_info->width = final_width;
  190430. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  190431. }
  190432. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  190433. transformations = transformations; /* silence compiler warning */
  190434. #endif
  190435. }
  190436. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  190437. void /* PRIVATE */
  190438. png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row,
  190439. png_bytep prev_row, int filter)
  190440. {
  190441. png_debug(1, "in png_read_filter_row\n");
  190442. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  190443. switch (filter)
  190444. {
  190445. case PNG_FILTER_VALUE_NONE:
  190446. break;
  190447. case PNG_FILTER_VALUE_SUB:
  190448. {
  190449. png_uint_32 i;
  190450. png_uint_32 istop = row_info->rowbytes;
  190451. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  190452. png_bytep rp = row + bpp;
  190453. png_bytep lp = row;
  190454. for (i = bpp; i < istop; i++)
  190455. {
  190456. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  190457. rp++;
  190458. }
  190459. break;
  190460. }
  190461. case PNG_FILTER_VALUE_UP:
  190462. {
  190463. png_uint_32 i;
  190464. png_uint_32 istop = row_info->rowbytes;
  190465. png_bytep rp = row;
  190466. png_bytep pp = prev_row;
  190467. for (i = 0; i < istop; i++)
  190468. {
  190469. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  190470. rp++;
  190471. }
  190472. break;
  190473. }
  190474. case PNG_FILTER_VALUE_AVG:
  190475. {
  190476. png_uint_32 i;
  190477. png_bytep rp = row;
  190478. png_bytep pp = prev_row;
  190479. png_bytep lp = row;
  190480. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  190481. png_uint_32 istop = row_info->rowbytes - bpp;
  190482. for (i = 0; i < bpp; i++)
  190483. {
  190484. *rp = (png_byte)(((int)(*rp) +
  190485. ((int)(*pp++) / 2 )) & 0xff);
  190486. rp++;
  190487. }
  190488. for (i = 0; i < istop; i++)
  190489. {
  190490. *rp = (png_byte)(((int)(*rp) +
  190491. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  190492. rp++;
  190493. }
  190494. break;
  190495. }
  190496. case PNG_FILTER_VALUE_PAETH:
  190497. {
  190498. png_uint_32 i;
  190499. png_bytep rp = row;
  190500. png_bytep pp = prev_row;
  190501. png_bytep lp = row;
  190502. png_bytep cp = prev_row;
  190503. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  190504. png_uint_32 istop=row_info->rowbytes - bpp;
  190505. for (i = 0; i < bpp; i++)
  190506. {
  190507. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  190508. rp++;
  190509. }
  190510. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  190511. {
  190512. int a, b, c, pa, pb, pc, p;
  190513. a = *lp++;
  190514. b = *pp++;
  190515. c = *cp++;
  190516. p = b - c;
  190517. pc = a - c;
  190518. #ifdef PNG_USE_ABS
  190519. pa = abs(p);
  190520. pb = abs(pc);
  190521. pc = abs(p + pc);
  190522. #else
  190523. pa = p < 0 ? -p : p;
  190524. pb = pc < 0 ? -pc : pc;
  190525. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  190526. #endif
  190527. /*
  190528. if (pa <= pb && pa <= pc)
  190529. p = a;
  190530. else if (pb <= pc)
  190531. p = b;
  190532. else
  190533. p = c;
  190534. */
  190535. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  190536. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  190537. rp++;
  190538. }
  190539. break;
  190540. }
  190541. default:
  190542. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  190543. *row=0;
  190544. break;
  190545. }
  190546. }
  190547. void /* PRIVATE */
  190548. png_read_finish_row(png_structp png_ptr)
  190549. {
  190550. #ifdef PNG_USE_LOCAL_ARRAYS
  190551. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  190552. /* start of interlace block */
  190553. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  190554. /* offset to next interlace block */
  190555. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  190556. /* start of interlace block in the y direction */
  190557. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  190558. /* offset to next interlace block in the y direction */
  190559. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  190560. #endif
  190561. png_debug(1, "in png_read_finish_row\n");
  190562. png_ptr->row_number++;
  190563. if (png_ptr->row_number < png_ptr->num_rows)
  190564. return;
  190565. if (png_ptr->interlaced)
  190566. {
  190567. png_ptr->row_number = 0;
  190568. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  190569. png_ptr->rowbytes + 1);
  190570. do
  190571. {
  190572. png_ptr->pass++;
  190573. if (png_ptr->pass >= 7)
  190574. break;
  190575. png_ptr->iwidth = (png_ptr->width +
  190576. png_pass_inc[png_ptr->pass] - 1 -
  190577. png_pass_start[png_ptr->pass]) /
  190578. png_pass_inc[png_ptr->pass];
  190579. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  190580. png_ptr->iwidth) + 1;
  190581. if (!(png_ptr->transformations & PNG_INTERLACE))
  190582. {
  190583. png_ptr->num_rows = (png_ptr->height +
  190584. png_pass_yinc[png_ptr->pass] - 1 -
  190585. png_pass_ystart[png_ptr->pass]) /
  190586. png_pass_yinc[png_ptr->pass];
  190587. if (!(png_ptr->num_rows))
  190588. continue;
  190589. }
  190590. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  190591. break;
  190592. } while (png_ptr->iwidth == 0);
  190593. if (png_ptr->pass < 7)
  190594. return;
  190595. }
  190596. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  190597. {
  190598. #ifdef PNG_USE_LOCAL_ARRAYS
  190599. PNG_CONST PNG_IDAT;
  190600. #endif
  190601. char extra;
  190602. int ret;
  190603. png_ptr->zstream.next_out = (Byte *)&extra;
  190604. png_ptr->zstream.avail_out = (uInt)1;
  190605. for(;;)
  190606. {
  190607. if (!(png_ptr->zstream.avail_in))
  190608. {
  190609. while (!png_ptr->idat_size)
  190610. {
  190611. png_byte chunk_length[4];
  190612. png_crc_finish(png_ptr, 0);
  190613. png_read_data(png_ptr, chunk_length, 4);
  190614. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  190615. png_reset_crc(png_ptr);
  190616. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  190617. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  190618. png_error(png_ptr, "Not enough image data");
  190619. }
  190620. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  190621. png_ptr->zstream.next_in = png_ptr->zbuf;
  190622. if (png_ptr->zbuf_size > png_ptr->idat_size)
  190623. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  190624. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  190625. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  190626. }
  190627. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  190628. if (ret == Z_STREAM_END)
  190629. {
  190630. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  190631. png_ptr->idat_size)
  190632. png_warning(png_ptr, "Extra compressed data");
  190633. png_ptr->mode |= PNG_AFTER_IDAT;
  190634. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  190635. break;
  190636. }
  190637. if (ret != Z_OK)
  190638. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  190639. "Decompression Error");
  190640. if (!(png_ptr->zstream.avail_out))
  190641. {
  190642. png_warning(png_ptr, "Extra compressed data.");
  190643. png_ptr->mode |= PNG_AFTER_IDAT;
  190644. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  190645. break;
  190646. }
  190647. }
  190648. png_ptr->zstream.avail_out = 0;
  190649. }
  190650. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  190651. png_warning(png_ptr, "Extra compression data");
  190652. inflateReset(&png_ptr->zstream);
  190653. png_ptr->mode |= PNG_AFTER_IDAT;
  190654. }
  190655. void /* PRIVATE */
  190656. png_read_start_row(png_structp png_ptr)
  190657. {
  190658. #ifdef PNG_USE_LOCAL_ARRAYS
  190659. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  190660. /* start of interlace block */
  190661. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  190662. /* offset to next interlace block */
  190663. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  190664. /* start of interlace block in the y direction */
  190665. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  190666. /* offset to next interlace block in the y direction */
  190667. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  190668. #endif
  190669. int max_pixel_depth;
  190670. png_uint_32 row_bytes;
  190671. png_debug(1, "in png_read_start_row\n");
  190672. png_ptr->zstream.avail_in = 0;
  190673. png_init_read_transformations(png_ptr);
  190674. if (png_ptr->interlaced)
  190675. {
  190676. if (!(png_ptr->transformations & PNG_INTERLACE))
  190677. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  190678. png_pass_ystart[0]) / png_pass_yinc[0];
  190679. else
  190680. png_ptr->num_rows = png_ptr->height;
  190681. png_ptr->iwidth = (png_ptr->width +
  190682. png_pass_inc[png_ptr->pass] - 1 -
  190683. png_pass_start[png_ptr->pass]) /
  190684. png_pass_inc[png_ptr->pass];
  190685. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  190686. png_ptr->irowbytes = (png_size_t)row_bytes;
  190687. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  190688. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  190689. }
  190690. else
  190691. {
  190692. png_ptr->num_rows = png_ptr->height;
  190693. png_ptr->iwidth = png_ptr->width;
  190694. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  190695. }
  190696. max_pixel_depth = png_ptr->pixel_depth;
  190697. #if defined(PNG_READ_PACK_SUPPORTED)
  190698. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  190699. max_pixel_depth = 8;
  190700. #endif
  190701. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190702. if (png_ptr->transformations & PNG_EXPAND)
  190703. {
  190704. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190705. {
  190706. if (png_ptr->num_trans)
  190707. max_pixel_depth = 32;
  190708. else
  190709. max_pixel_depth = 24;
  190710. }
  190711. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  190712. {
  190713. if (max_pixel_depth < 8)
  190714. max_pixel_depth = 8;
  190715. if (png_ptr->num_trans)
  190716. max_pixel_depth *= 2;
  190717. }
  190718. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  190719. {
  190720. if (png_ptr->num_trans)
  190721. {
  190722. max_pixel_depth *= 4;
  190723. max_pixel_depth /= 3;
  190724. }
  190725. }
  190726. }
  190727. #endif
  190728. #if defined(PNG_READ_FILLER_SUPPORTED)
  190729. if (png_ptr->transformations & (PNG_FILLER))
  190730. {
  190731. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190732. max_pixel_depth = 32;
  190733. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  190734. {
  190735. if (max_pixel_depth <= 8)
  190736. max_pixel_depth = 16;
  190737. else
  190738. max_pixel_depth = 32;
  190739. }
  190740. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  190741. {
  190742. if (max_pixel_depth <= 32)
  190743. max_pixel_depth = 32;
  190744. else
  190745. max_pixel_depth = 64;
  190746. }
  190747. }
  190748. #endif
  190749. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190750. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190751. {
  190752. if (
  190753. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190754. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  190755. #endif
  190756. #if defined(PNG_READ_FILLER_SUPPORTED)
  190757. (png_ptr->transformations & (PNG_FILLER)) ||
  190758. #endif
  190759. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  190760. {
  190761. if (max_pixel_depth <= 16)
  190762. max_pixel_depth = 32;
  190763. else
  190764. max_pixel_depth = 64;
  190765. }
  190766. else
  190767. {
  190768. if (max_pixel_depth <= 8)
  190769. {
  190770. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190771. max_pixel_depth = 32;
  190772. else
  190773. max_pixel_depth = 24;
  190774. }
  190775. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190776. max_pixel_depth = 64;
  190777. else
  190778. max_pixel_depth = 48;
  190779. }
  190780. }
  190781. #endif
  190782. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  190783. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  190784. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  190785. {
  190786. int user_pixel_depth=png_ptr->user_transform_depth*
  190787. png_ptr->user_transform_channels;
  190788. if(user_pixel_depth > max_pixel_depth)
  190789. max_pixel_depth=user_pixel_depth;
  190790. }
  190791. #endif
  190792. /* align the width on the next larger 8 pixels. Mainly used
  190793. for interlacing */
  190794. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  190795. /* calculate the maximum bytes needed, adding a byte and a pixel
  190796. for safety's sake */
  190797. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  190798. 1 + ((max_pixel_depth + 7) >> 3);
  190799. #ifdef PNG_MAX_MALLOC_64K
  190800. if (row_bytes > (png_uint_32)65536L)
  190801. png_error(png_ptr, "This image requires a row greater than 64KB");
  190802. #endif
  190803. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  190804. png_ptr->row_buf = png_ptr->big_row_buf+32;
  190805. #ifdef PNG_MAX_MALLOC_64K
  190806. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  190807. png_error(png_ptr, "This image requires a row greater than 64KB");
  190808. #endif
  190809. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  190810. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  190811. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  190812. png_ptr->rowbytes + 1));
  190813. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  190814. png_debug1(3, "width = %lu,\n", png_ptr->width);
  190815. png_debug1(3, "height = %lu,\n", png_ptr->height);
  190816. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  190817. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  190818. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  190819. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  190820. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  190821. }
  190822. #endif /* PNG_READ_SUPPORTED */
  190823. /********* End of inlined file: pngrutil.c *********/
  190824. /********* Start of inlined file: pngset.c *********/
  190825. /* pngset.c - storage of image information into info struct
  190826. *
  190827. * Last changed in libpng 1.2.21 [October 4, 2007]
  190828. * For conditions of distribution and use, see copyright notice in png.h
  190829. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190830. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190831. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190832. *
  190833. * The functions here are used during reads to store data from the file
  190834. * into the info struct, and during writes to store application data
  190835. * into the info struct for writing into the file. This abstracts the
  190836. * info struct and allows us to change the structure in the future.
  190837. */
  190838. #define PNG_INTERNAL
  190839. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  190840. #if defined(PNG_bKGD_SUPPORTED)
  190841. void PNGAPI
  190842. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  190843. {
  190844. png_debug1(1, "in %s storage function\n", "bKGD");
  190845. if (png_ptr == NULL || info_ptr == NULL)
  190846. return;
  190847. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  190848. info_ptr->valid |= PNG_INFO_bKGD;
  190849. }
  190850. #endif
  190851. #if defined(PNG_cHRM_SUPPORTED)
  190852. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190853. void PNGAPI
  190854. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  190855. double white_x, double white_y, double red_x, double red_y,
  190856. double green_x, double green_y, double blue_x, double blue_y)
  190857. {
  190858. png_debug1(1, "in %s storage function\n", "cHRM");
  190859. if (png_ptr == NULL || info_ptr == NULL)
  190860. return;
  190861. if (white_x < 0.0 || white_y < 0.0 ||
  190862. red_x < 0.0 || red_y < 0.0 ||
  190863. green_x < 0.0 || green_y < 0.0 ||
  190864. blue_x < 0.0 || blue_y < 0.0)
  190865. {
  190866. png_warning(png_ptr,
  190867. "Ignoring attempt to set negative chromaticity value");
  190868. return;
  190869. }
  190870. if (white_x > 21474.83 || white_y > 21474.83 ||
  190871. red_x > 21474.83 || red_y > 21474.83 ||
  190872. green_x > 21474.83 || green_y > 21474.83 ||
  190873. blue_x > 21474.83 || blue_y > 21474.83)
  190874. {
  190875. png_warning(png_ptr,
  190876. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  190877. return;
  190878. }
  190879. info_ptr->x_white = (float)white_x;
  190880. info_ptr->y_white = (float)white_y;
  190881. info_ptr->x_red = (float)red_x;
  190882. info_ptr->y_red = (float)red_y;
  190883. info_ptr->x_green = (float)green_x;
  190884. info_ptr->y_green = (float)green_y;
  190885. info_ptr->x_blue = (float)blue_x;
  190886. info_ptr->y_blue = (float)blue_y;
  190887. #ifdef PNG_FIXED_POINT_SUPPORTED
  190888. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  190889. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  190890. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  190891. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  190892. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  190893. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  190894. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  190895. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  190896. #endif
  190897. info_ptr->valid |= PNG_INFO_cHRM;
  190898. }
  190899. #endif
  190900. #ifdef PNG_FIXED_POINT_SUPPORTED
  190901. void PNGAPI
  190902. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  190903. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  190904. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  190905. png_fixed_point blue_x, png_fixed_point blue_y)
  190906. {
  190907. png_debug1(1, "in %s storage function\n", "cHRM");
  190908. if (png_ptr == NULL || info_ptr == NULL)
  190909. return;
  190910. if (white_x < 0 || white_y < 0 ||
  190911. red_x < 0 || red_y < 0 ||
  190912. green_x < 0 || green_y < 0 ||
  190913. blue_x < 0 || blue_y < 0)
  190914. {
  190915. png_warning(png_ptr,
  190916. "Ignoring attempt to set negative chromaticity value");
  190917. return;
  190918. }
  190919. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190920. if (white_x > (double) PNG_UINT_31_MAX ||
  190921. white_y > (double) PNG_UINT_31_MAX ||
  190922. red_x > (double) PNG_UINT_31_MAX ||
  190923. red_y > (double) PNG_UINT_31_MAX ||
  190924. green_x > (double) PNG_UINT_31_MAX ||
  190925. green_y > (double) PNG_UINT_31_MAX ||
  190926. blue_x > (double) PNG_UINT_31_MAX ||
  190927. blue_y > (double) PNG_UINT_31_MAX)
  190928. #else
  190929. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190930. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190931. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190932. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190933. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190934. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190935. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190936. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  190937. #endif
  190938. {
  190939. png_warning(png_ptr,
  190940. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  190941. return;
  190942. }
  190943. info_ptr->int_x_white = white_x;
  190944. info_ptr->int_y_white = white_y;
  190945. info_ptr->int_x_red = red_x;
  190946. info_ptr->int_y_red = red_y;
  190947. info_ptr->int_x_green = green_x;
  190948. info_ptr->int_y_green = green_y;
  190949. info_ptr->int_x_blue = blue_x;
  190950. info_ptr->int_y_blue = blue_y;
  190951. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190952. info_ptr->x_white = (float)(white_x/100000.);
  190953. info_ptr->y_white = (float)(white_y/100000.);
  190954. info_ptr->x_red = (float)( red_x/100000.);
  190955. info_ptr->y_red = (float)( red_y/100000.);
  190956. info_ptr->x_green = (float)(green_x/100000.);
  190957. info_ptr->y_green = (float)(green_y/100000.);
  190958. info_ptr->x_blue = (float)( blue_x/100000.);
  190959. info_ptr->y_blue = (float)( blue_y/100000.);
  190960. #endif
  190961. info_ptr->valid |= PNG_INFO_cHRM;
  190962. }
  190963. #endif
  190964. #endif
  190965. #if defined(PNG_gAMA_SUPPORTED)
  190966. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190967. void PNGAPI
  190968. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  190969. {
  190970. double gamma;
  190971. png_debug1(1, "in %s storage function\n", "gAMA");
  190972. if (png_ptr == NULL || info_ptr == NULL)
  190973. return;
  190974. /* Check for overflow */
  190975. if (file_gamma > 21474.83)
  190976. {
  190977. png_warning(png_ptr, "Limiting gamma to 21474.83");
  190978. gamma=21474.83;
  190979. }
  190980. else
  190981. gamma=file_gamma;
  190982. info_ptr->gamma = (float)gamma;
  190983. #ifdef PNG_FIXED_POINT_SUPPORTED
  190984. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  190985. #endif
  190986. info_ptr->valid |= PNG_INFO_gAMA;
  190987. if(gamma == 0.0)
  190988. png_warning(png_ptr, "Setting gamma=0");
  190989. }
  190990. #endif
  190991. void PNGAPI
  190992. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  190993. int_gamma)
  190994. {
  190995. png_fixed_point gamma;
  190996. png_debug1(1, "in %s storage function\n", "gAMA");
  190997. if (png_ptr == NULL || info_ptr == NULL)
  190998. return;
  190999. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  191000. {
  191001. png_warning(png_ptr, "Limiting gamma to 21474.83");
  191002. gamma=PNG_UINT_31_MAX;
  191003. }
  191004. else
  191005. {
  191006. if (int_gamma < 0)
  191007. {
  191008. png_warning(png_ptr, "Setting negative gamma to zero");
  191009. gamma=0;
  191010. }
  191011. else
  191012. gamma=int_gamma;
  191013. }
  191014. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191015. info_ptr->gamma = (float)(gamma/100000.);
  191016. #endif
  191017. #ifdef PNG_FIXED_POINT_SUPPORTED
  191018. info_ptr->int_gamma = gamma;
  191019. #endif
  191020. info_ptr->valid |= PNG_INFO_gAMA;
  191021. if(gamma == 0)
  191022. png_warning(png_ptr, "Setting gamma=0");
  191023. }
  191024. #endif
  191025. #if defined(PNG_hIST_SUPPORTED)
  191026. void PNGAPI
  191027. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  191028. {
  191029. int i;
  191030. png_debug1(1, "in %s storage function\n", "hIST");
  191031. if (png_ptr == NULL || info_ptr == NULL)
  191032. return;
  191033. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  191034. > PNG_MAX_PALETTE_LENGTH)
  191035. {
  191036. png_warning(png_ptr,
  191037. "Invalid palette size, hIST allocation skipped.");
  191038. return;
  191039. }
  191040. #ifdef PNG_FREE_ME_SUPPORTED
  191041. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  191042. #endif
  191043. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  191044. 1.2.1 */
  191045. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  191046. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  191047. if (png_ptr->hist == NULL)
  191048. {
  191049. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  191050. return;
  191051. }
  191052. for (i = 0; i < info_ptr->num_palette; i++)
  191053. png_ptr->hist[i] = hist[i];
  191054. info_ptr->hist = png_ptr->hist;
  191055. info_ptr->valid |= PNG_INFO_hIST;
  191056. #ifdef PNG_FREE_ME_SUPPORTED
  191057. info_ptr->free_me |= PNG_FREE_HIST;
  191058. #else
  191059. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  191060. #endif
  191061. }
  191062. #endif
  191063. void PNGAPI
  191064. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  191065. png_uint_32 width, png_uint_32 height, int bit_depth,
  191066. int color_type, int interlace_type, int compression_type,
  191067. int filter_type)
  191068. {
  191069. png_debug1(1, "in %s storage function\n", "IHDR");
  191070. if (png_ptr == NULL || info_ptr == NULL)
  191071. return;
  191072. /* check for width and height valid values */
  191073. if (width == 0 || height == 0)
  191074. png_error(png_ptr, "Image width or height is zero in IHDR");
  191075. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  191076. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  191077. png_error(png_ptr, "image size exceeds user limits in IHDR");
  191078. #else
  191079. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  191080. png_error(png_ptr, "image size exceeds user limits in IHDR");
  191081. #endif
  191082. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  191083. png_error(png_ptr, "Invalid image size in IHDR");
  191084. if ( width > (PNG_UINT_32_MAX
  191085. >> 3) /* 8-byte RGBA pixels */
  191086. - 64 /* bigrowbuf hack */
  191087. - 1 /* filter byte */
  191088. - 7*8 /* rounding of width to multiple of 8 pixels */
  191089. - 8) /* extra max_pixel_depth pad */
  191090. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  191091. /* check other values */
  191092. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  191093. bit_depth != 8 && bit_depth != 16)
  191094. png_error(png_ptr, "Invalid bit depth in IHDR");
  191095. if (color_type < 0 || color_type == 1 ||
  191096. color_type == 5 || color_type > 6)
  191097. png_error(png_ptr, "Invalid color type in IHDR");
  191098. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  191099. ((color_type == PNG_COLOR_TYPE_RGB ||
  191100. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  191101. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  191102. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  191103. if (interlace_type >= PNG_INTERLACE_LAST)
  191104. png_error(png_ptr, "Unknown interlace method in IHDR");
  191105. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  191106. png_error(png_ptr, "Unknown compression method in IHDR");
  191107. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  191108. /* Accept filter_method 64 (intrapixel differencing) only if
  191109. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  191110. * 2. Libpng did not read a PNG signature (this filter_method is only
  191111. * used in PNG datastreams that are embedded in MNG datastreams) and
  191112. * 3. The application called png_permit_mng_features with a mask that
  191113. * included PNG_FLAG_MNG_FILTER_64 and
  191114. * 4. The filter_method is 64 and
  191115. * 5. The color_type is RGB or RGBA
  191116. */
  191117. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  191118. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  191119. if(filter_type != PNG_FILTER_TYPE_BASE)
  191120. {
  191121. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  191122. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  191123. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  191124. (color_type == PNG_COLOR_TYPE_RGB ||
  191125. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  191126. png_error(png_ptr, "Unknown filter method in IHDR");
  191127. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  191128. png_warning(png_ptr, "Invalid filter method in IHDR");
  191129. }
  191130. #else
  191131. if(filter_type != PNG_FILTER_TYPE_BASE)
  191132. png_error(png_ptr, "Unknown filter method in IHDR");
  191133. #endif
  191134. info_ptr->width = width;
  191135. info_ptr->height = height;
  191136. info_ptr->bit_depth = (png_byte)bit_depth;
  191137. info_ptr->color_type =(png_byte) color_type;
  191138. info_ptr->compression_type = (png_byte)compression_type;
  191139. info_ptr->filter_type = (png_byte)filter_type;
  191140. info_ptr->interlace_type = (png_byte)interlace_type;
  191141. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191142. info_ptr->channels = 1;
  191143. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191144. info_ptr->channels = 3;
  191145. else
  191146. info_ptr->channels = 1;
  191147. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191148. info_ptr->channels++;
  191149. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  191150. /* check for potential overflow */
  191151. if (width > (PNG_UINT_32_MAX
  191152. >> 3) /* 8-byte RGBA pixels */
  191153. - 64 /* bigrowbuf hack */
  191154. - 1 /* filter byte */
  191155. - 7*8 /* rounding of width to multiple of 8 pixels */
  191156. - 8) /* extra max_pixel_depth pad */
  191157. info_ptr->rowbytes = (png_size_t)0;
  191158. else
  191159. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  191160. }
  191161. #if defined(PNG_oFFs_SUPPORTED)
  191162. void PNGAPI
  191163. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  191164. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  191165. {
  191166. png_debug1(1, "in %s storage function\n", "oFFs");
  191167. if (png_ptr == NULL || info_ptr == NULL)
  191168. return;
  191169. info_ptr->x_offset = offset_x;
  191170. info_ptr->y_offset = offset_y;
  191171. info_ptr->offset_unit_type = (png_byte)unit_type;
  191172. info_ptr->valid |= PNG_INFO_oFFs;
  191173. }
  191174. #endif
  191175. #if defined(PNG_pCAL_SUPPORTED)
  191176. void PNGAPI
  191177. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  191178. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  191179. png_charp units, png_charpp params)
  191180. {
  191181. png_uint_32 length;
  191182. int i;
  191183. png_debug1(1, "in %s storage function\n", "pCAL");
  191184. if (png_ptr == NULL || info_ptr == NULL)
  191185. return;
  191186. length = png_strlen(purpose) + 1;
  191187. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  191188. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  191189. if (info_ptr->pcal_purpose == NULL)
  191190. {
  191191. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  191192. return;
  191193. }
  191194. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  191195. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  191196. info_ptr->pcal_X0 = X0;
  191197. info_ptr->pcal_X1 = X1;
  191198. info_ptr->pcal_type = (png_byte)type;
  191199. info_ptr->pcal_nparams = (png_byte)nparams;
  191200. length = png_strlen(units) + 1;
  191201. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  191202. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  191203. if (info_ptr->pcal_units == NULL)
  191204. {
  191205. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  191206. return;
  191207. }
  191208. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  191209. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  191210. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  191211. if (info_ptr->pcal_params == NULL)
  191212. {
  191213. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  191214. return;
  191215. }
  191216. info_ptr->pcal_params[nparams] = NULL;
  191217. for (i = 0; i < nparams; i++)
  191218. {
  191219. length = png_strlen(params[i]) + 1;
  191220. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  191221. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  191222. if (info_ptr->pcal_params[i] == NULL)
  191223. {
  191224. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  191225. return;
  191226. }
  191227. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  191228. }
  191229. info_ptr->valid |= PNG_INFO_pCAL;
  191230. #ifdef PNG_FREE_ME_SUPPORTED
  191231. info_ptr->free_me |= PNG_FREE_PCAL;
  191232. #endif
  191233. }
  191234. #endif
  191235. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  191236. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191237. void PNGAPI
  191238. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  191239. int unit, double width, double height)
  191240. {
  191241. png_debug1(1, "in %s storage function\n", "sCAL");
  191242. if (png_ptr == NULL || info_ptr == NULL)
  191243. return;
  191244. info_ptr->scal_unit = (png_byte)unit;
  191245. info_ptr->scal_pixel_width = width;
  191246. info_ptr->scal_pixel_height = height;
  191247. info_ptr->valid |= PNG_INFO_sCAL;
  191248. }
  191249. #else
  191250. #ifdef PNG_FIXED_POINT_SUPPORTED
  191251. void PNGAPI
  191252. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  191253. int unit, png_charp swidth, png_charp sheight)
  191254. {
  191255. png_uint_32 length;
  191256. png_debug1(1, "in %s storage function\n", "sCAL");
  191257. if (png_ptr == NULL || info_ptr == NULL)
  191258. return;
  191259. info_ptr->scal_unit = (png_byte)unit;
  191260. length = png_strlen(swidth) + 1;
  191261. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  191262. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  191263. if (info_ptr->scal_s_width == NULL)
  191264. {
  191265. png_warning(png_ptr,
  191266. "Memory allocation failed while processing sCAL.");
  191267. }
  191268. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  191269. length = png_strlen(sheight) + 1;
  191270. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  191271. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  191272. if (info_ptr->scal_s_height == NULL)
  191273. {
  191274. png_free (png_ptr, info_ptr->scal_s_width);
  191275. png_warning(png_ptr,
  191276. "Memory allocation failed while processing sCAL.");
  191277. }
  191278. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  191279. info_ptr->valid |= PNG_INFO_sCAL;
  191280. #ifdef PNG_FREE_ME_SUPPORTED
  191281. info_ptr->free_me |= PNG_FREE_SCAL;
  191282. #endif
  191283. }
  191284. #endif
  191285. #endif
  191286. #endif
  191287. #if defined(PNG_pHYs_SUPPORTED)
  191288. void PNGAPI
  191289. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  191290. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  191291. {
  191292. png_debug1(1, "in %s storage function\n", "pHYs");
  191293. if (png_ptr == NULL || info_ptr == NULL)
  191294. return;
  191295. info_ptr->x_pixels_per_unit = res_x;
  191296. info_ptr->y_pixels_per_unit = res_y;
  191297. info_ptr->phys_unit_type = (png_byte)unit_type;
  191298. info_ptr->valid |= PNG_INFO_pHYs;
  191299. }
  191300. #endif
  191301. void PNGAPI
  191302. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  191303. png_colorp palette, int num_palette)
  191304. {
  191305. png_debug1(1, "in %s storage function\n", "PLTE");
  191306. if (png_ptr == NULL || info_ptr == NULL)
  191307. return;
  191308. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  191309. {
  191310. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191311. png_error(png_ptr, "Invalid palette length");
  191312. else
  191313. {
  191314. png_warning(png_ptr, "Invalid palette length");
  191315. return;
  191316. }
  191317. }
  191318. /*
  191319. * It may not actually be necessary to set png_ptr->palette here;
  191320. * we do it for backward compatibility with the way the png_handle_tRNS
  191321. * function used to do the allocation.
  191322. */
  191323. #ifdef PNG_FREE_ME_SUPPORTED
  191324. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  191325. #endif
  191326. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  191327. of num_palette entries,
  191328. in case of an invalid PNG file that has too-large sample values. */
  191329. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  191330. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  191331. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  191332. png_sizeof(png_color));
  191333. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  191334. info_ptr->palette = png_ptr->palette;
  191335. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  191336. #ifdef PNG_FREE_ME_SUPPORTED
  191337. info_ptr->free_me |= PNG_FREE_PLTE;
  191338. #else
  191339. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  191340. #endif
  191341. info_ptr->valid |= PNG_INFO_PLTE;
  191342. }
  191343. #if defined(PNG_sBIT_SUPPORTED)
  191344. void PNGAPI
  191345. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  191346. png_color_8p sig_bit)
  191347. {
  191348. png_debug1(1, "in %s storage function\n", "sBIT");
  191349. if (png_ptr == NULL || info_ptr == NULL)
  191350. return;
  191351. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  191352. info_ptr->valid |= PNG_INFO_sBIT;
  191353. }
  191354. #endif
  191355. #if defined(PNG_sRGB_SUPPORTED)
  191356. void PNGAPI
  191357. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  191358. {
  191359. png_debug1(1, "in %s storage function\n", "sRGB");
  191360. if (png_ptr == NULL || info_ptr == NULL)
  191361. return;
  191362. info_ptr->srgb_intent = (png_byte)intent;
  191363. info_ptr->valid |= PNG_INFO_sRGB;
  191364. }
  191365. void PNGAPI
  191366. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  191367. int intent)
  191368. {
  191369. #if defined(PNG_gAMA_SUPPORTED)
  191370. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191371. float file_gamma;
  191372. #endif
  191373. #ifdef PNG_FIXED_POINT_SUPPORTED
  191374. png_fixed_point int_file_gamma;
  191375. #endif
  191376. #endif
  191377. #if defined(PNG_cHRM_SUPPORTED)
  191378. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191379. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  191380. #endif
  191381. #ifdef PNG_FIXED_POINT_SUPPORTED
  191382. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  191383. int_green_y, int_blue_x, int_blue_y;
  191384. #endif
  191385. #endif
  191386. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  191387. if (png_ptr == NULL || info_ptr == NULL)
  191388. return;
  191389. png_set_sRGB(png_ptr, info_ptr, intent);
  191390. #if defined(PNG_gAMA_SUPPORTED)
  191391. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191392. file_gamma = (float).45455;
  191393. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  191394. #endif
  191395. #ifdef PNG_FIXED_POINT_SUPPORTED
  191396. int_file_gamma = 45455L;
  191397. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  191398. #endif
  191399. #endif
  191400. #if defined(PNG_cHRM_SUPPORTED)
  191401. #ifdef PNG_FIXED_POINT_SUPPORTED
  191402. int_white_x = 31270L;
  191403. int_white_y = 32900L;
  191404. int_red_x = 64000L;
  191405. int_red_y = 33000L;
  191406. int_green_x = 30000L;
  191407. int_green_y = 60000L;
  191408. int_blue_x = 15000L;
  191409. int_blue_y = 6000L;
  191410. png_set_cHRM_fixed(png_ptr, info_ptr,
  191411. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  191412. int_blue_x, int_blue_y);
  191413. #endif
  191414. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191415. white_x = (float).3127;
  191416. white_y = (float).3290;
  191417. red_x = (float).64;
  191418. red_y = (float).33;
  191419. green_x = (float).30;
  191420. green_y = (float).60;
  191421. blue_x = (float).15;
  191422. blue_y = (float).06;
  191423. png_set_cHRM(png_ptr, info_ptr,
  191424. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  191425. #endif
  191426. #endif
  191427. }
  191428. #endif
  191429. #if defined(PNG_iCCP_SUPPORTED)
  191430. void PNGAPI
  191431. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  191432. png_charp name, int compression_type,
  191433. png_charp profile, png_uint_32 proflen)
  191434. {
  191435. png_charp new_iccp_name;
  191436. png_charp new_iccp_profile;
  191437. png_debug1(1, "in %s storage function\n", "iCCP");
  191438. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  191439. return;
  191440. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  191441. if (new_iccp_name == NULL)
  191442. {
  191443. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  191444. return;
  191445. }
  191446. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  191447. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  191448. if (new_iccp_profile == NULL)
  191449. {
  191450. png_free (png_ptr, new_iccp_name);
  191451. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  191452. return;
  191453. }
  191454. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  191455. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  191456. info_ptr->iccp_proflen = proflen;
  191457. info_ptr->iccp_name = new_iccp_name;
  191458. info_ptr->iccp_profile = new_iccp_profile;
  191459. /* Compression is always zero but is here so the API and info structure
  191460. * does not have to change if we introduce multiple compression types */
  191461. info_ptr->iccp_compression = (png_byte)compression_type;
  191462. #ifdef PNG_FREE_ME_SUPPORTED
  191463. info_ptr->free_me |= PNG_FREE_ICCP;
  191464. #endif
  191465. info_ptr->valid |= PNG_INFO_iCCP;
  191466. }
  191467. #endif
  191468. #if defined(PNG_TEXT_SUPPORTED)
  191469. void PNGAPI
  191470. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  191471. int num_text)
  191472. {
  191473. int ret;
  191474. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  191475. if (ret)
  191476. png_error(png_ptr, "Insufficient memory to store text");
  191477. }
  191478. int /* PRIVATE */
  191479. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  191480. int num_text)
  191481. {
  191482. int i;
  191483. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  191484. "text" : (png_const_charp)png_ptr->chunk_name));
  191485. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  191486. return(0);
  191487. /* Make sure we have enough space in the "text" array in info_struct
  191488. * to hold all of the incoming text_ptr objects.
  191489. */
  191490. if (info_ptr->num_text + num_text > info_ptr->max_text)
  191491. {
  191492. if (info_ptr->text != NULL)
  191493. {
  191494. png_textp old_text;
  191495. int old_max;
  191496. old_max = info_ptr->max_text;
  191497. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  191498. old_text = info_ptr->text;
  191499. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  191500. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  191501. if (info_ptr->text == NULL)
  191502. {
  191503. png_free(png_ptr, old_text);
  191504. return(1);
  191505. }
  191506. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  191507. png_sizeof(png_text)));
  191508. png_free(png_ptr, old_text);
  191509. }
  191510. else
  191511. {
  191512. info_ptr->max_text = num_text + 8;
  191513. info_ptr->num_text = 0;
  191514. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  191515. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  191516. if (info_ptr->text == NULL)
  191517. return(1);
  191518. #ifdef PNG_FREE_ME_SUPPORTED
  191519. info_ptr->free_me |= PNG_FREE_TEXT;
  191520. #endif
  191521. }
  191522. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  191523. info_ptr->max_text);
  191524. }
  191525. for (i = 0; i < num_text; i++)
  191526. {
  191527. png_size_t text_length,key_len;
  191528. png_size_t lang_len,lang_key_len;
  191529. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  191530. if (text_ptr[i].key == NULL)
  191531. continue;
  191532. key_len = png_strlen(text_ptr[i].key);
  191533. if(text_ptr[i].compression <= 0)
  191534. {
  191535. lang_len = 0;
  191536. lang_key_len = 0;
  191537. }
  191538. else
  191539. #ifdef PNG_iTXt_SUPPORTED
  191540. {
  191541. /* set iTXt data */
  191542. if (text_ptr[i].lang != NULL)
  191543. lang_len = png_strlen(text_ptr[i].lang);
  191544. else
  191545. lang_len = 0;
  191546. if (text_ptr[i].lang_key != NULL)
  191547. lang_key_len = png_strlen(text_ptr[i].lang_key);
  191548. else
  191549. lang_key_len = 0;
  191550. }
  191551. #else
  191552. {
  191553. png_warning(png_ptr, "iTXt chunk not supported.");
  191554. continue;
  191555. }
  191556. #endif
  191557. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  191558. {
  191559. text_length = 0;
  191560. #ifdef PNG_iTXt_SUPPORTED
  191561. if(text_ptr[i].compression > 0)
  191562. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  191563. else
  191564. #endif
  191565. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  191566. }
  191567. else
  191568. {
  191569. text_length = png_strlen(text_ptr[i].text);
  191570. textp->compression = text_ptr[i].compression;
  191571. }
  191572. textp->key = (png_charp)png_malloc_warn(png_ptr,
  191573. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  191574. if (textp->key == NULL)
  191575. return(1);
  191576. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  191577. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  191578. (int)textp->key);
  191579. png_memcpy(textp->key, text_ptr[i].key,
  191580. (png_size_t)(key_len));
  191581. *(textp->key+key_len) = '\0';
  191582. #ifdef PNG_iTXt_SUPPORTED
  191583. if (text_ptr[i].compression > 0)
  191584. {
  191585. textp->lang=textp->key + key_len + 1;
  191586. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  191587. *(textp->lang+lang_len) = '\0';
  191588. textp->lang_key=textp->lang + lang_len + 1;
  191589. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  191590. *(textp->lang_key+lang_key_len) = '\0';
  191591. textp->text=textp->lang_key + lang_key_len + 1;
  191592. }
  191593. else
  191594. #endif
  191595. {
  191596. #ifdef PNG_iTXt_SUPPORTED
  191597. textp->lang=NULL;
  191598. textp->lang_key=NULL;
  191599. #endif
  191600. textp->text=textp->key + key_len + 1;
  191601. }
  191602. if(text_length)
  191603. png_memcpy(textp->text, text_ptr[i].text,
  191604. (png_size_t)(text_length));
  191605. *(textp->text+text_length) = '\0';
  191606. #ifdef PNG_iTXt_SUPPORTED
  191607. if(textp->compression > 0)
  191608. {
  191609. textp->text_length = 0;
  191610. textp->itxt_length = text_length;
  191611. }
  191612. else
  191613. #endif
  191614. {
  191615. textp->text_length = text_length;
  191616. #ifdef PNG_iTXt_SUPPORTED
  191617. textp->itxt_length = 0;
  191618. #endif
  191619. }
  191620. info_ptr->num_text++;
  191621. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  191622. }
  191623. return(0);
  191624. }
  191625. #endif
  191626. #if defined(PNG_tIME_SUPPORTED)
  191627. void PNGAPI
  191628. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  191629. {
  191630. png_debug1(1, "in %s storage function\n", "tIME");
  191631. if (png_ptr == NULL || info_ptr == NULL ||
  191632. (png_ptr->mode & PNG_WROTE_tIME))
  191633. return;
  191634. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  191635. info_ptr->valid |= PNG_INFO_tIME;
  191636. }
  191637. #endif
  191638. #if defined(PNG_tRNS_SUPPORTED)
  191639. void PNGAPI
  191640. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  191641. png_bytep trans, int num_trans, png_color_16p trans_values)
  191642. {
  191643. png_debug1(1, "in %s storage function\n", "tRNS");
  191644. if (png_ptr == NULL || info_ptr == NULL)
  191645. return;
  191646. if (trans != NULL)
  191647. {
  191648. /*
  191649. * It may not actually be necessary to set png_ptr->trans here;
  191650. * we do it for backward compatibility with the way the png_handle_tRNS
  191651. * function used to do the allocation.
  191652. */
  191653. #ifdef PNG_FREE_ME_SUPPORTED
  191654. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  191655. #endif
  191656. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  191657. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  191658. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  191659. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  191660. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  191661. #ifdef PNG_FREE_ME_SUPPORTED
  191662. info_ptr->free_me |= PNG_FREE_TRNS;
  191663. #else
  191664. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  191665. #endif
  191666. }
  191667. if (trans_values != NULL)
  191668. {
  191669. png_memcpy(&(info_ptr->trans_values), trans_values,
  191670. png_sizeof(png_color_16));
  191671. if (num_trans == 0)
  191672. num_trans = 1;
  191673. }
  191674. info_ptr->num_trans = (png_uint_16)num_trans;
  191675. info_ptr->valid |= PNG_INFO_tRNS;
  191676. }
  191677. #endif
  191678. #if defined(PNG_sPLT_SUPPORTED)
  191679. void PNGAPI
  191680. png_set_sPLT(png_structp png_ptr,
  191681. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  191682. {
  191683. png_sPLT_tp np;
  191684. int i;
  191685. if (png_ptr == NULL || info_ptr == NULL)
  191686. return;
  191687. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  191688. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  191689. if (np == NULL)
  191690. {
  191691. png_warning(png_ptr, "No memory for sPLT palettes.");
  191692. return;
  191693. }
  191694. png_memcpy(np, info_ptr->splt_palettes,
  191695. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  191696. png_free(png_ptr, info_ptr->splt_palettes);
  191697. info_ptr->splt_palettes=NULL;
  191698. for (i = 0; i < nentries; i++)
  191699. {
  191700. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  191701. png_sPLT_tp from = entries + i;
  191702. to->name = (png_charp)png_malloc_warn(png_ptr,
  191703. png_strlen(from->name) + 1);
  191704. if (to->name == NULL)
  191705. {
  191706. png_warning(png_ptr,
  191707. "Out of memory while processing sPLT chunk");
  191708. }
  191709. /* TODO: use png_malloc_warn */
  191710. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  191711. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  191712. from->nentries * png_sizeof(png_sPLT_entry));
  191713. /* TODO: use png_malloc_warn */
  191714. png_memcpy(to->entries, from->entries,
  191715. from->nentries * png_sizeof(png_sPLT_entry));
  191716. if (to->entries == NULL)
  191717. {
  191718. png_warning(png_ptr,
  191719. "Out of memory while processing sPLT chunk");
  191720. png_free(png_ptr,to->name);
  191721. to->name = NULL;
  191722. }
  191723. to->nentries = from->nentries;
  191724. to->depth = from->depth;
  191725. }
  191726. info_ptr->splt_palettes = np;
  191727. info_ptr->splt_palettes_num += nentries;
  191728. info_ptr->valid |= PNG_INFO_sPLT;
  191729. #ifdef PNG_FREE_ME_SUPPORTED
  191730. info_ptr->free_me |= PNG_FREE_SPLT;
  191731. #endif
  191732. }
  191733. #endif /* PNG_sPLT_SUPPORTED */
  191734. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  191735. void PNGAPI
  191736. png_set_unknown_chunks(png_structp png_ptr,
  191737. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  191738. {
  191739. png_unknown_chunkp np;
  191740. int i;
  191741. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  191742. return;
  191743. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  191744. (info_ptr->unknown_chunks_num + num_unknowns) *
  191745. png_sizeof(png_unknown_chunk));
  191746. if (np == NULL)
  191747. {
  191748. png_warning(png_ptr,
  191749. "Out of memory while processing unknown chunk.");
  191750. return;
  191751. }
  191752. png_memcpy(np, info_ptr->unknown_chunks,
  191753. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  191754. png_free(png_ptr, info_ptr->unknown_chunks);
  191755. info_ptr->unknown_chunks=NULL;
  191756. for (i = 0; i < num_unknowns; i++)
  191757. {
  191758. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  191759. png_unknown_chunkp from = unknowns + i;
  191760. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  191761. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  191762. if (to->data == NULL)
  191763. {
  191764. png_warning(png_ptr,
  191765. "Out of memory while processing unknown chunk.");
  191766. }
  191767. else
  191768. {
  191769. png_memcpy(to->data, from->data, from->size);
  191770. to->size = from->size;
  191771. /* note our location in the read or write sequence */
  191772. to->location = (png_byte)(png_ptr->mode & 0xff);
  191773. }
  191774. }
  191775. info_ptr->unknown_chunks = np;
  191776. info_ptr->unknown_chunks_num += num_unknowns;
  191777. #ifdef PNG_FREE_ME_SUPPORTED
  191778. info_ptr->free_me |= PNG_FREE_UNKN;
  191779. #endif
  191780. }
  191781. void PNGAPI
  191782. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  191783. int chunk, int location)
  191784. {
  191785. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  191786. (int)info_ptr->unknown_chunks_num)
  191787. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  191788. }
  191789. #endif
  191790. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  191791. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  191792. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  191793. void PNGAPI
  191794. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  191795. {
  191796. /* This function is deprecated in favor of png_permit_mng_features()
  191797. and will be removed from libpng-1.3.0 */
  191798. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  191799. if (png_ptr == NULL)
  191800. return;
  191801. png_ptr->mng_features_permitted = (png_byte)
  191802. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  191803. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  191804. }
  191805. #endif
  191806. #endif
  191807. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  191808. png_uint_32 PNGAPI
  191809. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  191810. {
  191811. png_debug(1, "in png_permit_mng_features\n");
  191812. if (png_ptr == NULL)
  191813. return (png_uint_32)0;
  191814. png_ptr->mng_features_permitted =
  191815. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  191816. return (png_uint_32)png_ptr->mng_features_permitted;
  191817. }
  191818. #endif
  191819. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  191820. void PNGAPI
  191821. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  191822. chunk_list, int num_chunks)
  191823. {
  191824. png_bytep new_list, p;
  191825. int i, old_num_chunks;
  191826. if (png_ptr == NULL)
  191827. return;
  191828. if (num_chunks == 0)
  191829. {
  191830. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  191831. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  191832. else
  191833. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  191834. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  191835. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  191836. else
  191837. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  191838. return;
  191839. }
  191840. if (chunk_list == NULL)
  191841. return;
  191842. old_num_chunks=png_ptr->num_chunk_list;
  191843. new_list=(png_bytep)png_malloc(png_ptr,
  191844. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  191845. if(png_ptr->chunk_list != NULL)
  191846. {
  191847. png_memcpy(new_list, png_ptr->chunk_list,
  191848. (png_size_t)(5*old_num_chunks));
  191849. png_free(png_ptr, png_ptr->chunk_list);
  191850. png_ptr->chunk_list=NULL;
  191851. }
  191852. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  191853. (png_size_t)(5*num_chunks));
  191854. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  191855. *p=(png_byte)keep;
  191856. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  191857. png_ptr->chunk_list=new_list;
  191858. #ifdef PNG_FREE_ME_SUPPORTED
  191859. png_ptr->free_me |= PNG_FREE_LIST;
  191860. #endif
  191861. }
  191862. #endif
  191863. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191864. void PNGAPI
  191865. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  191866. png_user_chunk_ptr read_user_chunk_fn)
  191867. {
  191868. png_debug(1, "in png_set_read_user_chunk_fn\n");
  191869. if (png_ptr == NULL)
  191870. return;
  191871. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  191872. png_ptr->user_chunk_ptr = user_chunk_ptr;
  191873. }
  191874. #endif
  191875. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  191876. void PNGAPI
  191877. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  191878. {
  191879. png_debug1(1, "in %s storage function\n", "rows");
  191880. if (png_ptr == NULL || info_ptr == NULL)
  191881. return;
  191882. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  191883. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  191884. info_ptr->row_pointers = row_pointers;
  191885. if(row_pointers)
  191886. info_ptr->valid |= PNG_INFO_IDAT;
  191887. }
  191888. #endif
  191889. #ifdef PNG_WRITE_SUPPORTED
  191890. void PNGAPI
  191891. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  191892. {
  191893. if (png_ptr == NULL)
  191894. return;
  191895. if(png_ptr->zbuf)
  191896. png_free(png_ptr, png_ptr->zbuf);
  191897. png_ptr->zbuf_size = (png_size_t)size;
  191898. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  191899. png_ptr->zstream.next_out = png_ptr->zbuf;
  191900. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  191901. }
  191902. #endif
  191903. void PNGAPI
  191904. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  191905. {
  191906. if (png_ptr && info_ptr)
  191907. info_ptr->valid &= ~(mask);
  191908. }
  191909. #ifndef PNG_1_0_X
  191910. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  191911. /* function was added to libpng 1.2.0 and should always exist by default */
  191912. void PNGAPI
  191913. png_set_asm_flags (png_structp png_ptr, png_uint_32 asm_flags)
  191914. {
  191915. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  191916. if (png_ptr != NULL)
  191917. png_ptr->asm_flags = 0;
  191918. }
  191919. /* this function was added to libpng 1.2.0 */
  191920. void PNGAPI
  191921. png_set_mmx_thresholds (png_structp png_ptr,
  191922. png_byte mmx_bitdepth_threshold,
  191923. png_uint_32 mmx_rowbytes_threshold)
  191924. {
  191925. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  191926. if (png_ptr == NULL)
  191927. return;
  191928. }
  191929. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  191930. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  191931. /* this function was added to libpng 1.2.6 */
  191932. void PNGAPI
  191933. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  191934. png_uint_32 user_height_max)
  191935. {
  191936. /* Images with dimensions larger than these limits will be
  191937. * rejected by png_set_IHDR(). To accept any PNG datastream
  191938. * regardless of dimensions, set both limits to 0x7ffffffL.
  191939. */
  191940. if(png_ptr == NULL) return;
  191941. png_ptr->user_width_max = user_width_max;
  191942. png_ptr->user_height_max = user_height_max;
  191943. }
  191944. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  191945. #endif /* ?PNG_1_0_X */
  191946. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  191947. /********* End of inlined file: pngset.c *********/
  191948. /********* Start of inlined file: pngtrans.c *********/
  191949. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  191950. *
  191951. * Last changed in libpng 1.2.17 May 15, 2007
  191952. * For conditions of distribution and use, see copyright notice in png.h
  191953. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  191954. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  191955. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  191956. */
  191957. #define PNG_INTERNAL
  191958. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  191959. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  191960. /* turn on BGR-to-RGB mapping */
  191961. void PNGAPI
  191962. png_set_bgr(png_structp png_ptr)
  191963. {
  191964. png_debug(1, "in png_set_bgr\n");
  191965. if(png_ptr == NULL) return;
  191966. png_ptr->transformations |= PNG_BGR;
  191967. }
  191968. #endif
  191969. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  191970. /* turn on 16 bit byte swapping */
  191971. void PNGAPI
  191972. png_set_swap(png_structp png_ptr)
  191973. {
  191974. png_debug(1, "in png_set_swap\n");
  191975. if(png_ptr == NULL) return;
  191976. if (png_ptr->bit_depth == 16)
  191977. png_ptr->transformations |= PNG_SWAP_BYTES;
  191978. }
  191979. #endif
  191980. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  191981. /* turn on pixel packing */
  191982. void PNGAPI
  191983. png_set_packing(png_structp png_ptr)
  191984. {
  191985. png_debug(1, "in png_set_packing\n");
  191986. if(png_ptr == NULL) return;
  191987. if (png_ptr->bit_depth < 8)
  191988. {
  191989. png_ptr->transformations |= PNG_PACK;
  191990. png_ptr->usr_bit_depth = 8;
  191991. }
  191992. }
  191993. #endif
  191994. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  191995. /* turn on packed pixel swapping */
  191996. void PNGAPI
  191997. png_set_packswap(png_structp png_ptr)
  191998. {
  191999. png_debug(1, "in png_set_packswap\n");
  192000. if(png_ptr == NULL) return;
  192001. if (png_ptr->bit_depth < 8)
  192002. png_ptr->transformations |= PNG_PACKSWAP;
  192003. }
  192004. #endif
  192005. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  192006. void PNGAPI
  192007. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  192008. {
  192009. png_debug(1, "in png_set_shift\n");
  192010. if(png_ptr == NULL) return;
  192011. png_ptr->transformations |= PNG_SHIFT;
  192012. png_ptr->shift = *true_bits;
  192013. }
  192014. #endif
  192015. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  192016. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  192017. int PNGAPI
  192018. png_set_interlace_handling(png_structp png_ptr)
  192019. {
  192020. png_debug(1, "in png_set_interlace handling\n");
  192021. if (png_ptr && png_ptr->interlaced)
  192022. {
  192023. png_ptr->transformations |= PNG_INTERLACE;
  192024. return (7);
  192025. }
  192026. return (1);
  192027. }
  192028. #endif
  192029. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  192030. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  192031. * The filler type has changed in v0.95 to allow future 2-byte fillers
  192032. * for 48-bit input data, as well as to avoid problems with some compilers
  192033. * that don't like bytes as parameters.
  192034. */
  192035. void PNGAPI
  192036. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  192037. {
  192038. png_debug(1, "in png_set_filler\n");
  192039. if(png_ptr == NULL) return;
  192040. png_ptr->transformations |= PNG_FILLER;
  192041. png_ptr->filler = (png_byte)filler;
  192042. if (filler_loc == PNG_FILLER_AFTER)
  192043. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  192044. else
  192045. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  192046. /* This should probably go in the "do_read_filler" routine.
  192047. * I attempted to do that in libpng-1.0.1a but that caused problems
  192048. * so I restored it in libpng-1.0.2a
  192049. */
  192050. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  192051. {
  192052. png_ptr->usr_channels = 4;
  192053. }
  192054. /* Also I added this in libpng-1.0.2a (what happens when we expand
  192055. * a less-than-8-bit grayscale to GA? */
  192056. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  192057. {
  192058. png_ptr->usr_channels = 2;
  192059. }
  192060. }
  192061. #if !defined(PNG_1_0_X)
  192062. /* Added to libpng-1.2.7 */
  192063. void PNGAPI
  192064. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  192065. {
  192066. png_debug(1, "in png_set_add_alpha\n");
  192067. if(png_ptr == NULL) return;
  192068. png_set_filler(png_ptr, filler, filler_loc);
  192069. png_ptr->transformations |= PNG_ADD_ALPHA;
  192070. }
  192071. #endif
  192072. #endif
  192073. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  192074. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  192075. void PNGAPI
  192076. png_set_swap_alpha(png_structp png_ptr)
  192077. {
  192078. png_debug(1, "in png_set_swap_alpha\n");
  192079. if(png_ptr == NULL) return;
  192080. png_ptr->transformations |= PNG_SWAP_ALPHA;
  192081. }
  192082. #endif
  192083. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  192084. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  192085. void PNGAPI
  192086. png_set_invert_alpha(png_structp png_ptr)
  192087. {
  192088. png_debug(1, "in png_set_invert_alpha\n");
  192089. if(png_ptr == NULL) return;
  192090. png_ptr->transformations |= PNG_INVERT_ALPHA;
  192091. }
  192092. #endif
  192093. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  192094. void PNGAPI
  192095. png_set_invert_mono(png_structp png_ptr)
  192096. {
  192097. png_debug(1, "in png_set_invert_mono\n");
  192098. if(png_ptr == NULL) return;
  192099. png_ptr->transformations |= PNG_INVERT_MONO;
  192100. }
  192101. /* invert monochrome grayscale data */
  192102. void /* PRIVATE */
  192103. png_do_invert(png_row_infop row_info, png_bytep row)
  192104. {
  192105. png_debug(1, "in png_do_invert\n");
  192106. /* This test removed from libpng version 1.0.13 and 1.2.0:
  192107. * if (row_info->bit_depth == 1 &&
  192108. */
  192109. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192110. if (row == NULL || row_info == NULL)
  192111. return;
  192112. #endif
  192113. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192114. {
  192115. png_bytep rp = row;
  192116. png_uint_32 i;
  192117. png_uint_32 istop = row_info->rowbytes;
  192118. for (i = 0; i < istop; i++)
  192119. {
  192120. *rp = (png_byte)(~(*rp));
  192121. rp++;
  192122. }
  192123. }
  192124. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  192125. row_info->bit_depth == 8)
  192126. {
  192127. png_bytep rp = row;
  192128. png_uint_32 i;
  192129. png_uint_32 istop = row_info->rowbytes;
  192130. for (i = 0; i < istop; i+=2)
  192131. {
  192132. *rp = (png_byte)(~(*rp));
  192133. rp+=2;
  192134. }
  192135. }
  192136. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  192137. row_info->bit_depth == 16)
  192138. {
  192139. png_bytep rp = row;
  192140. png_uint_32 i;
  192141. png_uint_32 istop = row_info->rowbytes;
  192142. for (i = 0; i < istop; i+=4)
  192143. {
  192144. *rp = (png_byte)(~(*rp));
  192145. *(rp+1) = (png_byte)(~(*(rp+1)));
  192146. rp+=4;
  192147. }
  192148. }
  192149. }
  192150. #endif
  192151. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  192152. /* swaps byte order on 16 bit depth images */
  192153. void /* PRIVATE */
  192154. png_do_swap(png_row_infop row_info, png_bytep row)
  192155. {
  192156. png_debug(1, "in png_do_swap\n");
  192157. if (
  192158. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192159. row != NULL && row_info != NULL &&
  192160. #endif
  192161. row_info->bit_depth == 16)
  192162. {
  192163. png_bytep rp = row;
  192164. png_uint_32 i;
  192165. png_uint_32 istop= row_info->width * row_info->channels;
  192166. for (i = 0; i < istop; i++, rp += 2)
  192167. {
  192168. png_byte t = *rp;
  192169. *rp = *(rp + 1);
  192170. *(rp + 1) = t;
  192171. }
  192172. }
  192173. }
  192174. #endif
  192175. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  192176. static PNG_CONST png_byte onebppswaptable[256] = {
  192177. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  192178. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  192179. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  192180. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  192181. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  192182. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  192183. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  192184. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  192185. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  192186. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  192187. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  192188. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  192189. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  192190. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  192191. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  192192. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  192193. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  192194. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  192195. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  192196. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  192197. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  192198. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  192199. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  192200. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  192201. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  192202. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  192203. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  192204. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  192205. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  192206. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  192207. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  192208. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  192209. };
  192210. static PNG_CONST png_byte twobppswaptable[256] = {
  192211. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  192212. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  192213. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  192214. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  192215. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  192216. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  192217. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  192218. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  192219. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  192220. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  192221. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  192222. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  192223. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  192224. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  192225. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  192226. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  192227. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  192228. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  192229. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  192230. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  192231. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  192232. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  192233. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  192234. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  192235. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  192236. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  192237. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  192238. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  192239. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  192240. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  192241. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  192242. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  192243. };
  192244. static PNG_CONST png_byte fourbppswaptable[256] = {
  192245. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  192246. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  192247. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  192248. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  192249. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  192250. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  192251. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  192252. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  192253. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  192254. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  192255. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  192256. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  192257. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  192258. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  192259. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  192260. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  192261. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  192262. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  192263. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  192264. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  192265. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  192266. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  192267. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  192268. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  192269. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  192270. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  192271. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  192272. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  192273. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  192274. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  192275. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  192276. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  192277. };
  192278. /* swaps pixel packing order within bytes */
  192279. void /* PRIVATE */
  192280. png_do_packswap(png_row_infop row_info, png_bytep row)
  192281. {
  192282. png_debug(1, "in png_do_packswap\n");
  192283. if (
  192284. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192285. row != NULL && row_info != NULL &&
  192286. #endif
  192287. row_info->bit_depth < 8)
  192288. {
  192289. png_bytep rp, end, table;
  192290. end = row + row_info->rowbytes;
  192291. if (row_info->bit_depth == 1)
  192292. table = (png_bytep)onebppswaptable;
  192293. else if (row_info->bit_depth == 2)
  192294. table = (png_bytep)twobppswaptable;
  192295. else if (row_info->bit_depth == 4)
  192296. table = (png_bytep)fourbppswaptable;
  192297. else
  192298. return;
  192299. for (rp = row; rp < end; rp++)
  192300. *rp = table[*rp];
  192301. }
  192302. }
  192303. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  192304. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  192305. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  192306. /* remove filler or alpha byte(s) */
  192307. void /* PRIVATE */
  192308. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  192309. {
  192310. png_debug(1, "in png_do_strip_filler\n");
  192311. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192312. if (row != NULL && row_info != NULL)
  192313. #endif
  192314. {
  192315. png_bytep sp=row;
  192316. png_bytep dp=row;
  192317. png_uint_32 row_width=row_info->width;
  192318. png_uint_32 i;
  192319. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  192320. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  192321. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  192322. row_info->channels == 4)
  192323. {
  192324. if (row_info->bit_depth == 8)
  192325. {
  192326. /* This converts from RGBX or RGBA to RGB */
  192327. if (flags & PNG_FLAG_FILLER_AFTER)
  192328. {
  192329. dp+=3; sp+=4;
  192330. for (i = 1; i < row_width; i++)
  192331. {
  192332. *dp++ = *sp++;
  192333. *dp++ = *sp++;
  192334. *dp++ = *sp++;
  192335. sp++;
  192336. }
  192337. }
  192338. /* This converts from XRGB or ARGB to RGB */
  192339. else
  192340. {
  192341. for (i = 0; i < row_width; i++)
  192342. {
  192343. sp++;
  192344. *dp++ = *sp++;
  192345. *dp++ = *sp++;
  192346. *dp++ = *sp++;
  192347. }
  192348. }
  192349. row_info->pixel_depth = 24;
  192350. row_info->rowbytes = row_width * 3;
  192351. }
  192352. else /* if (row_info->bit_depth == 16) */
  192353. {
  192354. if (flags & PNG_FLAG_FILLER_AFTER)
  192355. {
  192356. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  192357. sp += 8; dp += 6;
  192358. for (i = 1; i < row_width; i++)
  192359. {
  192360. /* This could be (although png_memcpy is probably slower):
  192361. png_memcpy(dp, sp, 6);
  192362. sp += 8;
  192363. dp += 6;
  192364. */
  192365. *dp++ = *sp++;
  192366. *dp++ = *sp++;
  192367. *dp++ = *sp++;
  192368. *dp++ = *sp++;
  192369. *dp++ = *sp++;
  192370. *dp++ = *sp++;
  192371. sp += 2;
  192372. }
  192373. }
  192374. else
  192375. {
  192376. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  192377. for (i = 0; i < row_width; i++)
  192378. {
  192379. /* This could be (although png_memcpy is probably slower):
  192380. png_memcpy(dp, sp, 6);
  192381. sp += 8;
  192382. dp += 6;
  192383. */
  192384. sp+=2;
  192385. *dp++ = *sp++;
  192386. *dp++ = *sp++;
  192387. *dp++ = *sp++;
  192388. *dp++ = *sp++;
  192389. *dp++ = *sp++;
  192390. *dp++ = *sp++;
  192391. }
  192392. }
  192393. row_info->pixel_depth = 48;
  192394. row_info->rowbytes = row_width * 6;
  192395. }
  192396. row_info->channels = 3;
  192397. }
  192398. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  192399. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  192400. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  192401. row_info->channels == 2)
  192402. {
  192403. if (row_info->bit_depth == 8)
  192404. {
  192405. /* This converts from GX or GA to G */
  192406. if (flags & PNG_FLAG_FILLER_AFTER)
  192407. {
  192408. for (i = 0; i < row_width; i++)
  192409. {
  192410. *dp++ = *sp++;
  192411. sp++;
  192412. }
  192413. }
  192414. /* This converts from XG or AG to G */
  192415. else
  192416. {
  192417. for (i = 0; i < row_width; i++)
  192418. {
  192419. sp++;
  192420. *dp++ = *sp++;
  192421. }
  192422. }
  192423. row_info->pixel_depth = 8;
  192424. row_info->rowbytes = row_width;
  192425. }
  192426. else /* if (row_info->bit_depth == 16) */
  192427. {
  192428. if (flags & PNG_FLAG_FILLER_AFTER)
  192429. {
  192430. /* This converts from GGXX or GGAA to GG */
  192431. sp += 4; dp += 2;
  192432. for (i = 1; i < row_width; i++)
  192433. {
  192434. *dp++ = *sp++;
  192435. *dp++ = *sp++;
  192436. sp += 2;
  192437. }
  192438. }
  192439. else
  192440. {
  192441. /* This converts from XXGG or AAGG to GG */
  192442. for (i = 0; i < row_width; i++)
  192443. {
  192444. sp += 2;
  192445. *dp++ = *sp++;
  192446. *dp++ = *sp++;
  192447. }
  192448. }
  192449. row_info->pixel_depth = 16;
  192450. row_info->rowbytes = row_width * 2;
  192451. }
  192452. row_info->channels = 1;
  192453. }
  192454. if (flags & PNG_FLAG_STRIP_ALPHA)
  192455. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192456. }
  192457. }
  192458. #endif
  192459. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  192460. /* swaps red and blue bytes within a pixel */
  192461. void /* PRIVATE */
  192462. png_do_bgr(png_row_infop row_info, png_bytep row)
  192463. {
  192464. png_debug(1, "in png_do_bgr\n");
  192465. if (
  192466. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192467. row != NULL && row_info != NULL &&
  192468. #endif
  192469. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192470. {
  192471. png_uint_32 row_width = row_info->width;
  192472. if (row_info->bit_depth == 8)
  192473. {
  192474. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192475. {
  192476. png_bytep rp;
  192477. png_uint_32 i;
  192478. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  192479. {
  192480. png_byte save = *rp;
  192481. *rp = *(rp + 2);
  192482. *(rp + 2) = save;
  192483. }
  192484. }
  192485. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192486. {
  192487. png_bytep rp;
  192488. png_uint_32 i;
  192489. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  192490. {
  192491. png_byte save = *rp;
  192492. *rp = *(rp + 2);
  192493. *(rp + 2) = save;
  192494. }
  192495. }
  192496. }
  192497. else if (row_info->bit_depth == 16)
  192498. {
  192499. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192500. {
  192501. png_bytep rp;
  192502. png_uint_32 i;
  192503. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  192504. {
  192505. png_byte save = *rp;
  192506. *rp = *(rp + 4);
  192507. *(rp + 4) = save;
  192508. save = *(rp + 1);
  192509. *(rp + 1) = *(rp + 5);
  192510. *(rp + 5) = save;
  192511. }
  192512. }
  192513. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192514. {
  192515. png_bytep rp;
  192516. png_uint_32 i;
  192517. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  192518. {
  192519. png_byte save = *rp;
  192520. *rp = *(rp + 4);
  192521. *(rp + 4) = save;
  192522. save = *(rp + 1);
  192523. *(rp + 1) = *(rp + 5);
  192524. *(rp + 5) = save;
  192525. }
  192526. }
  192527. }
  192528. }
  192529. }
  192530. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  192531. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  192532. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  192533. defined(PNG_LEGACY_SUPPORTED)
  192534. void PNGAPI
  192535. png_set_user_transform_info(png_structp png_ptr, png_voidp
  192536. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  192537. {
  192538. png_debug(1, "in png_set_user_transform_info\n");
  192539. if(png_ptr == NULL) return;
  192540. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  192541. png_ptr->user_transform_ptr = user_transform_ptr;
  192542. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  192543. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  192544. #else
  192545. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  192546. png_warning(png_ptr,
  192547. "This version of libpng does not support user transform info");
  192548. #endif
  192549. }
  192550. #endif
  192551. /* This function returns a pointer to the user_transform_ptr associated with
  192552. * the user transform functions. The application should free any memory
  192553. * associated with this pointer before png_write_destroy and png_read_destroy
  192554. * are called.
  192555. */
  192556. png_voidp PNGAPI
  192557. png_get_user_transform_ptr(png_structp png_ptr)
  192558. {
  192559. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  192560. if (png_ptr == NULL) return (NULL);
  192561. return ((png_voidp)png_ptr->user_transform_ptr);
  192562. #else
  192563. return (NULL);
  192564. #endif
  192565. }
  192566. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  192567. /********* End of inlined file: pngtrans.c *********/
  192568. /********* Start of inlined file: pngwio.c *********/
  192569. /* pngwio.c - functions for data output
  192570. *
  192571. * Last changed in libpng 1.2.13 November 13, 2006
  192572. * For conditions of distribution and use, see copyright notice in png.h
  192573. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  192574. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  192575. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  192576. *
  192577. * This file provides a location for all output. Users who need
  192578. * special handling are expected to write functions that have the same
  192579. * arguments as these and perform similar functions, but that possibly
  192580. * use different output methods. Note that you shouldn't change these
  192581. * functions, but rather write replacement functions and then change
  192582. * them at run time with png_set_write_fn(...).
  192583. */
  192584. #define PNG_INTERNAL
  192585. #ifdef PNG_WRITE_SUPPORTED
  192586. /* Write the data to whatever output you are using. The default routine
  192587. writes to a file pointer. Note that this routine sometimes gets called
  192588. with very small lengths, so you should implement some kind of simple
  192589. buffering if you are using unbuffered writes. This should never be asked
  192590. to write more than 64K on a 16 bit machine. */
  192591. void /* PRIVATE */
  192592. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  192593. {
  192594. if (png_ptr->write_data_fn != NULL )
  192595. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  192596. else
  192597. png_error(png_ptr, "Call to NULL write function");
  192598. }
  192599. #if !defined(PNG_NO_STDIO)
  192600. /* This is the function that does the actual writing of data. If you are
  192601. not writing to a standard C stream, you should create a replacement
  192602. write_data function and use it at run time with png_set_write_fn(), rather
  192603. than changing the library. */
  192604. #ifndef USE_FAR_KEYWORD
  192605. void PNGAPI
  192606. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  192607. {
  192608. png_uint_32 check;
  192609. if(png_ptr == NULL) return;
  192610. #if defined(_WIN32_WCE)
  192611. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  192612. check = 0;
  192613. #else
  192614. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  192615. #endif
  192616. if (check != length)
  192617. png_error(png_ptr, "Write Error");
  192618. }
  192619. #else
  192620. /* this is the model-independent version. Since the standard I/O library
  192621. can't handle far buffers in the medium and small models, we have to copy
  192622. the data.
  192623. */
  192624. #define NEAR_BUF_SIZE 1024
  192625. #define MIN(a,b) (a <= b ? a : b)
  192626. void PNGAPI
  192627. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  192628. {
  192629. png_uint_32 check;
  192630. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  192631. png_FILE_p io_ptr;
  192632. if(png_ptr == NULL) return;
  192633. /* Check if data really is near. If so, use usual code. */
  192634. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  192635. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  192636. if ((png_bytep)near_data == data)
  192637. {
  192638. #if defined(_WIN32_WCE)
  192639. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  192640. check = 0;
  192641. #else
  192642. check = fwrite(near_data, 1, length, io_ptr);
  192643. #endif
  192644. }
  192645. else
  192646. {
  192647. png_byte buf[NEAR_BUF_SIZE];
  192648. png_size_t written, remaining, err;
  192649. check = 0;
  192650. remaining = length;
  192651. do
  192652. {
  192653. written = MIN(NEAR_BUF_SIZE, remaining);
  192654. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  192655. #if defined(_WIN32_WCE)
  192656. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  192657. err = 0;
  192658. #else
  192659. err = fwrite(buf, 1, written, io_ptr);
  192660. #endif
  192661. if (err != written)
  192662. break;
  192663. else
  192664. check += err;
  192665. data += written;
  192666. remaining -= written;
  192667. }
  192668. while (remaining != 0);
  192669. }
  192670. if (check != length)
  192671. png_error(png_ptr, "Write Error");
  192672. }
  192673. #endif
  192674. #endif
  192675. /* This function is called to output any data pending writing (normally
  192676. to disk). After png_flush is called, there should be no data pending
  192677. writing in any buffers. */
  192678. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  192679. void /* PRIVATE */
  192680. png_flush(png_structp png_ptr)
  192681. {
  192682. if (png_ptr->output_flush_fn != NULL)
  192683. (*(png_ptr->output_flush_fn))(png_ptr);
  192684. }
  192685. #if !defined(PNG_NO_STDIO)
  192686. void PNGAPI
  192687. png_default_flush(png_structp png_ptr)
  192688. {
  192689. #if !defined(_WIN32_WCE)
  192690. png_FILE_p io_ptr;
  192691. #endif
  192692. if(png_ptr == NULL) return;
  192693. #if !defined(_WIN32_WCE)
  192694. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  192695. if (io_ptr != NULL)
  192696. fflush(io_ptr);
  192697. #endif
  192698. }
  192699. #endif
  192700. #endif
  192701. /* This function allows the application to supply new output functions for
  192702. libpng if standard C streams aren't being used.
  192703. This function takes as its arguments:
  192704. png_ptr - pointer to a png output data structure
  192705. io_ptr - pointer to user supplied structure containing info about
  192706. the output functions. May be NULL.
  192707. write_data_fn - pointer to a new output function that takes as its
  192708. arguments a pointer to a png_struct, a pointer to
  192709. data to be written, and a 32-bit unsigned int that is
  192710. the number of bytes to be written. The new write
  192711. function should call png_error(png_ptr, "Error msg")
  192712. to exit and output any fatal error messages.
  192713. flush_data_fn - pointer to a new flush function that takes as its
  192714. arguments a pointer to a png_struct. After a call to
  192715. the flush function, there should be no data in any buffers
  192716. or pending transmission. If the output method doesn't do
  192717. any buffering of ouput, a function prototype must still be
  192718. supplied although it doesn't have to do anything. If
  192719. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  192720. time, output_flush_fn will be ignored, although it must be
  192721. supplied for compatibility. */
  192722. void PNGAPI
  192723. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  192724. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  192725. {
  192726. if(png_ptr == NULL) return;
  192727. png_ptr->io_ptr = io_ptr;
  192728. #if !defined(PNG_NO_STDIO)
  192729. if (write_data_fn != NULL)
  192730. png_ptr->write_data_fn = write_data_fn;
  192731. else
  192732. png_ptr->write_data_fn = png_default_write_data;
  192733. #else
  192734. png_ptr->write_data_fn = write_data_fn;
  192735. #endif
  192736. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  192737. #if !defined(PNG_NO_STDIO)
  192738. if (output_flush_fn != NULL)
  192739. png_ptr->output_flush_fn = output_flush_fn;
  192740. else
  192741. png_ptr->output_flush_fn = png_default_flush;
  192742. #else
  192743. png_ptr->output_flush_fn = output_flush_fn;
  192744. #endif
  192745. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  192746. /* It is an error to read while writing a png file */
  192747. if (png_ptr->read_data_fn != NULL)
  192748. {
  192749. png_ptr->read_data_fn = NULL;
  192750. png_warning(png_ptr,
  192751. "Attempted to set both read_data_fn and write_data_fn in");
  192752. png_warning(png_ptr,
  192753. "the same structure. Resetting read_data_fn to NULL.");
  192754. }
  192755. }
  192756. #if defined(USE_FAR_KEYWORD)
  192757. #if defined(_MSC_VER)
  192758. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  192759. {
  192760. void *near_ptr;
  192761. void FAR *far_ptr;
  192762. FP_OFF(near_ptr) = FP_OFF(ptr);
  192763. far_ptr = (void FAR *)near_ptr;
  192764. if(check != 0)
  192765. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  192766. png_error(png_ptr,"segment lost in conversion");
  192767. return(near_ptr);
  192768. }
  192769. # else
  192770. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  192771. {
  192772. void *near_ptr;
  192773. void FAR *far_ptr;
  192774. near_ptr = (void FAR *)ptr;
  192775. far_ptr = (void FAR *)near_ptr;
  192776. if(check != 0)
  192777. if(far_ptr != ptr)
  192778. png_error(png_ptr,"segment lost in conversion");
  192779. return(near_ptr);
  192780. }
  192781. # endif
  192782. # endif
  192783. #endif /* PNG_WRITE_SUPPORTED */
  192784. /********* End of inlined file: pngwio.c *********/
  192785. /********* Start of inlined file: pngwrite.c *********/
  192786. /* pngwrite.c - general routines to write a PNG file
  192787. *
  192788. * Last changed in libpng 1.2.15 January 5, 2007
  192789. * For conditions of distribution and use, see copyright notice in png.h
  192790. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  192791. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  192792. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  192793. */
  192794. /* get internal access to png.h */
  192795. #define PNG_INTERNAL
  192796. #ifdef PNG_WRITE_SUPPORTED
  192797. /* Writes all the PNG information. This is the suggested way to use the
  192798. * library. If you have a new chunk to add, make a function to write it,
  192799. * and put it in the correct location here. If you want the chunk written
  192800. * after the image data, put it in png_write_end(). I strongly encourage
  192801. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  192802. * the chunk, as that will keep the code from breaking if you want to just
  192803. * write a plain PNG file. If you have long comments, I suggest writing
  192804. * them in png_write_end(), and compressing them.
  192805. */
  192806. void PNGAPI
  192807. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  192808. {
  192809. png_debug(1, "in png_write_info_before_PLTE\n");
  192810. if (png_ptr == NULL || info_ptr == NULL)
  192811. return;
  192812. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  192813. {
  192814. png_write_sig(png_ptr); /* write PNG signature */
  192815. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192816. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  192817. {
  192818. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  192819. png_ptr->mng_features_permitted=0;
  192820. }
  192821. #endif
  192822. /* write IHDR information. */
  192823. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  192824. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  192825. info_ptr->filter_type,
  192826. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  192827. info_ptr->interlace_type);
  192828. #else
  192829. 0);
  192830. #endif
  192831. /* the rest of these check to see if the valid field has the appropriate
  192832. flag set, and if it does, writes the chunk. */
  192833. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  192834. if (info_ptr->valid & PNG_INFO_gAMA)
  192835. {
  192836. # ifdef PNG_FLOATING_POINT_SUPPORTED
  192837. png_write_gAMA(png_ptr, info_ptr->gamma);
  192838. #else
  192839. #ifdef PNG_FIXED_POINT_SUPPORTED
  192840. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  192841. # endif
  192842. #endif
  192843. }
  192844. #endif
  192845. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  192846. if (info_ptr->valid & PNG_INFO_sRGB)
  192847. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  192848. #endif
  192849. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  192850. if (info_ptr->valid & PNG_INFO_iCCP)
  192851. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  192852. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  192853. #endif
  192854. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  192855. if (info_ptr->valid & PNG_INFO_sBIT)
  192856. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  192857. #endif
  192858. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  192859. if (info_ptr->valid & PNG_INFO_cHRM)
  192860. {
  192861. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192862. png_write_cHRM(png_ptr,
  192863. info_ptr->x_white, info_ptr->y_white,
  192864. info_ptr->x_red, info_ptr->y_red,
  192865. info_ptr->x_green, info_ptr->y_green,
  192866. info_ptr->x_blue, info_ptr->y_blue);
  192867. #else
  192868. # ifdef PNG_FIXED_POINT_SUPPORTED
  192869. png_write_cHRM_fixed(png_ptr,
  192870. info_ptr->int_x_white, info_ptr->int_y_white,
  192871. info_ptr->int_x_red, info_ptr->int_y_red,
  192872. info_ptr->int_x_green, info_ptr->int_y_green,
  192873. info_ptr->int_x_blue, info_ptr->int_y_blue);
  192874. # endif
  192875. #endif
  192876. }
  192877. #endif
  192878. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  192879. if (info_ptr->unknown_chunks_num)
  192880. {
  192881. png_unknown_chunk *up;
  192882. png_debug(5, "writing extra chunks\n");
  192883. for (up = info_ptr->unknown_chunks;
  192884. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  192885. up++)
  192886. {
  192887. int keep=png_handle_as_unknown(png_ptr, up->name);
  192888. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  192889. up->location && !(up->location & PNG_HAVE_PLTE) &&
  192890. !(up->location & PNG_HAVE_IDAT) &&
  192891. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  192892. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  192893. {
  192894. png_write_chunk(png_ptr, up->name, up->data, up->size);
  192895. }
  192896. }
  192897. }
  192898. #endif
  192899. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  192900. }
  192901. }
  192902. void PNGAPI
  192903. png_write_info(png_structp png_ptr, png_infop info_ptr)
  192904. {
  192905. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  192906. int i;
  192907. #endif
  192908. png_debug(1, "in png_write_info\n");
  192909. if (png_ptr == NULL || info_ptr == NULL)
  192910. return;
  192911. png_write_info_before_PLTE(png_ptr, info_ptr);
  192912. if (info_ptr->valid & PNG_INFO_PLTE)
  192913. png_write_PLTE(png_ptr, info_ptr->palette,
  192914. (png_uint_32)info_ptr->num_palette);
  192915. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192916. png_error(png_ptr, "Valid palette required for paletted images");
  192917. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  192918. if (info_ptr->valid & PNG_INFO_tRNS)
  192919. {
  192920. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  192921. /* invert the alpha channel (in tRNS) */
  192922. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  192923. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192924. {
  192925. int j;
  192926. for (j=0; j<(int)info_ptr->num_trans; j++)
  192927. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  192928. }
  192929. #endif
  192930. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  192931. info_ptr->num_trans, info_ptr->color_type);
  192932. }
  192933. #endif
  192934. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  192935. if (info_ptr->valid & PNG_INFO_bKGD)
  192936. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  192937. #endif
  192938. #if defined(PNG_WRITE_hIST_SUPPORTED)
  192939. if (info_ptr->valid & PNG_INFO_hIST)
  192940. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  192941. #endif
  192942. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  192943. if (info_ptr->valid & PNG_INFO_oFFs)
  192944. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  192945. info_ptr->offset_unit_type);
  192946. #endif
  192947. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  192948. if (info_ptr->valid & PNG_INFO_pCAL)
  192949. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  192950. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  192951. info_ptr->pcal_units, info_ptr->pcal_params);
  192952. #endif
  192953. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  192954. if (info_ptr->valid & PNG_INFO_sCAL)
  192955. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  192956. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  192957. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  192958. #else
  192959. #ifdef PNG_FIXED_POINT_SUPPORTED
  192960. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  192961. info_ptr->scal_s_width, info_ptr->scal_s_height);
  192962. #else
  192963. png_warning(png_ptr,
  192964. "png_write_sCAL not supported; sCAL chunk not written.");
  192965. #endif
  192966. #endif
  192967. #endif
  192968. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  192969. if (info_ptr->valid & PNG_INFO_pHYs)
  192970. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  192971. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  192972. #endif
  192973. #if defined(PNG_WRITE_tIME_SUPPORTED)
  192974. if (info_ptr->valid & PNG_INFO_tIME)
  192975. {
  192976. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  192977. png_ptr->mode |= PNG_WROTE_tIME;
  192978. }
  192979. #endif
  192980. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  192981. if (info_ptr->valid & PNG_INFO_sPLT)
  192982. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  192983. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  192984. #endif
  192985. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  192986. /* Check to see if we need to write text chunks */
  192987. for (i = 0; i < info_ptr->num_text; i++)
  192988. {
  192989. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  192990. info_ptr->text[i].compression);
  192991. /* an internationalized chunk? */
  192992. if (info_ptr->text[i].compression > 0)
  192993. {
  192994. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  192995. /* write international chunk */
  192996. png_write_iTXt(png_ptr,
  192997. info_ptr->text[i].compression,
  192998. info_ptr->text[i].key,
  192999. info_ptr->text[i].lang,
  193000. info_ptr->text[i].lang_key,
  193001. info_ptr->text[i].text);
  193002. #else
  193003. png_warning(png_ptr, "Unable to write international text");
  193004. #endif
  193005. /* Mark this chunk as written */
  193006. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  193007. }
  193008. /* If we want a compressed text chunk */
  193009. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  193010. {
  193011. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  193012. /* write compressed chunk */
  193013. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  193014. info_ptr->text[i].text, 0,
  193015. info_ptr->text[i].compression);
  193016. #else
  193017. png_warning(png_ptr, "Unable to write compressed text");
  193018. #endif
  193019. /* Mark this chunk as written */
  193020. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  193021. }
  193022. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  193023. {
  193024. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  193025. /* write uncompressed chunk */
  193026. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  193027. info_ptr->text[i].text,
  193028. 0);
  193029. #else
  193030. png_warning(png_ptr, "Unable to write uncompressed text");
  193031. #endif
  193032. /* Mark this chunk as written */
  193033. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  193034. }
  193035. }
  193036. #endif
  193037. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  193038. if (info_ptr->unknown_chunks_num)
  193039. {
  193040. png_unknown_chunk *up;
  193041. png_debug(5, "writing extra chunks\n");
  193042. for (up = info_ptr->unknown_chunks;
  193043. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  193044. up++)
  193045. {
  193046. int keep=png_handle_as_unknown(png_ptr, up->name);
  193047. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  193048. up->location && (up->location & PNG_HAVE_PLTE) &&
  193049. !(up->location & PNG_HAVE_IDAT) &&
  193050. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  193051. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  193052. {
  193053. png_write_chunk(png_ptr, up->name, up->data, up->size);
  193054. }
  193055. }
  193056. }
  193057. #endif
  193058. }
  193059. /* Writes the end of the PNG file. If you don't want to write comments or
  193060. * time information, you can pass NULL for info. If you already wrote these
  193061. * in png_write_info(), do not write them again here. If you have long
  193062. * comments, I suggest writing them here, and compressing them.
  193063. */
  193064. void PNGAPI
  193065. png_write_end(png_structp png_ptr, png_infop info_ptr)
  193066. {
  193067. png_debug(1, "in png_write_end\n");
  193068. if (png_ptr == NULL)
  193069. return;
  193070. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  193071. png_error(png_ptr, "No IDATs written into file");
  193072. /* see if user wants us to write information chunks */
  193073. if (info_ptr != NULL)
  193074. {
  193075. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  193076. int i; /* local index variable */
  193077. #endif
  193078. #if defined(PNG_WRITE_tIME_SUPPORTED)
  193079. /* check to see if user has supplied a time chunk */
  193080. if ((info_ptr->valid & PNG_INFO_tIME) &&
  193081. !(png_ptr->mode & PNG_WROTE_tIME))
  193082. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  193083. #endif
  193084. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  193085. /* loop through comment chunks */
  193086. for (i = 0; i < info_ptr->num_text; i++)
  193087. {
  193088. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  193089. info_ptr->text[i].compression);
  193090. /* an internationalized chunk? */
  193091. if (info_ptr->text[i].compression > 0)
  193092. {
  193093. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  193094. /* write international chunk */
  193095. png_write_iTXt(png_ptr,
  193096. info_ptr->text[i].compression,
  193097. info_ptr->text[i].key,
  193098. info_ptr->text[i].lang,
  193099. info_ptr->text[i].lang_key,
  193100. info_ptr->text[i].text);
  193101. #else
  193102. png_warning(png_ptr, "Unable to write international text");
  193103. #endif
  193104. /* Mark this chunk as written */
  193105. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  193106. }
  193107. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  193108. {
  193109. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  193110. /* write compressed chunk */
  193111. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  193112. info_ptr->text[i].text, 0,
  193113. info_ptr->text[i].compression);
  193114. #else
  193115. png_warning(png_ptr, "Unable to write compressed text");
  193116. #endif
  193117. /* Mark this chunk as written */
  193118. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  193119. }
  193120. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  193121. {
  193122. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  193123. /* write uncompressed chunk */
  193124. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  193125. info_ptr->text[i].text, 0);
  193126. #else
  193127. png_warning(png_ptr, "Unable to write uncompressed text");
  193128. #endif
  193129. /* Mark this chunk as written */
  193130. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  193131. }
  193132. }
  193133. #endif
  193134. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  193135. if (info_ptr->unknown_chunks_num)
  193136. {
  193137. png_unknown_chunk *up;
  193138. png_debug(5, "writing extra chunks\n");
  193139. for (up = info_ptr->unknown_chunks;
  193140. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  193141. up++)
  193142. {
  193143. int keep=png_handle_as_unknown(png_ptr, up->name);
  193144. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  193145. up->location && (up->location & PNG_AFTER_IDAT) &&
  193146. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  193147. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  193148. {
  193149. png_write_chunk(png_ptr, up->name, up->data, up->size);
  193150. }
  193151. }
  193152. }
  193153. #endif
  193154. }
  193155. png_ptr->mode |= PNG_AFTER_IDAT;
  193156. /* write end of PNG file */
  193157. png_write_IEND(png_ptr);
  193158. }
  193159. #if defined(PNG_WRITE_tIME_SUPPORTED)
  193160. #if !defined(_WIN32_WCE)
  193161. /* "time.h" functions are not supported on WindowsCE */
  193162. void PNGAPI
  193163. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  193164. {
  193165. png_debug(1, "in png_convert_from_struct_tm\n");
  193166. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  193167. ptime->month = (png_byte)(ttime->tm_mon + 1);
  193168. ptime->day = (png_byte)ttime->tm_mday;
  193169. ptime->hour = (png_byte)ttime->tm_hour;
  193170. ptime->minute = (png_byte)ttime->tm_min;
  193171. ptime->second = (png_byte)ttime->tm_sec;
  193172. }
  193173. void PNGAPI
  193174. png_convert_from_time_t(png_timep ptime, time_t ttime)
  193175. {
  193176. struct tm *tbuf;
  193177. png_debug(1, "in png_convert_from_time_t\n");
  193178. tbuf = gmtime(&ttime);
  193179. png_convert_from_struct_tm(ptime, tbuf);
  193180. }
  193181. #endif
  193182. #endif
  193183. /* Initialize png_ptr structure, and allocate any memory needed */
  193184. png_structp PNGAPI
  193185. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  193186. png_error_ptr error_fn, png_error_ptr warn_fn)
  193187. {
  193188. #ifdef PNG_USER_MEM_SUPPORTED
  193189. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  193190. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  193191. }
  193192. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  193193. png_structp PNGAPI
  193194. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  193195. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  193196. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  193197. {
  193198. #endif /* PNG_USER_MEM_SUPPORTED */
  193199. png_structp png_ptr;
  193200. #ifdef PNG_SETJMP_SUPPORTED
  193201. #ifdef USE_FAR_KEYWORD
  193202. jmp_buf jmpbuf;
  193203. #endif
  193204. #endif
  193205. int i;
  193206. png_debug(1, "in png_create_write_struct\n");
  193207. #ifdef PNG_USER_MEM_SUPPORTED
  193208. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  193209. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  193210. #else
  193211. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  193212. #endif /* PNG_USER_MEM_SUPPORTED */
  193213. if (png_ptr == NULL)
  193214. return (NULL);
  193215. /* added at libpng-1.2.6 */
  193216. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  193217. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  193218. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  193219. #endif
  193220. #ifdef PNG_SETJMP_SUPPORTED
  193221. #ifdef USE_FAR_KEYWORD
  193222. if (setjmp(jmpbuf))
  193223. #else
  193224. if (setjmp(png_ptr->jmpbuf))
  193225. #endif
  193226. {
  193227. png_free(png_ptr, png_ptr->zbuf);
  193228. png_ptr->zbuf=NULL;
  193229. png_destroy_struct(png_ptr);
  193230. return (NULL);
  193231. }
  193232. #ifdef USE_FAR_KEYWORD
  193233. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  193234. #endif
  193235. #endif
  193236. #ifdef PNG_USER_MEM_SUPPORTED
  193237. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  193238. #endif /* PNG_USER_MEM_SUPPORTED */
  193239. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  193240. i=0;
  193241. do
  193242. {
  193243. if(user_png_ver[i] != png_libpng_ver[i])
  193244. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  193245. } while (png_libpng_ver[i++]);
  193246. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  193247. {
  193248. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  193249. * we must recompile any applications that use any older library version.
  193250. * For versions after libpng 1.0, we will be compatible, so we need
  193251. * only check the first digit.
  193252. */
  193253. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  193254. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  193255. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  193256. {
  193257. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193258. char msg[80];
  193259. if (user_png_ver)
  193260. {
  193261. png_snprintf(msg, 80,
  193262. "Application was compiled with png.h from libpng-%.20s",
  193263. user_png_ver);
  193264. png_warning(png_ptr, msg);
  193265. }
  193266. png_snprintf(msg, 80,
  193267. "Application is running with png.c from libpng-%.20s",
  193268. png_libpng_ver);
  193269. png_warning(png_ptr, msg);
  193270. #endif
  193271. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  193272. png_ptr->flags=0;
  193273. #endif
  193274. png_error(png_ptr,
  193275. "Incompatible libpng version in application and library");
  193276. }
  193277. }
  193278. /* initialize zbuf - compression buffer */
  193279. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  193280. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  193281. (png_uint_32)png_ptr->zbuf_size);
  193282. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  193283. png_flush_ptr_NULL);
  193284. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  193285. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  193286. 1, png_doublep_NULL, png_doublep_NULL);
  193287. #endif
  193288. #ifdef PNG_SETJMP_SUPPORTED
  193289. /* Applications that neglect to set up their own setjmp() and then encounter
  193290. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  193291. abort instead of returning. */
  193292. #ifdef USE_FAR_KEYWORD
  193293. if (setjmp(jmpbuf))
  193294. PNG_ABORT();
  193295. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  193296. #else
  193297. if (setjmp(png_ptr->jmpbuf))
  193298. PNG_ABORT();
  193299. #endif
  193300. #endif
  193301. return (png_ptr);
  193302. }
  193303. /* Initialize png_ptr structure, and allocate any memory needed */
  193304. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  193305. /* Deprecated. */
  193306. #undef png_write_init
  193307. void PNGAPI
  193308. png_write_init(png_structp png_ptr)
  193309. {
  193310. /* We only come here via pre-1.0.7-compiled applications */
  193311. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  193312. }
  193313. void PNGAPI
  193314. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  193315. png_size_t png_struct_size, png_size_t png_info_size)
  193316. {
  193317. /* We only come here via pre-1.0.12-compiled applications */
  193318. if(png_ptr == NULL) return;
  193319. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193320. if(png_sizeof(png_struct) > png_struct_size ||
  193321. png_sizeof(png_info) > png_info_size)
  193322. {
  193323. char msg[80];
  193324. png_ptr->warning_fn=NULL;
  193325. if (user_png_ver)
  193326. {
  193327. png_snprintf(msg, 80,
  193328. "Application was compiled with png.h from libpng-%.20s",
  193329. user_png_ver);
  193330. png_warning(png_ptr, msg);
  193331. }
  193332. png_snprintf(msg, 80,
  193333. "Application is running with png.c from libpng-%.20s",
  193334. png_libpng_ver);
  193335. png_warning(png_ptr, msg);
  193336. }
  193337. #endif
  193338. if(png_sizeof(png_struct) > png_struct_size)
  193339. {
  193340. png_ptr->error_fn=NULL;
  193341. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  193342. png_ptr->flags=0;
  193343. #endif
  193344. png_error(png_ptr,
  193345. "The png struct allocated by the application for writing is too small.");
  193346. }
  193347. if(png_sizeof(png_info) > png_info_size)
  193348. {
  193349. png_ptr->error_fn=NULL;
  193350. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  193351. png_ptr->flags=0;
  193352. #endif
  193353. png_error(png_ptr,
  193354. "The info struct allocated by the application for writing is too small.");
  193355. }
  193356. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  193357. }
  193358. #endif /* PNG_1_0_X || PNG_1_2_X */
  193359. void PNGAPI
  193360. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  193361. png_size_t png_struct_size)
  193362. {
  193363. png_structp png_ptr=*ptr_ptr;
  193364. #ifdef PNG_SETJMP_SUPPORTED
  193365. jmp_buf tmp_jmp; /* to save current jump buffer */
  193366. #endif
  193367. int i = 0;
  193368. if (png_ptr == NULL)
  193369. return;
  193370. do
  193371. {
  193372. if (user_png_ver[i] != png_libpng_ver[i])
  193373. {
  193374. #ifdef PNG_LEGACY_SUPPORTED
  193375. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  193376. #else
  193377. png_ptr->warning_fn=NULL;
  193378. png_warning(png_ptr,
  193379. "Application uses deprecated png_write_init() and should be recompiled.");
  193380. break;
  193381. #endif
  193382. }
  193383. } while (png_libpng_ver[i++]);
  193384. png_debug(1, "in png_write_init_3\n");
  193385. #ifdef PNG_SETJMP_SUPPORTED
  193386. /* save jump buffer and error functions */
  193387. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  193388. #endif
  193389. if (png_sizeof(png_struct) > png_struct_size)
  193390. {
  193391. png_destroy_struct(png_ptr);
  193392. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  193393. *ptr_ptr = png_ptr;
  193394. }
  193395. /* reset all variables to 0 */
  193396. png_memset(png_ptr, 0, png_sizeof (png_struct));
  193397. /* added at libpng-1.2.6 */
  193398. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  193399. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  193400. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  193401. #endif
  193402. #ifdef PNG_SETJMP_SUPPORTED
  193403. /* restore jump buffer */
  193404. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  193405. #endif
  193406. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  193407. png_flush_ptr_NULL);
  193408. /* initialize zbuf - compression buffer */
  193409. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  193410. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  193411. (png_uint_32)png_ptr->zbuf_size);
  193412. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  193413. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  193414. 1, png_doublep_NULL, png_doublep_NULL);
  193415. #endif
  193416. }
  193417. /* Write a few rows of image data. If the image is interlaced,
  193418. * either you will have to write the 7 sub images, or, if you
  193419. * have called png_set_interlace_handling(), you will have to
  193420. * "write" the image seven times.
  193421. */
  193422. void PNGAPI
  193423. png_write_rows(png_structp png_ptr, png_bytepp row,
  193424. png_uint_32 num_rows)
  193425. {
  193426. png_uint_32 i; /* row counter */
  193427. png_bytepp rp; /* row pointer */
  193428. png_debug(1, "in png_write_rows\n");
  193429. if (png_ptr == NULL)
  193430. return;
  193431. /* loop through the rows */
  193432. for (i = 0, rp = row; i < num_rows; i++, rp++)
  193433. {
  193434. png_write_row(png_ptr, *rp);
  193435. }
  193436. }
  193437. /* Write the image. You only need to call this function once, even
  193438. * if you are writing an interlaced image.
  193439. */
  193440. void PNGAPI
  193441. png_write_image(png_structp png_ptr, png_bytepp image)
  193442. {
  193443. png_uint_32 i; /* row index */
  193444. int pass, num_pass; /* pass variables */
  193445. png_bytepp rp; /* points to current row */
  193446. if (png_ptr == NULL)
  193447. return;
  193448. png_debug(1, "in png_write_image\n");
  193449. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  193450. /* intialize interlace handling. If image is not interlaced,
  193451. this will set pass to 1 */
  193452. num_pass = png_set_interlace_handling(png_ptr);
  193453. #else
  193454. num_pass = 1;
  193455. #endif
  193456. /* loop through passes */
  193457. for (pass = 0; pass < num_pass; pass++)
  193458. {
  193459. /* loop through image */
  193460. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  193461. {
  193462. png_write_row(png_ptr, *rp);
  193463. }
  193464. }
  193465. }
  193466. /* called by user to write a row of image data */
  193467. void PNGAPI
  193468. png_write_row(png_structp png_ptr, png_bytep row)
  193469. {
  193470. if (png_ptr == NULL)
  193471. return;
  193472. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  193473. png_ptr->row_number, png_ptr->pass);
  193474. /* initialize transformations and other stuff if first time */
  193475. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  193476. {
  193477. /* make sure we wrote the header info */
  193478. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  193479. png_error(png_ptr,
  193480. "png_write_info was never called before png_write_row.");
  193481. /* check for transforms that have been set but were defined out */
  193482. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  193483. if (png_ptr->transformations & PNG_INVERT_MONO)
  193484. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  193485. #endif
  193486. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  193487. if (png_ptr->transformations & PNG_FILLER)
  193488. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  193489. #endif
  193490. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  193491. if (png_ptr->transformations & PNG_PACKSWAP)
  193492. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  193493. #endif
  193494. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  193495. if (png_ptr->transformations & PNG_PACK)
  193496. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  193497. #endif
  193498. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  193499. if (png_ptr->transformations & PNG_SHIFT)
  193500. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  193501. #endif
  193502. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  193503. if (png_ptr->transformations & PNG_BGR)
  193504. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  193505. #endif
  193506. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  193507. if (png_ptr->transformations & PNG_SWAP_BYTES)
  193508. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  193509. #endif
  193510. png_write_start_row(png_ptr);
  193511. }
  193512. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  193513. /* if interlaced and not interested in row, return */
  193514. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  193515. {
  193516. switch (png_ptr->pass)
  193517. {
  193518. case 0:
  193519. if (png_ptr->row_number & 0x07)
  193520. {
  193521. png_write_finish_row(png_ptr);
  193522. return;
  193523. }
  193524. break;
  193525. case 1:
  193526. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  193527. {
  193528. png_write_finish_row(png_ptr);
  193529. return;
  193530. }
  193531. break;
  193532. case 2:
  193533. if ((png_ptr->row_number & 0x07) != 4)
  193534. {
  193535. png_write_finish_row(png_ptr);
  193536. return;
  193537. }
  193538. break;
  193539. case 3:
  193540. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  193541. {
  193542. png_write_finish_row(png_ptr);
  193543. return;
  193544. }
  193545. break;
  193546. case 4:
  193547. if ((png_ptr->row_number & 0x03) != 2)
  193548. {
  193549. png_write_finish_row(png_ptr);
  193550. return;
  193551. }
  193552. break;
  193553. case 5:
  193554. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  193555. {
  193556. png_write_finish_row(png_ptr);
  193557. return;
  193558. }
  193559. break;
  193560. case 6:
  193561. if (!(png_ptr->row_number & 0x01))
  193562. {
  193563. png_write_finish_row(png_ptr);
  193564. return;
  193565. }
  193566. break;
  193567. }
  193568. }
  193569. #endif
  193570. /* set up row info for transformations */
  193571. png_ptr->row_info.color_type = png_ptr->color_type;
  193572. png_ptr->row_info.width = png_ptr->usr_width;
  193573. png_ptr->row_info.channels = png_ptr->usr_channels;
  193574. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  193575. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  193576. png_ptr->row_info.channels);
  193577. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  193578. png_ptr->row_info.width);
  193579. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  193580. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  193581. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  193582. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  193583. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  193584. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  193585. /* Copy user's row into buffer, leaving room for filter byte. */
  193586. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  193587. png_ptr->row_info.rowbytes);
  193588. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  193589. /* handle interlacing */
  193590. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  193591. (png_ptr->transformations & PNG_INTERLACE))
  193592. {
  193593. png_do_write_interlace(&(png_ptr->row_info),
  193594. png_ptr->row_buf + 1, png_ptr->pass);
  193595. /* this should always get caught above, but still ... */
  193596. if (!(png_ptr->row_info.width))
  193597. {
  193598. png_write_finish_row(png_ptr);
  193599. return;
  193600. }
  193601. }
  193602. #endif
  193603. /* handle other transformations */
  193604. if (png_ptr->transformations)
  193605. png_do_write_transformations(png_ptr);
  193606. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193607. /* Write filter_method 64 (intrapixel differencing) only if
  193608. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  193609. * 2. Libpng did not write a PNG signature (this filter_method is only
  193610. * used in PNG datastreams that are embedded in MNG datastreams) and
  193611. * 3. The application called png_permit_mng_features with a mask that
  193612. * included PNG_FLAG_MNG_FILTER_64 and
  193613. * 4. The filter_method is 64 and
  193614. * 5. The color_type is RGB or RGBA
  193615. */
  193616. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  193617. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  193618. {
  193619. /* Intrapixel differencing */
  193620. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  193621. }
  193622. #endif
  193623. /* Find a filter if necessary, filter the row and write it out. */
  193624. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  193625. if (png_ptr->write_row_fn != NULL)
  193626. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  193627. }
  193628. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  193629. /* Set the automatic flush interval or 0 to turn flushing off */
  193630. void PNGAPI
  193631. png_set_flush(png_structp png_ptr, int nrows)
  193632. {
  193633. png_debug(1, "in png_set_flush\n");
  193634. if (png_ptr == NULL)
  193635. return;
  193636. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  193637. }
  193638. /* flush the current output buffers now */
  193639. void PNGAPI
  193640. png_write_flush(png_structp png_ptr)
  193641. {
  193642. int wrote_IDAT;
  193643. png_debug(1, "in png_write_flush\n");
  193644. if (png_ptr == NULL)
  193645. return;
  193646. /* We have already written out all of the data */
  193647. if (png_ptr->row_number >= png_ptr->num_rows)
  193648. return;
  193649. do
  193650. {
  193651. int ret;
  193652. /* compress the data */
  193653. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  193654. wrote_IDAT = 0;
  193655. /* check for compression errors */
  193656. if (ret != Z_OK)
  193657. {
  193658. if (png_ptr->zstream.msg != NULL)
  193659. png_error(png_ptr, png_ptr->zstream.msg);
  193660. else
  193661. png_error(png_ptr, "zlib error");
  193662. }
  193663. if (!(png_ptr->zstream.avail_out))
  193664. {
  193665. /* write the IDAT and reset the zlib output buffer */
  193666. png_write_IDAT(png_ptr, png_ptr->zbuf,
  193667. png_ptr->zbuf_size);
  193668. png_ptr->zstream.next_out = png_ptr->zbuf;
  193669. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193670. wrote_IDAT = 1;
  193671. }
  193672. } while(wrote_IDAT == 1);
  193673. /* If there is any data left to be output, write it into a new IDAT */
  193674. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  193675. {
  193676. /* write the IDAT and reset the zlib output buffer */
  193677. png_write_IDAT(png_ptr, png_ptr->zbuf,
  193678. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  193679. png_ptr->zstream.next_out = png_ptr->zbuf;
  193680. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193681. }
  193682. png_ptr->flush_rows = 0;
  193683. png_flush(png_ptr);
  193684. }
  193685. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  193686. /* free all memory used by the write */
  193687. void PNGAPI
  193688. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  193689. {
  193690. png_structp png_ptr = NULL;
  193691. png_infop info_ptr = NULL;
  193692. #ifdef PNG_USER_MEM_SUPPORTED
  193693. png_free_ptr free_fn = NULL;
  193694. png_voidp mem_ptr = NULL;
  193695. #endif
  193696. png_debug(1, "in png_destroy_write_struct\n");
  193697. if (png_ptr_ptr != NULL)
  193698. {
  193699. png_ptr = *png_ptr_ptr;
  193700. #ifdef PNG_USER_MEM_SUPPORTED
  193701. free_fn = png_ptr->free_fn;
  193702. mem_ptr = png_ptr->mem_ptr;
  193703. #endif
  193704. }
  193705. if (info_ptr_ptr != NULL)
  193706. info_ptr = *info_ptr_ptr;
  193707. if (info_ptr != NULL)
  193708. {
  193709. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  193710. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  193711. if (png_ptr->num_chunk_list)
  193712. {
  193713. png_free(png_ptr, png_ptr->chunk_list);
  193714. png_ptr->chunk_list=NULL;
  193715. png_ptr->num_chunk_list=0;
  193716. }
  193717. #endif
  193718. #ifdef PNG_USER_MEM_SUPPORTED
  193719. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  193720. (png_voidp)mem_ptr);
  193721. #else
  193722. png_destroy_struct((png_voidp)info_ptr);
  193723. #endif
  193724. *info_ptr_ptr = NULL;
  193725. }
  193726. if (png_ptr != NULL)
  193727. {
  193728. png_write_destroy(png_ptr);
  193729. #ifdef PNG_USER_MEM_SUPPORTED
  193730. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  193731. (png_voidp)mem_ptr);
  193732. #else
  193733. png_destroy_struct((png_voidp)png_ptr);
  193734. #endif
  193735. *png_ptr_ptr = NULL;
  193736. }
  193737. }
  193738. /* Free any memory used in png_ptr struct (old method) */
  193739. void /* PRIVATE */
  193740. png_write_destroy(png_structp png_ptr)
  193741. {
  193742. #ifdef PNG_SETJMP_SUPPORTED
  193743. jmp_buf tmp_jmp; /* save jump buffer */
  193744. #endif
  193745. png_error_ptr error_fn;
  193746. png_error_ptr warning_fn;
  193747. png_voidp error_ptr;
  193748. #ifdef PNG_USER_MEM_SUPPORTED
  193749. png_free_ptr free_fn;
  193750. #endif
  193751. png_debug(1, "in png_write_destroy\n");
  193752. /* free any memory zlib uses */
  193753. deflateEnd(&png_ptr->zstream);
  193754. /* free our memory. png_free checks NULL for us. */
  193755. png_free(png_ptr, png_ptr->zbuf);
  193756. png_free(png_ptr, png_ptr->row_buf);
  193757. png_free(png_ptr, png_ptr->prev_row);
  193758. png_free(png_ptr, png_ptr->sub_row);
  193759. png_free(png_ptr, png_ptr->up_row);
  193760. png_free(png_ptr, png_ptr->avg_row);
  193761. png_free(png_ptr, png_ptr->paeth_row);
  193762. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  193763. png_free(png_ptr, png_ptr->time_buffer);
  193764. #endif
  193765. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  193766. png_free(png_ptr, png_ptr->prev_filters);
  193767. png_free(png_ptr, png_ptr->filter_weights);
  193768. png_free(png_ptr, png_ptr->inv_filter_weights);
  193769. png_free(png_ptr, png_ptr->filter_costs);
  193770. png_free(png_ptr, png_ptr->inv_filter_costs);
  193771. #endif
  193772. #ifdef PNG_SETJMP_SUPPORTED
  193773. /* reset structure */
  193774. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  193775. #endif
  193776. error_fn = png_ptr->error_fn;
  193777. warning_fn = png_ptr->warning_fn;
  193778. error_ptr = png_ptr->error_ptr;
  193779. #ifdef PNG_USER_MEM_SUPPORTED
  193780. free_fn = png_ptr->free_fn;
  193781. #endif
  193782. png_memset(png_ptr, 0, png_sizeof (png_struct));
  193783. png_ptr->error_fn = error_fn;
  193784. png_ptr->warning_fn = warning_fn;
  193785. png_ptr->error_ptr = error_ptr;
  193786. #ifdef PNG_USER_MEM_SUPPORTED
  193787. png_ptr->free_fn = free_fn;
  193788. #endif
  193789. #ifdef PNG_SETJMP_SUPPORTED
  193790. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  193791. #endif
  193792. }
  193793. /* Allow the application to select one or more row filters to use. */
  193794. void PNGAPI
  193795. png_set_filter(png_structp png_ptr, int method, int filters)
  193796. {
  193797. png_debug(1, "in png_set_filter\n");
  193798. if (png_ptr == NULL)
  193799. return;
  193800. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193801. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  193802. (method == PNG_INTRAPIXEL_DIFFERENCING))
  193803. method = PNG_FILTER_TYPE_BASE;
  193804. #endif
  193805. if (method == PNG_FILTER_TYPE_BASE)
  193806. {
  193807. switch (filters & (PNG_ALL_FILTERS | 0x07))
  193808. {
  193809. #ifndef PNG_NO_WRITE_FILTER
  193810. case 5:
  193811. case 6:
  193812. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  193813. #endif /* PNG_NO_WRITE_FILTER */
  193814. case PNG_FILTER_VALUE_NONE:
  193815. png_ptr->do_filter=PNG_FILTER_NONE; break;
  193816. #ifndef PNG_NO_WRITE_FILTER
  193817. case PNG_FILTER_VALUE_SUB:
  193818. png_ptr->do_filter=PNG_FILTER_SUB; break;
  193819. case PNG_FILTER_VALUE_UP:
  193820. png_ptr->do_filter=PNG_FILTER_UP; break;
  193821. case PNG_FILTER_VALUE_AVG:
  193822. png_ptr->do_filter=PNG_FILTER_AVG; break;
  193823. case PNG_FILTER_VALUE_PAETH:
  193824. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  193825. default: png_ptr->do_filter = (png_byte)filters; break;
  193826. #else
  193827. default: png_warning(png_ptr, "Unknown row filter for method 0");
  193828. #endif /* PNG_NO_WRITE_FILTER */
  193829. }
  193830. /* If we have allocated the row_buf, this means we have already started
  193831. * with the image and we should have allocated all of the filter buffers
  193832. * that have been selected. If prev_row isn't already allocated, then
  193833. * it is too late to start using the filters that need it, since we
  193834. * will be missing the data in the previous row. If an application
  193835. * wants to start and stop using particular filters during compression,
  193836. * it should start out with all of the filters, and then add and
  193837. * remove them after the start of compression.
  193838. */
  193839. if (png_ptr->row_buf != NULL)
  193840. {
  193841. #ifndef PNG_NO_WRITE_FILTER
  193842. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  193843. {
  193844. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  193845. (png_ptr->rowbytes + 1));
  193846. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  193847. }
  193848. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  193849. {
  193850. if (png_ptr->prev_row == NULL)
  193851. {
  193852. png_warning(png_ptr, "Can't add Up filter after starting");
  193853. png_ptr->do_filter &= ~PNG_FILTER_UP;
  193854. }
  193855. else
  193856. {
  193857. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  193858. (png_ptr->rowbytes + 1));
  193859. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  193860. }
  193861. }
  193862. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  193863. {
  193864. if (png_ptr->prev_row == NULL)
  193865. {
  193866. png_warning(png_ptr, "Can't add Average filter after starting");
  193867. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  193868. }
  193869. else
  193870. {
  193871. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  193872. (png_ptr->rowbytes + 1));
  193873. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  193874. }
  193875. }
  193876. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  193877. png_ptr->paeth_row == NULL)
  193878. {
  193879. if (png_ptr->prev_row == NULL)
  193880. {
  193881. png_warning(png_ptr, "Can't add Paeth filter after starting");
  193882. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  193883. }
  193884. else
  193885. {
  193886. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  193887. (png_ptr->rowbytes + 1));
  193888. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  193889. }
  193890. }
  193891. if (png_ptr->do_filter == PNG_NO_FILTERS)
  193892. #endif /* PNG_NO_WRITE_FILTER */
  193893. png_ptr->do_filter = PNG_FILTER_NONE;
  193894. }
  193895. }
  193896. else
  193897. png_error(png_ptr, "Unknown custom filter method");
  193898. }
  193899. /* This allows us to influence the way in which libpng chooses the "best"
  193900. * filter for the current scanline. While the "minimum-sum-of-absolute-
  193901. * differences metric is relatively fast and effective, there is some
  193902. * question as to whether it can be improved upon by trying to keep the
  193903. * filtered data going to zlib more consistent, hopefully resulting in
  193904. * better compression.
  193905. */
  193906. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  193907. void PNGAPI
  193908. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  193909. int num_weights, png_doublep filter_weights,
  193910. png_doublep filter_costs)
  193911. {
  193912. int i;
  193913. png_debug(1, "in png_set_filter_heuristics\n");
  193914. if (png_ptr == NULL)
  193915. return;
  193916. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  193917. {
  193918. png_warning(png_ptr, "Unknown filter heuristic method");
  193919. return;
  193920. }
  193921. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  193922. {
  193923. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  193924. }
  193925. if (num_weights < 0 || filter_weights == NULL ||
  193926. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  193927. {
  193928. num_weights = 0;
  193929. }
  193930. png_ptr->num_prev_filters = (png_byte)num_weights;
  193931. png_ptr->heuristic_method = (png_byte)heuristic_method;
  193932. if (num_weights > 0)
  193933. {
  193934. if (png_ptr->prev_filters == NULL)
  193935. {
  193936. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  193937. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  193938. /* To make sure that the weighting starts out fairly */
  193939. for (i = 0; i < num_weights; i++)
  193940. {
  193941. png_ptr->prev_filters[i] = 255;
  193942. }
  193943. }
  193944. if (png_ptr->filter_weights == NULL)
  193945. {
  193946. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  193947. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  193948. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  193949. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  193950. for (i = 0; i < num_weights; i++)
  193951. {
  193952. png_ptr->inv_filter_weights[i] =
  193953. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  193954. }
  193955. }
  193956. for (i = 0; i < num_weights; i++)
  193957. {
  193958. if (filter_weights[i] < 0.0)
  193959. {
  193960. png_ptr->inv_filter_weights[i] =
  193961. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  193962. }
  193963. else
  193964. {
  193965. png_ptr->inv_filter_weights[i] =
  193966. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  193967. png_ptr->filter_weights[i] =
  193968. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  193969. }
  193970. }
  193971. }
  193972. /* If, in the future, there are other filter methods, this would
  193973. * need to be based on png_ptr->filter.
  193974. */
  193975. if (png_ptr->filter_costs == NULL)
  193976. {
  193977. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  193978. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  193979. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  193980. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  193981. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  193982. {
  193983. png_ptr->inv_filter_costs[i] =
  193984. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  193985. }
  193986. }
  193987. /* Here is where we set the relative costs of the different filters. We
  193988. * should take the desired compression level into account when setting
  193989. * the costs, so that Paeth, for instance, has a high relative cost at low
  193990. * compression levels, while it has a lower relative cost at higher
  193991. * compression settings. The filter types are in order of increasing
  193992. * relative cost, so it would be possible to do this with an algorithm.
  193993. */
  193994. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  193995. {
  193996. if (filter_costs == NULL || filter_costs[i] < 0.0)
  193997. {
  193998. png_ptr->inv_filter_costs[i] =
  193999. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  194000. }
  194001. else if (filter_costs[i] >= 1.0)
  194002. {
  194003. png_ptr->inv_filter_costs[i] =
  194004. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  194005. png_ptr->filter_costs[i] =
  194006. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  194007. }
  194008. }
  194009. }
  194010. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  194011. void PNGAPI
  194012. png_set_compression_level(png_structp png_ptr, int level)
  194013. {
  194014. png_debug(1, "in png_set_compression_level\n");
  194015. if (png_ptr == NULL)
  194016. return;
  194017. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  194018. png_ptr->zlib_level = level;
  194019. }
  194020. void PNGAPI
  194021. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  194022. {
  194023. png_debug(1, "in png_set_compression_mem_level\n");
  194024. if (png_ptr == NULL)
  194025. return;
  194026. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  194027. png_ptr->zlib_mem_level = mem_level;
  194028. }
  194029. void PNGAPI
  194030. png_set_compression_strategy(png_structp png_ptr, int strategy)
  194031. {
  194032. png_debug(1, "in png_set_compression_strategy\n");
  194033. if (png_ptr == NULL)
  194034. return;
  194035. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  194036. png_ptr->zlib_strategy = strategy;
  194037. }
  194038. void PNGAPI
  194039. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  194040. {
  194041. if (png_ptr == NULL)
  194042. return;
  194043. if (window_bits > 15)
  194044. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  194045. else if (window_bits < 8)
  194046. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  194047. #ifndef WBITS_8_OK
  194048. /* avoid libpng bug with 256-byte windows */
  194049. if (window_bits == 8)
  194050. {
  194051. png_warning(png_ptr, "Compression window is being reset to 512");
  194052. window_bits=9;
  194053. }
  194054. #endif
  194055. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  194056. png_ptr->zlib_window_bits = window_bits;
  194057. }
  194058. void PNGAPI
  194059. png_set_compression_method(png_structp png_ptr, int method)
  194060. {
  194061. png_debug(1, "in png_set_compression_method\n");
  194062. if (png_ptr == NULL)
  194063. return;
  194064. if (method != 8)
  194065. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  194066. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  194067. png_ptr->zlib_method = method;
  194068. }
  194069. void PNGAPI
  194070. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  194071. {
  194072. if (png_ptr == NULL)
  194073. return;
  194074. png_ptr->write_row_fn = write_row_fn;
  194075. }
  194076. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  194077. void PNGAPI
  194078. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  194079. write_user_transform_fn)
  194080. {
  194081. png_debug(1, "in png_set_write_user_transform_fn\n");
  194082. if (png_ptr == NULL)
  194083. return;
  194084. png_ptr->transformations |= PNG_USER_TRANSFORM;
  194085. png_ptr->write_user_transform_fn = write_user_transform_fn;
  194086. }
  194087. #endif
  194088. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  194089. void PNGAPI
  194090. png_write_png(png_structp png_ptr, png_infop info_ptr,
  194091. int transforms, voidp params)
  194092. {
  194093. if (png_ptr == NULL || info_ptr == NULL)
  194094. return;
  194095. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  194096. /* invert the alpha channel from opacity to transparency */
  194097. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  194098. png_set_invert_alpha(png_ptr);
  194099. #endif
  194100. /* Write the file header information. */
  194101. png_write_info(png_ptr, info_ptr);
  194102. /* ------ these transformations don't touch the info structure ------- */
  194103. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  194104. /* invert monochrome pixels */
  194105. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  194106. png_set_invert_mono(png_ptr);
  194107. #endif
  194108. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  194109. /* Shift the pixels up to a legal bit depth and fill in
  194110. * as appropriate to correctly scale the image.
  194111. */
  194112. if ((transforms & PNG_TRANSFORM_SHIFT)
  194113. && (info_ptr->valid & PNG_INFO_sBIT))
  194114. png_set_shift(png_ptr, &info_ptr->sig_bit);
  194115. #endif
  194116. #if defined(PNG_WRITE_PACK_SUPPORTED)
  194117. /* pack pixels into bytes */
  194118. if (transforms & PNG_TRANSFORM_PACKING)
  194119. png_set_packing(png_ptr);
  194120. #endif
  194121. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  194122. /* swap location of alpha bytes from ARGB to RGBA */
  194123. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  194124. png_set_swap_alpha(png_ptr);
  194125. #endif
  194126. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  194127. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  194128. * RGB (4 channels -> 3 channels). The second parameter is not used.
  194129. */
  194130. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  194131. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  194132. #endif
  194133. #if defined(PNG_WRITE_BGR_SUPPORTED)
  194134. /* flip BGR pixels to RGB */
  194135. if (transforms & PNG_TRANSFORM_BGR)
  194136. png_set_bgr(png_ptr);
  194137. #endif
  194138. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  194139. /* swap bytes of 16-bit files to most significant byte first */
  194140. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  194141. png_set_swap(png_ptr);
  194142. #endif
  194143. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  194144. /* swap bits of 1, 2, 4 bit packed pixel formats */
  194145. if (transforms & PNG_TRANSFORM_PACKSWAP)
  194146. png_set_packswap(png_ptr);
  194147. #endif
  194148. /* ----------------------- end of transformations ------------------- */
  194149. /* write the bits */
  194150. if (info_ptr->valid & PNG_INFO_IDAT)
  194151. png_write_image(png_ptr, info_ptr->row_pointers);
  194152. /* It is REQUIRED to call this to finish writing the rest of the file */
  194153. png_write_end(png_ptr, info_ptr);
  194154. transforms = transforms; /* quiet compiler warnings */
  194155. params = params;
  194156. }
  194157. #endif
  194158. #endif /* PNG_WRITE_SUPPORTED */
  194159. /********* End of inlined file: pngwrite.c *********/
  194160. /********* Start of inlined file: pngwtran.c *********/
  194161. /* pngwtran.c - transforms the data in a row for PNG writers
  194162. *
  194163. * Last changed in libpng 1.2.9 April 14, 2006
  194164. * For conditions of distribution and use, see copyright notice in png.h
  194165. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  194166. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194167. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194168. */
  194169. #define PNG_INTERNAL
  194170. #ifdef PNG_WRITE_SUPPORTED
  194171. /* Transform the data according to the user's wishes. The order of
  194172. * transformations is significant.
  194173. */
  194174. void /* PRIVATE */
  194175. png_do_write_transformations(png_structp png_ptr)
  194176. {
  194177. png_debug(1, "in png_do_write_transformations\n");
  194178. if (png_ptr == NULL)
  194179. return;
  194180. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  194181. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  194182. if(png_ptr->write_user_transform_fn != NULL)
  194183. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  194184. (png_ptr, /* png_ptr */
  194185. &(png_ptr->row_info), /* row_info: */
  194186. /* png_uint_32 width; width of row */
  194187. /* png_uint_32 rowbytes; number of bytes in row */
  194188. /* png_byte color_type; color type of pixels */
  194189. /* png_byte bit_depth; bit depth of samples */
  194190. /* png_byte channels; number of channels (1-4) */
  194191. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  194192. png_ptr->row_buf + 1); /* start of pixel data for row */
  194193. #endif
  194194. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  194195. if (png_ptr->transformations & PNG_FILLER)
  194196. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  194197. png_ptr->flags);
  194198. #endif
  194199. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  194200. if (png_ptr->transformations & PNG_PACKSWAP)
  194201. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194202. #endif
  194203. #if defined(PNG_WRITE_PACK_SUPPORTED)
  194204. if (png_ptr->transformations & PNG_PACK)
  194205. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  194206. (png_uint_32)png_ptr->bit_depth);
  194207. #endif
  194208. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  194209. if (png_ptr->transformations & PNG_SWAP_BYTES)
  194210. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194211. #endif
  194212. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  194213. if (png_ptr->transformations & PNG_SHIFT)
  194214. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  194215. &(png_ptr->shift));
  194216. #endif
  194217. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  194218. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  194219. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194220. #endif
  194221. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  194222. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  194223. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194224. #endif
  194225. #if defined(PNG_WRITE_BGR_SUPPORTED)
  194226. if (png_ptr->transformations & PNG_BGR)
  194227. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194228. #endif
  194229. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  194230. if (png_ptr->transformations & PNG_INVERT_MONO)
  194231. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  194232. #endif
  194233. }
  194234. #if defined(PNG_WRITE_PACK_SUPPORTED)
  194235. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  194236. * row_info bit depth should be 8 (one pixel per byte). The channels
  194237. * should be 1 (this only happens on grayscale and paletted images).
  194238. */
  194239. void /* PRIVATE */
  194240. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  194241. {
  194242. png_debug(1, "in png_do_pack\n");
  194243. if (row_info->bit_depth == 8 &&
  194244. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194245. row != NULL && row_info != NULL &&
  194246. #endif
  194247. row_info->channels == 1)
  194248. {
  194249. switch ((int)bit_depth)
  194250. {
  194251. case 1:
  194252. {
  194253. png_bytep sp, dp;
  194254. int mask, v;
  194255. png_uint_32 i;
  194256. png_uint_32 row_width = row_info->width;
  194257. sp = row;
  194258. dp = row;
  194259. mask = 0x80;
  194260. v = 0;
  194261. for (i = 0; i < row_width; i++)
  194262. {
  194263. if (*sp != 0)
  194264. v |= mask;
  194265. sp++;
  194266. if (mask > 1)
  194267. mask >>= 1;
  194268. else
  194269. {
  194270. mask = 0x80;
  194271. *dp = (png_byte)v;
  194272. dp++;
  194273. v = 0;
  194274. }
  194275. }
  194276. if (mask != 0x80)
  194277. *dp = (png_byte)v;
  194278. break;
  194279. }
  194280. case 2:
  194281. {
  194282. png_bytep sp, dp;
  194283. int shift, v;
  194284. png_uint_32 i;
  194285. png_uint_32 row_width = row_info->width;
  194286. sp = row;
  194287. dp = row;
  194288. shift = 6;
  194289. v = 0;
  194290. for (i = 0; i < row_width; i++)
  194291. {
  194292. png_byte value;
  194293. value = (png_byte)(*sp & 0x03);
  194294. v |= (value << shift);
  194295. if (shift == 0)
  194296. {
  194297. shift = 6;
  194298. *dp = (png_byte)v;
  194299. dp++;
  194300. v = 0;
  194301. }
  194302. else
  194303. shift -= 2;
  194304. sp++;
  194305. }
  194306. if (shift != 6)
  194307. *dp = (png_byte)v;
  194308. break;
  194309. }
  194310. case 4:
  194311. {
  194312. png_bytep sp, dp;
  194313. int shift, v;
  194314. png_uint_32 i;
  194315. png_uint_32 row_width = row_info->width;
  194316. sp = row;
  194317. dp = row;
  194318. shift = 4;
  194319. v = 0;
  194320. for (i = 0; i < row_width; i++)
  194321. {
  194322. png_byte value;
  194323. value = (png_byte)(*sp & 0x0f);
  194324. v |= (value << shift);
  194325. if (shift == 0)
  194326. {
  194327. shift = 4;
  194328. *dp = (png_byte)v;
  194329. dp++;
  194330. v = 0;
  194331. }
  194332. else
  194333. shift -= 4;
  194334. sp++;
  194335. }
  194336. if (shift != 4)
  194337. *dp = (png_byte)v;
  194338. break;
  194339. }
  194340. }
  194341. row_info->bit_depth = (png_byte)bit_depth;
  194342. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  194343. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  194344. row_info->width);
  194345. }
  194346. }
  194347. #endif
  194348. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  194349. /* Shift pixel values to take advantage of whole range. Pass the
  194350. * true number of bits in bit_depth. The row should be packed
  194351. * according to row_info->bit_depth. Thus, if you had a row of
  194352. * bit depth 4, but the pixels only had values from 0 to 7, you
  194353. * would pass 3 as bit_depth, and this routine would translate the
  194354. * data to 0 to 15.
  194355. */
  194356. void /* PRIVATE */
  194357. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  194358. {
  194359. png_debug(1, "in png_do_shift\n");
  194360. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194361. if (row != NULL && row_info != NULL &&
  194362. #else
  194363. if (
  194364. #endif
  194365. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  194366. {
  194367. int shift_start[4], shift_dec[4];
  194368. int channels = 0;
  194369. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  194370. {
  194371. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  194372. shift_dec[channels] = bit_depth->red;
  194373. channels++;
  194374. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  194375. shift_dec[channels] = bit_depth->green;
  194376. channels++;
  194377. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  194378. shift_dec[channels] = bit_depth->blue;
  194379. channels++;
  194380. }
  194381. else
  194382. {
  194383. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  194384. shift_dec[channels] = bit_depth->gray;
  194385. channels++;
  194386. }
  194387. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  194388. {
  194389. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  194390. shift_dec[channels] = bit_depth->alpha;
  194391. channels++;
  194392. }
  194393. /* with low row depths, could only be grayscale, so one channel */
  194394. if (row_info->bit_depth < 8)
  194395. {
  194396. png_bytep bp = row;
  194397. png_uint_32 i;
  194398. png_byte mask;
  194399. png_uint_32 row_bytes = row_info->rowbytes;
  194400. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  194401. mask = 0x55;
  194402. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  194403. mask = 0x11;
  194404. else
  194405. mask = 0xff;
  194406. for (i = 0; i < row_bytes; i++, bp++)
  194407. {
  194408. png_uint_16 v;
  194409. int j;
  194410. v = *bp;
  194411. *bp = 0;
  194412. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  194413. {
  194414. if (j > 0)
  194415. *bp |= (png_byte)((v << j) & 0xff);
  194416. else
  194417. *bp |= (png_byte)((v >> (-j)) & mask);
  194418. }
  194419. }
  194420. }
  194421. else if (row_info->bit_depth == 8)
  194422. {
  194423. png_bytep bp = row;
  194424. png_uint_32 i;
  194425. png_uint_32 istop = channels * row_info->width;
  194426. for (i = 0; i < istop; i++, bp++)
  194427. {
  194428. png_uint_16 v;
  194429. int j;
  194430. int c = (int)(i%channels);
  194431. v = *bp;
  194432. *bp = 0;
  194433. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  194434. {
  194435. if (j > 0)
  194436. *bp |= (png_byte)((v << j) & 0xff);
  194437. else
  194438. *bp |= (png_byte)((v >> (-j)) & 0xff);
  194439. }
  194440. }
  194441. }
  194442. else
  194443. {
  194444. png_bytep bp;
  194445. png_uint_32 i;
  194446. png_uint_32 istop = channels * row_info->width;
  194447. for (bp = row, i = 0; i < istop; i++)
  194448. {
  194449. int c = (int)(i%channels);
  194450. png_uint_16 value, v;
  194451. int j;
  194452. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  194453. value = 0;
  194454. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  194455. {
  194456. if (j > 0)
  194457. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  194458. else
  194459. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  194460. }
  194461. *bp++ = (png_byte)(value >> 8);
  194462. *bp++ = (png_byte)(value & 0xff);
  194463. }
  194464. }
  194465. }
  194466. }
  194467. #endif
  194468. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  194469. void /* PRIVATE */
  194470. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  194471. {
  194472. png_debug(1, "in png_do_write_swap_alpha\n");
  194473. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194474. if (row != NULL && row_info != NULL)
  194475. #endif
  194476. {
  194477. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194478. {
  194479. /* This converts from ARGB to RGBA */
  194480. if (row_info->bit_depth == 8)
  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. png_byte save = *(sp++);
  194488. *(dp++) = *(sp++);
  194489. *(dp++) = *(sp++);
  194490. *(dp++) = *(sp++);
  194491. *(dp++) = save;
  194492. }
  194493. }
  194494. /* This converts from AARRGGBB to RRGGBBAA */
  194495. else
  194496. {
  194497. png_bytep sp, dp;
  194498. png_uint_32 i;
  194499. png_uint_32 row_width = row_info->width;
  194500. for (i = 0, sp = dp = row; i < row_width; i++)
  194501. {
  194502. png_byte save[2];
  194503. save[0] = *(sp++);
  194504. save[1] = *(sp++);
  194505. *(dp++) = *(sp++);
  194506. *(dp++) = *(sp++);
  194507. *(dp++) = *(sp++);
  194508. *(dp++) = *(sp++);
  194509. *(dp++) = *(sp++);
  194510. *(dp++) = *(sp++);
  194511. *(dp++) = save[0];
  194512. *(dp++) = save[1];
  194513. }
  194514. }
  194515. }
  194516. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  194517. {
  194518. /* This converts from AG to GA */
  194519. if (row_info->bit_depth == 8)
  194520. {
  194521. png_bytep sp, dp;
  194522. png_uint_32 i;
  194523. png_uint_32 row_width = row_info->width;
  194524. for (i = 0, sp = dp = row; i < row_width; i++)
  194525. {
  194526. png_byte save = *(sp++);
  194527. *(dp++) = *(sp++);
  194528. *(dp++) = save;
  194529. }
  194530. }
  194531. /* This converts from AAGG to GGAA */
  194532. else
  194533. {
  194534. png_bytep sp, dp;
  194535. png_uint_32 i;
  194536. png_uint_32 row_width = row_info->width;
  194537. for (i = 0, sp = dp = row; i < row_width; i++)
  194538. {
  194539. png_byte save[2];
  194540. save[0] = *(sp++);
  194541. save[1] = *(sp++);
  194542. *(dp++) = *(sp++);
  194543. *(dp++) = *(sp++);
  194544. *(dp++) = save[0];
  194545. *(dp++) = save[1];
  194546. }
  194547. }
  194548. }
  194549. }
  194550. }
  194551. #endif
  194552. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  194553. void /* PRIVATE */
  194554. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  194555. {
  194556. png_debug(1, "in png_do_write_invert_alpha\n");
  194557. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194558. if (row != NULL && row_info != NULL)
  194559. #endif
  194560. {
  194561. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194562. {
  194563. /* This inverts the alpha channel in RGBA */
  194564. if (row_info->bit_depth == 8)
  194565. {
  194566. png_bytep sp, dp;
  194567. png_uint_32 i;
  194568. png_uint_32 row_width = row_info->width;
  194569. for (i = 0, sp = dp = row; i < row_width; i++)
  194570. {
  194571. /* does nothing
  194572. *(dp++) = *(sp++);
  194573. *(dp++) = *(sp++);
  194574. *(dp++) = *(sp++);
  194575. */
  194576. sp+=3; dp = sp;
  194577. *(dp++) = (png_byte)(255 - *(sp++));
  194578. }
  194579. }
  194580. /* This inverts the alpha channel in RRGGBBAA */
  194581. else
  194582. {
  194583. png_bytep sp, dp;
  194584. png_uint_32 i;
  194585. png_uint_32 row_width = row_info->width;
  194586. for (i = 0, sp = dp = row; i < row_width; i++)
  194587. {
  194588. /* does nothing
  194589. *(dp++) = *(sp++);
  194590. *(dp++) = *(sp++);
  194591. *(dp++) = *(sp++);
  194592. *(dp++) = *(sp++);
  194593. *(dp++) = *(sp++);
  194594. *(dp++) = *(sp++);
  194595. */
  194596. sp+=6; dp = sp;
  194597. *(dp++) = (png_byte)(255 - *(sp++));
  194598. *(dp++) = (png_byte)(255 - *(sp++));
  194599. }
  194600. }
  194601. }
  194602. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  194603. {
  194604. /* This inverts the alpha channel in GA */
  194605. if (row_info->bit_depth == 8)
  194606. {
  194607. png_bytep sp, dp;
  194608. png_uint_32 i;
  194609. png_uint_32 row_width = row_info->width;
  194610. for (i = 0, sp = dp = row; i < row_width; i++)
  194611. {
  194612. *(dp++) = *(sp++);
  194613. *(dp++) = (png_byte)(255 - *(sp++));
  194614. }
  194615. }
  194616. /* This inverts the alpha channel in GGAA */
  194617. else
  194618. {
  194619. png_bytep sp, dp;
  194620. png_uint_32 i;
  194621. png_uint_32 row_width = row_info->width;
  194622. for (i = 0, sp = dp = row; i < row_width; i++)
  194623. {
  194624. /* does nothing
  194625. *(dp++) = *(sp++);
  194626. *(dp++) = *(sp++);
  194627. */
  194628. sp+=2; dp = sp;
  194629. *(dp++) = (png_byte)(255 - *(sp++));
  194630. *(dp++) = (png_byte)(255 - *(sp++));
  194631. }
  194632. }
  194633. }
  194634. }
  194635. }
  194636. #endif
  194637. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194638. /* undoes intrapixel differencing */
  194639. void /* PRIVATE */
  194640. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  194641. {
  194642. png_debug(1, "in png_do_write_intrapixel\n");
  194643. if (
  194644. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194645. row != NULL && row_info != NULL &&
  194646. #endif
  194647. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194648. {
  194649. int bytes_per_pixel;
  194650. png_uint_32 row_width = row_info->width;
  194651. if (row_info->bit_depth == 8)
  194652. {
  194653. png_bytep rp;
  194654. png_uint_32 i;
  194655. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194656. bytes_per_pixel = 3;
  194657. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194658. bytes_per_pixel = 4;
  194659. else
  194660. return;
  194661. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194662. {
  194663. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  194664. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  194665. }
  194666. }
  194667. else if (row_info->bit_depth == 16)
  194668. {
  194669. png_bytep rp;
  194670. png_uint_32 i;
  194671. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194672. bytes_per_pixel = 6;
  194673. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194674. bytes_per_pixel = 8;
  194675. else
  194676. return;
  194677. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194678. {
  194679. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  194680. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  194681. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  194682. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  194683. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  194684. *(rp ) = (png_byte)((red >> 8) & 0xff);
  194685. *(rp+1) = (png_byte)(red & 0xff);
  194686. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  194687. *(rp+5) = (png_byte)(blue & 0xff);
  194688. }
  194689. }
  194690. }
  194691. }
  194692. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  194693. #endif /* PNG_WRITE_SUPPORTED */
  194694. /********* End of inlined file: pngwtran.c *********/
  194695. /********* Start of inlined file: pngwutil.c *********/
  194696. /* pngwutil.c - utilities to write a PNG file
  194697. *
  194698. * Last changed in libpng 1.2.20 Septhember 3, 2007
  194699. * For conditions of distribution and use, see copyright notice in png.h
  194700. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194701. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194702. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194703. */
  194704. #define PNG_INTERNAL
  194705. #ifdef PNG_WRITE_SUPPORTED
  194706. /* Place a 32-bit number into a buffer in PNG byte order. We work
  194707. * with unsigned numbers for convenience, although one supported
  194708. * ancillary chunk uses signed (two's complement) numbers.
  194709. */
  194710. void PNGAPI
  194711. png_save_uint_32(png_bytep buf, png_uint_32 i)
  194712. {
  194713. buf[0] = (png_byte)((i >> 24) & 0xff);
  194714. buf[1] = (png_byte)((i >> 16) & 0xff);
  194715. buf[2] = (png_byte)((i >> 8) & 0xff);
  194716. buf[3] = (png_byte)(i & 0xff);
  194717. }
  194718. /* The png_save_int_32 function assumes integers are stored in two's
  194719. * complement format. If this isn't the case, then this routine needs to
  194720. * be modified to write data in two's complement format.
  194721. */
  194722. void PNGAPI
  194723. png_save_int_32(png_bytep buf, png_int_32 i)
  194724. {
  194725. buf[0] = (png_byte)((i >> 24) & 0xff);
  194726. buf[1] = (png_byte)((i >> 16) & 0xff);
  194727. buf[2] = (png_byte)((i >> 8) & 0xff);
  194728. buf[3] = (png_byte)(i & 0xff);
  194729. }
  194730. /* Place a 16-bit number into a buffer in PNG byte order.
  194731. * The parameter is declared unsigned int, not png_uint_16,
  194732. * just to avoid potential problems on pre-ANSI C compilers.
  194733. */
  194734. void PNGAPI
  194735. png_save_uint_16(png_bytep buf, unsigned int i)
  194736. {
  194737. buf[0] = (png_byte)((i >> 8) & 0xff);
  194738. buf[1] = (png_byte)(i & 0xff);
  194739. }
  194740. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  194741. * representing the chunk name. The array must be at least 4 bytes in
  194742. * length, and does not need to be null terminated. To be safe, pass the
  194743. * pre-defined chunk names here, and if you need a new one, define it
  194744. * where the others are defined. The length is the length of the data.
  194745. * All the data must be present. If that is not possible, use the
  194746. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  194747. * functions instead.
  194748. */
  194749. void PNGAPI
  194750. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  194751. png_bytep data, png_size_t length)
  194752. {
  194753. if(png_ptr == NULL) return;
  194754. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  194755. png_write_chunk_data(png_ptr, data, length);
  194756. png_write_chunk_end(png_ptr);
  194757. }
  194758. /* Write the start of a PNG chunk. The type is the chunk type.
  194759. * The total_length is the sum of the lengths of all the data you will be
  194760. * passing in png_write_chunk_data().
  194761. */
  194762. void PNGAPI
  194763. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  194764. png_uint_32 length)
  194765. {
  194766. png_byte buf[4];
  194767. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  194768. if(png_ptr == NULL) return;
  194769. /* write the length */
  194770. png_save_uint_32(buf, length);
  194771. png_write_data(png_ptr, buf, (png_size_t)4);
  194772. /* write the chunk name */
  194773. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  194774. /* reset the crc and run it over the chunk name */
  194775. png_reset_crc(png_ptr);
  194776. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  194777. }
  194778. /* Write the data of a PNG chunk started with png_write_chunk_start().
  194779. * Note that multiple calls to this function are allowed, and that the
  194780. * sum of the lengths from these calls *must* add up to the total_length
  194781. * given to png_write_chunk_start().
  194782. */
  194783. void PNGAPI
  194784. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  194785. {
  194786. /* write the data, and run the CRC over it */
  194787. if(png_ptr == NULL) return;
  194788. if (data != NULL && length > 0)
  194789. {
  194790. png_calculate_crc(png_ptr, data, length);
  194791. png_write_data(png_ptr, data, length);
  194792. }
  194793. }
  194794. /* Finish a chunk started with png_write_chunk_start(). */
  194795. void PNGAPI
  194796. png_write_chunk_end(png_structp png_ptr)
  194797. {
  194798. png_byte buf[4];
  194799. if(png_ptr == NULL) return;
  194800. /* write the crc */
  194801. png_save_uint_32(buf, png_ptr->crc);
  194802. png_write_data(png_ptr, buf, (png_size_t)4);
  194803. }
  194804. /* Simple function to write the signature. If we have already written
  194805. * the magic bytes of the signature, or more likely, the PNG stream is
  194806. * being embedded into another stream and doesn't need its own signature,
  194807. * we should call png_set_sig_bytes() to tell libpng how many of the
  194808. * bytes have already been written.
  194809. */
  194810. void /* PRIVATE */
  194811. png_write_sig(png_structp png_ptr)
  194812. {
  194813. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  194814. /* write the rest of the 8 byte signature */
  194815. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  194816. (png_size_t)8 - png_ptr->sig_bytes);
  194817. if(png_ptr->sig_bytes < 3)
  194818. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  194819. }
  194820. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  194821. /*
  194822. * This pair of functions encapsulates the operation of (a) compressing a
  194823. * text string, and (b) issuing it later as a series of chunk data writes.
  194824. * The compression_state structure is shared context for these functions
  194825. * set up by the caller in order to make the whole mess thread-safe.
  194826. */
  194827. typedef struct
  194828. {
  194829. char *input; /* the uncompressed input data */
  194830. int input_len; /* its length */
  194831. int num_output_ptr; /* number of output pointers used */
  194832. int max_output_ptr; /* size of output_ptr */
  194833. png_charpp output_ptr; /* array of pointers to output */
  194834. } compression_state;
  194835. /* compress given text into storage in the png_ptr structure */
  194836. static int /* PRIVATE */
  194837. png_text_compress(png_structp png_ptr,
  194838. png_charp text, png_size_t text_len, int compression,
  194839. compression_state *comp)
  194840. {
  194841. int ret;
  194842. comp->num_output_ptr = 0;
  194843. comp->max_output_ptr = 0;
  194844. comp->output_ptr = NULL;
  194845. comp->input = NULL;
  194846. comp->input_len = 0;
  194847. /* we may just want to pass the text right through */
  194848. if (compression == PNG_TEXT_COMPRESSION_NONE)
  194849. {
  194850. comp->input = text;
  194851. comp->input_len = text_len;
  194852. return((int)text_len);
  194853. }
  194854. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  194855. {
  194856. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194857. char msg[50];
  194858. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  194859. png_warning(png_ptr, msg);
  194860. #else
  194861. png_warning(png_ptr, "Unknown compression type");
  194862. #endif
  194863. }
  194864. /* We can't write the chunk until we find out how much data we have,
  194865. * which means we need to run the compressor first and save the
  194866. * output. This shouldn't be a problem, as the vast majority of
  194867. * comments should be reasonable, but we will set up an array of
  194868. * malloc'd pointers to be sure.
  194869. *
  194870. * If we knew the application was well behaved, we could simplify this
  194871. * greatly by assuming we can always malloc an output buffer large
  194872. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  194873. * and malloc this directly. The only time this would be a bad idea is
  194874. * if we can't malloc more than 64K and we have 64K of random input
  194875. * data, or if the input string is incredibly large (although this
  194876. * wouldn't cause a failure, just a slowdown due to swapping).
  194877. */
  194878. /* set up the compression buffers */
  194879. png_ptr->zstream.avail_in = (uInt)text_len;
  194880. png_ptr->zstream.next_in = (Bytef *)text;
  194881. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194882. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  194883. /* this is the same compression loop as in png_write_row() */
  194884. do
  194885. {
  194886. /* compress the data */
  194887. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  194888. if (ret != Z_OK)
  194889. {
  194890. /* error */
  194891. if (png_ptr->zstream.msg != NULL)
  194892. png_error(png_ptr, png_ptr->zstream.msg);
  194893. else
  194894. png_error(png_ptr, "zlib error");
  194895. }
  194896. /* check to see if we need more room */
  194897. if (!(png_ptr->zstream.avail_out))
  194898. {
  194899. /* make sure the output array has room */
  194900. if (comp->num_output_ptr >= comp->max_output_ptr)
  194901. {
  194902. int old_max;
  194903. old_max = comp->max_output_ptr;
  194904. comp->max_output_ptr = comp->num_output_ptr + 4;
  194905. if (comp->output_ptr != NULL)
  194906. {
  194907. png_charpp old_ptr;
  194908. old_ptr = comp->output_ptr;
  194909. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194910. (png_uint_32)(comp->max_output_ptr *
  194911. png_sizeof (png_charpp)));
  194912. png_memcpy(comp->output_ptr, old_ptr, old_max
  194913. * png_sizeof (png_charp));
  194914. png_free(png_ptr, old_ptr);
  194915. }
  194916. else
  194917. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194918. (png_uint_32)(comp->max_output_ptr *
  194919. png_sizeof (png_charp)));
  194920. }
  194921. /* save the data */
  194922. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  194923. (png_uint_32)png_ptr->zbuf_size);
  194924. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  194925. png_ptr->zbuf_size);
  194926. comp->num_output_ptr++;
  194927. /* and reset the buffer */
  194928. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194929. png_ptr->zstream.next_out = png_ptr->zbuf;
  194930. }
  194931. /* continue until we don't have any more to compress */
  194932. } while (png_ptr->zstream.avail_in);
  194933. /* finish the compression */
  194934. do
  194935. {
  194936. /* tell zlib we are finished */
  194937. ret = deflate(&png_ptr->zstream, Z_FINISH);
  194938. if (ret == Z_OK)
  194939. {
  194940. /* check to see if we need more room */
  194941. if (!(png_ptr->zstream.avail_out))
  194942. {
  194943. /* check to make sure our output array has room */
  194944. if (comp->num_output_ptr >= comp->max_output_ptr)
  194945. {
  194946. int old_max;
  194947. old_max = comp->max_output_ptr;
  194948. comp->max_output_ptr = comp->num_output_ptr + 4;
  194949. if (comp->output_ptr != NULL)
  194950. {
  194951. png_charpp old_ptr;
  194952. old_ptr = comp->output_ptr;
  194953. /* This could be optimized to realloc() */
  194954. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194955. (png_uint_32)(comp->max_output_ptr *
  194956. png_sizeof (png_charpp)));
  194957. png_memcpy(comp->output_ptr, old_ptr,
  194958. old_max * png_sizeof (png_charp));
  194959. png_free(png_ptr, old_ptr);
  194960. }
  194961. else
  194962. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194963. (png_uint_32)(comp->max_output_ptr *
  194964. png_sizeof (png_charp)));
  194965. }
  194966. /* save off the data */
  194967. comp->output_ptr[comp->num_output_ptr] =
  194968. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  194969. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  194970. png_ptr->zbuf_size);
  194971. comp->num_output_ptr++;
  194972. /* and reset the buffer pointers */
  194973. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194974. png_ptr->zstream.next_out = png_ptr->zbuf;
  194975. }
  194976. }
  194977. else if (ret != Z_STREAM_END)
  194978. {
  194979. /* we got an error */
  194980. if (png_ptr->zstream.msg != NULL)
  194981. png_error(png_ptr, png_ptr->zstream.msg);
  194982. else
  194983. png_error(png_ptr, "zlib error");
  194984. }
  194985. } while (ret != Z_STREAM_END);
  194986. /* text length is number of buffers plus last buffer */
  194987. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  194988. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  194989. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  194990. return((int)text_len);
  194991. }
  194992. /* ship the compressed text out via chunk writes */
  194993. static void /* PRIVATE */
  194994. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  194995. {
  194996. int i;
  194997. /* handle the no-compression case */
  194998. if (comp->input)
  194999. {
  195000. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  195001. (png_size_t)comp->input_len);
  195002. return;
  195003. }
  195004. /* write saved output buffers, if any */
  195005. for (i = 0; i < comp->num_output_ptr; i++)
  195006. {
  195007. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  195008. png_ptr->zbuf_size);
  195009. png_free(png_ptr, comp->output_ptr[i]);
  195010. comp->output_ptr[i]=NULL;
  195011. }
  195012. if (comp->max_output_ptr != 0)
  195013. png_free(png_ptr, comp->output_ptr);
  195014. comp->output_ptr=NULL;
  195015. /* write anything left in zbuf */
  195016. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  195017. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  195018. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  195019. /* reset zlib for another zTXt/iTXt or image data */
  195020. deflateReset(&png_ptr->zstream);
  195021. png_ptr->zstream.data_type = Z_BINARY;
  195022. }
  195023. #endif
  195024. /* Write the IHDR chunk, and update the png_struct with the necessary
  195025. * information. Note that the rest of this code depends upon this
  195026. * information being correct.
  195027. */
  195028. void /* PRIVATE */
  195029. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  195030. int bit_depth, int color_type, int compression_type, int filter_type,
  195031. int interlace_type)
  195032. {
  195033. #ifdef PNG_USE_LOCAL_ARRAYS
  195034. PNG_IHDR;
  195035. #endif
  195036. png_byte buf[13]; /* buffer to store the IHDR info */
  195037. png_debug(1, "in png_write_IHDR\n");
  195038. /* Check that we have valid input data from the application info */
  195039. switch (color_type)
  195040. {
  195041. case PNG_COLOR_TYPE_GRAY:
  195042. switch (bit_depth)
  195043. {
  195044. case 1:
  195045. case 2:
  195046. case 4:
  195047. case 8:
  195048. case 16: png_ptr->channels = 1; break;
  195049. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  195050. }
  195051. break;
  195052. case PNG_COLOR_TYPE_RGB:
  195053. if (bit_depth != 8 && bit_depth != 16)
  195054. png_error(png_ptr, "Invalid bit depth for RGB image");
  195055. png_ptr->channels = 3;
  195056. break;
  195057. case PNG_COLOR_TYPE_PALETTE:
  195058. switch (bit_depth)
  195059. {
  195060. case 1:
  195061. case 2:
  195062. case 4:
  195063. case 8: png_ptr->channels = 1; break;
  195064. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  195065. }
  195066. break;
  195067. case PNG_COLOR_TYPE_GRAY_ALPHA:
  195068. if (bit_depth != 8 && bit_depth != 16)
  195069. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  195070. png_ptr->channels = 2;
  195071. break;
  195072. case PNG_COLOR_TYPE_RGB_ALPHA:
  195073. if (bit_depth != 8 && bit_depth != 16)
  195074. png_error(png_ptr, "Invalid bit depth for RGBA image");
  195075. png_ptr->channels = 4;
  195076. break;
  195077. default:
  195078. png_error(png_ptr, "Invalid image color type specified");
  195079. }
  195080. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  195081. {
  195082. png_warning(png_ptr, "Invalid compression type specified");
  195083. compression_type = PNG_COMPRESSION_TYPE_BASE;
  195084. }
  195085. /* Write filter_method 64 (intrapixel differencing) only if
  195086. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  195087. * 2. Libpng did not write a PNG signature (this filter_method is only
  195088. * used in PNG datastreams that are embedded in MNG datastreams) and
  195089. * 3. The application called png_permit_mng_features with a mask that
  195090. * included PNG_FLAG_MNG_FILTER_64 and
  195091. * 4. The filter_method is 64 and
  195092. * 5. The color_type is RGB or RGBA
  195093. */
  195094. if (
  195095. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195096. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  195097. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  195098. (color_type == PNG_COLOR_TYPE_RGB ||
  195099. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  195100. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  195101. #endif
  195102. filter_type != PNG_FILTER_TYPE_BASE)
  195103. {
  195104. png_warning(png_ptr, "Invalid filter type specified");
  195105. filter_type = PNG_FILTER_TYPE_BASE;
  195106. }
  195107. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  195108. if (interlace_type != PNG_INTERLACE_NONE &&
  195109. interlace_type != PNG_INTERLACE_ADAM7)
  195110. {
  195111. png_warning(png_ptr, "Invalid interlace type specified");
  195112. interlace_type = PNG_INTERLACE_ADAM7;
  195113. }
  195114. #else
  195115. interlace_type=PNG_INTERLACE_NONE;
  195116. #endif
  195117. /* save off the relevent information */
  195118. png_ptr->bit_depth = (png_byte)bit_depth;
  195119. png_ptr->color_type = (png_byte)color_type;
  195120. png_ptr->interlaced = (png_byte)interlace_type;
  195121. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195122. png_ptr->filter_type = (png_byte)filter_type;
  195123. #endif
  195124. png_ptr->compression_type = (png_byte)compression_type;
  195125. png_ptr->width = width;
  195126. png_ptr->height = height;
  195127. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  195128. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  195129. /* set the usr info, so any transformations can modify it */
  195130. png_ptr->usr_width = png_ptr->width;
  195131. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  195132. png_ptr->usr_channels = png_ptr->channels;
  195133. /* pack the header information into the buffer */
  195134. png_save_uint_32(buf, width);
  195135. png_save_uint_32(buf + 4, height);
  195136. buf[8] = (png_byte)bit_depth;
  195137. buf[9] = (png_byte)color_type;
  195138. buf[10] = (png_byte)compression_type;
  195139. buf[11] = (png_byte)filter_type;
  195140. buf[12] = (png_byte)interlace_type;
  195141. /* write the chunk */
  195142. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  195143. /* initialize zlib with PNG info */
  195144. png_ptr->zstream.zalloc = png_zalloc;
  195145. png_ptr->zstream.zfree = png_zfree;
  195146. png_ptr->zstream.opaque = (voidpf)png_ptr;
  195147. if (!(png_ptr->do_filter))
  195148. {
  195149. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  195150. png_ptr->bit_depth < 8)
  195151. png_ptr->do_filter = PNG_FILTER_NONE;
  195152. else
  195153. png_ptr->do_filter = PNG_ALL_FILTERS;
  195154. }
  195155. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  195156. {
  195157. if (png_ptr->do_filter != PNG_FILTER_NONE)
  195158. png_ptr->zlib_strategy = Z_FILTERED;
  195159. else
  195160. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  195161. }
  195162. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  195163. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  195164. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  195165. png_ptr->zlib_mem_level = 8;
  195166. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  195167. png_ptr->zlib_window_bits = 15;
  195168. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  195169. png_ptr->zlib_method = 8;
  195170. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  195171. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  195172. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  195173. png_error(png_ptr, "zlib failed to initialize compressor");
  195174. png_ptr->zstream.next_out = png_ptr->zbuf;
  195175. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195176. /* libpng is not interested in zstream.data_type */
  195177. /* set it to a predefined value, to avoid its evaluation inside zlib */
  195178. png_ptr->zstream.data_type = Z_BINARY;
  195179. png_ptr->mode = PNG_HAVE_IHDR;
  195180. }
  195181. /* write the palette. We are careful not to trust png_color to be in the
  195182. * correct order for PNG, so people can redefine it to any convenient
  195183. * structure.
  195184. */
  195185. void /* PRIVATE */
  195186. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  195187. {
  195188. #ifdef PNG_USE_LOCAL_ARRAYS
  195189. PNG_PLTE;
  195190. #endif
  195191. png_uint_32 i;
  195192. png_colorp pal_ptr;
  195193. png_byte buf[3];
  195194. png_debug(1, "in png_write_PLTE\n");
  195195. if ((
  195196. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195197. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  195198. #endif
  195199. num_pal == 0) || num_pal > 256)
  195200. {
  195201. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195202. {
  195203. png_error(png_ptr, "Invalid number of colors in palette");
  195204. }
  195205. else
  195206. {
  195207. png_warning(png_ptr, "Invalid number of colors in palette");
  195208. return;
  195209. }
  195210. }
  195211. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  195212. {
  195213. png_warning(png_ptr,
  195214. "Ignoring request to write a PLTE chunk in grayscale PNG");
  195215. return;
  195216. }
  195217. png_ptr->num_palette = (png_uint_16)num_pal;
  195218. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  195219. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  195220. #ifndef PNG_NO_POINTER_INDEXING
  195221. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  195222. {
  195223. buf[0] = pal_ptr->red;
  195224. buf[1] = pal_ptr->green;
  195225. buf[2] = pal_ptr->blue;
  195226. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  195227. }
  195228. #else
  195229. /* This is a little slower but some buggy compilers need to do this instead */
  195230. pal_ptr=palette;
  195231. for (i = 0; i < num_pal; i++)
  195232. {
  195233. buf[0] = pal_ptr[i].red;
  195234. buf[1] = pal_ptr[i].green;
  195235. buf[2] = pal_ptr[i].blue;
  195236. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  195237. }
  195238. #endif
  195239. png_write_chunk_end(png_ptr);
  195240. png_ptr->mode |= PNG_HAVE_PLTE;
  195241. }
  195242. /* write an IDAT chunk */
  195243. void /* PRIVATE */
  195244. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  195245. {
  195246. #ifdef PNG_USE_LOCAL_ARRAYS
  195247. PNG_IDAT;
  195248. #endif
  195249. png_debug(1, "in png_write_IDAT\n");
  195250. /* Optimize the CMF field in the zlib stream. */
  195251. /* This hack of the zlib stream is compliant to the stream specification. */
  195252. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  195253. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  195254. {
  195255. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  195256. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  195257. {
  195258. /* Avoid memory underflows and multiplication overflows. */
  195259. /* The conditions below are practically always satisfied;
  195260. however, they still must be checked. */
  195261. if (length >= 2 &&
  195262. png_ptr->height < 16384 && png_ptr->width < 16384)
  195263. {
  195264. png_uint_32 uncompressed_idat_size = png_ptr->height *
  195265. ((png_ptr->width *
  195266. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  195267. unsigned int z_cinfo = z_cmf >> 4;
  195268. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  195269. while (uncompressed_idat_size <= half_z_window_size &&
  195270. half_z_window_size >= 256)
  195271. {
  195272. z_cinfo--;
  195273. half_z_window_size >>= 1;
  195274. }
  195275. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  195276. if (data[0] != (png_byte)z_cmf)
  195277. {
  195278. data[0] = (png_byte)z_cmf;
  195279. data[1] &= 0xe0;
  195280. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  195281. }
  195282. }
  195283. }
  195284. else
  195285. png_error(png_ptr,
  195286. "Invalid zlib compression method or flags in IDAT");
  195287. }
  195288. png_write_chunk(png_ptr, png_IDAT, data, length);
  195289. png_ptr->mode |= PNG_HAVE_IDAT;
  195290. }
  195291. /* write an IEND chunk */
  195292. void /* PRIVATE */
  195293. png_write_IEND(png_structp png_ptr)
  195294. {
  195295. #ifdef PNG_USE_LOCAL_ARRAYS
  195296. PNG_IEND;
  195297. #endif
  195298. png_debug(1, "in png_write_IEND\n");
  195299. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  195300. (png_size_t)0);
  195301. png_ptr->mode |= PNG_HAVE_IEND;
  195302. }
  195303. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  195304. /* write a gAMA chunk */
  195305. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195306. void /* PRIVATE */
  195307. png_write_gAMA(png_structp png_ptr, double file_gamma)
  195308. {
  195309. #ifdef PNG_USE_LOCAL_ARRAYS
  195310. PNG_gAMA;
  195311. #endif
  195312. png_uint_32 igamma;
  195313. png_byte buf[4];
  195314. png_debug(1, "in png_write_gAMA\n");
  195315. /* file_gamma is saved in 1/100,000ths */
  195316. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  195317. png_save_uint_32(buf, igamma);
  195318. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  195319. }
  195320. #endif
  195321. #ifdef PNG_FIXED_POINT_SUPPORTED
  195322. void /* PRIVATE */
  195323. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  195324. {
  195325. #ifdef PNG_USE_LOCAL_ARRAYS
  195326. PNG_gAMA;
  195327. #endif
  195328. png_byte buf[4];
  195329. png_debug(1, "in png_write_gAMA\n");
  195330. /* file_gamma is saved in 1/100,000ths */
  195331. png_save_uint_32(buf, (png_uint_32)file_gamma);
  195332. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  195333. }
  195334. #endif
  195335. #endif
  195336. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  195337. /* write a sRGB chunk */
  195338. void /* PRIVATE */
  195339. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  195340. {
  195341. #ifdef PNG_USE_LOCAL_ARRAYS
  195342. PNG_sRGB;
  195343. #endif
  195344. png_byte buf[1];
  195345. png_debug(1, "in png_write_sRGB\n");
  195346. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  195347. png_warning(png_ptr,
  195348. "Invalid sRGB rendering intent specified");
  195349. buf[0]=(png_byte)srgb_intent;
  195350. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  195351. }
  195352. #endif
  195353. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  195354. /* write an iCCP chunk */
  195355. void /* PRIVATE */
  195356. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  195357. png_charp profile, int profile_len)
  195358. {
  195359. #ifdef PNG_USE_LOCAL_ARRAYS
  195360. PNG_iCCP;
  195361. #endif
  195362. png_size_t name_len;
  195363. png_charp new_name;
  195364. compression_state comp;
  195365. int embedded_profile_len = 0;
  195366. png_debug(1, "in png_write_iCCP\n");
  195367. comp.num_output_ptr = 0;
  195368. comp.max_output_ptr = 0;
  195369. comp.output_ptr = NULL;
  195370. comp.input = NULL;
  195371. comp.input_len = 0;
  195372. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  195373. &new_name)) == 0)
  195374. {
  195375. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  195376. return;
  195377. }
  195378. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  195379. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  195380. if (profile == NULL)
  195381. profile_len = 0;
  195382. if (profile_len > 3)
  195383. embedded_profile_len =
  195384. ((*( (png_bytep)profile ))<<24) |
  195385. ((*( (png_bytep)profile+1))<<16) |
  195386. ((*( (png_bytep)profile+2))<< 8) |
  195387. ((*( (png_bytep)profile+3)) );
  195388. if (profile_len < embedded_profile_len)
  195389. {
  195390. png_warning(png_ptr,
  195391. "Embedded profile length too large in iCCP chunk");
  195392. return;
  195393. }
  195394. if (profile_len > embedded_profile_len)
  195395. {
  195396. png_warning(png_ptr,
  195397. "Truncating profile to actual length in iCCP chunk");
  195398. profile_len = embedded_profile_len;
  195399. }
  195400. if (profile_len)
  195401. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  195402. PNG_COMPRESSION_TYPE_BASE, &comp);
  195403. /* make sure we include the NULL after the name and the compression type */
  195404. png_write_chunk_start(png_ptr, png_iCCP,
  195405. (png_uint_32)name_len+profile_len+2);
  195406. new_name[name_len+1]=0x00;
  195407. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  195408. if (profile_len)
  195409. png_write_compressed_data_out(png_ptr, &comp);
  195410. png_write_chunk_end(png_ptr);
  195411. png_free(png_ptr, new_name);
  195412. }
  195413. #endif
  195414. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  195415. /* write a sPLT chunk */
  195416. void /* PRIVATE */
  195417. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  195418. {
  195419. #ifdef PNG_USE_LOCAL_ARRAYS
  195420. PNG_sPLT;
  195421. #endif
  195422. png_size_t name_len;
  195423. png_charp new_name;
  195424. png_byte entrybuf[10];
  195425. int entry_size = (spalette->depth == 8 ? 6 : 10);
  195426. int palette_size = entry_size * spalette->nentries;
  195427. png_sPLT_entryp ep;
  195428. #ifdef PNG_NO_POINTER_INDEXING
  195429. int i;
  195430. #endif
  195431. png_debug(1, "in png_write_sPLT\n");
  195432. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  195433. spalette->name, &new_name))==0)
  195434. {
  195435. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  195436. return;
  195437. }
  195438. /* make sure we include the NULL after the name */
  195439. png_write_chunk_start(png_ptr, png_sPLT,
  195440. (png_uint_32)(name_len + 2 + palette_size));
  195441. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  195442. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  195443. /* loop through each palette entry, writing appropriately */
  195444. #ifndef PNG_NO_POINTER_INDEXING
  195445. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  195446. {
  195447. if (spalette->depth == 8)
  195448. {
  195449. entrybuf[0] = (png_byte)ep->red;
  195450. entrybuf[1] = (png_byte)ep->green;
  195451. entrybuf[2] = (png_byte)ep->blue;
  195452. entrybuf[3] = (png_byte)ep->alpha;
  195453. png_save_uint_16(entrybuf + 4, ep->frequency);
  195454. }
  195455. else
  195456. {
  195457. png_save_uint_16(entrybuf + 0, ep->red);
  195458. png_save_uint_16(entrybuf + 2, ep->green);
  195459. png_save_uint_16(entrybuf + 4, ep->blue);
  195460. png_save_uint_16(entrybuf + 6, ep->alpha);
  195461. png_save_uint_16(entrybuf + 8, ep->frequency);
  195462. }
  195463. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  195464. }
  195465. #else
  195466. ep=spalette->entries;
  195467. for (i=0; i>spalette->nentries; i++)
  195468. {
  195469. if (spalette->depth == 8)
  195470. {
  195471. entrybuf[0] = (png_byte)ep[i].red;
  195472. entrybuf[1] = (png_byte)ep[i].green;
  195473. entrybuf[2] = (png_byte)ep[i].blue;
  195474. entrybuf[3] = (png_byte)ep[i].alpha;
  195475. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  195476. }
  195477. else
  195478. {
  195479. png_save_uint_16(entrybuf + 0, ep[i].red);
  195480. png_save_uint_16(entrybuf + 2, ep[i].green);
  195481. png_save_uint_16(entrybuf + 4, ep[i].blue);
  195482. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  195483. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  195484. }
  195485. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  195486. }
  195487. #endif
  195488. png_write_chunk_end(png_ptr);
  195489. png_free(png_ptr, new_name);
  195490. }
  195491. #endif
  195492. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  195493. /* write the sBIT chunk */
  195494. void /* PRIVATE */
  195495. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  195496. {
  195497. #ifdef PNG_USE_LOCAL_ARRAYS
  195498. PNG_sBIT;
  195499. #endif
  195500. png_byte buf[4];
  195501. png_size_t size;
  195502. png_debug(1, "in png_write_sBIT\n");
  195503. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  195504. if (color_type & PNG_COLOR_MASK_COLOR)
  195505. {
  195506. png_byte maxbits;
  195507. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  195508. png_ptr->usr_bit_depth);
  195509. if (sbit->red == 0 || sbit->red > maxbits ||
  195510. sbit->green == 0 || sbit->green > maxbits ||
  195511. sbit->blue == 0 || sbit->blue > maxbits)
  195512. {
  195513. png_warning(png_ptr, "Invalid sBIT depth specified");
  195514. return;
  195515. }
  195516. buf[0] = sbit->red;
  195517. buf[1] = sbit->green;
  195518. buf[2] = sbit->blue;
  195519. size = 3;
  195520. }
  195521. else
  195522. {
  195523. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  195524. {
  195525. png_warning(png_ptr, "Invalid sBIT depth specified");
  195526. return;
  195527. }
  195528. buf[0] = sbit->gray;
  195529. size = 1;
  195530. }
  195531. if (color_type & PNG_COLOR_MASK_ALPHA)
  195532. {
  195533. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  195534. {
  195535. png_warning(png_ptr, "Invalid sBIT depth specified");
  195536. return;
  195537. }
  195538. buf[size++] = sbit->alpha;
  195539. }
  195540. png_write_chunk(png_ptr, png_sBIT, buf, size);
  195541. }
  195542. #endif
  195543. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  195544. /* write the cHRM chunk */
  195545. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195546. void /* PRIVATE */
  195547. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  195548. double red_x, double red_y, double green_x, double green_y,
  195549. double blue_x, double blue_y)
  195550. {
  195551. #ifdef PNG_USE_LOCAL_ARRAYS
  195552. PNG_cHRM;
  195553. #endif
  195554. png_byte buf[32];
  195555. png_uint_32 itemp;
  195556. png_debug(1, "in png_write_cHRM\n");
  195557. /* each value is saved in 1/100,000ths */
  195558. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  195559. white_x + white_y > 1.0)
  195560. {
  195561. png_warning(png_ptr, "Invalid cHRM white point specified");
  195562. #if !defined(PNG_NO_CONSOLE_IO)
  195563. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  195564. #endif
  195565. return;
  195566. }
  195567. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  195568. png_save_uint_32(buf, itemp);
  195569. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  195570. png_save_uint_32(buf + 4, itemp);
  195571. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  195572. {
  195573. png_warning(png_ptr, "Invalid cHRM red point specified");
  195574. return;
  195575. }
  195576. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  195577. png_save_uint_32(buf + 8, itemp);
  195578. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  195579. png_save_uint_32(buf + 12, itemp);
  195580. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  195581. {
  195582. png_warning(png_ptr, "Invalid cHRM green point specified");
  195583. return;
  195584. }
  195585. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  195586. png_save_uint_32(buf + 16, itemp);
  195587. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  195588. png_save_uint_32(buf + 20, itemp);
  195589. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  195590. {
  195591. png_warning(png_ptr, "Invalid cHRM blue point specified");
  195592. return;
  195593. }
  195594. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  195595. png_save_uint_32(buf + 24, itemp);
  195596. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  195597. png_save_uint_32(buf + 28, itemp);
  195598. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  195599. }
  195600. #endif
  195601. #ifdef PNG_FIXED_POINT_SUPPORTED
  195602. void /* PRIVATE */
  195603. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  195604. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  195605. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  195606. png_fixed_point blue_y)
  195607. {
  195608. #ifdef PNG_USE_LOCAL_ARRAYS
  195609. PNG_cHRM;
  195610. #endif
  195611. png_byte buf[32];
  195612. png_debug(1, "in png_write_cHRM\n");
  195613. /* each value is saved in 1/100,000ths */
  195614. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  195615. {
  195616. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  195617. #if !defined(PNG_NO_CONSOLE_IO)
  195618. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  195619. #endif
  195620. return;
  195621. }
  195622. png_save_uint_32(buf, (png_uint_32)white_x);
  195623. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  195624. if (red_x + red_y > 100000L)
  195625. {
  195626. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  195627. return;
  195628. }
  195629. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  195630. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  195631. if (green_x + green_y > 100000L)
  195632. {
  195633. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  195634. return;
  195635. }
  195636. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  195637. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  195638. if (blue_x + blue_y > 100000L)
  195639. {
  195640. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  195641. return;
  195642. }
  195643. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  195644. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  195645. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  195646. }
  195647. #endif
  195648. #endif
  195649. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  195650. /* write the tRNS chunk */
  195651. void /* PRIVATE */
  195652. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  195653. int num_trans, int color_type)
  195654. {
  195655. #ifdef PNG_USE_LOCAL_ARRAYS
  195656. PNG_tRNS;
  195657. #endif
  195658. png_byte buf[6];
  195659. png_debug(1, "in png_write_tRNS\n");
  195660. if (color_type == PNG_COLOR_TYPE_PALETTE)
  195661. {
  195662. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  195663. {
  195664. png_warning(png_ptr,"Invalid number of transparent colors specified");
  195665. return;
  195666. }
  195667. /* write the chunk out as it is */
  195668. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  195669. }
  195670. else if (color_type == PNG_COLOR_TYPE_GRAY)
  195671. {
  195672. /* one 16 bit value */
  195673. if(tran->gray >= (1 << png_ptr->bit_depth))
  195674. {
  195675. png_warning(png_ptr,
  195676. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  195677. return;
  195678. }
  195679. png_save_uint_16(buf, tran->gray);
  195680. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  195681. }
  195682. else if (color_type == PNG_COLOR_TYPE_RGB)
  195683. {
  195684. /* three 16 bit values */
  195685. png_save_uint_16(buf, tran->red);
  195686. png_save_uint_16(buf + 2, tran->green);
  195687. png_save_uint_16(buf + 4, tran->blue);
  195688. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  195689. {
  195690. png_warning(png_ptr,
  195691. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  195692. return;
  195693. }
  195694. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  195695. }
  195696. else
  195697. {
  195698. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  195699. }
  195700. }
  195701. #endif
  195702. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  195703. /* write the background chunk */
  195704. void /* PRIVATE */
  195705. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  195706. {
  195707. #ifdef PNG_USE_LOCAL_ARRAYS
  195708. PNG_bKGD;
  195709. #endif
  195710. png_byte buf[6];
  195711. png_debug(1, "in png_write_bKGD\n");
  195712. if (color_type == PNG_COLOR_TYPE_PALETTE)
  195713. {
  195714. if (
  195715. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195716. (png_ptr->num_palette ||
  195717. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  195718. #endif
  195719. back->index > png_ptr->num_palette)
  195720. {
  195721. png_warning(png_ptr, "Invalid background palette index");
  195722. return;
  195723. }
  195724. buf[0] = back->index;
  195725. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  195726. }
  195727. else if (color_type & PNG_COLOR_MASK_COLOR)
  195728. {
  195729. png_save_uint_16(buf, back->red);
  195730. png_save_uint_16(buf + 2, back->green);
  195731. png_save_uint_16(buf + 4, back->blue);
  195732. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  195733. {
  195734. png_warning(png_ptr,
  195735. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  195736. return;
  195737. }
  195738. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  195739. }
  195740. else
  195741. {
  195742. if(back->gray >= (1 << png_ptr->bit_depth))
  195743. {
  195744. png_warning(png_ptr,
  195745. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  195746. return;
  195747. }
  195748. png_save_uint_16(buf, back->gray);
  195749. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  195750. }
  195751. }
  195752. #endif
  195753. #if defined(PNG_WRITE_hIST_SUPPORTED)
  195754. /* write the histogram */
  195755. void /* PRIVATE */
  195756. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  195757. {
  195758. #ifdef PNG_USE_LOCAL_ARRAYS
  195759. PNG_hIST;
  195760. #endif
  195761. int i;
  195762. png_byte buf[3];
  195763. png_debug(1, "in png_write_hIST\n");
  195764. if (num_hist > (int)png_ptr->num_palette)
  195765. {
  195766. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  195767. png_ptr->num_palette);
  195768. png_warning(png_ptr, "Invalid number of histogram entries specified");
  195769. return;
  195770. }
  195771. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  195772. for (i = 0; i < num_hist; i++)
  195773. {
  195774. png_save_uint_16(buf, hist[i]);
  195775. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  195776. }
  195777. png_write_chunk_end(png_ptr);
  195778. }
  195779. #endif
  195780. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  195781. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  195782. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  195783. * and if invalid, correct the keyword rather than discarding the entire
  195784. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  195785. * length, forbids leading or trailing whitespace, multiple internal spaces,
  195786. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  195787. *
  195788. * The new_key is allocated to hold the corrected keyword and must be freed
  195789. * by the calling routine. This avoids problems with trying to write to
  195790. * static keywords without having to have duplicate copies of the strings.
  195791. */
  195792. png_size_t /* PRIVATE */
  195793. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  195794. {
  195795. png_size_t key_len;
  195796. png_charp kp, dp;
  195797. int kflag;
  195798. int kwarn=0;
  195799. png_debug(1, "in png_check_keyword\n");
  195800. *new_key = NULL;
  195801. if (key == NULL || (key_len = png_strlen(key)) == 0)
  195802. {
  195803. png_warning(png_ptr, "zero length keyword");
  195804. return ((png_size_t)0);
  195805. }
  195806. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  195807. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  195808. if (*new_key == NULL)
  195809. {
  195810. png_warning(png_ptr, "Out of memory while procesing keyword");
  195811. return ((png_size_t)0);
  195812. }
  195813. /* Replace non-printing characters with a blank and print a warning */
  195814. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  195815. {
  195816. if ((png_byte)*kp < 0x20 ||
  195817. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  195818. {
  195819. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  195820. char msg[40];
  195821. png_snprintf(msg, 40,
  195822. "invalid keyword character 0x%02X", (png_byte)*kp);
  195823. png_warning(png_ptr, msg);
  195824. #else
  195825. png_warning(png_ptr, "invalid character in keyword");
  195826. #endif
  195827. *dp = ' ';
  195828. }
  195829. else
  195830. {
  195831. *dp = *kp;
  195832. }
  195833. }
  195834. *dp = '\0';
  195835. /* Remove any trailing white space. */
  195836. kp = *new_key + key_len - 1;
  195837. if (*kp == ' ')
  195838. {
  195839. png_warning(png_ptr, "trailing spaces removed from keyword");
  195840. while (*kp == ' ')
  195841. {
  195842. *(kp--) = '\0';
  195843. key_len--;
  195844. }
  195845. }
  195846. /* Remove any leading white space. */
  195847. kp = *new_key;
  195848. if (*kp == ' ')
  195849. {
  195850. png_warning(png_ptr, "leading spaces removed from keyword");
  195851. while (*kp == ' ')
  195852. {
  195853. kp++;
  195854. key_len--;
  195855. }
  195856. }
  195857. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  195858. /* Remove multiple internal spaces. */
  195859. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  195860. {
  195861. if (*kp == ' ' && kflag == 0)
  195862. {
  195863. *(dp++) = *kp;
  195864. kflag = 1;
  195865. }
  195866. else if (*kp == ' ')
  195867. {
  195868. key_len--;
  195869. kwarn=1;
  195870. }
  195871. else
  195872. {
  195873. *(dp++) = *kp;
  195874. kflag = 0;
  195875. }
  195876. }
  195877. *dp = '\0';
  195878. if(kwarn)
  195879. png_warning(png_ptr, "extra interior spaces removed from keyword");
  195880. if (key_len == 0)
  195881. {
  195882. png_free(png_ptr, *new_key);
  195883. *new_key=NULL;
  195884. png_warning(png_ptr, "Zero length keyword");
  195885. }
  195886. if (key_len > 79)
  195887. {
  195888. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  195889. new_key[79] = '\0';
  195890. key_len = 79;
  195891. }
  195892. return (key_len);
  195893. }
  195894. #endif
  195895. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  195896. /* write a tEXt chunk */
  195897. void /* PRIVATE */
  195898. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  195899. png_size_t text_len)
  195900. {
  195901. #ifdef PNG_USE_LOCAL_ARRAYS
  195902. PNG_tEXt;
  195903. #endif
  195904. png_size_t key_len;
  195905. png_charp new_key;
  195906. png_debug(1, "in png_write_tEXt\n");
  195907. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  195908. {
  195909. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  195910. return;
  195911. }
  195912. if (text == NULL || *text == '\0')
  195913. text_len = 0;
  195914. else
  195915. text_len = png_strlen(text);
  195916. /* make sure we include the 0 after the key */
  195917. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  195918. /*
  195919. * We leave it to the application to meet PNG-1.0 requirements on the
  195920. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  195921. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  195922. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  195923. */
  195924. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  195925. if (text_len)
  195926. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  195927. png_write_chunk_end(png_ptr);
  195928. png_free(png_ptr, new_key);
  195929. }
  195930. #endif
  195931. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  195932. /* write a compressed text chunk */
  195933. void /* PRIVATE */
  195934. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  195935. png_size_t text_len, int compression)
  195936. {
  195937. #ifdef PNG_USE_LOCAL_ARRAYS
  195938. PNG_zTXt;
  195939. #endif
  195940. png_size_t key_len;
  195941. char buf[1];
  195942. png_charp new_key;
  195943. compression_state comp;
  195944. png_debug(1, "in png_write_zTXt\n");
  195945. comp.num_output_ptr = 0;
  195946. comp.max_output_ptr = 0;
  195947. comp.output_ptr = NULL;
  195948. comp.input = NULL;
  195949. comp.input_len = 0;
  195950. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  195951. {
  195952. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  195953. return;
  195954. }
  195955. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  195956. {
  195957. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  195958. png_free(png_ptr, new_key);
  195959. return;
  195960. }
  195961. text_len = png_strlen(text);
  195962. /* compute the compressed data; do it now for the length */
  195963. text_len = png_text_compress(png_ptr, text, text_len, compression,
  195964. &comp);
  195965. /* write start of chunk */
  195966. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  195967. (key_len+text_len+2));
  195968. /* write key */
  195969. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  195970. png_free(png_ptr, new_key);
  195971. buf[0] = (png_byte)compression;
  195972. /* write compression */
  195973. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  195974. /* write the compressed data */
  195975. png_write_compressed_data_out(png_ptr, &comp);
  195976. /* close the chunk */
  195977. png_write_chunk_end(png_ptr);
  195978. }
  195979. #endif
  195980. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  195981. /* write an iTXt chunk */
  195982. void /* PRIVATE */
  195983. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  195984. png_charp lang, png_charp lang_key, png_charp text)
  195985. {
  195986. #ifdef PNG_USE_LOCAL_ARRAYS
  195987. PNG_iTXt;
  195988. #endif
  195989. png_size_t lang_len, key_len, lang_key_len, text_len;
  195990. png_charp new_lang, new_key;
  195991. png_byte cbuf[2];
  195992. compression_state comp;
  195993. png_debug(1, "in png_write_iTXt\n");
  195994. comp.num_output_ptr = 0;
  195995. comp.max_output_ptr = 0;
  195996. comp.output_ptr = NULL;
  195997. comp.input = NULL;
  195998. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  195999. {
  196000. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  196001. return;
  196002. }
  196003. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  196004. {
  196005. png_warning(png_ptr, "Empty language field in iTXt chunk");
  196006. new_lang = NULL;
  196007. lang_len = 0;
  196008. }
  196009. if (lang_key == NULL)
  196010. lang_key_len = 0;
  196011. else
  196012. lang_key_len = png_strlen(lang_key);
  196013. if (text == NULL)
  196014. text_len = 0;
  196015. else
  196016. text_len = png_strlen(text);
  196017. /* compute the compressed data; do it now for the length */
  196018. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  196019. &comp);
  196020. /* make sure we include the compression flag, the compression byte,
  196021. * and the NULs after the key, lang, and lang_key parts */
  196022. png_write_chunk_start(png_ptr, png_iTXt,
  196023. (png_uint_32)(
  196024. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  196025. + key_len
  196026. + lang_len
  196027. + lang_key_len
  196028. + text_len));
  196029. /*
  196030. * We leave it to the application to meet PNG-1.0 requirements on the
  196031. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  196032. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  196033. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  196034. */
  196035. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  196036. /* set the compression flag */
  196037. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  196038. compression == PNG_TEXT_COMPRESSION_NONE)
  196039. cbuf[0] = 0;
  196040. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  196041. cbuf[0] = 1;
  196042. /* set the compression method */
  196043. cbuf[1] = 0;
  196044. png_write_chunk_data(png_ptr, cbuf, 2);
  196045. cbuf[0] = 0;
  196046. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  196047. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  196048. png_write_compressed_data_out(png_ptr, &comp);
  196049. png_write_chunk_end(png_ptr);
  196050. png_free(png_ptr, new_key);
  196051. if (new_lang)
  196052. png_free(png_ptr, new_lang);
  196053. }
  196054. #endif
  196055. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  196056. /* write the oFFs chunk */
  196057. void /* PRIVATE */
  196058. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  196059. int unit_type)
  196060. {
  196061. #ifdef PNG_USE_LOCAL_ARRAYS
  196062. PNG_oFFs;
  196063. #endif
  196064. png_byte buf[9];
  196065. png_debug(1, "in png_write_oFFs\n");
  196066. if (unit_type >= PNG_OFFSET_LAST)
  196067. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  196068. png_save_int_32(buf, x_offset);
  196069. png_save_int_32(buf + 4, y_offset);
  196070. buf[8] = (png_byte)unit_type;
  196071. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  196072. }
  196073. #endif
  196074. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  196075. /* write the pCAL chunk (described in the PNG extensions document) */
  196076. void /* PRIVATE */
  196077. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  196078. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  196079. {
  196080. #ifdef PNG_USE_LOCAL_ARRAYS
  196081. PNG_pCAL;
  196082. #endif
  196083. png_size_t purpose_len, units_len, total_len;
  196084. png_uint_32p params_len;
  196085. png_byte buf[10];
  196086. png_charp new_purpose;
  196087. int i;
  196088. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  196089. if (type >= PNG_EQUATION_LAST)
  196090. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  196091. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  196092. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  196093. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  196094. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  196095. total_len = purpose_len + units_len + 10;
  196096. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  196097. *png_sizeof(png_uint_32)));
  196098. /* Find the length of each parameter, making sure we don't count the
  196099. null terminator for the last parameter. */
  196100. for (i = 0; i < nparams; i++)
  196101. {
  196102. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  196103. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  196104. total_len += (png_size_t)params_len[i];
  196105. }
  196106. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  196107. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  196108. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  196109. png_save_int_32(buf, X0);
  196110. png_save_int_32(buf + 4, X1);
  196111. buf[8] = (png_byte)type;
  196112. buf[9] = (png_byte)nparams;
  196113. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  196114. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  196115. png_free(png_ptr, new_purpose);
  196116. for (i = 0; i < nparams; i++)
  196117. {
  196118. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  196119. (png_size_t)params_len[i]);
  196120. }
  196121. png_free(png_ptr, params_len);
  196122. png_write_chunk_end(png_ptr);
  196123. }
  196124. #endif
  196125. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  196126. /* write the sCAL chunk */
  196127. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  196128. void /* PRIVATE */
  196129. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  196130. {
  196131. #ifdef PNG_USE_LOCAL_ARRAYS
  196132. PNG_sCAL;
  196133. #endif
  196134. char buf[64];
  196135. png_size_t total_len;
  196136. png_debug(1, "in png_write_sCAL\n");
  196137. buf[0] = (char)unit;
  196138. #if defined(_WIN32_WCE)
  196139. /* sprintf() function is not supported on WindowsCE */
  196140. {
  196141. wchar_t wc_buf[32];
  196142. size_t wc_len;
  196143. swprintf(wc_buf, TEXT("%12.12e"), width);
  196144. wc_len = wcslen(wc_buf);
  196145. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  196146. total_len = wc_len + 2;
  196147. swprintf(wc_buf, TEXT("%12.12e"), height);
  196148. wc_len = wcslen(wc_buf);
  196149. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  196150. NULL, NULL);
  196151. total_len += wc_len;
  196152. }
  196153. #else
  196154. png_snprintf(buf + 1, 63, "%12.12e", width);
  196155. total_len = 1 + png_strlen(buf + 1) + 1;
  196156. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  196157. total_len += png_strlen(buf + total_len);
  196158. #endif
  196159. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  196160. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  196161. }
  196162. #else
  196163. #ifdef PNG_FIXED_POINT_SUPPORTED
  196164. void /* PRIVATE */
  196165. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  196166. png_charp height)
  196167. {
  196168. #ifdef PNG_USE_LOCAL_ARRAYS
  196169. PNG_sCAL;
  196170. #endif
  196171. png_byte buf[64];
  196172. png_size_t wlen, hlen, total_len;
  196173. png_debug(1, "in png_write_sCAL_s\n");
  196174. wlen = png_strlen(width);
  196175. hlen = png_strlen(height);
  196176. total_len = wlen + hlen + 2;
  196177. if (total_len > 64)
  196178. {
  196179. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  196180. return;
  196181. }
  196182. buf[0] = (png_byte)unit;
  196183. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  196184. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  196185. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  196186. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  196187. }
  196188. #endif
  196189. #endif
  196190. #endif
  196191. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  196192. /* write the pHYs chunk */
  196193. void /* PRIVATE */
  196194. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  196195. png_uint_32 y_pixels_per_unit,
  196196. int unit_type)
  196197. {
  196198. #ifdef PNG_USE_LOCAL_ARRAYS
  196199. PNG_pHYs;
  196200. #endif
  196201. png_byte buf[9];
  196202. png_debug(1, "in png_write_pHYs\n");
  196203. if (unit_type >= PNG_RESOLUTION_LAST)
  196204. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  196205. png_save_uint_32(buf, x_pixels_per_unit);
  196206. png_save_uint_32(buf + 4, y_pixels_per_unit);
  196207. buf[8] = (png_byte)unit_type;
  196208. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  196209. }
  196210. #endif
  196211. #if defined(PNG_WRITE_tIME_SUPPORTED)
  196212. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  196213. * or png_convert_from_time_t(), or fill in the structure yourself.
  196214. */
  196215. void /* PRIVATE */
  196216. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  196217. {
  196218. #ifdef PNG_USE_LOCAL_ARRAYS
  196219. PNG_tIME;
  196220. #endif
  196221. png_byte buf[7];
  196222. png_debug(1, "in png_write_tIME\n");
  196223. if (mod_time->month > 12 || mod_time->month < 1 ||
  196224. mod_time->day > 31 || mod_time->day < 1 ||
  196225. mod_time->hour > 23 || mod_time->second > 60)
  196226. {
  196227. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  196228. return;
  196229. }
  196230. png_save_uint_16(buf, mod_time->year);
  196231. buf[2] = mod_time->month;
  196232. buf[3] = mod_time->day;
  196233. buf[4] = mod_time->hour;
  196234. buf[5] = mod_time->minute;
  196235. buf[6] = mod_time->second;
  196236. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  196237. }
  196238. #endif
  196239. /* initializes the row writing capability of libpng */
  196240. void /* PRIVATE */
  196241. png_write_start_row(png_structp png_ptr)
  196242. {
  196243. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196244. #ifdef PNG_USE_LOCAL_ARRAYS
  196245. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196246. /* start of interlace block */
  196247. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196248. /* offset to next interlace block */
  196249. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196250. /* start of interlace block in the y direction */
  196251. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196252. /* offset to next interlace block in the y direction */
  196253. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196254. #endif
  196255. #endif
  196256. png_size_t buf_size;
  196257. png_debug(1, "in png_write_start_row\n");
  196258. buf_size = (png_size_t)(PNG_ROWBYTES(
  196259. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  196260. /* set up row buffer */
  196261. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  196262. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  196263. #ifndef PNG_NO_WRITE_FILTERING
  196264. /* set up filtering buffer, if using this filter */
  196265. if (png_ptr->do_filter & PNG_FILTER_SUB)
  196266. {
  196267. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  196268. (png_ptr->rowbytes + 1));
  196269. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  196270. }
  196271. /* We only need to keep the previous row if we are using one of these. */
  196272. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  196273. {
  196274. /* set up previous row buffer */
  196275. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  196276. png_memset(png_ptr->prev_row, 0, buf_size);
  196277. if (png_ptr->do_filter & PNG_FILTER_UP)
  196278. {
  196279. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  196280. (png_ptr->rowbytes + 1));
  196281. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  196282. }
  196283. if (png_ptr->do_filter & PNG_FILTER_AVG)
  196284. {
  196285. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  196286. (png_ptr->rowbytes + 1));
  196287. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  196288. }
  196289. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  196290. {
  196291. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  196292. (png_ptr->rowbytes + 1));
  196293. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  196294. }
  196295. #endif /* PNG_NO_WRITE_FILTERING */
  196296. }
  196297. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196298. /* if interlaced, we need to set up width and height of pass */
  196299. if (png_ptr->interlaced)
  196300. {
  196301. if (!(png_ptr->transformations & PNG_INTERLACE))
  196302. {
  196303. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196304. png_pass_ystart[0]) / png_pass_yinc[0];
  196305. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  196306. png_pass_start[0]) / png_pass_inc[0];
  196307. }
  196308. else
  196309. {
  196310. png_ptr->num_rows = png_ptr->height;
  196311. png_ptr->usr_width = png_ptr->width;
  196312. }
  196313. }
  196314. else
  196315. #endif
  196316. {
  196317. png_ptr->num_rows = png_ptr->height;
  196318. png_ptr->usr_width = png_ptr->width;
  196319. }
  196320. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196321. png_ptr->zstream.next_out = png_ptr->zbuf;
  196322. }
  196323. /* Internal use only. Called when finished processing a row of data. */
  196324. void /* PRIVATE */
  196325. png_write_finish_row(png_structp png_ptr)
  196326. {
  196327. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196328. #ifdef PNG_USE_LOCAL_ARRAYS
  196329. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196330. /* start of interlace block */
  196331. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196332. /* offset to next interlace block */
  196333. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196334. /* start of interlace block in the y direction */
  196335. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196336. /* offset to next interlace block in the y direction */
  196337. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196338. #endif
  196339. #endif
  196340. int ret;
  196341. png_debug(1, "in png_write_finish_row\n");
  196342. /* next row */
  196343. png_ptr->row_number++;
  196344. /* see if we are done */
  196345. if (png_ptr->row_number < png_ptr->num_rows)
  196346. return;
  196347. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196348. /* if interlaced, go to next pass */
  196349. if (png_ptr->interlaced)
  196350. {
  196351. png_ptr->row_number = 0;
  196352. if (png_ptr->transformations & PNG_INTERLACE)
  196353. {
  196354. png_ptr->pass++;
  196355. }
  196356. else
  196357. {
  196358. /* loop until we find a non-zero width or height pass */
  196359. do
  196360. {
  196361. png_ptr->pass++;
  196362. if (png_ptr->pass >= 7)
  196363. break;
  196364. png_ptr->usr_width = (png_ptr->width +
  196365. png_pass_inc[png_ptr->pass] - 1 -
  196366. png_pass_start[png_ptr->pass]) /
  196367. png_pass_inc[png_ptr->pass];
  196368. png_ptr->num_rows = (png_ptr->height +
  196369. png_pass_yinc[png_ptr->pass] - 1 -
  196370. png_pass_ystart[png_ptr->pass]) /
  196371. png_pass_yinc[png_ptr->pass];
  196372. if (png_ptr->transformations & PNG_INTERLACE)
  196373. break;
  196374. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  196375. }
  196376. /* reset the row above the image for the next pass */
  196377. if (png_ptr->pass < 7)
  196378. {
  196379. if (png_ptr->prev_row != NULL)
  196380. png_memset(png_ptr->prev_row, 0,
  196381. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  196382. png_ptr->usr_bit_depth,png_ptr->width))+1);
  196383. return;
  196384. }
  196385. }
  196386. #endif
  196387. /* if we get here, we've just written the last row, so we need
  196388. to flush the compressor */
  196389. do
  196390. {
  196391. /* tell the compressor we are done */
  196392. ret = deflate(&png_ptr->zstream, Z_FINISH);
  196393. /* check for an error */
  196394. if (ret == Z_OK)
  196395. {
  196396. /* check to see if we need more room */
  196397. if (!(png_ptr->zstream.avail_out))
  196398. {
  196399. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  196400. png_ptr->zstream.next_out = png_ptr->zbuf;
  196401. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196402. }
  196403. }
  196404. else if (ret != Z_STREAM_END)
  196405. {
  196406. if (png_ptr->zstream.msg != NULL)
  196407. png_error(png_ptr, png_ptr->zstream.msg);
  196408. else
  196409. png_error(png_ptr, "zlib error");
  196410. }
  196411. } while (ret != Z_STREAM_END);
  196412. /* write any extra space */
  196413. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  196414. {
  196415. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  196416. png_ptr->zstream.avail_out);
  196417. }
  196418. deflateReset(&png_ptr->zstream);
  196419. png_ptr->zstream.data_type = Z_BINARY;
  196420. }
  196421. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  196422. /* Pick out the correct pixels for the interlace pass.
  196423. * The basic idea here is to go through the row with a source
  196424. * pointer and a destination pointer (sp and dp), and copy the
  196425. * correct pixels for the pass. As the row gets compacted,
  196426. * sp will always be >= dp, so we should never overwrite anything.
  196427. * See the default: case for the easiest code to understand.
  196428. */
  196429. void /* PRIVATE */
  196430. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  196431. {
  196432. #ifdef PNG_USE_LOCAL_ARRAYS
  196433. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196434. /* start of interlace block */
  196435. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196436. /* offset to next interlace block */
  196437. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196438. #endif
  196439. png_debug(1, "in png_do_write_interlace\n");
  196440. /* we don't have to do anything on the last pass (6) */
  196441. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196442. if (row != NULL && row_info != NULL && pass < 6)
  196443. #else
  196444. if (pass < 6)
  196445. #endif
  196446. {
  196447. /* each pixel depth is handled separately */
  196448. switch (row_info->pixel_depth)
  196449. {
  196450. case 1:
  196451. {
  196452. png_bytep sp;
  196453. png_bytep dp;
  196454. int shift;
  196455. int d;
  196456. int value;
  196457. png_uint_32 i;
  196458. png_uint_32 row_width = row_info->width;
  196459. dp = row;
  196460. d = 0;
  196461. shift = 7;
  196462. for (i = png_pass_start[pass]; i < row_width;
  196463. i += png_pass_inc[pass])
  196464. {
  196465. sp = row + (png_size_t)(i >> 3);
  196466. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  196467. d |= (value << shift);
  196468. if (shift == 0)
  196469. {
  196470. shift = 7;
  196471. *dp++ = (png_byte)d;
  196472. d = 0;
  196473. }
  196474. else
  196475. shift--;
  196476. }
  196477. if (shift != 7)
  196478. *dp = (png_byte)d;
  196479. break;
  196480. }
  196481. case 2:
  196482. {
  196483. png_bytep sp;
  196484. png_bytep dp;
  196485. int shift;
  196486. int d;
  196487. int value;
  196488. png_uint_32 i;
  196489. png_uint_32 row_width = row_info->width;
  196490. dp = row;
  196491. shift = 6;
  196492. d = 0;
  196493. for (i = png_pass_start[pass]; i < row_width;
  196494. i += png_pass_inc[pass])
  196495. {
  196496. sp = row + (png_size_t)(i >> 2);
  196497. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  196498. d |= (value << shift);
  196499. if (shift == 0)
  196500. {
  196501. shift = 6;
  196502. *dp++ = (png_byte)d;
  196503. d = 0;
  196504. }
  196505. else
  196506. shift -= 2;
  196507. }
  196508. if (shift != 6)
  196509. *dp = (png_byte)d;
  196510. break;
  196511. }
  196512. case 4:
  196513. {
  196514. png_bytep sp;
  196515. png_bytep dp;
  196516. int shift;
  196517. int d;
  196518. int value;
  196519. png_uint_32 i;
  196520. png_uint_32 row_width = row_info->width;
  196521. dp = row;
  196522. shift = 4;
  196523. d = 0;
  196524. for (i = png_pass_start[pass]; i < row_width;
  196525. i += png_pass_inc[pass])
  196526. {
  196527. sp = row + (png_size_t)(i >> 1);
  196528. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  196529. d |= (value << shift);
  196530. if (shift == 0)
  196531. {
  196532. shift = 4;
  196533. *dp++ = (png_byte)d;
  196534. d = 0;
  196535. }
  196536. else
  196537. shift -= 4;
  196538. }
  196539. if (shift != 4)
  196540. *dp = (png_byte)d;
  196541. break;
  196542. }
  196543. default:
  196544. {
  196545. png_bytep sp;
  196546. png_bytep dp;
  196547. png_uint_32 i;
  196548. png_uint_32 row_width = row_info->width;
  196549. png_size_t pixel_bytes;
  196550. /* start at the beginning */
  196551. dp = row;
  196552. /* find out how many bytes each pixel takes up */
  196553. pixel_bytes = (row_info->pixel_depth >> 3);
  196554. /* loop through the row, only looking at the pixels that
  196555. matter */
  196556. for (i = png_pass_start[pass]; i < row_width;
  196557. i += png_pass_inc[pass])
  196558. {
  196559. /* find out where the original pixel is */
  196560. sp = row + (png_size_t)i * pixel_bytes;
  196561. /* move the pixel */
  196562. if (dp != sp)
  196563. png_memcpy(dp, sp, pixel_bytes);
  196564. /* next pixel */
  196565. dp += pixel_bytes;
  196566. }
  196567. break;
  196568. }
  196569. }
  196570. /* set new row width */
  196571. row_info->width = (row_info->width +
  196572. png_pass_inc[pass] - 1 -
  196573. png_pass_start[pass]) /
  196574. png_pass_inc[pass];
  196575. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  196576. row_info->width);
  196577. }
  196578. }
  196579. #endif
  196580. /* This filters the row, chooses which filter to use, if it has not already
  196581. * been specified by the application, and then writes the row out with the
  196582. * chosen filter.
  196583. */
  196584. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  196585. #define PNG_HISHIFT 10
  196586. #define PNG_LOMASK ((png_uint_32)0xffffL)
  196587. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  196588. void /* PRIVATE */
  196589. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  196590. {
  196591. png_bytep best_row;
  196592. #ifndef PNG_NO_WRITE_FILTER
  196593. png_bytep prev_row, row_buf;
  196594. png_uint_32 mins, bpp;
  196595. png_byte filter_to_do = png_ptr->do_filter;
  196596. png_uint_32 row_bytes = row_info->rowbytes;
  196597. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196598. int num_p_filters = (int)png_ptr->num_prev_filters;
  196599. #endif
  196600. png_debug(1, "in png_write_find_filter\n");
  196601. /* find out how many bytes offset each pixel is */
  196602. bpp = (row_info->pixel_depth + 7) >> 3;
  196603. prev_row = png_ptr->prev_row;
  196604. #endif
  196605. best_row = png_ptr->row_buf;
  196606. #ifndef PNG_NO_WRITE_FILTER
  196607. row_buf = best_row;
  196608. mins = PNG_MAXSUM;
  196609. /* The prediction method we use is to find which method provides the
  196610. * smallest value when summing the absolute values of the distances
  196611. * from zero, using anything >= 128 as negative numbers. This is known
  196612. * as the "minimum sum of absolute differences" heuristic. Other
  196613. * heuristics are the "weighted minimum sum of absolute differences"
  196614. * (experimental and can in theory improve compression), and the "zlib
  196615. * predictive" method (not implemented yet), which does test compressions
  196616. * of lines using different filter methods, and then chooses the
  196617. * (series of) filter(s) that give minimum compressed data size (VERY
  196618. * computationally expensive).
  196619. *
  196620. * GRR 980525: consider also
  196621. * (1) minimum sum of absolute differences from running average (i.e.,
  196622. * keep running sum of non-absolute differences & count of bytes)
  196623. * [track dispersion, too? restart average if dispersion too large?]
  196624. * (1b) minimum sum of absolute differences from sliding average, probably
  196625. * with window size <= deflate window (usually 32K)
  196626. * (2) minimum sum of squared differences from zero or running average
  196627. * (i.e., ~ root-mean-square approach)
  196628. */
  196629. /* We don't need to test the 'no filter' case if this is the only filter
  196630. * that has been chosen, as it doesn't actually do anything to the data.
  196631. */
  196632. if ((filter_to_do & PNG_FILTER_NONE) &&
  196633. filter_to_do != PNG_FILTER_NONE)
  196634. {
  196635. png_bytep rp;
  196636. png_uint_32 sum = 0;
  196637. png_uint_32 i;
  196638. int v;
  196639. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  196640. {
  196641. v = *rp;
  196642. sum += (v < 128) ? v : 256 - v;
  196643. }
  196644. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196645. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196646. {
  196647. png_uint_32 sumhi, sumlo;
  196648. int j;
  196649. sumlo = sum & PNG_LOMASK;
  196650. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  196651. /* Reduce the sum if we match any of the previous rows */
  196652. for (j = 0; j < num_p_filters; j++)
  196653. {
  196654. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  196655. {
  196656. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  196657. PNG_WEIGHT_SHIFT;
  196658. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  196659. PNG_WEIGHT_SHIFT;
  196660. }
  196661. }
  196662. /* Factor in the cost of this filter (this is here for completeness,
  196663. * but it makes no sense to have a "cost" for the NONE filter, as
  196664. * it has the minimum possible computational cost - none).
  196665. */
  196666. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  196667. PNG_COST_SHIFT;
  196668. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  196669. PNG_COST_SHIFT;
  196670. if (sumhi > PNG_HIMASK)
  196671. sum = PNG_MAXSUM;
  196672. else
  196673. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196674. }
  196675. #endif
  196676. mins = sum;
  196677. }
  196678. /* sub filter */
  196679. if (filter_to_do == PNG_FILTER_SUB)
  196680. /* it's the only filter so no testing is needed */
  196681. {
  196682. png_bytep rp, lp, dp;
  196683. png_uint_32 i;
  196684. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  196685. i++, rp++, dp++)
  196686. {
  196687. *dp = *rp;
  196688. }
  196689. for (lp = row_buf + 1; i < row_bytes;
  196690. i++, rp++, lp++, dp++)
  196691. {
  196692. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  196693. }
  196694. best_row = png_ptr->sub_row;
  196695. }
  196696. else if (filter_to_do & PNG_FILTER_SUB)
  196697. {
  196698. png_bytep rp, dp, lp;
  196699. png_uint_32 sum = 0, lmins = mins;
  196700. png_uint_32 i;
  196701. int v;
  196702. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196703. /* We temporarily increase the "minimum sum" by the factor we
  196704. * would reduce the sum of this filter, so that we can do the
  196705. * early exit comparison without scaling the sum each time.
  196706. */
  196707. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196708. {
  196709. int j;
  196710. png_uint_32 lmhi, lmlo;
  196711. lmlo = lmins & PNG_LOMASK;
  196712. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196713. for (j = 0; j < num_p_filters; j++)
  196714. {
  196715. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  196716. {
  196717. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196718. PNG_WEIGHT_SHIFT;
  196719. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196720. PNG_WEIGHT_SHIFT;
  196721. }
  196722. }
  196723. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  196724. PNG_COST_SHIFT;
  196725. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  196726. PNG_COST_SHIFT;
  196727. if (lmhi > PNG_HIMASK)
  196728. lmins = PNG_MAXSUM;
  196729. else
  196730. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196731. }
  196732. #endif
  196733. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  196734. i++, rp++, dp++)
  196735. {
  196736. v = *dp = *rp;
  196737. sum += (v < 128) ? v : 256 - v;
  196738. }
  196739. for (lp = row_buf + 1; i < row_bytes;
  196740. i++, rp++, lp++, dp++)
  196741. {
  196742. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  196743. sum += (v < 128) ? v : 256 - v;
  196744. if (sum > lmins) /* We are already worse, don't continue. */
  196745. break;
  196746. }
  196747. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196748. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196749. {
  196750. int j;
  196751. png_uint_32 sumhi, sumlo;
  196752. sumlo = sum & PNG_LOMASK;
  196753. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196754. for (j = 0; j < num_p_filters; j++)
  196755. {
  196756. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  196757. {
  196758. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  196759. PNG_WEIGHT_SHIFT;
  196760. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  196761. PNG_WEIGHT_SHIFT;
  196762. }
  196763. }
  196764. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  196765. PNG_COST_SHIFT;
  196766. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  196767. PNG_COST_SHIFT;
  196768. if (sumhi > PNG_HIMASK)
  196769. sum = PNG_MAXSUM;
  196770. else
  196771. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196772. }
  196773. #endif
  196774. if (sum < mins)
  196775. {
  196776. mins = sum;
  196777. best_row = png_ptr->sub_row;
  196778. }
  196779. }
  196780. /* up filter */
  196781. if (filter_to_do == PNG_FILTER_UP)
  196782. {
  196783. png_bytep rp, dp, pp;
  196784. png_uint_32 i;
  196785. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  196786. pp = prev_row + 1; i < row_bytes;
  196787. i++, rp++, pp++, dp++)
  196788. {
  196789. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  196790. }
  196791. best_row = png_ptr->up_row;
  196792. }
  196793. else if (filter_to_do & PNG_FILTER_UP)
  196794. {
  196795. png_bytep rp, dp, pp;
  196796. png_uint_32 sum = 0, lmins = mins;
  196797. png_uint_32 i;
  196798. int v;
  196799. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196800. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196801. {
  196802. int j;
  196803. png_uint_32 lmhi, lmlo;
  196804. lmlo = lmins & PNG_LOMASK;
  196805. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196806. for (j = 0; j < num_p_filters; j++)
  196807. {
  196808. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  196809. {
  196810. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196811. PNG_WEIGHT_SHIFT;
  196812. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196813. PNG_WEIGHT_SHIFT;
  196814. }
  196815. }
  196816. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  196817. PNG_COST_SHIFT;
  196818. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  196819. PNG_COST_SHIFT;
  196820. if (lmhi > PNG_HIMASK)
  196821. lmins = PNG_MAXSUM;
  196822. else
  196823. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196824. }
  196825. #endif
  196826. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  196827. pp = prev_row + 1; i < row_bytes; i++)
  196828. {
  196829. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  196830. sum += (v < 128) ? v : 256 - v;
  196831. if (sum > lmins) /* We are already worse, don't continue. */
  196832. break;
  196833. }
  196834. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196835. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196836. {
  196837. int j;
  196838. png_uint_32 sumhi, sumlo;
  196839. sumlo = sum & PNG_LOMASK;
  196840. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196841. for (j = 0; j < num_p_filters; j++)
  196842. {
  196843. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  196844. {
  196845. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  196846. PNG_WEIGHT_SHIFT;
  196847. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  196848. PNG_WEIGHT_SHIFT;
  196849. }
  196850. }
  196851. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  196852. PNG_COST_SHIFT;
  196853. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  196854. PNG_COST_SHIFT;
  196855. if (sumhi > PNG_HIMASK)
  196856. sum = PNG_MAXSUM;
  196857. else
  196858. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196859. }
  196860. #endif
  196861. if (sum < mins)
  196862. {
  196863. mins = sum;
  196864. best_row = png_ptr->up_row;
  196865. }
  196866. }
  196867. /* avg filter */
  196868. if (filter_to_do == PNG_FILTER_AVG)
  196869. {
  196870. png_bytep rp, dp, pp, lp;
  196871. png_uint_32 i;
  196872. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  196873. pp = prev_row + 1; i < bpp; i++)
  196874. {
  196875. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  196876. }
  196877. for (lp = row_buf + 1; i < row_bytes; i++)
  196878. {
  196879. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  196880. & 0xff);
  196881. }
  196882. best_row = png_ptr->avg_row;
  196883. }
  196884. else if (filter_to_do & PNG_FILTER_AVG)
  196885. {
  196886. png_bytep rp, dp, pp, lp;
  196887. png_uint_32 sum = 0, lmins = mins;
  196888. png_uint_32 i;
  196889. int v;
  196890. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196891. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196892. {
  196893. int j;
  196894. png_uint_32 lmhi, lmlo;
  196895. lmlo = lmins & PNG_LOMASK;
  196896. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196897. for (j = 0; j < num_p_filters; j++)
  196898. {
  196899. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  196900. {
  196901. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196902. PNG_WEIGHT_SHIFT;
  196903. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196904. PNG_WEIGHT_SHIFT;
  196905. }
  196906. }
  196907. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196908. PNG_COST_SHIFT;
  196909. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196910. PNG_COST_SHIFT;
  196911. if (lmhi > PNG_HIMASK)
  196912. lmins = PNG_MAXSUM;
  196913. else
  196914. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196915. }
  196916. #endif
  196917. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  196918. pp = prev_row + 1; i < bpp; i++)
  196919. {
  196920. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  196921. sum += (v < 128) ? v : 256 - v;
  196922. }
  196923. for (lp = row_buf + 1; i < row_bytes; i++)
  196924. {
  196925. v = *dp++ =
  196926. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  196927. sum += (v < 128) ? v : 256 - v;
  196928. if (sum > lmins) /* We are already worse, don't continue. */
  196929. break;
  196930. }
  196931. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196932. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196933. {
  196934. int j;
  196935. png_uint_32 sumhi, sumlo;
  196936. sumlo = sum & PNG_LOMASK;
  196937. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196938. for (j = 0; j < num_p_filters; j++)
  196939. {
  196940. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  196941. {
  196942. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  196943. PNG_WEIGHT_SHIFT;
  196944. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  196945. PNG_WEIGHT_SHIFT;
  196946. }
  196947. }
  196948. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196949. PNG_COST_SHIFT;
  196950. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196951. PNG_COST_SHIFT;
  196952. if (sumhi > PNG_HIMASK)
  196953. sum = PNG_MAXSUM;
  196954. else
  196955. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196956. }
  196957. #endif
  196958. if (sum < mins)
  196959. {
  196960. mins = sum;
  196961. best_row = png_ptr->avg_row;
  196962. }
  196963. }
  196964. /* Paeth filter */
  196965. if (filter_to_do == PNG_FILTER_PAETH)
  196966. {
  196967. png_bytep rp, dp, pp, cp, lp;
  196968. png_uint_32 i;
  196969. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  196970. pp = prev_row + 1; i < bpp; i++)
  196971. {
  196972. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  196973. }
  196974. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  196975. {
  196976. int a, b, c, pa, pb, pc, p;
  196977. b = *pp++;
  196978. c = *cp++;
  196979. a = *lp++;
  196980. p = b - c;
  196981. pc = a - c;
  196982. #ifdef PNG_USE_ABS
  196983. pa = abs(p);
  196984. pb = abs(pc);
  196985. pc = abs(p + pc);
  196986. #else
  196987. pa = p < 0 ? -p : p;
  196988. pb = pc < 0 ? -pc : pc;
  196989. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196990. #endif
  196991. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196992. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  196993. }
  196994. best_row = png_ptr->paeth_row;
  196995. }
  196996. else if (filter_to_do & PNG_FILTER_PAETH)
  196997. {
  196998. png_bytep rp, dp, pp, cp, lp;
  196999. png_uint_32 sum = 0, lmins = mins;
  197000. png_uint_32 i;
  197001. int v;
  197002. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197003. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197004. {
  197005. int j;
  197006. png_uint_32 lmhi, lmlo;
  197007. lmlo = lmins & PNG_LOMASK;
  197008. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  197009. for (j = 0; j < num_p_filters; j++)
  197010. {
  197011. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  197012. {
  197013. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  197014. PNG_WEIGHT_SHIFT;
  197015. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  197016. PNG_WEIGHT_SHIFT;
  197017. }
  197018. }
  197019. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  197020. PNG_COST_SHIFT;
  197021. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  197022. PNG_COST_SHIFT;
  197023. if (lmhi > PNG_HIMASK)
  197024. lmins = PNG_MAXSUM;
  197025. else
  197026. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  197027. }
  197028. #endif
  197029. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  197030. pp = prev_row + 1; i < bpp; i++)
  197031. {
  197032. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  197033. sum += (v < 128) ? v : 256 - v;
  197034. }
  197035. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  197036. {
  197037. int a, b, c, pa, pb, pc, p;
  197038. b = *pp++;
  197039. c = *cp++;
  197040. a = *lp++;
  197041. #ifndef PNG_SLOW_PAETH
  197042. p = b - c;
  197043. pc = a - c;
  197044. #ifdef PNG_USE_ABS
  197045. pa = abs(p);
  197046. pb = abs(pc);
  197047. pc = abs(p + pc);
  197048. #else
  197049. pa = p < 0 ? -p : p;
  197050. pb = pc < 0 ? -pc : pc;
  197051. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  197052. #endif
  197053. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  197054. #else /* PNG_SLOW_PAETH */
  197055. p = a + b - c;
  197056. pa = abs(p - a);
  197057. pb = abs(p - b);
  197058. pc = abs(p - c);
  197059. if (pa <= pb && pa <= pc)
  197060. p = a;
  197061. else if (pb <= pc)
  197062. p = b;
  197063. else
  197064. p = c;
  197065. #endif /* PNG_SLOW_PAETH */
  197066. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  197067. sum += (v < 128) ? v : 256 - v;
  197068. if (sum > lmins) /* We are already worse, don't continue. */
  197069. break;
  197070. }
  197071. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197072. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  197073. {
  197074. int j;
  197075. png_uint_32 sumhi, sumlo;
  197076. sumlo = sum & PNG_LOMASK;
  197077. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  197078. for (j = 0; j < num_p_filters; j++)
  197079. {
  197080. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  197081. {
  197082. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  197083. PNG_WEIGHT_SHIFT;
  197084. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  197085. PNG_WEIGHT_SHIFT;
  197086. }
  197087. }
  197088. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  197089. PNG_COST_SHIFT;
  197090. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  197091. PNG_COST_SHIFT;
  197092. if (sumhi > PNG_HIMASK)
  197093. sum = PNG_MAXSUM;
  197094. else
  197095. sum = (sumhi << PNG_HISHIFT) + sumlo;
  197096. }
  197097. #endif
  197098. if (sum < mins)
  197099. {
  197100. best_row = png_ptr->paeth_row;
  197101. }
  197102. }
  197103. #endif /* PNG_NO_WRITE_FILTER */
  197104. /* Do the actual writing of the filtered row data from the chosen filter. */
  197105. png_write_filtered_row(png_ptr, best_row);
  197106. #ifndef PNG_NO_WRITE_FILTER
  197107. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  197108. /* Save the type of filter we picked this time for future calculations */
  197109. if (png_ptr->num_prev_filters > 0)
  197110. {
  197111. int j;
  197112. for (j = 1; j < num_p_filters; j++)
  197113. {
  197114. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  197115. }
  197116. png_ptr->prev_filters[j] = best_row[0];
  197117. }
  197118. #endif
  197119. #endif /* PNG_NO_WRITE_FILTER */
  197120. }
  197121. /* Do the actual writing of a previously filtered row. */
  197122. void /* PRIVATE */
  197123. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  197124. {
  197125. png_debug(1, "in png_write_filtered_row\n");
  197126. png_debug1(2, "filter = %d\n", filtered_row[0]);
  197127. /* set up the zlib input buffer */
  197128. png_ptr->zstream.next_in = filtered_row;
  197129. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  197130. /* repeat until we have compressed all the data */
  197131. do
  197132. {
  197133. int ret; /* return of zlib */
  197134. /* compress the data */
  197135. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  197136. /* check for compression errors */
  197137. if (ret != Z_OK)
  197138. {
  197139. if (png_ptr->zstream.msg != NULL)
  197140. png_error(png_ptr, png_ptr->zstream.msg);
  197141. else
  197142. png_error(png_ptr, "zlib error");
  197143. }
  197144. /* see if it is time to write another IDAT */
  197145. if (!(png_ptr->zstream.avail_out))
  197146. {
  197147. /* write the IDAT and reset the zlib output buffer */
  197148. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  197149. png_ptr->zstream.next_out = png_ptr->zbuf;
  197150. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197151. }
  197152. /* repeat until all data has been compressed */
  197153. } while (png_ptr->zstream.avail_in);
  197154. /* swap the current and previous rows */
  197155. if (png_ptr->prev_row != NULL)
  197156. {
  197157. png_bytep tptr;
  197158. tptr = png_ptr->prev_row;
  197159. png_ptr->prev_row = png_ptr->row_buf;
  197160. png_ptr->row_buf = tptr;
  197161. }
  197162. /* finish row - updates counters and flushes zlib if last row */
  197163. png_write_finish_row(png_ptr);
  197164. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  197165. png_ptr->flush_rows++;
  197166. if (png_ptr->flush_dist > 0 &&
  197167. png_ptr->flush_rows >= png_ptr->flush_dist)
  197168. {
  197169. png_write_flush(png_ptr);
  197170. }
  197171. #endif
  197172. }
  197173. #endif /* PNG_WRITE_SUPPORTED */
  197174. /********* End of inlined file: pngwutil.c *********/
  197175. }
  197176. }
  197177. #ifdef _MSC_VER
  197178. #pragma warning (pop)
  197179. #endif
  197180. BEGIN_JUCE_NAMESPACE
  197181. using namespace pnglibNamespace;
  197182. using ::malloc;
  197183. using ::free;
  197184. static void pngReadCallback (png_structp pngReadStruct, png_bytep data, png_size_t length) throw()
  197185. {
  197186. InputStream* const in = (InputStream*) png_get_io_ptr (pngReadStruct);
  197187. in->read (data, (int) length);
  197188. }
  197189. struct PNGErrorStruct {};
  197190. static void pngErrorCallback (png_structp, png_const_charp)
  197191. {
  197192. throw PNGErrorStruct();
  197193. }
  197194. Image* juce_loadPNGImageFromStream (InputStream& in) throw()
  197195. {
  197196. Image* image = 0;
  197197. png_structp pngReadStruct;
  197198. png_infop pngInfoStruct;
  197199. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  197200. if (pngReadStruct != 0)
  197201. {
  197202. pngInfoStruct = png_create_info_struct (pngReadStruct);
  197203. if (pngInfoStruct == 0)
  197204. {
  197205. png_destroy_read_struct (&pngReadStruct, 0, 0);
  197206. return 0;
  197207. }
  197208. png_set_error_fn (pngReadStruct, 0, pngErrorCallback, pngErrorCallback);
  197209. // read the header..
  197210. png_set_read_fn (pngReadStruct, &in, pngReadCallback);
  197211. png_uint_32 width, height;
  197212. int bitDepth, colorType, interlaceType;
  197213. try
  197214. {
  197215. png_read_info (pngReadStruct, pngInfoStruct);
  197216. png_get_IHDR (pngReadStruct, pngInfoStruct,
  197217. &width, &height,
  197218. &bitDepth, &colorType,
  197219. &interlaceType, 0, 0);
  197220. }
  197221. catch (...)
  197222. {
  197223. png_destroy_read_struct (&pngReadStruct, 0, 0);
  197224. return 0;
  197225. }
  197226. if (bitDepth == 16)
  197227. png_set_strip_16 (pngReadStruct);
  197228. if (colorType == PNG_COLOR_TYPE_PALETTE)
  197229. png_set_expand (pngReadStruct);
  197230. if (bitDepth < 8)
  197231. png_set_expand (pngReadStruct);
  197232. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  197233. png_set_expand (pngReadStruct);
  197234. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  197235. png_set_gray_to_rgb (pngReadStruct);
  197236. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  197237. const bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  197238. || pngInfoStruct->num_trans > 0;
  197239. // Load the image into a temp buffer in the pnglib format..
  197240. uint8* const tempBuffer = (uint8*) juce_malloc (height * (width << 2));
  197241. png_bytepp rows = (png_bytepp) juce_malloc (sizeof (png_bytep) * height);
  197242. int y;
  197243. for (y = (int) height; --y >= 0;)
  197244. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  197245. bool crashed = false;
  197246. try
  197247. {
  197248. png_read_image (pngReadStruct, rows);
  197249. png_read_end (pngReadStruct, pngInfoStruct);
  197250. }
  197251. catch (...)
  197252. {
  197253. crashed = true;
  197254. }
  197255. juce_free (rows);
  197256. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  197257. if (crashed)
  197258. return 0;
  197259. // now convert the data to a juce image format..
  197260. image = new Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  197261. width, height, hasAlphaChan);
  197262. int stride, pixelStride;
  197263. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  197264. uint8* srcRow = tempBuffer;
  197265. uint8* destRow = pixels;
  197266. for (y = 0; y < (int) height; ++y)
  197267. {
  197268. const uint8* src = srcRow;
  197269. srcRow += (width << 2);
  197270. uint8* dest = destRow;
  197271. destRow += stride;
  197272. if (hasAlphaChan)
  197273. {
  197274. for (int i = width; --i >= 0;)
  197275. {
  197276. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  197277. ((PixelARGB*) dest)->premultiply();
  197278. dest += pixelStride;
  197279. src += 4;
  197280. }
  197281. }
  197282. else
  197283. {
  197284. for (int i = width; --i >= 0;)
  197285. {
  197286. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  197287. dest += pixelStride;
  197288. src += 4;
  197289. }
  197290. }
  197291. }
  197292. image->releasePixelDataReadWrite (pixels);
  197293. juce_free (tempBuffer);
  197294. }
  197295. return image;
  197296. }
  197297. static void pngWriteDataCallback (png_structp png_ptr, png_bytep data, png_size_t length) throw()
  197298. {
  197299. OutputStream* const out = (OutputStream*) png_ptr->io_ptr;
  197300. const bool ok = out->write (data, length);
  197301. (void) ok;
  197302. jassert (ok);
  197303. }
  197304. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw()
  197305. {
  197306. const int width = image.getWidth();
  197307. const int height = image.getHeight();
  197308. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  197309. if (pngWriteStruct == 0)
  197310. return false;
  197311. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  197312. if (pngInfoStruct == 0)
  197313. {
  197314. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  197315. return false;
  197316. }
  197317. png_set_write_fn (pngWriteStruct, &out, pngWriteDataCallback, 0);
  197318. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  197319. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  197320. : PNG_COLOR_TYPE_RGB,
  197321. PNG_INTERLACE_NONE,
  197322. PNG_COMPRESSION_TYPE_BASE,
  197323. PNG_FILTER_TYPE_BASE);
  197324. png_bytep rowData = (png_bytep) juce_malloc (width * 4 * sizeof (png_byte));
  197325. png_color_8 sig_bit;
  197326. sig_bit.red = 8;
  197327. sig_bit.green = 8;
  197328. sig_bit.blue = 8;
  197329. sig_bit.alpha = 8;
  197330. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  197331. png_write_info (pngWriteStruct, pngInfoStruct);
  197332. png_set_shift (pngWriteStruct, &sig_bit);
  197333. png_set_packing (pngWriteStruct);
  197334. for (int y = 0; y < height; ++y)
  197335. {
  197336. uint8* dst = (uint8*) rowData;
  197337. int stride, pixelStride;
  197338. const uint8* pixels = image.lockPixelDataReadOnly (0, y, width, 1, stride, pixelStride);
  197339. const uint8* src = pixels;
  197340. if (image.hasAlphaChannel())
  197341. {
  197342. for (int i = width; --i >= 0;)
  197343. {
  197344. PixelARGB p (*(const PixelARGB*) src);
  197345. p.unpremultiply();
  197346. *dst++ = p.getRed();
  197347. *dst++ = p.getGreen();
  197348. *dst++ = p.getBlue();
  197349. *dst++ = p.getAlpha();
  197350. src += pixelStride;
  197351. }
  197352. }
  197353. else
  197354. {
  197355. for (int i = width; --i >= 0;)
  197356. {
  197357. *dst++ = ((const PixelRGB*) src)->getRed();
  197358. *dst++ = ((const PixelRGB*) src)->getGreen();
  197359. *dst++ = ((const PixelRGB*) src)->getBlue();
  197360. src += pixelStride;
  197361. }
  197362. }
  197363. png_write_rows (pngWriteStruct, &rowData, 1);
  197364. image.releasePixelDataReadOnly (pixels);
  197365. }
  197366. juce_free (rowData);
  197367. png_write_end (pngWriteStruct, pngInfoStruct);
  197368. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  197369. out.flush();
  197370. return true;
  197371. }
  197372. END_JUCE_NAMESPACE
  197373. /********* End of inlined file: juce_PNGLoader.cpp *********/
  197374. #endif
  197375. //==============================================================================
  197376. #if JUCE_WIN32
  197377. /********* Start of inlined file: juce_win32_Files.cpp *********/
  197378. #ifdef _MSC_VER
  197379. #pragma warning (disable: 4514)
  197380. #pragma warning (push)
  197381. #endif
  197382. #include <ctime>
  197383. #ifndef _WIN32_IE
  197384. #define _WIN32_IE 0x0400
  197385. #endif
  197386. #include <shlobj.h>
  197387. #ifndef CSIDL_MYMUSIC
  197388. #define CSIDL_MYMUSIC 0x000d
  197389. #endif
  197390. #ifndef CSIDL_MYVIDEO
  197391. #define CSIDL_MYVIDEO 0x000e
  197392. #endif
  197393. BEGIN_JUCE_NAMESPACE
  197394. #ifdef _MSC_VER
  197395. #pragma warning (pop)
  197396. #endif
  197397. const tchar File::separator = T('\\');
  197398. const tchar* File::separatorString = T("\\");
  197399. bool juce_fileExists (const String& fileName,
  197400. const bool dontCountDirectories) throw()
  197401. {
  197402. if (fileName.isEmpty())
  197403. return false;
  197404. const DWORD attr = GetFileAttributes (fileName);
  197405. return dontCountDirectories ? ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
  197406. : (attr != 0xffffffff);
  197407. }
  197408. bool juce_isDirectory (const String& fileName) throw()
  197409. {
  197410. const DWORD attr = GetFileAttributes (fileName);
  197411. return (attr != 0xffffffff)
  197412. && ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
  197413. }
  197414. bool juce_canWriteToFile (const String& fileName) throw()
  197415. {
  197416. const DWORD attr = GetFileAttributes (fileName);
  197417. return ((attr & FILE_ATTRIBUTE_READONLY) == 0);
  197418. }
  197419. bool juce_setFileReadOnly (const String& fileName,
  197420. bool isReadOnly)
  197421. {
  197422. DWORD attr = GetFileAttributes (fileName);
  197423. if (attr == 0xffffffff)
  197424. return false;
  197425. if (isReadOnly != juce_canWriteToFile (fileName))
  197426. return true;
  197427. if (isReadOnly)
  197428. attr |= FILE_ATTRIBUTE_READONLY;
  197429. else
  197430. attr &= ~FILE_ATTRIBUTE_READONLY;
  197431. return SetFileAttributes (fileName, attr) != FALSE;
  197432. }
  197433. bool File::isHidden() const throw()
  197434. {
  197435. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  197436. }
  197437. bool juce_deleteFile (const String& fileName) throw()
  197438. {
  197439. if (juce_isDirectory (fileName))
  197440. return RemoveDirectory (fileName) != 0;
  197441. return DeleteFile (fileName) != 0;
  197442. }
  197443. bool juce_moveFile (const String& source, const String& dest) throw()
  197444. {
  197445. return MoveFile (source, dest) != 0;
  197446. }
  197447. bool juce_copyFile (const String& source, const String& dest) throw()
  197448. {
  197449. return CopyFile (source, dest, false) != 0;
  197450. }
  197451. void juce_createDirectory (const String& fileName) throw()
  197452. {
  197453. if (! juce_fileExists (fileName, true))
  197454. {
  197455. CreateDirectory (fileName, 0);
  197456. }
  197457. }
  197458. // return 0 if not possible
  197459. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  197460. {
  197461. HANDLE h;
  197462. if (forWriting)
  197463. {
  197464. h = CreateFile (fileName, GENERIC_WRITE, FILE_SHARE_READ, 0,
  197465. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  197466. if (h != INVALID_HANDLE_VALUE)
  197467. SetFilePointer (h, 0, 0, FILE_END);
  197468. else
  197469. h = 0;
  197470. }
  197471. else
  197472. {
  197473. h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  197474. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  197475. if (h == INVALID_HANDLE_VALUE)
  197476. h = 0;
  197477. }
  197478. return (void*) h;
  197479. }
  197480. void juce_fileClose (void* handle) throw()
  197481. {
  197482. CloseHandle (handle);
  197483. }
  197484. int juce_fileRead (void* handle, void* buffer, int size) throw()
  197485. {
  197486. DWORD num = 0;
  197487. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  197488. return num;
  197489. }
  197490. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  197491. {
  197492. DWORD num;
  197493. WriteFile ((HANDLE) handle,
  197494. buffer, size,
  197495. &num, 0);
  197496. return num;
  197497. }
  197498. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  197499. {
  197500. LARGE_INTEGER li;
  197501. li.QuadPart = pos;
  197502. li.LowPart = SetFilePointer ((HANDLE) handle,
  197503. li.LowPart,
  197504. &li.HighPart,
  197505. FILE_BEGIN); // (returns -1 if it fails)
  197506. return li.QuadPart;
  197507. }
  197508. int64 juce_fileGetPosition (void* handle) throw()
  197509. {
  197510. LARGE_INTEGER li;
  197511. li.QuadPart = 0;
  197512. li.LowPart = SetFilePointer ((HANDLE) handle,
  197513. 0, &li.HighPart,
  197514. FILE_CURRENT); // (returns -1 if it fails)
  197515. return jmax ((int64) 0, li.QuadPart);
  197516. }
  197517. void juce_fileFlush (void* handle) throw()
  197518. {
  197519. FlushFileBuffers ((HANDLE) handle);
  197520. }
  197521. int64 juce_getFileSize (const String& fileName) throw()
  197522. {
  197523. WIN32_FILE_ATTRIBUTE_DATA attributes;
  197524. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  197525. {
  197526. return (((int64) attributes.nFileSizeHigh) << 32)
  197527. | attributes.nFileSizeLow;
  197528. }
  197529. return 0;
  197530. }
  197531. static int64 fileTimeToTime (const FILETIME* const ft) throw()
  197532. {
  197533. // tell me if this fails!
  197534. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME));
  197535. #if JUCE_GCC
  197536. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000LL) / 10000;
  197537. #else
  197538. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000) / 10000;
  197539. #endif
  197540. }
  197541. static void timeToFileTime (const int64 time, FILETIME* const ft) throw()
  197542. {
  197543. #if JUCE_GCC
  197544. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000LL;
  197545. #else
  197546. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000;
  197547. #endif
  197548. }
  197549. void juce_getFileTimes (const String& fileName,
  197550. int64& modificationTime,
  197551. int64& accessTime,
  197552. int64& creationTime) throw()
  197553. {
  197554. WIN32_FILE_ATTRIBUTE_DATA attributes;
  197555. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  197556. {
  197557. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  197558. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  197559. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  197560. }
  197561. else
  197562. {
  197563. creationTime = accessTime = modificationTime = 0;
  197564. }
  197565. }
  197566. bool juce_setFileTimes (const String& fileName,
  197567. int64 modificationTime,
  197568. int64 accessTime,
  197569. int64 creationTime) throw()
  197570. {
  197571. FILETIME m, a, c;
  197572. if (modificationTime > 0)
  197573. timeToFileTime (modificationTime, &m);
  197574. if (accessTime > 0)
  197575. timeToFileTime (accessTime, &a);
  197576. if (creationTime > 0)
  197577. timeToFileTime (creationTime, &c);
  197578. void* const h = juce_fileOpen (fileName, true);
  197579. bool ok = false;
  197580. if (h != 0)
  197581. {
  197582. ok = SetFileTime ((HANDLE) h,
  197583. (creationTime > 0) ? &c : 0,
  197584. (accessTime > 0) ? &a : 0,
  197585. (modificationTime > 0) ? &m : 0) != 0;
  197586. juce_fileClose (h);
  197587. }
  197588. return ok;
  197589. }
  197590. // return '\0' separated list of strings
  197591. const StringArray juce_getFileSystemRoots() throw()
  197592. {
  197593. TCHAR buffer [2048];
  197594. buffer[0] = 0;
  197595. buffer[1] = 0;
  197596. GetLogicalDriveStrings (2048, buffer);
  197597. TCHAR* n = buffer;
  197598. StringArray roots;
  197599. while (*n != 0)
  197600. {
  197601. roots.add (String (n));
  197602. while (*n++ != 0)
  197603. {
  197604. }
  197605. }
  197606. roots.sort (true);
  197607. return roots;
  197608. }
  197609. const String juce_getVolumeLabel (const String& filenameOnVolume,
  197610. int& volumeSerialNumber) throw()
  197611. {
  197612. TCHAR n [4];
  197613. n[0] = *(const TCHAR*) filenameOnVolume;
  197614. n[1] = L':';
  197615. n[2] = L'\\';
  197616. n[3] = 0;
  197617. TCHAR dest [64];
  197618. DWORD serialNum;
  197619. if (! GetVolumeInformation (n, dest, 64, (DWORD*) &serialNum, 0, 0, 0, 0))
  197620. {
  197621. dest[0] = 0;
  197622. serialNum = 0;
  197623. }
  197624. volumeSerialNumber = serialNum;
  197625. return String (dest);
  197626. }
  197627. int64 File::getBytesFreeOnVolume() const throw()
  197628. {
  197629. String fn (getFullPathName());
  197630. if (fn[1] == T(':'))
  197631. fn = fn.substring (0, 2) + T("\\");
  197632. ULARGE_INTEGER spc;
  197633. ULARGE_INTEGER tot;
  197634. ULARGE_INTEGER totFree;
  197635. if (GetDiskFreeSpaceEx (fn, &spc, &tot, &totFree))
  197636. return (int64)(spc.QuadPart);
  197637. return 0;
  197638. }
  197639. static unsigned int getWindowsDriveType (const String& fileName) throw()
  197640. {
  197641. TCHAR n[4];
  197642. n[0] = *(const TCHAR*) fileName;
  197643. n[1] = L':';
  197644. n[2] = L'\\';
  197645. n[3] = 0;
  197646. return GetDriveType (n);
  197647. }
  197648. bool File::isOnCDRomDrive() const throw()
  197649. {
  197650. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  197651. }
  197652. bool File::isOnHardDisk() const throw()
  197653. {
  197654. if (fullPath.isEmpty())
  197655. return false;
  197656. const unsigned int n = getWindowsDriveType (getFullPathName());
  197657. if (fullPath.toLowerCase()[0] <= 'b'
  197658. && fullPath[1] == T(':'))
  197659. {
  197660. return n != DRIVE_REMOVABLE;
  197661. }
  197662. else
  197663. {
  197664. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  197665. }
  197666. }
  197667. bool File::isOnRemovableDrive() const throw()
  197668. {
  197669. if (fullPath.isEmpty())
  197670. return false;
  197671. const unsigned int n = getWindowsDriveType (getFullPathName());
  197672. return n == DRIVE_CDROM
  197673. || n == DRIVE_REMOTE
  197674. || n == DRIVE_REMOVABLE
  197675. || n == DRIVE_RAMDISK;
  197676. }
  197677. #define MAX_PATH_CHARS (MAX_PATH + 256)
  197678. static const File juce_getSpecialFolderPath (int type) throw()
  197679. {
  197680. WCHAR path [MAX_PATH_CHARS];
  197681. if (SHGetSpecialFolderPath (0, path, type, 0))
  197682. return File (String (path));
  197683. return File::nonexistent;
  197684. }
  197685. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  197686. {
  197687. int csidlType = 0;
  197688. switch (type)
  197689. {
  197690. case userHomeDirectory:
  197691. case userDocumentsDirectory:
  197692. csidlType = CSIDL_PERSONAL;
  197693. break;
  197694. case userDesktopDirectory:
  197695. csidlType = CSIDL_DESKTOP;
  197696. break;
  197697. case userApplicationDataDirectory:
  197698. csidlType = CSIDL_APPDATA;
  197699. break;
  197700. case commonApplicationDataDirectory:
  197701. csidlType = CSIDL_COMMON_APPDATA;
  197702. break;
  197703. case globalApplicationsDirectory:
  197704. csidlType = CSIDL_PROGRAM_FILES;
  197705. break;
  197706. case userMusicDirectory:
  197707. csidlType = CSIDL_MYMUSIC;
  197708. break;
  197709. case userMoviesDirectory:
  197710. csidlType = CSIDL_MYVIDEO;
  197711. break;
  197712. case tempDirectory:
  197713. {
  197714. WCHAR dest [2048];
  197715. dest[0] = 0;
  197716. GetTempPath (2048, dest);
  197717. return File (String (dest));
  197718. }
  197719. case currentExecutableFile:
  197720. case currentApplicationFile:
  197721. {
  197722. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  197723. WCHAR dest [MAX_PATH_CHARS];
  197724. dest[0] = 0;
  197725. GetModuleFileName (moduleHandle, dest, MAX_PATH_CHARS);
  197726. return File (String (dest));
  197727. }
  197728. break;
  197729. default:
  197730. jassertfalse // unknown type?
  197731. return File::nonexistent;
  197732. }
  197733. return juce_getSpecialFolderPath (csidlType);
  197734. }
  197735. void juce_setCurrentExecutableFileName (const String&) throw()
  197736. {
  197737. // n/a on windows
  197738. }
  197739. const File File::getCurrentWorkingDirectory() throw()
  197740. {
  197741. WCHAR dest [MAX_PATH_CHARS];
  197742. dest[0] = 0;
  197743. GetCurrentDirectory (MAX_PATH_CHARS, dest);
  197744. return File (String (dest));
  197745. }
  197746. bool File::setAsCurrentWorkingDirectory() const throw()
  197747. {
  197748. return SetCurrentDirectory (getFullPathName()) != FALSE;
  197749. }
  197750. template <class FindDataType>
  197751. static void getFindFileInfo (FindDataType& findData,
  197752. String& filename, bool* const isDir, bool* const isHidden,
  197753. int64* const fileSize, Time* const modTime, Time* const creationTime,
  197754. bool* const isReadOnly) throw()
  197755. {
  197756. filename = findData.cFileName;
  197757. if (isDir != 0)
  197758. *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  197759. if (isHidden != 0)
  197760. *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  197761. if (fileSize != 0)
  197762. *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  197763. if (modTime != 0)
  197764. *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  197765. if (creationTime != 0)
  197766. *creationTime = fileTimeToTime (&findData.ftCreationTime);
  197767. if (isReadOnly != 0)
  197768. *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  197769. }
  197770. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResult,
  197771. bool* isDir, bool* isHidden, int64* fileSize,
  197772. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  197773. {
  197774. String wc (directory);
  197775. if (! wc.endsWithChar (File::separator))
  197776. wc += File::separator;
  197777. wc += wildCard;
  197778. WIN32_FIND_DATA findData;
  197779. HANDLE h = FindFirstFile (wc, &findData);
  197780. if (h != INVALID_HANDLE_VALUE)
  197781. {
  197782. getFindFileInfo (findData, firstResult, isDir, isHidden, fileSize,
  197783. modTime, creationTime, isReadOnly);
  197784. return h;
  197785. }
  197786. firstResult = String::empty;
  197787. return 0;
  197788. }
  197789. bool juce_findFileNext (void* handle, String& resultFile,
  197790. bool* isDir, bool* isHidden, int64* fileSize,
  197791. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  197792. {
  197793. WIN32_FIND_DATA findData;
  197794. if (handle != 0 && FindNextFile ((HANDLE) handle, &findData) != 0)
  197795. {
  197796. getFindFileInfo (findData, resultFile, isDir, isHidden, fileSize,
  197797. modTime, creationTime, isReadOnly);
  197798. return true;
  197799. }
  197800. resultFile = String::empty;
  197801. return false;
  197802. }
  197803. void juce_findFileClose (void* handle) throw()
  197804. {
  197805. FindClose (handle);
  197806. }
  197807. bool juce_launchFile (const String& fileName,
  197808. const String& parameters) throw()
  197809. {
  197810. HINSTANCE hInstance = 0;
  197811. JUCE_TRY
  197812. {
  197813. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  197814. }
  197815. JUCE_CATCH_ALL
  197816. return hInstance > (HINSTANCE) 32;
  197817. }
  197818. struct NamedPipeInternal
  197819. {
  197820. HANDLE pipeH;
  197821. HANDLE cancelEvent;
  197822. bool connected, createdPipe;
  197823. NamedPipeInternal()
  197824. : pipeH (0),
  197825. cancelEvent (0),
  197826. connected (false),
  197827. createdPipe (false)
  197828. {
  197829. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  197830. }
  197831. ~NamedPipeInternal()
  197832. {
  197833. disconnect();
  197834. if (pipeH != 0)
  197835. CloseHandle (pipeH);
  197836. CloseHandle (cancelEvent);
  197837. }
  197838. bool connect (const int timeOutMs)
  197839. {
  197840. if (! createdPipe)
  197841. return true;
  197842. if (! connected)
  197843. {
  197844. OVERLAPPED over;
  197845. zerostruct (over);
  197846. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  197847. if (ConnectNamedPipe (pipeH, &over))
  197848. {
  197849. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  197850. }
  197851. else
  197852. {
  197853. const int err = GetLastError();
  197854. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  197855. {
  197856. HANDLE handles[] = { over.hEvent, cancelEvent };
  197857. if (WaitForMultipleObjects (2, handles, FALSE,
  197858. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  197859. connected = true;
  197860. }
  197861. else if (err == ERROR_PIPE_CONNECTED)
  197862. {
  197863. connected = true;
  197864. }
  197865. }
  197866. CloseHandle (over.hEvent);
  197867. }
  197868. return connected;
  197869. }
  197870. void disconnect()
  197871. {
  197872. if (connected)
  197873. {
  197874. DisconnectNamedPipe (pipeH);
  197875. connected = false;
  197876. }
  197877. }
  197878. };
  197879. void NamedPipe::close()
  197880. {
  197881. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197882. delete intern;
  197883. internal = 0;
  197884. }
  197885. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  197886. {
  197887. close();
  197888. NamedPipeInternal* const intern = new NamedPipeInternal();
  197889. String file ("\\\\.\\pipe\\");
  197890. file += pipeName;
  197891. intern->createdPipe = createPipe;
  197892. if (createPipe)
  197893. {
  197894. intern->pipeH = CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  197895. 1, 64, 64, 0, NULL);
  197896. }
  197897. else
  197898. {
  197899. intern->pipeH = CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING,
  197900. FILE_FLAG_OVERLAPPED, 0);
  197901. }
  197902. if (intern->pipeH != INVALID_HANDLE_VALUE)
  197903. {
  197904. internal = intern;
  197905. return true;
  197906. }
  197907. delete intern;
  197908. return false;
  197909. }
  197910. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  197911. {
  197912. int bytesRead = -1;
  197913. bool waitAgain = true;
  197914. while (waitAgain && internal != 0)
  197915. {
  197916. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197917. waitAgain = false;
  197918. if (! intern->connect (timeOutMilliseconds))
  197919. break;
  197920. if (maxBytesToRead <= 0)
  197921. return 0;
  197922. OVERLAPPED over;
  197923. zerostruct (over);
  197924. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  197925. unsigned long numRead;
  197926. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  197927. {
  197928. bytesRead = (int) numRead;
  197929. }
  197930. else if (GetLastError() == ERROR_IO_PENDING)
  197931. {
  197932. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  197933. if (WaitForMultipleObjects (2, handles, FALSE,
  197934. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  197935. : INFINITE) == WAIT_OBJECT_0)
  197936. {
  197937. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  197938. {
  197939. bytesRead = (int) numRead;
  197940. }
  197941. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  197942. {
  197943. intern->disconnect();
  197944. waitAgain = true;
  197945. }
  197946. }
  197947. }
  197948. else
  197949. {
  197950. waitAgain = internal != 0;
  197951. Sleep (5);
  197952. }
  197953. CloseHandle (over.hEvent);
  197954. }
  197955. return bytesRead;
  197956. }
  197957. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  197958. {
  197959. int bytesWritten = -1;
  197960. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197961. if (intern != 0 && intern->connect (timeOutMilliseconds))
  197962. {
  197963. if (numBytesToWrite <= 0)
  197964. return 0;
  197965. OVERLAPPED over;
  197966. zerostruct (over);
  197967. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  197968. unsigned long numWritten;
  197969. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  197970. {
  197971. bytesWritten = (int) numWritten;
  197972. }
  197973. else if (GetLastError() == ERROR_IO_PENDING)
  197974. {
  197975. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  197976. if (WaitForMultipleObjects (2, handles, FALSE, timeOutMilliseconds >= 0 ? timeOutMilliseconds
  197977. : INFINITE) == WAIT_OBJECT_0)
  197978. {
  197979. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  197980. {
  197981. bytesWritten = (int) numWritten;
  197982. }
  197983. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  197984. {
  197985. intern->disconnect();
  197986. }
  197987. }
  197988. }
  197989. CloseHandle (over.hEvent);
  197990. }
  197991. return bytesWritten;
  197992. }
  197993. void NamedPipe::cancelPendingReads()
  197994. {
  197995. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197996. if (intern != 0)
  197997. SetEvent (intern->cancelEvent);
  197998. }
  197999. END_JUCE_NAMESPACE
  198000. /********* End of inlined file: juce_win32_Files.cpp *********/
  198001. /********* Start of inlined file: juce_win32_Network.cpp *********/
  198002. #ifdef _MSC_VER
  198003. #pragma warning (disable: 4514)
  198004. #pragma warning (push)
  198005. #endif
  198006. #include <wininet.h>
  198007. #include <nb30.h>
  198008. #include <iphlpapi.h>
  198009. #include <mapi.h>
  198010. BEGIN_JUCE_NAMESPACE
  198011. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  198012. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198013. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198014. #ifndef DOXYGEN
  198015. // use with DynamicLibraryLoader to simplify importing functions
  198016. //
  198017. // functionName: function to import
  198018. // localFunctionName: name you want to use to actually call it (must be different)
  198019. // returnType: the return type
  198020. // object: the DynamicLibraryLoader to use
  198021. // params: list of params (bracketed)
  198022. //
  198023. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  198024. typedef returnType (WINAPI *type##localFunctionName) params; \
  198025. type##localFunctionName localFunctionName \
  198026. = (type##localFunctionName)object.findProcAddress (#functionName);
  198027. // loads and unloads a DLL automatically
  198028. class JUCE_API DynamicLibraryLoader
  198029. {
  198030. public:
  198031. DynamicLibraryLoader (const String& name);
  198032. ~DynamicLibraryLoader();
  198033. void* findProcAddress (const String& functionName);
  198034. private:
  198035. void* libHandle;
  198036. };
  198037. #endif
  198038. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198039. /********* End of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  198040. #ifndef INTERNET_FLAG_NEED_FILE
  198041. #define INTERNET_FLAG_NEED_FILE 0x00000010
  198042. #endif
  198043. #ifdef _MSC_VER
  198044. #pragma warning (pop)
  198045. #endif
  198046. bool juce_isOnLine()
  198047. {
  198048. DWORD connectionType;
  198049. return InternetGetConnectedState (&connectionType, 0) != 0
  198050. || (connectionType & (INTERNET_CONNECTION_LAN | INTERNET_CONNECTION_PROXY)) != 0;
  198051. }
  198052. struct ConnectionAndRequestStruct
  198053. {
  198054. HINTERNET connection, request;
  198055. };
  198056. static HINTERNET sessionHandle = 0;
  198057. void* juce_openInternetFile (const String& url,
  198058. const String& headers,
  198059. const MemoryBlock& postData,
  198060. const bool isPost,
  198061. URL::OpenStreamProgressCallback* callback,
  198062. void* callbackContext,
  198063. int timeOutMs)
  198064. {
  198065. if (sessionHandle == 0)
  198066. sessionHandle = InternetOpen (_T("juce"),
  198067. INTERNET_OPEN_TYPE_PRECONFIG,
  198068. 0, 0, 0);
  198069. if (sessionHandle != 0)
  198070. {
  198071. // break up the url..
  198072. TCHAR file[1024], server[1024];
  198073. URL_COMPONENTS uc;
  198074. zerostruct (uc);
  198075. uc.dwStructSize = sizeof (uc);
  198076. uc.dwUrlPathLength = sizeof (file);
  198077. uc.dwHostNameLength = sizeof (server);
  198078. uc.lpszUrlPath = file;
  198079. uc.lpszHostName = server;
  198080. if (InternetCrackUrl (url, 0, 0, &uc))
  198081. {
  198082. if (timeOutMs == 0)
  198083. timeOutMs = 30000;
  198084. else if (timeOutMs < 0)
  198085. timeOutMs = -1;
  198086. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  198087. const bool isFtp = url.startsWithIgnoreCase (T("ftp:"));
  198088. HINTERNET connection = InternetConnect (sessionHandle,
  198089. uc.lpszHostName,
  198090. uc.nPort,
  198091. _T(""), _T(""),
  198092. isFtp ? INTERNET_SERVICE_FTP
  198093. : INTERNET_SERVICE_HTTP,
  198094. 0, 0);
  198095. if (connection != 0)
  198096. {
  198097. if (isFtp)
  198098. {
  198099. HINTERNET request = FtpOpenFile (connection,
  198100. uc.lpszUrlPath,
  198101. GENERIC_READ,
  198102. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  198103. 0);
  198104. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  198105. result->connection = connection;
  198106. result->request = request;
  198107. return result;
  198108. }
  198109. else
  198110. {
  198111. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  198112. HINTERNET request = HttpOpenRequest (connection,
  198113. isPost ? _T("POST")
  198114. : _T("GET"),
  198115. uc.lpszUrlPath,
  198116. 0, 0, mimeTypes,
  198117. INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE,
  198118. 0);
  198119. if (request != 0)
  198120. {
  198121. INTERNET_BUFFERS buffers;
  198122. zerostruct (buffers);
  198123. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  198124. buffers.lpcszHeader = (LPCTSTR) headers;
  198125. buffers.dwHeadersLength = headers.length();
  198126. buffers.dwBufferTotal = (DWORD) postData.getSize();
  198127. ConnectionAndRequestStruct* result = 0;
  198128. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  198129. {
  198130. int bytesSent = 0;
  198131. for (;;)
  198132. {
  198133. const int bytesToDo = jmin (1024, postData.getSize() - bytesSent);
  198134. DWORD bytesDone = 0;
  198135. if (bytesToDo > 0
  198136. && ! InternetWriteFile (request,
  198137. ((const char*) postData.getData()) + bytesSent,
  198138. bytesToDo, &bytesDone))
  198139. {
  198140. break;
  198141. }
  198142. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  198143. {
  198144. result = new ConnectionAndRequestStruct();
  198145. result->connection = connection;
  198146. result->request = request;
  198147. HttpEndRequest (request, 0, 0, 0);
  198148. return result;
  198149. }
  198150. bytesSent += bytesDone;
  198151. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  198152. break;
  198153. }
  198154. }
  198155. InternetCloseHandle (request);
  198156. }
  198157. InternetCloseHandle (connection);
  198158. }
  198159. }
  198160. }
  198161. }
  198162. return 0;
  198163. }
  198164. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  198165. {
  198166. DWORD bytesRead = 0;
  198167. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  198168. if (crs != 0)
  198169. InternetReadFile (crs->request,
  198170. buffer, bytesToRead,
  198171. &bytesRead);
  198172. return bytesRead;
  198173. }
  198174. int juce_seekInInternetFile (void* handle, int newPosition)
  198175. {
  198176. if (handle != 0)
  198177. {
  198178. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  198179. return InternetSetFilePointer (crs->request,
  198180. newPosition, 0,
  198181. FILE_BEGIN, 0);
  198182. }
  198183. else
  198184. {
  198185. return -1;
  198186. }
  198187. }
  198188. void juce_closeInternetFile (void* handle)
  198189. {
  198190. if (handle != 0)
  198191. {
  198192. ConnectionAndRequestStruct* const crs = (ConnectionAndRequestStruct*) handle;
  198193. InternetCloseHandle (crs->request);
  198194. InternetCloseHandle (crs->connection);
  198195. delete crs;
  198196. }
  198197. }
  198198. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  198199. {
  198200. int numFound = 0;
  198201. DynamicLibraryLoader dll ("iphlpapi.dll");
  198202. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  198203. if (getAdaptersInfo != 0)
  198204. {
  198205. ULONG len = sizeof (IP_ADAPTER_INFO);
  198206. MemoryBlock mb;
  198207. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  198208. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  198209. {
  198210. mb.setSize (len);
  198211. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  198212. }
  198213. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  198214. {
  198215. PIP_ADAPTER_INFO adapter = adapterInfo;
  198216. while (adapter != 0)
  198217. {
  198218. int64 mac = 0;
  198219. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  198220. mac = (mac << 8) | adapter->Address[i];
  198221. if (littleEndian)
  198222. mac = (int64) swapByteOrder ((uint64) mac);
  198223. if (numFound < maxNum && mac != 0)
  198224. addresses [numFound++] = mac;
  198225. adapter = adapter->Next;
  198226. }
  198227. }
  198228. }
  198229. return numFound;
  198230. }
  198231. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  198232. {
  198233. int numFound = 0;
  198234. DynamicLibraryLoader dll ("netapi32.dll");
  198235. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  198236. if (NetbiosCall != 0)
  198237. {
  198238. NCB ncb;
  198239. zerostruct (ncb);
  198240. typedef struct _ASTAT_
  198241. {
  198242. ADAPTER_STATUS adapt;
  198243. NAME_BUFFER NameBuff [30];
  198244. } ASTAT;
  198245. ASTAT astat;
  198246. zerostruct (astat);
  198247. LANA_ENUM enums;
  198248. zerostruct (enums);
  198249. ncb.ncb_command = NCBENUM;
  198250. ncb.ncb_buffer = (unsigned char*) &enums;
  198251. ncb.ncb_length = sizeof (LANA_ENUM);
  198252. NetbiosCall (&ncb);
  198253. for (int i = 0; i < enums.length; ++i)
  198254. {
  198255. zerostruct (ncb);
  198256. ncb.ncb_command = NCBRESET;
  198257. ncb.ncb_lana_num = enums.lana[i];
  198258. if (NetbiosCall (&ncb) == 0)
  198259. {
  198260. zerostruct (ncb);
  198261. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  198262. ncb.ncb_command = NCBASTAT;
  198263. ncb.ncb_lana_num = enums.lana[i];
  198264. ncb.ncb_buffer = (unsigned char*) &astat;
  198265. ncb.ncb_length = sizeof (ASTAT);
  198266. if (NetbiosCall (&ncb) == 0)
  198267. {
  198268. if (astat.adapt.adapter_type == 0xfe)
  198269. {
  198270. int64 mac = 0;
  198271. for (unsigned int i = 0; i < 6; ++i)
  198272. mac = (mac << 8) | astat.adapt.adapter_address[i];
  198273. if (littleEndian)
  198274. mac = (int64) swapByteOrder ((uint64) mac);
  198275. if (numFound < maxNum && mac != 0)
  198276. addresses [numFound++] = mac;
  198277. }
  198278. }
  198279. }
  198280. }
  198281. }
  198282. return numFound;
  198283. }
  198284. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  198285. {
  198286. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  198287. if (numFound == 0)
  198288. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  198289. return numFound;
  198290. }
  198291. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  198292. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  198293. const String& emailSubject,
  198294. const String& bodyText,
  198295. const StringArray& filesToAttach)
  198296. {
  198297. HMODULE h = LoadLibraryA ("MAPI32.dll");
  198298. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  198299. bool ok = false;
  198300. if (mapiSendMail != 0)
  198301. {
  198302. MapiMessage message;
  198303. zerostruct (message);
  198304. message.lpszSubject = (LPSTR) (LPCSTR) emailSubject;
  198305. message.lpszNoteText = (LPSTR) (LPCSTR) bodyText;
  198306. MapiRecipDesc recip;
  198307. zerostruct (recip);
  198308. recip.ulRecipClass = MAPI_TO;
  198309. recip.lpszName = (LPSTR) (LPCSTR) targetEmailAddress;
  198310. message.nRecipCount = 1;
  198311. message.lpRecips = &recip;
  198312. MemoryBlock mb (sizeof (MapiFileDesc) * filesToAttach.size());
  198313. mb.fillWith (0);
  198314. MapiFileDesc* files = (MapiFileDesc*) mb.getData();
  198315. message.nFileCount = filesToAttach.size();
  198316. message.lpFiles = files;
  198317. for (int i = 0; i < filesToAttach.size(); ++i)
  198318. {
  198319. files[i].nPosition = (ULONG) -1;
  198320. files[i].lpszPathName = (LPSTR) (LPCSTR) filesToAttach [i];
  198321. }
  198322. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  198323. }
  198324. FreeLibrary (h);
  198325. return ok;
  198326. }
  198327. END_JUCE_NAMESPACE
  198328. /********* End of inlined file: juce_win32_Network.cpp *********/
  198329. /********* Start of inlined file: juce_win32_Misc.cpp *********/
  198330. BEGIN_JUCE_NAMESPACE
  198331. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198332. bool AlertWindow::showNativeDialogBox (const String& title,
  198333. const String& bodyText,
  198334. bool isOkCancel)
  198335. {
  198336. return MessageBox (0, bodyText, title,
  198337. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  198338. : MB_OK)) == IDOK;
  198339. }
  198340. #endif
  198341. void PlatformUtilities::beep()
  198342. {
  198343. MessageBeep (MB_OK);
  198344. }
  198345. #if JUCE_MSVC
  198346. #pragma warning (disable : 4127) // "Conditional expression is constant" warning
  198347. #endif
  198348. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198349. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  198350. {
  198351. if (OpenClipboard (0) != 0)
  198352. {
  198353. if (EmptyClipboard() != 0)
  198354. {
  198355. const int len = text.length();
  198356. if (len > 0)
  198357. {
  198358. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  198359. (len + 1) * sizeof (wchar_t));
  198360. if (bufH != 0)
  198361. {
  198362. wchar_t* const data = (wchar_t*) GlobalLock (bufH);
  198363. text.copyToBuffer (data, len);
  198364. GlobalUnlock (bufH);
  198365. SetClipboardData (CF_UNICODETEXT, bufH);
  198366. }
  198367. }
  198368. }
  198369. CloseClipboard();
  198370. }
  198371. }
  198372. const String SystemClipboard::getTextFromClipboard() throw()
  198373. {
  198374. String result;
  198375. if (OpenClipboard (0) != 0)
  198376. {
  198377. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  198378. if (bufH != 0)
  198379. {
  198380. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  198381. if (data != 0)
  198382. {
  198383. result = String (data, (int) (GlobalSize (bufH) / sizeof (tchar)));
  198384. GlobalUnlock (bufH);
  198385. }
  198386. }
  198387. CloseClipboard();
  198388. }
  198389. return result;
  198390. }
  198391. #endif
  198392. END_JUCE_NAMESPACE
  198393. /********* End of inlined file: juce_win32_Misc.cpp *********/
  198394. /********* Start of inlined file: juce_win32_PlatformUtils.cpp *********/
  198395. #ifdef _MSC_VER
  198396. #pragma warning (disable: 4514)
  198397. #pragma warning (push)
  198398. #endif
  198399. #include <float.h>
  198400. BEGIN_JUCE_NAMESPACE
  198401. #ifdef _MSC_VER
  198402. #pragma warning (pop)
  198403. #endif
  198404. static HKEY findKeyForPath (String name,
  198405. const bool createForWriting,
  198406. String& valueName) throw()
  198407. {
  198408. HKEY rootKey = 0;
  198409. if (name.startsWithIgnoreCase (T("HKEY_CURRENT_USER\\")))
  198410. rootKey = HKEY_CURRENT_USER;
  198411. else if (name.startsWithIgnoreCase (T("HKEY_LOCAL_MACHINE\\")))
  198412. rootKey = HKEY_LOCAL_MACHINE;
  198413. else if (name.startsWithIgnoreCase (T("HKEY_CLASSES_ROOT\\")))
  198414. rootKey = HKEY_CLASSES_ROOT;
  198415. if (rootKey != 0)
  198416. {
  198417. name = name.substring (name.indexOfChar (T('\\')) + 1);
  198418. const int lastSlash = name.lastIndexOfChar (T('\\'));
  198419. valueName = name.substring (lastSlash + 1);
  198420. name = name.substring (0, lastSlash);
  198421. HKEY key;
  198422. DWORD result;
  198423. if (createForWriting)
  198424. {
  198425. if (RegCreateKeyEx (rootKey, name, 0, L"", REG_OPTION_NON_VOLATILE,
  198426. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  198427. return key;
  198428. }
  198429. else
  198430. {
  198431. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  198432. return key;
  198433. }
  198434. }
  198435. return 0;
  198436. }
  198437. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  198438. const String& defaultValue)
  198439. {
  198440. String valueName, s;
  198441. HKEY k = findKeyForPath (regValuePath, false, valueName);
  198442. if (k != 0)
  198443. {
  198444. WCHAR buffer [2048];
  198445. unsigned long bufferSize = sizeof (buffer);
  198446. DWORD type = REG_SZ;
  198447. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  198448. s = buffer;
  198449. else
  198450. s = defaultValue;
  198451. RegCloseKey (k);
  198452. }
  198453. return s;
  198454. }
  198455. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  198456. const String& value)
  198457. {
  198458. String valueName;
  198459. HKEY k = findKeyForPath (regValuePath, true, valueName);
  198460. if (k != 0)
  198461. {
  198462. RegSetValueEx (k, valueName, 0, REG_SZ,
  198463. (const BYTE*) (const WCHAR*) value,
  198464. sizeof (WCHAR) * (value.length() + 1));
  198465. RegCloseKey (k);
  198466. }
  198467. }
  198468. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  198469. {
  198470. bool exists = false;
  198471. String valueName;
  198472. HKEY k = findKeyForPath (regValuePath, false, valueName);
  198473. if (k != 0)
  198474. {
  198475. unsigned char buffer [2048];
  198476. unsigned long bufferSize = sizeof (buffer);
  198477. DWORD type = 0;
  198478. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  198479. exists = true;
  198480. RegCloseKey (k);
  198481. }
  198482. return exists;
  198483. }
  198484. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  198485. {
  198486. String valueName;
  198487. HKEY k = findKeyForPath (regValuePath, true, valueName);
  198488. if (k != 0)
  198489. {
  198490. RegDeleteValue (k, valueName);
  198491. RegCloseKey (k);
  198492. }
  198493. }
  198494. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  198495. {
  198496. String valueName;
  198497. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  198498. if (k != 0)
  198499. {
  198500. RegDeleteKey (k, valueName);
  198501. RegCloseKey (k);
  198502. }
  198503. }
  198504. bool juce_IsRunningInWine() throw()
  198505. {
  198506. HKEY key;
  198507. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  198508. {
  198509. RegCloseKey (key);
  198510. return true;
  198511. }
  198512. return false;
  198513. }
  198514. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams() throw()
  198515. {
  198516. String s (::GetCommandLineW());
  198517. StringArray tokens;
  198518. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  198519. return tokens.joinIntoString (T(" "), 1);
  198520. }
  198521. static void* currentModuleHandle = 0;
  198522. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  198523. {
  198524. if (currentModuleHandle == 0)
  198525. currentModuleHandle = GetModuleHandle (0);
  198526. return currentModuleHandle;
  198527. }
  198528. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  198529. {
  198530. currentModuleHandle = newHandle;
  198531. }
  198532. void PlatformUtilities::fpuReset()
  198533. {
  198534. #if JUCE_MSVC
  198535. _clearfp();
  198536. #endif
  198537. }
  198538. END_JUCE_NAMESPACE
  198539. /********* End of inlined file: juce_win32_PlatformUtils.cpp *********/
  198540. /********* Start of inlined file: juce_win32_SystemStats.cpp *********/
  198541. // Auto-link the other win32 libs that are needed by library calls..
  198542. #if defined (JUCE_DLL_BUILD) && JUCE_MSVC
  198543. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  198544. // Auto-links to various win32 libs that are needed by library calls..
  198545. #pragma comment(lib, "kernel32.lib")
  198546. #pragma comment(lib, "user32.lib")
  198547. #pragma comment(lib, "shell32.lib")
  198548. #pragma comment(lib, "gdi32.lib")
  198549. #pragma comment(lib, "vfw32.lib")
  198550. #pragma comment(lib, "comdlg32.lib")
  198551. #pragma comment(lib, "winmm.lib")
  198552. #pragma comment(lib, "wininet.lib")
  198553. #pragma comment(lib, "ole32.lib")
  198554. #pragma comment(lib, "advapi32.lib")
  198555. #pragma comment(lib, "ws2_32.lib")
  198556. #pragma comment(lib, "comsupp.lib")
  198557. #if JUCE_OPENGL
  198558. #pragma comment(lib, "OpenGL32.Lib")
  198559. #pragma comment(lib, "GlU32.Lib")
  198560. #endif
  198561. #if JUCE_QUICKTIME
  198562. #pragma comment (lib, "QTMLClient.lib")
  198563. #endif
  198564. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  198565. #endif
  198566. BEGIN_JUCE_NAMESPACE
  198567. extern void juce_updateMultiMonitorInfo() throw();
  198568. extern void juce_initialiseThreadEvents() throw();
  198569. void Logger::outputDebugString (const String& text) throw()
  198570. {
  198571. OutputDebugString (text + T("\n"));
  198572. }
  198573. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  198574. {
  198575. String text;
  198576. va_list args;
  198577. va_start (args, format);
  198578. text.vprintf(format, args);
  198579. outputDebugString (text);
  198580. }
  198581. static int64 hiResTicksPerSecond;
  198582. static double hiResTicksScaleFactor;
  198583. #if JUCE_USE_INTRINSICS
  198584. // CPU info functions using intrinsics...
  198585. #pragma intrinsic (__cpuid)
  198586. #pragma intrinsic (__rdtsc)
  198587. /*static unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0) throw()
  198588. {
  198589. int info [4];
  198590. __cpuid (info, 1);
  198591. if (familyModel != 0)
  198592. *familyModel = info [0];
  198593. if (extFeatures != 0)
  198594. *extFeatures = info[1];
  198595. return info[3];
  198596. }*/
  198597. const String SystemStats::getCpuVendor() throw()
  198598. {
  198599. int info [4];
  198600. __cpuid (info, 0);
  198601. char v [12];
  198602. memcpy (v, info + 1, 4);
  198603. memcpy (v + 4, info + 3, 4);
  198604. memcpy (v + 8, info + 2, 4);
  198605. return String (v, 12);
  198606. }
  198607. #else
  198608. // CPU info functions using old fashioned inline asm...
  198609. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0)
  198610. {
  198611. unsigned int cpu = 0;
  198612. unsigned int ext = 0;
  198613. unsigned int family = 0;
  198614. #if JUCE_GCC
  198615. unsigned int dummy = 0;
  198616. #endif
  198617. #ifndef __MINGW32__
  198618. __try
  198619. #endif
  198620. {
  198621. #if JUCE_GCC
  198622. __asm__ ("cpuid" : "=a" (family), "=b" (ext), "=c" (dummy),"=d" (cpu) : "a" (1));
  198623. #else
  198624. __asm
  198625. {
  198626. mov eax, 1
  198627. cpuid
  198628. mov cpu, edx
  198629. mov family, eax
  198630. mov ext, ebx
  198631. }
  198632. #endif
  198633. }
  198634. #ifndef __MINGW32__
  198635. __except (EXCEPTION_EXECUTE_HANDLER)
  198636. {
  198637. return 0;
  198638. }
  198639. #endif
  198640. if (familyModel != 0)
  198641. *familyModel = family;
  198642. if (extFeatures != 0)
  198643. *extFeatures = ext;
  198644. return cpu;
  198645. }*/
  198646. static void juce_getCpuVendor (char* const v)
  198647. {
  198648. int vendor[4];
  198649. zeromem (vendor, 16);
  198650. #ifdef JUCE_64BIT
  198651. #else
  198652. #ifndef __MINGW32__
  198653. __try
  198654. #endif
  198655. {
  198656. #if JUCE_GCC
  198657. unsigned int dummy = 0;
  198658. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  198659. #else
  198660. __asm
  198661. {
  198662. mov eax, 0
  198663. cpuid
  198664. mov [vendor], ebx
  198665. mov [vendor + 4], edx
  198666. mov [vendor + 8], ecx
  198667. }
  198668. #endif
  198669. }
  198670. #ifndef __MINGW32__
  198671. __except (EXCEPTION_EXECUTE_HANDLER)
  198672. {
  198673. *v = 0;
  198674. }
  198675. #endif
  198676. #endif
  198677. memcpy (v, vendor, 16);
  198678. }
  198679. const String SystemStats::getCpuVendor() throw()
  198680. {
  198681. char v [16];
  198682. juce_getCpuVendor (v);
  198683. return String (v, 16);
  198684. }
  198685. #endif
  198686. struct CPUFlags
  198687. {
  198688. bool hasMMX : 1;
  198689. bool hasSSE : 1;
  198690. bool hasSSE2 : 1;
  198691. bool has3DNow : 1;
  198692. };
  198693. static CPUFlags cpuFlags;
  198694. bool SystemStats::hasMMX() throw()
  198695. {
  198696. return cpuFlags.hasMMX;
  198697. }
  198698. bool SystemStats::hasSSE() throw()
  198699. {
  198700. return cpuFlags.hasSSE;
  198701. }
  198702. bool SystemStats::hasSSE2() throw()
  198703. {
  198704. return cpuFlags.hasSSE2;
  198705. }
  198706. bool SystemStats::has3DNow() throw()
  198707. {
  198708. return cpuFlags.has3DNow;
  198709. }
  198710. void SystemStats::initialiseStats() throw()
  198711. {
  198712. juce_initialiseThreadEvents();
  198713. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  198714. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  198715. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  198716. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  198717. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  198718. #else
  198719. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  198720. #endif
  198721. LARGE_INTEGER f;
  198722. QueryPerformanceFrequency (&f);
  198723. hiResTicksPerSecond = f.QuadPart;
  198724. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  198725. String s (SystemStats::getJUCEVersion());
  198726. #ifdef JUCE_DEBUG
  198727. const MMRESULT res = timeBeginPeriod (1);
  198728. jassert (res == TIMERR_NOERROR);
  198729. #else
  198730. timeBeginPeriod (1);
  198731. #endif
  198732. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  198733. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  198734. #endif
  198735. }
  198736. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  198737. {
  198738. OSVERSIONINFO info;
  198739. info.dwOSVersionInfoSize = sizeof (info);
  198740. GetVersionEx (&info);
  198741. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  198742. {
  198743. switch (info.dwMajorVersion)
  198744. {
  198745. case 5:
  198746. return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  198747. case 6:
  198748. return WinVista;
  198749. default:
  198750. jassertfalse // !! not a supported OS!
  198751. break;
  198752. }
  198753. }
  198754. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  198755. {
  198756. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  198757. return Win98;
  198758. }
  198759. return UnknownOS;
  198760. }
  198761. const String SystemStats::getOperatingSystemName() throw()
  198762. {
  198763. const char* name = "Unknown OS";
  198764. switch (getOperatingSystemType())
  198765. {
  198766. case WinVista:
  198767. name = "Windows Vista";
  198768. break;
  198769. case WinXP:
  198770. name = "Windows XP";
  198771. break;
  198772. case Win2000:
  198773. name = "Windows 2000";
  198774. break;
  198775. case Win98:
  198776. name = "Windows 98";
  198777. break;
  198778. default:
  198779. jassertfalse // !! new type of OS?
  198780. break;
  198781. }
  198782. return name;
  198783. }
  198784. bool SystemStats::isOperatingSystem64Bit() throw()
  198785. {
  198786. #ifdef _WIN64
  198787. return true;
  198788. #else
  198789. typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  198790. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  198791. BOOL isWow64 = FALSE;
  198792. return (fnIsWow64Process != 0)
  198793. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  198794. && (isWow64 != FALSE);
  198795. #endif
  198796. }
  198797. int SystemStats::getMemorySizeInMegabytes() throw()
  198798. {
  198799. MEMORYSTATUS mem;
  198800. GlobalMemoryStatus (&mem);
  198801. return (int) (mem.dwTotalPhys / (1024 * 1024)) + 1;
  198802. }
  198803. int SystemStats::getNumCpus() throw()
  198804. {
  198805. SYSTEM_INFO systemInfo;
  198806. GetSystemInfo (&systemInfo);
  198807. return systemInfo.dwNumberOfProcessors;
  198808. }
  198809. uint32 juce_millisecondsSinceStartup() throw()
  198810. {
  198811. return (uint32) GetTickCount();
  198812. }
  198813. int64 Time::getHighResolutionTicks() throw()
  198814. {
  198815. LARGE_INTEGER ticks;
  198816. QueryPerformanceCounter (&ticks);
  198817. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  198818. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  198819. // fix for a very obscure PCI hardware bug that can make the counter
  198820. // sometimes jump forwards by a few seconds..
  198821. static int64 hiResTicksOffset = 0;
  198822. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  198823. if (offsetDrift > (hiResTicksPerSecond >> 1))
  198824. hiResTicksOffset = newOffset;
  198825. return ticks.QuadPart + hiResTicksOffset;
  198826. }
  198827. double Time::getMillisecondCounterHiRes() throw()
  198828. {
  198829. return getHighResolutionTicks() * hiResTicksScaleFactor;
  198830. }
  198831. int64 Time::getHighResolutionTicksPerSecond() throw()
  198832. {
  198833. return hiResTicksPerSecond;
  198834. }
  198835. int64 SystemStats::getClockCycleCounter() throw()
  198836. {
  198837. #if JUCE_USE_INTRINSICS
  198838. // MS intrinsics version...
  198839. return __rdtsc();
  198840. #elif JUCE_GCC
  198841. // GNU inline asm version...
  198842. unsigned int hi = 0, lo = 0;
  198843. __asm__ __volatile__ (
  198844. "xor %%eax, %%eax \n\
  198845. xor %%edx, %%edx \n\
  198846. rdtsc \n\
  198847. movl %%eax, %[lo] \n\
  198848. movl %%edx, %[hi]"
  198849. :
  198850. : [hi] "m" (hi),
  198851. [lo] "m" (lo)
  198852. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  198853. return (int64) ((((uint64) hi) << 32) | lo);
  198854. #else
  198855. // MSVC inline asm version...
  198856. unsigned int hi = 0, lo = 0;
  198857. __asm
  198858. {
  198859. xor eax, eax
  198860. xor edx, edx
  198861. rdtsc
  198862. mov lo, eax
  198863. mov hi, edx
  198864. }
  198865. return (int64) ((((uint64) hi) << 32) | lo);
  198866. #endif
  198867. }
  198868. int SystemStats::getCpuSpeedInMegaherz() throw()
  198869. {
  198870. const int64 cycles = SystemStats::getClockCycleCounter();
  198871. const uint32 millis = Time::getMillisecondCounter();
  198872. int lastResult = 0;
  198873. for (;;)
  198874. {
  198875. int n = 1000000;
  198876. while (--n > 0) {}
  198877. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  198878. const int64 cyclesNow = SystemStats::getClockCycleCounter();
  198879. if (millisElapsed > 80)
  198880. {
  198881. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  198882. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  198883. return newResult;
  198884. lastResult = newResult;
  198885. }
  198886. }
  198887. }
  198888. bool Time::setSystemTimeToThisTime() const throw()
  198889. {
  198890. SYSTEMTIME st;
  198891. st.wDayOfWeek = 0;
  198892. st.wYear = (WORD) getYear();
  198893. st.wMonth = (WORD) (getMonth() + 1);
  198894. st.wDay = (WORD) getDayOfMonth();
  198895. st.wHour = (WORD) getHours();
  198896. st.wMinute = (WORD) getMinutes();
  198897. st.wSecond = (WORD) getSeconds();
  198898. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  198899. // do this twice because of daylight saving conversion problems - the
  198900. // first one sets it up, the second one kicks it in.
  198901. return SetLocalTime (&st) != 0
  198902. && SetLocalTime (&st) != 0;
  198903. }
  198904. int SystemStats::getPageSize() throw()
  198905. {
  198906. SYSTEM_INFO systemInfo;
  198907. GetSystemInfo (&systemInfo);
  198908. return systemInfo.dwPageSize;
  198909. }
  198910. END_JUCE_NAMESPACE
  198911. /********* End of inlined file: juce_win32_SystemStats.cpp *********/
  198912. /********* Start of inlined file: juce_win32_Threads.cpp *********/
  198913. #ifdef _MSC_VER
  198914. #pragma warning (disable: 4514)
  198915. #pragma warning (push)
  198916. #include <crtdbg.h>
  198917. #endif
  198918. #include <process.h>
  198919. BEGIN_JUCE_NAMESPACE
  198920. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198921. extern HWND juce_messageWindowHandle;
  198922. #endif
  198923. #ifdef _MSC_VER
  198924. #pragma warning (pop)
  198925. #endif
  198926. CriticalSection::CriticalSection() throw()
  198927. {
  198928. // (just to check the MS haven't changed this structure and broken things...)
  198929. #if _MSC_VER >= 1400
  198930. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  198931. #else
  198932. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  198933. #endif
  198934. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  198935. }
  198936. CriticalSection::~CriticalSection() throw()
  198937. {
  198938. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  198939. }
  198940. void CriticalSection::enter() const throw()
  198941. {
  198942. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  198943. }
  198944. bool CriticalSection::tryEnter() const throw()
  198945. {
  198946. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  198947. }
  198948. void CriticalSection::exit() const throw()
  198949. {
  198950. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  198951. }
  198952. WaitableEvent::WaitableEvent() throw()
  198953. : internal (CreateEvent (0, FALSE, FALSE, 0))
  198954. {
  198955. }
  198956. WaitableEvent::~WaitableEvent() throw()
  198957. {
  198958. CloseHandle (internal);
  198959. }
  198960. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  198961. {
  198962. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  198963. }
  198964. void WaitableEvent::signal() const throw()
  198965. {
  198966. SetEvent (internal);
  198967. }
  198968. void WaitableEvent::reset() const throw()
  198969. {
  198970. ResetEvent (internal);
  198971. }
  198972. void JUCE_API juce_threadEntryPoint (void*);
  198973. static unsigned int __stdcall threadEntryProc (void* userData) throw()
  198974. {
  198975. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198976. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  198977. GetCurrentThreadId(), TRUE);
  198978. #endif
  198979. juce_threadEntryPoint (userData);
  198980. _endthreadex(0);
  198981. return 0;
  198982. }
  198983. void juce_CloseThreadHandle (void* handle) throw()
  198984. {
  198985. CloseHandle ((HANDLE) handle);
  198986. }
  198987. void* juce_createThread (void* userData) throw()
  198988. {
  198989. unsigned int threadId;
  198990. return (void*) _beginthreadex (0, 0,
  198991. &threadEntryProc,
  198992. userData,
  198993. 0, &threadId);
  198994. }
  198995. void juce_killThread (void* handle) throw()
  198996. {
  198997. if (handle != 0)
  198998. {
  198999. #ifdef JUCE_DEBUG
  199000. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  199001. #endif
  199002. TerminateThread (handle, 0);
  199003. }
  199004. }
  199005. void juce_setCurrentThreadName (const String& name) throw()
  199006. {
  199007. #if defined (JUCE_DEBUG) && JUCE_MSVC
  199008. struct
  199009. {
  199010. DWORD dwType;
  199011. LPCSTR szName;
  199012. DWORD dwThreadID;
  199013. DWORD dwFlags;
  199014. } info;
  199015. info.dwType = 0x1000;
  199016. info.szName = name;
  199017. info.dwThreadID = GetCurrentThreadId();
  199018. info.dwFlags = 0;
  199019. #define MS_VC_EXCEPTION 0x406d1388
  199020. __try
  199021. {
  199022. RaiseException (MS_VC_EXCEPTION, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  199023. }
  199024. __except (EXCEPTION_CONTINUE_EXECUTION)
  199025. {}
  199026. #else
  199027. (void) name;
  199028. #endif
  199029. }
  199030. int Thread::getCurrentThreadId() throw()
  199031. {
  199032. return (int) GetCurrentThreadId();
  199033. }
  199034. // priority 1 to 10 where 5=normal, 1=low
  199035. void juce_setThreadPriority (void* threadHandle, int priority) throw()
  199036. {
  199037. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  199038. if (priority < 1)
  199039. pri = THREAD_PRIORITY_IDLE;
  199040. else if (priority < 2)
  199041. pri = THREAD_PRIORITY_LOWEST;
  199042. else if (priority < 5)
  199043. pri = THREAD_PRIORITY_BELOW_NORMAL;
  199044. else if (priority < 7)
  199045. pri = THREAD_PRIORITY_NORMAL;
  199046. else if (priority < 9)
  199047. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  199048. else if (priority < 10)
  199049. pri = THREAD_PRIORITY_HIGHEST;
  199050. if (threadHandle == 0)
  199051. threadHandle = GetCurrentThread();
  199052. SetThreadPriority (threadHandle, pri);
  199053. }
  199054. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  199055. {
  199056. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  199057. }
  199058. static HANDLE sleepEvent = 0;
  199059. void juce_initialiseThreadEvents() throw()
  199060. {
  199061. if (sleepEvent == 0)
  199062. #ifdef JUCE_DEBUG
  199063. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  199064. #else
  199065. sleepEvent = CreateEvent (0, 0, 0, 0);
  199066. #endif
  199067. }
  199068. void Thread::yield() throw()
  199069. {
  199070. Sleep (0);
  199071. }
  199072. void JUCE_CALLTYPE Thread::sleep (const int millisecs) throw()
  199073. {
  199074. if (millisecs >= 10)
  199075. {
  199076. Sleep (millisecs);
  199077. }
  199078. else
  199079. {
  199080. jassert (sleepEvent != 0);
  199081. // unlike Sleep() this is guaranteed to return to the current thread after
  199082. // the time expires, so we'll use this for short waits, which are more likely
  199083. // to need to be accurate
  199084. WaitForSingleObject (sleepEvent, millisecs);
  199085. }
  199086. }
  199087. static int lastProcessPriority = -1;
  199088. // called by WindowDriver because Windows does wierd things to process priority
  199089. // when you swap apps, and this forces an update when the app is brought to the front.
  199090. void juce_repeatLastProcessPriority() throw()
  199091. {
  199092. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  199093. {
  199094. DWORD p;
  199095. switch (lastProcessPriority)
  199096. {
  199097. case Process::LowPriority:
  199098. p = IDLE_PRIORITY_CLASS;
  199099. break;
  199100. case Process::NormalPriority:
  199101. p = NORMAL_PRIORITY_CLASS;
  199102. break;
  199103. case Process::HighPriority:
  199104. p = HIGH_PRIORITY_CLASS;
  199105. break;
  199106. case Process::RealtimePriority:
  199107. p = REALTIME_PRIORITY_CLASS;
  199108. break;
  199109. default:
  199110. jassertfalse // bad priority value
  199111. return;
  199112. }
  199113. SetPriorityClass (GetCurrentProcess(), p);
  199114. }
  199115. }
  199116. void Process::setPriority (ProcessPriority prior)
  199117. {
  199118. if (lastProcessPriority != (int) prior)
  199119. {
  199120. lastProcessPriority = (int) prior;
  199121. juce_repeatLastProcessPriority();
  199122. }
  199123. }
  199124. bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  199125. {
  199126. return IsDebuggerPresent() != FALSE;
  199127. }
  199128. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  199129. {
  199130. return juce_isRunningUnderDebugger();
  199131. }
  199132. void Process::raisePrivilege()
  199133. {
  199134. jassertfalse // xxx not implemented
  199135. }
  199136. void Process::lowerPrivilege()
  199137. {
  199138. jassertfalse // xxx not implemented
  199139. }
  199140. void Process::terminate()
  199141. {
  199142. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  199143. _CrtDumpMemoryLeaks();
  199144. #endif
  199145. // bullet in the head in case there's a problem shutting down..
  199146. ExitProcess (0);
  199147. }
  199148. void* Process::loadDynamicLibrary (const String& name)
  199149. {
  199150. void* result = 0;
  199151. JUCE_TRY
  199152. {
  199153. result = (void*) LoadLibrary (name);
  199154. }
  199155. JUCE_CATCH_ALL
  199156. return result;
  199157. }
  199158. void Process::freeDynamicLibrary (void* h)
  199159. {
  199160. JUCE_TRY
  199161. {
  199162. if (h != 0)
  199163. FreeLibrary ((HMODULE) h);
  199164. }
  199165. JUCE_CATCH_ALL
  199166. }
  199167. void* Process::getProcedureEntryPoint (void* h, const String& name)
  199168. {
  199169. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name)
  199170. : 0;
  199171. }
  199172. InterProcessLock::InterProcessLock (const String& name_) throw()
  199173. : internal (0),
  199174. name (name_),
  199175. reentrancyLevel (0)
  199176. {
  199177. }
  199178. InterProcessLock::~InterProcessLock() throw()
  199179. {
  199180. exit();
  199181. }
  199182. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  199183. {
  199184. if (reentrancyLevel++ == 0)
  199185. {
  199186. internal = CreateMutex (0, TRUE, name);
  199187. if (internal != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  199188. {
  199189. if (timeOutMillisecs == 0
  199190. || WaitForSingleObject (internal, (timeOutMillisecs < 0) ? INFINITE : timeOutMillisecs)
  199191. == WAIT_TIMEOUT)
  199192. {
  199193. ReleaseMutex (internal);
  199194. CloseHandle (internal);
  199195. internal = 0;
  199196. }
  199197. }
  199198. }
  199199. return (internal != 0);
  199200. }
  199201. void InterProcessLock::exit() throw()
  199202. {
  199203. if (--reentrancyLevel == 0 && internal != 0)
  199204. {
  199205. ReleaseMutex (internal);
  199206. CloseHandle (internal);
  199207. internal = 0;
  199208. }
  199209. }
  199210. END_JUCE_NAMESPACE
  199211. /********* End of inlined file: juce_win32_Threads.cpp *********/
  199212. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  199213. BEGIN_JUCE_NAMESPACE
  199214. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  199215. {
  199216. libHandle = LoadLibrary (name);
  199217. }
  199218. DynamicLibraryLoader::~DynamicLibraryLoader()
  199219. {
  199220. FreeLibrary ((HMODULE) libHandle);
  199221. }
  199222. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  199223. {
  199224. return (void*) GetProcAddress ((HMODULE) libHandle, functionName);
  199225. }
  199226. END_JUCE_NAMESPACE
  199227. /********* End of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  199228. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  199229. /********* Start of inlined file: juce_win32_ASIO.cpp *********/
  199230. #undef WINDOWS
  199231. #if JUCE_ASIO
  199232. /*
  199233. This is very frustrating - we only need to use a handful of definitions from
  199234. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  199235. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  199236. implementation...
  199237. ..unfortunately that would break Steinberg's license agreement for use of
  199238. their SDK, so I'm not allowed to do this.
  199239. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  199240. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  199241. (see www.steinberg.net/Steinberg/Developers.asp).
  199242. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  199243. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  199244. if you prefer). Make sure that your header search path will find the
  199245. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  199246. files are actually needed - so to simplify things, you could just copy
  199247. these into your JUCE directory).
  199248. */
  199249. #include "iasiodrv.h" // if you're compiling and this line causes an error because
  199250. // you don't have the ASIO SDK installed, you can disable ASIO
  199251. // support by commenting-out the "#define JUCE_ASIO" line in
  199252. // juce_Config.h
  199253. BEGIN_JUCE_NAMESPACE
  199254. // #define ASIO_DEBUGGING
  199255. #ifdef ASIO_DEBUGGING
  199256. #define log(a) { Logger::writeToLog (a); DBG (a) }
  199257. #else
  199258. #define log(a) {}
  199259. #endif
  199260. #ifdef ASIO_DEBUGGING
  199261. static void logError (const String& context, long error)
  199262. {
  199263. String err ("unknown error");
  199264. if (error == ASE_NotPresent)
  199265. err = "Not Present";
  199266. else if (error == ASE_HWMalfunction)
  199267. err = "Hardware Malfunction";
  199268. else if (error == ASE_InvalidParameter)
  199269. err = "Invalid Parameter";
  199270. else if (error == ASE_InvalidMode)
  199271. err = "Invalid Mode";
  199272. else if (error == ASE_SPNotAdvancing)
  199273. err = "Sample position not advancing";
  199274. else if (error == ASE_NoClock)
  199275. err = "No Clock";
  199276. else if (error == ASE_NoMemory)
  199277. err = "Out of memory";
  199278. log (T("!!error: ") + context + T(" - ") + err);
  199279. }
  199280. #else
  199281. #define logError(a, b) {}
  199282. #endif
  199283. class ASIOAudioIODevice;
  199284. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  199285. static const int maxASIOChannels = 160;
  199286. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  199287. private Timer
  199288. {
  199289. public:
  199290. Component ourWindow;
  199291. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber)
  199292. : AudioIODevice (name_, T("ASIO")),
  199293. asioObject (0),
  199294. classId (classId_),
  199295. currentBitDepth (16),
  199296. currentSampleRate (0),
  199297. tempBuffer (0),
  199298. isOpen_ (false),
  199299. isStarted (false),
  199300. postOutput (true),
  199301. insideControlPanelModalLoop (false),
  199302. shouldUsePreferredSize (false)
  199303. {
  199304. name = name_;
  199305. ourWindow.addToDesktop (0);
  199306. windowHandle = ourWindow.getWindowHandle();
  199307. jassert (currentASIODev [slotNumber] == 0);
  199308. currentASIODev [slotNumber] = this;
  199309. openDevice();
  199310. }
  199311. ~ASIOAudioIODevice()
  199312. {
  199313. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  199314. if (currentASIODev[i] == this)
  199315. currentASIODev[i] = 0;
  199316. close();
  199317. log ("ASIO - exiting");
  199318. removeCurrentDriver();
  199319. juce_free (tempBuffer);
  199320. }
  199321. void updateSampleRates()
  199322. {
  199323. // find a list of sample rates..
  199324. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  199325. sampleRates.clear();
  199326. if (asioObject != 0)
  199327. {
  199328. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  199329. {
  199330. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  199331. if (err == 0)
  199332. {
  199333. sampleRates.add ((int) possibleSampleRates[index]);
  199334. log (T("rate: ") + String ((int) possibleSampleRates[index]));
  199335. }
  199336. else if (err != ASE_NoClock)
  199337. {
  199338. logError (T("CanSampleRate"), err);
  199339. }
  199340. }
  199341. if (sampleRates.size() == 0)
  199342. {
  199343. double cr = 0;
  199344. const long err = asioObject->getSampleRate (&cr);
  199345. log (T("No sample rates supported - current rate: ") + String ((int) cr));
  199346. if (err == 0)
  199347. sampleRates.add ((int) cr);
  199348. }
  199349. }
  199350. }
  199351. const StringArray getOutputChannelNames()
  199352. {
  199353. return outputChannelNames;
  199354. }
  199355. const StringArray getInputChannelNames()
  199356. {
  199357. return inputChannelNames;
  199358. }
  199359. int getNumSampleRates()
  199360. {
  199361. return sampleRates.size();
  199362. }
  199363. double getSampleRate (int index)
  199364. {
  199365. return sampleRates [index];
  199366. }
  199367. int getNumBufferSizesAvailable()
  199368. {
  199369. return bufferSizes.size();
  199370. }
  199371. int getBufferSizeSamples (int index)
  199372. {
  199373. return bufferSizes [index];
  199374. }
  199375. int getDefaultBufferSize()
  199376. {
  199377. return preferredSize;
  199378. }
  199379. const String open (const BitArray& inputChannels,
  199380. const BitArray& outputChannels,
  199381. double sr,
  199382. int bufferSizeSamples)
  199383. {
  199384. close();
  199385. currentCallback = 0;
  199386. if (bufferSizeSamples <= 0)
  199387. shouldUsePreferredSize = true;
  199388. if (asioObject == 0 || ! isASIOOpen)
  199389. {
  199390. log ("Warning: device not open");
  199391. const String err (openDevice());
  199392. if (asioObject == 0 || ! isASIOOpen)
  199393. return err;
  199394. }
  199395. isStarted = false;
  199396. bufferIndex = -1;
  199397. long err = 0;
  199398. long newPreferredSize = 0;
  199399. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  199400. minSize = 0;
  199401. maxSize = 0;
  199402. newPreferredSize = 0;
  199403. granularity = 0;
  199404. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  199405. {
  199406. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  199407. shouldUsePreferredSize = true;
  199408. preferredSize = newPreferredSize;
  199409. }
  199410. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  199411. // dynamic changes to the buffer size...
  199412. shouldUsePreferredSize = shouldUsePreferredSize
  199413. || getName().containsIgnoreCase (T("Digidesign"));
  199414. if (shouldUsePreferredSize)
  199415. {
  199416. log ("Using preferred size for buffer..");
  199417. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  199418. {
  199419. bufferSizeSamples = preferredSize;
  199420. }
  199421. else
  199422. {
  199423. bufferSizeSamples = 1024;
  199424. logError ("GetBufferSize1", err);
  199425. }
  199426. shouldUsePreferredSize = false;
  199427. }
  199428. int sampleRate = roundDoubleToInt (sr);
  199429. currentSampleRate = sampleRate;
  199430. currentBlockSizeSamples = bufferSizeSamples;
  199431. currentChansOut.clear();
  199432. currentChansIn.clear();
  199433. zeromem (inBuffers, sizeof (inBuffers));
  199434. zeromem (outBuffers, sizeof (outBuffers));
  199435. updateSampleRates();
  199436. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  199437. sampleRate = sampleRates[0];
  199438. jassert (sampleRate != 0);
  199439. if (sampleRate == 0)
  199440. sampleRate = 44100;
  199441. long numSources = 32;
  199442. ASIOClockSource clocks[32];
  199443. zeromem (clocks, sizeof (clocks));
  199444. asioObject->getClockSources (clocks, &numSources);
  199445. bool isSourceSet = false;
  199446. // careful not to remove this loop because it does more than just logging!
  199447. int i;
  199448. for (i = 0; i < numSources; ++i)
  199449. {
  199450. String s ("clock: ");
  199451. s += clocks[i].name;
  199452. if (clocks[i].isCurrentSource)
  199453. {
  199454. isSourceSet = true;
  199455. s << " (cur)";
  199456. }
  199457. log (s);
  199458. }
  199459. if (numSources > 1 && ! isSourceSet)
  199460. {
  199461. log ("setting clock source");
  199462. asioObject->setClockSource (clocks[0].index);
  199463. Thread::sleep (20);
  199464. }
  199465. else
  199466. {
  199467. if (numSources == 0)
  199468. {
  199469. log ("ASIO - no clock sources!");
  199470. }
  199471. }
  199472. double cr = 0;
  199473. err = asioObject->getSampleRate (&cr);
  199474. if (err == 0)
  199475. {
  199476. currentSampleRate = cr;
  199477. }
  199478. else
  199479. {
  199480. logError ("GetSampleRate", err);
  199481. currentSampleRate = 0;
  199482. }
  199483. error = String::empty;
  199484. needToReset = false;
  199485. isReSync = false;
  199486. err = 0;
  199487. bool buffersCreated = false;
  199488. if (currentSampleRate != sampleRate)
  199489. {
  199490. log (T("ASIO samplerate: ") + String (currentSampleRate) + T(" to ") + String (sampleRate));
  199491. err = asioObject->setSampleRate (sampleRate);
  199492. if (err == ASE_NoClock && numSources > 0)
  199493. {
  199494. log ("trying to set a clock source..");
  199495. Thread::sleep (10);
  199496. err = asioObject->setClockSource (clocks[0].index);
  199497. if (err != 0)
  199498. {
  199499. logError ("SetClock", err);
  199500. }
  199501. Thread::sleep (10);
  199502. err = asioObject->setSampleRate (sampleRate);
  199503. }
  199504. }
  199505. if (err == 0)
  199506. {
  199507. currentSampleRate = sampleRate;
  199508. if (needToReset)
  199509. {
  199510. if (isReSync)
  199511. {
  199512. log ("Resync request");
  199513. }
  199514. log ("! Resetting ASIO after sample rate change");
  199515. removeCurrentDriver();
  199516. loadDriver();
  199517. const String error (initDriver());
  199518. if (error.isNotEmpty())
  199519. {
  199520. log (T("ASIOInit: ") + error);
  199521. }
  199522. needToReset = false;
  199523. isReSync = false;
  199524. }
  199525. numActiveInputChans = 0;
  199526. numActiveOutputChans = 0;
  199527. ASIOBufferInfo* info = bufferInfos;
  199528. int i;
  199529. for (i = 0; i < totalNumInputChans; ++i)
  199530. {
  199531. if (inputChannels[i])
  199532. {
  199533. currentChansIn.setBit (i);
  199534. info->isInput = 1;
  199535. info->channelNum = i;
  199536. info->buffers[0] = info->buffers[1] = 0;
  199537. ++info;
  199538. ++numActiveInputChans;
  199539. }
  199540. }
  199541. for (i = 0; i < totalNumOutputChans; ++i)
  199542. {
  199543. if (outputChannels[i])
  199544. {
  199545. currentChansOut.setBit (i);
  199546. info->isInput = 0;
  199547. info->channelNum = i;
  199548. info->buffers[0] = info->buffers[1] = 0;
  199549. ++info;
  199550. ++numActiveOutputChans;
  199551. }
  199552. }
  199553. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  199554. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  199555. if (currentASIODev[0] == this)
  199556. {
  199557. callbacks.bufferSwitch = &bufferSwitchCallback0;
  199558. callbacks.asioMessage = &asioMessagesCallback0;
  199559. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  199560. }
  199561. else if (currentASIODev[1] == this)
  199562. {
  199563. callbacks.bufferSwitch = &bufferSwitchCallback1;
  199564. callbacks.asioMessage = &asioMessagesCallback1;
  199565. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  199566. }
  199567. else if (currentASIODev[2] == this)
  199568. {
  199569. callbacks.bufferSwitch = &bufferSwitchCallback2;
  199570. callbacks.asioMessage = &asioMessagesCallback2;
  199571. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  199572. }
  199573. else
  199574. {
  199575. jassertfalse
  199576. }
  199577. log ("disposing buffers");
  199578. err = asioObject->disposeBuffers();
  199579. log (T("creating buffers: ") + String (totalBuffers) + T(", ") + String (currentBlockSizeSamples));
  199580. err = asioObject->createBuffers (bufferInfos,
  199581. totalBuffers,
  199582. currentBlockSizeSamples,
  199583. &callbacks);
  199584. if (err != 0)
  199585. {
  199586. currentBlockSizeSamples = preferredSize;
  199587. logError ("create buffers 2", err);
  199588. asioObject->disposeBuffers();
  199589. err = asioObject->createBuffers (bufferInfos,
  199590. totalBuffers,
  199591. currentBlockSizeSamples,
  199592. &callbacks);
  199593. }
  199594. if (err == 0)
  199595. {
  199596. buffersCreated = true;
  199597. juce_free (tempBuffer);
  199598. tempBuffer = (float*) juce_calloc (totalBuffers * currentBlockSizeSamples * sizeof (float) + 128);
  199599. int n = 0;
  199600. Array <int> types;
  199601. currentBitDepth = 16;
  199602. for (i = 0; i < jmin (totalNumInputChans, maxASIOChannels); ++i)
  199603. {
  199604. if (inputChannels[i])
  199605. {
  199606. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  199607. ASIOChannelInfo channelInfo;
  199608. zerostruct (channelInfo);
  199609. channelInfo.channel = i;
  199610. channelInfo.isInput = 1;
  199611. asioObject->getChannelInfo (&channelInfo);
  199612. types.addIfNotAlreadyThere (channelInfo.type);
  199613. typeToFormatParameters (channelInfo.type,
  199614. inputChannelBitDepths[n],
  199615. inputChannelBytesPerSample[n],
  199616. inputChannelIsFloat[n],
  199617. inputChannelLittleEndian[n]);
  199618. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  199619. ++n;
  199620. }
  199621. }
  199622. jassert (numActiveInputChans == n);
  199623. n = 0;
  199624. for (i = 0; i < jmin (totalNumOutputChans, maxASIOChannels); ++i)
  199625. {
  199626. if (outputChannels[i])
  199627. {
  199628. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  199629. ASIOChannelInfo channelInfo;
  199630. zerostruct (channelInfo);
  199631. channelInfo.channel = i;
  199632. channelInfo.isInput = 0;
  199633. asioObject->getChannelInfo (&channelInfo);
  199634. types.addIfNotAlreadyThere (channelInfo.type);
  199635. typeToFormatParameters (channelInfo.type,
  199636. outputChannelBitDepths[n],
  199637. outputChannelBytesPerSample[n],
  199638. outputChannelIsFloat[n],
  199639. outputChannelLittleEndian[n]);
  199640. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  199641. ++n;
  199642. }
  199643. }
  199644. jassert (numActiveOutputChans == n);
  199645. for (i = types.size(); --i >= 0;)
  199646. {
  199647. log (T("channel format: ") + String (types[i]));
  199648. }
  199649. jassert (n <= totalBuffers);
  199650. for (i = 0; i < numActiveOutputChans; ++i)
  199651. {
  199652. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  199653. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  199654. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  199655. {
  199656. log ("!! Null buffers");
  199657. }
  199658. else
  199659. {
  199660. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  199661. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  199662. }
  199663. }
  199664. inputLatency = outputLatency = 0;
  199665. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  199666. {
  199667. log ("ASIO - no latencies");
  199668. }
  199669. else
  199670. {
  199671. log (T("ASIO latencies: ")
  199672. + String ((int) outputLatency)
  199673. + T(", ")
  199674. + String ((int) inputLatency));
  199675. }
  199676. isOpen_ = true;
  199677. log ("starting ASIO");
  199678. calledback = false;
  199679. err = asioObject->start();
  199680. if (err != 0)
  199681. {
  199682. isOpen_ = false;
  199683. log ("ASIO - stop on failure");
  199684. Thread::sleep (10);
  199685. asioObject->stop();
  199686. error = "Can't start device";
  199687. Thread::sleep (10);
  199688. }
  199689. else
  199690. {
  199691. int count = 300;
  199692. while (--count > 0 && ! calledback)
  199693. Thread::sleep (10);
  199694. isStarted = true;
  199695. if (! calledback)
  199696. {
  199697. error = "Device didn't start correctly";
  199698. log ("ASIO didn't callback - stopping..");
  199699. asioObject->stop();
  199700. }
  199701. }
  199702. }
  199703. else
  199704. {
  199705. error = "Can't create i/o buffers";
  199706. }
  199707. }
  199708. else
  199709. {
  199710. error = "Can't set sample rate: ";
  199711. error << sampleRate;
  199712. }
  199713. if (error.isNotEmpty())
  199714. {
  199715. logError (error, err);
  199716. if (asioObject != 0 && buffersCreated)
  199717. asioObject->disposeBuffers();
  199718. Thread::sleep (20);
  199719. isStarted = false;
  199720. isOpen_ = false;
  199721. close();
  199722. }
  199723. needToReset = false;
  199724. isReSync = false;
  199725. return error;
  199726. }
  199727. void close()
  199728. {
  199729. error = String::empty;
  199730. stopTimer();
  199731. stop();
  199732. if (isASIOOpen && isOpen_)
  199733. {
  199734. const ScopedLock sl (callbackLock);
  199735. isOpen_ = false;
  199736. isStarted = false;
  199737. needToReset = false;
  199738. isReSync = false;
  199739. log ("ASIO - stopping");
  199740. if (asioObject != 0)
  199741. {
  199742. Thread::sleep (20);
  199743. asioObject->stop();
  199744. Thread::sleep (10);
  199745. asioObject->disposeBuffers();
  199746. }
  199747. Thread::sleep (10);
  199748. }
  199749. }
  199750. bool isOpen()
  199751. {
  199752. return isOpen_ || insideControlPanelModalLoop;
  199753. }
  199754. int getCurrentBufferSizeSamples()
  199755. {
  199756. return currentBlockSizeSamples;
  199757. }
  199758. double getCurrentSampleRate()
  199759. {
  199760. return currentSampleRate;
  199761. }
  199762. const BitArray getActiveOutputChannels() const
  199763. {
  199764. return currentChansOut;
  199765. }
  199766. const BitArray getActiveInputChannels() const
  199767. {
  199768. return currentChansIn;
  199769. }
  199770. int getCurrentBitDepth()
  199771. {
  199772. return currentBitDepth;
  199773. }
  199774. int getOutputLatencyInSamples()
  199775. {
  199776. return outputLatency + currentBlockSizeSamples / 4;
  199777. }
  199778. int getInputLatencyInSamples()
  199779. {
  199780. return inputLatency + currentBlockSizeSamples / 4;
  199781. }
  199782. void start (AudioIODeviceCallback* callback)
  199783. {
  199784. if (callback != 0)
  199785. {
  199786. callback->audioDeviceAboutToStart (this);
  199787. const ScopedLock sl (callbackLock);
  199788. currentCallback = callback;
  199789. }
  199790. }
  199791. void stop()
  199792. {
  199793. AudioIODeviceCallback* const lastCallback = currentCallback;
  199794. {
  199795. const ScopedLock sl (callbackLock);
  199796. currentCallback = 0;
  199797. }
  199798. if (lastCallback != 0)
  199799. lastCallback->audioDeviceStopped();
  199800. }
  199801. bool isPlaying()
  199802. {
  199803. return isASIOOpen && (currentCallback != 0);
  199804. }
  199805. const String getLastError()
  199806. {
  199807. return error;
  199808. }
  199809. bool hasControlPanel() const
  199810. {
  199811. return true;
  199812. }
  199813. bool showControlPanel()
  199814. {
  199815. log ("ASIO - showing control panel");
  199816. Component modalWindow (String::empty);
  199817. modalWindow.setOpaque (true);
  199818. modalWindow.addToDesktop (0);
  199819. modalWindow.enterModalState();
  199820. bool done = false;
  199821. JUCE_TRY
  199822. {
  199823. close();
  199824. insideControlPanelModalLoop = true;
  199825. const uint32 started = Time::getMillisecondCounter();
  199826. if (asioObject != 0)
  199827. {
  199828. asioObject->controlPanel();
  199829. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  199830. log (T("spent: ") + String (spent));
  199831. if (spent > 300)
  199832. {
  199833. shouldUsePreferredSize = true;
  199834. done = true;
  199835. }
  199836. }
  199837. }
  199838. JUCE_CATCH_ALL
  199839. insideControlPanelModalLoop = false;
  199840. return done;
  199841. }
  199842. void resetRequest() throw()
  199843. {
  199844. needToReset = true;
  199845. }
  199846. void resyncRequest() throw()
  199847. {
  199848. needToReset = true;
  199849. isReSync = true;
  199850. }
  199851. void timerCallback()
  199852. {
  199853. if (! insideControlPanelModalLoop)
  199854. {
  199855. stopTimer();
  199856. // used to cause a reset
  199857. log ("! ASIO restart request!");
  199858. if (isOpen_)
  199859. {
  199860. AudioIODeviceCallback* const oldCallback = currentCallback;
  199861. close();
  199862. open (BitArray (currentChansIn), BitArray (currentChansOut),
  199863. currentSampleRate, currentBlockSizeSamples);
  199864. if (oldCallback != 0)
  199865. start (oldCallback);
  199866. }
  199867. }
  199868. else
  199869. {
  199870. startTimer (100);
  199871. }
  199872. }
  199873. juce_UseDebuggingNewOperator
  199874. private:
  199875. IASIO* volatile asioObject;
  199876. ASIOCallbacks callbacks;
  199877. void* windowHandle;
  199878. CLSID classId;
  199879. String error;
  199880. long totalNumInputChans, totalNumOutputChans;
  199881. StringArray inputChannelNames, outputChannelNames;
  199882. Array<int> sampleRates, bufferSizes;
  199883. long inputLatency, outputLatency;
  199884. long minSize, maxSize, preferredSize, granularity;
  199885. int volatile currentBlockSizeSamples;
  199886. int volatile currentBitDepth;
  199887. double volatile currentSampleRate;
  199888. BitArray currentChansOut, currentChansIn;
  199889. AudioIODeviceCallback* volatile currentCallback;
  199890. CriticalSection callbackLock;
  199891. ASIOBufferInfo bufferInfos [maxASIOChannels];
  199892. float* inBuffers [maxASIOChannels];
  199893. float* outBuffers [maxASIOChannels];
  199894. int inputChannelBitDepths [maxASIOChannels];
  199895. int outputChannelBitDepths [maxASIOChannels];
  199896. int inputChannelBytesPerSample [maxASIOChannels];
  199897. int outputChannelBytesPerSample [maxASIOChannels];
  199898. bool inputChannelIsFloat [maxASIOChannels];
  199899. bool outputChannelIsFloat [maxASIOChannels];
  199900. bool inputChannelLittleEndian [maxASIOChannels];
  199901. bool outputChannelLittleEndian [maxASIOChannels];
  199902. WaitableEvent event1;
  199903. float* tempBuffer;
  199904. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  199905. bool isOpen_, isStarted;
  199906. bool volatile isASIOOpen;
  199907. bool volatile calledback;
  199908. bool volatile littleEndian, postOutput, needToReset, isReSync;
  199909. bool volatile insideControlPanelModalLoop;
  199910. bool volatile shouldUsePreferredSize;
  199911. void removeCurrentDriver()
  199912. {
  199913. if (asioObject != 0)
  199914. {
  199915. asioObject->Release();
  199916. asioObject = 0;
  199917. }
  199918. }
  199919. bool loadDriver()
  199920. {
  199921. removeCurrentDriver();
  199922. JUCE_TRY
  199923. {
  199924. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  199925. classId, (void**) &asioObject) == S_OK)
  199926. {
  199927. return true;
  199928. }
  199929. }
  199930. JUCE_CATCH_ALL
  199931. asioObject = 0;
  199932. return false;
  199933. }
  199934. const String initDriver()
  199935. {
  199936. if (asioObject != 0)
  199937. {
  199938. char buffer [256];
  199939. zeromem (buffer, sizeof (buffer));
  199940. if (! asioObject->init (windowHandle))
  199941. {
  199942. asioObject->getErrorMessage (buffer);
  199943. return String (buffer, sizeof (buffer) - 1);
  199944. }
  199945. // just in case any daft drivers expect this to be called..
  199946. asioObject->getDriverName (buffer);
  199947. return String::empty;
  199948. }
  199949. return "No Driver";
  199950. }
  199951. const String openDevice()
  199952. {
  199953. // use this in case the driver starts opening dialog boxes..
  199954. Component modalWindow (String::empty);
  199955. modalWindow.setOpaque (true);
  199956. modalWindow.addToDesktop (0);
  199957. modalWindow.enterModalState();
  199958. // open the device and get its info..
  199959. log (T("opening ASIO device: ") + getName());
  199960. needToReset = false;
  199961. isReSync = false;
  199962. outputChannelNames.clear();
  199963. inputChannelNames.clear();
  199964. bufferSizes.clear();
  199965. sampleRates.clear();
  199966. isASIOOpen = false;
  199967. isOpen_ = false;
  199968. totalNumInputChans = 0;
  199969. totalNumOutputChans = 0;
  199970. numActiveInputChans = 0;
  199971. numActiveOutputChans = 0;
  199972. currentCallback = 0;
  199973. error = String::empty;
  199974. if (getName().isEmpty())
  199975. return error;
  199976. long err = 0;
  199977. if (loadDriver())
  199978. {
  199979. if ((error = initDriver()).isEmpty())
  199980. {
  199981. numActiveInputChans = 0;
  199982. numActiveOutputChans = 0;
  199983. totalNumInputChans = 0;
  199984. totalNumOutputChans = 0;
  199985. if (asioObject != 0
  199986. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  199987. {
  199988. log (String ((int) totalNumInputChans) + T(" in, ") + String ((int) totalNumOutputChans) + T(" out"));
  199989. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  199990. {
  199991. // find a list of buffer sizes..
  199992. log (String ((int) minSize) + T(" ") + String ((int) maxSize) + T(" ") + String ((int)preferredSize) + T(" ") + String ((int)granularity));
  199993. if (granularity >= 0)
  199994. {
  199995. granularity = jmax (1, (int) granularity);
  199996. for (int i = jmax (minSize, (int) granularity); i < jmin (6400, maxSize); i += granularity)
  199997. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  199998. }
  199999. else if (granularity < 0)
  200000. {
  200001. for (int i = 0; i < 18; ++i)
  200002. {
  200003. const int s = (1 << i);
  200004. if (s >= minSize && s <= maxSize)
  200005. bufferSizes.add (s);
  200006. }
  200007. }
  200008. if (! bufferSizes.contains (preferredSize))
  200009. bufferSizes.insert (0, preferredSize);
  200010. double currentRate = 0;
  200011. asioObject->getSampleRate (&currentRate);
  200012. if (currentRate <= 0.0 || currentRate > 192001.0)
  200013. {
  200014. log ("setting sample rate");
  200015. err = asioObject->setSampleRate (44100.0);
  200016. if (err != 0)
  200017. {
  200018. logError ("setting sample rate", err);
  200019. }
  200020. asioObject->getSampleRate (&currentRate);
  200021. }
  200022. currentSampleRate = currentRate;
  200023. postOutput = (asioObject->outputReady() == 0);
  200024. if (postOutput)
  200025. {
  200026. log ("ASIO outputReady = ok");
  200027. }
  200028. updateSampleRates();
  200029. // ..because cubase does it at this point
  200030. inputLatency = outputLatency = 0;
  200031. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  200032. {
  200033. log ("ASIO - no latencies");
  200034. }
  200035. log (String ("latencies: ")
  200036. + String ((int) inputLatency)
  200037. + T(", ") + String ((int) outputLatency));
  200038. // create some dummy buffers now.. because cubase does..
  200039. numActiveInputChans = 0;
  200040. numActiveOutputChans = 0;
  200041. ASIOBufferInfo* info = bufferInfos;
  200042. int i, numChans = 0;
  200043. for (i = 0; i < jmin (2, totalNumInputChans); ++i)
  200044. {
  200045. info->isInput = 1;
  200046. info->channelNum = i;
  200047. info->buffers[0] = info->buffers[1] = 0;
  200048. ++info;
  200049. ++numChans;
  200050. }
  200051. const int outputBufferIndex = numChans;
  200052. for (i = 0; i < jmin (2, totalNumOutputChans); ++i)
  200053. {
  200054. info->isInput = 0;
  200055. info->channelNum = i;
  200056. info->buffers[0] = info->buffers[1] = 0;
  200057. ++info;
  200058. ++numChans;
  200059. }
  200060. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  200061. if (currentASIODev[0] == this)
  200062. {
  200063. callbacks.bufferSwitch = &bufferSwitchCallback0;
  200064. callbacks.asioMessage = &asioMessagesCallback0;
  200065. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  200066. }
  200067. else if (currentASIODev[1] == this)
  200068. {
  200069. callbacks.bufferSwitch = &bufferSwitchCallback1;
  200070. callbacks.asioMessage = &asioMessagesCallback1;
  200071. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  200072. }
  200073. else if (currentASIODev[2] == this)
  200074. {
  200075. callbacks.bufferSwitch = &bufferSwitchCallback2;
  200076. callbacks.asioMessage = &asioMessagesCallback2;
  200077. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  200078. }
  200079. else
  200080. {
  200081. jassertfalse
  200082. }
  200083. log (T("creating buffers (dummy): ") + String (numChans)
  200084. + T(", ") + String ((int) preferredSize));
  200085. if (preferredSize > 0)
  200086. {
  200087. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  200088. if (err != 0)
  200089. {
  200090. logError ("dummy buffers", err);
  200091. }
  200092. }
  200093. long newInps = 0, newOuts = 0;
  200094. asioObject->getChannels (&newInps, &newOuts);
  200095. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  200096. {
  200097. totalNumInputChans = newInps;
  200098. totalNumOutputChans = newOuts;
  200099. log (String ((int) totalNumInputChans) + T(" in; ")
  200100. + String ((int) totalNumOutputChans) + T(" out"));
  200101. }
  200102. updateSampleRates();
  200103. ASIOChannelInfo channelInfo;
  200104. channelInfo.type = 0;
  200105. for (i = 0; i < totalNumInputChans; ++i)
  200106. {
  200107. zerostruct (channelInfo);
  200108. channelInfo.channel = i;
  200109. channelInfo.isInput = 1;
  200110. asioObject->getChannelInfo (&channelInfo);
  200111. inputChannelNames.add (String (channelInfo.name));
  200112. }
  200113. for (i = 0; i < totalNumOutputChans; ++i)
  200114. {
  200115. zerostruct (channelInfo);
  200116. channelInfo.channel = i;
  200117. channelInfo.isInput = 0;
  200118. asioObject->getChannelInfo (&channelInfo);
  200119. outputChannelNames.add (String (channelInfo.name));
  200120. typeToFormatParameters (channelInfo.type,
  200121. outputChannelBitDepths[i],
  200122. outputChannelBytesPerSample[i],
  200123. outputChannelIsFloat[i],
  200124. outputChannelLittleEndian[i]);
  200125. if (i < 2)
  200126. {
  200127. // clear the channels that are used with the dummy stuff
  200128. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  200129. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  200130. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  200131. }
  200132. }
  200133. outputChannelNames.trim();
  200134. inputChannelNames.trim();
  200135. outputChannelNames.appendNumbersToDuplicates (false, true);
  200136. inputChannelNames.appendNumbersToDuplicates (false, true);
  200137. // start and stop because cubase does it..
  200138. asioObject->getLatencies (&inputLatency, &outputLatency);
  200139. if ((err = asioObject->start()) != 0)
  200140. {
  200141. // ignore an error here, as it might start later after setting other stuff up
  200142. logError ("ASIO start", err);
  200143. }
  200144. Thread::sleep (100);
  200145. asioObject->stop();
  200146. }
  200147. else
  200148. {
  200149. error = "Can't detect buffer sizes";
  200150. }
  200151. }
  200152. else
  200153. {
  200154. error = "Can't detect asio channels";
  200155. }
  200156. }
  200157. }
  200158. else
  200159. {
  200160. error = "No such device";
  200161. }
  200162. if (error.isNotEmpty())
  200163. {
  200164. logError (error, err);
  200165. if (asioObject != 0)
  200166. asioObject->disposeBuffers();
  200167. removeCurrentDriver();
  200168. isASIOOpen = false;
  200169. }
  200170. else
  200171. {
  200172. isASIOOpen = true;
  200173. log ("ASIO device open");
  200174. }
  200175. isOpen_ = false;
  200176. needToReset = false;
  200177. isReSync = false;
  200178. return error;
  200179. }
  200180. void callback (const long index) throw()
  200181. {
  200182. if (isStarted)
  200183. {
  200184. bufferIndex = index;
  200185. processBuffer();
  200186. }
  200187. else
  200188. {
  200189. if (postOutput && (asioObject != 0))
  200190. asioObject->outputReady();
  200191. }
  200192. calledback = true;
  200193. }
  200194. void processBuffer() throw()
  200195. {
  200196. const ASIOBufferInfo* const infos = bufferInfos;
  200197. const int bi = bufferIndex;
  200198. const ScopedLock sl (callbackLock);
  200199. if (needToReset)
  200200. {
  200201. needToReset = false;
  200202. if (isReSync)
  200203. {
  200204. log ("! ASIO resync");
  200205. isReSync = false;
  200206. }
  200207. else
  200208. {
  200209. startTimer (20);
  200210. }
  200211. }
  200212. if (bi >= 0)
  200213. {
  200214. const int samps = currentBlockSizeSamples;
  200215. if (currentCallback != 0)
  200216. {
  200217. int i;
  200218. for (i = 0; i < numActiveInputChans; ++i)
  200219. {
  200220. float* const dst = inBuffers[i];
  200221. jassert (dst != 0);
  200222. const char* const src = (const char*) (infos[i].buffers[bi]);
  200223. if (inputChannelIsFloat[i])
  200224. {
  200225. memcpy (dst, src, samps * sizeof (float));
  200226. }
  200227. else
  200228. {
  200229. jassert (dst == tempBuffer + (samps * i));
  200230. switch (inputChannelBitDepths[i])
  200231. {
  200232. case 16:
  200233. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  200234. samps, inputChannelLittleEndian[i]);
  200235. break;
  200236. case 24:
  200237. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  200238. samps, inputChannelLittleEndian[i]);
  200239. break;
  200240. case 32:
  200241. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  200242. samps, inputChannelLittleEndian[i]);
  200243. break;
  200244. case 64:
  200245. jassertfalse
  200246. break;
  200247. }
  200248. }
  200249. }
  200250. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  200251. numActiveInputChans,
  200252. outBuffers,
  200253. numActiveOutputChans,
  200254. samps);
  200255. for (i = 0; i < numActiveOutputChans; ++i)
  200256. {
  200257. float* const src = outBuffers[i];
  200258. jassert (src != 0);
  200259. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  200260. if (outputChannelIsFloat[i])
  200261. {
  200262. memcpy (dst, src, samps * sizeof (float));
  200263. }
  200264. else
  200265. {
  200266. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  200267. switch (outputChannelBitDepths[i])
  200268. {
  200269. case 16:
  200270. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  200271. samps, outputChannelLittleEndian[i]);
  200272. break;
  200273. case 24:
  200274. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  200275. samps, outputChannelLittleEndian[i]);
  200276. break;
  200277. case 32:
  200278. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  200279. samps, outputChannelLittleEndian[i]);
  200280. break;
  200281. case 64:
  200282. jassertfalse
  200283. break;
  200284. }
  200285. }
  200286. }
  200287. }
  200288. else
  200289. {
  200290. for (int i = 0; i < numActiveOutputChans; ++i)
  200291. {
  200292. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  200293. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  200294. }
  200295. }
  200296. }
  200297. if (postOutput)
  200298. asioObject->outputReady();
  200299. }
  200300. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long) throw()
  200301. {
  200302. if (currentASIODev[0] != 0)
  200303. currentASIODev[0]->callback (index);
  200304. return 0;
  200305. }
  200306. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long) throw()
  200307. {
  200308. if (currentASIODev[1] != 0)
  200309. currentASIODev[1]->callback (index);
  200310. return 0;
  200311. }
  200312. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long) throw()
  200313. {
  200314. if (currentASIODev[2] != 0)
  200315. currentASIODev[2]->callback (index);
  200316. return 0;
  200317. }
  200318. static void bufferSwitchCallback0 (long index, long) throw()
  200319. {
  200320. if (currentASIODev[0] != 0)
  200321. currentASIODev[0]->callback (index);
  200322. }
  200323. static void bufferSwitchCallback1 (long index, long) throw()
  200324. {
  200325. if (currentASIODev[1] != 0)
  200326. currentASIODev[1]->callback (index);
  200327. }
  200328. static void bufferSwitchCallback2 (long index, long) throw()
  200329. {
  200330. if (currentASIODev[2] != 0)
  200331. currentASIODev[2]->callback (index);
  200332. }
  200333. static long asioMessagesCallback0 (long selector, long value, void*, double*) throw()
  200334. {
  200335. return asioMessagesCallback (selector, value, 0);
  200336. }
  200337. static long asioMessagesCallback1 (long selector, long value, void*, double*) throw()
  200338. {
  200339. return asioMessagesCallback (selector, value, 1);
  200340. }
  200341. static long asioMessagesCallback2 (long selector, long value, void*, double*) throw()
  200342. {
  200343. return asioMessagesCallback (selector, value, 2);
  200344. }
  200345. static long asioMessagesCallback (long selector, long value, const int deviceIndex) throw()
  200346. {
  200347. switch (selector)
  200348. {
  200349. case kAsioSelectorSupported:
  200350. if (value == kAsioResetRequest
  200351. || value == kAsioEngineVersion
  200352. || value == kAsioResyncRequest
  200353. || value == kAsioLatenciesChanged
  200354. || value == kAsioSupportsInputMonitor)
  200355. return 1;
  200356. break;
  200357. case kAsioBufferSizeChange:
  200358. break;
  200359. case kAsioResetRequest:
  200360. if (currentASIODev[deviceIndex] != 0)
  200361. currentASIODev[deviceIndex]->resetRequest();
  200362. return 1;
  200363. case kAsioResyncRequest:
  200364. if (currentASIODev[deviceIndex] != 0)
  200365. currentASIODev[deviceIndex]->resyncRequest();
  200366. return 1;
  200367. case kAsioLatenciesChanged:
  200368. return 1;
  200369. case kAsioEngineVersion:
  200370. return 2;
  200371. case kAsioSupportsTimeInfo:
  200372. case kAsioSupportsTimeCode:
  200373. return 0;
  200374. }
  200375. return 0;
  200376. }
  200377. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  200378. {
  200379. }
  200380. static void convertInt16ToFloat (const char* src,
  200381. float* dest,
  200382. const int srcStrideBytes,
  200383. int numSamples,
  200384. const bool littleEndian) throw()
  200385. {
  200386. const double g = 1.0 / 32768.0;
  200387. if (littleEndian)
  200388. {
  200389. while (--numSamples >= 0)
  200390. {
  200391. *dest++ = (float) (g * (short) littleEndianShort (src));
  200392. src += srcStrideBytes;
  200393. }
  200394. }
  200395. else
  200396. {
  200397. while (--numSamples >= 0)
  200398. {
  200399. *dest++ = (float) (g * (short) bigEndianShort (src));
  200400. src += srcStrideBytes;
  200401. }
  200402. }
  200403. }
  200404. static void convertFloatToInt16 (const float* src,
  200405. char* dest,
  200406. const int dstStrideBytes,
  200407. int numSamples,
  200408. const bool littleEndian) throw()
  200409. {
  200410. const double maxVal = (double) 0x7fff;
  200411. if (littleEndian)
  200412. {
  200413. while (--numSamples >= 0)
  200414. {
  200415. *(uint16*) dest = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  200416. dest += dstStrideBytes;
  200417. }
  200418. }
  200419. else
  200420. {
  200421. while (--numSamples >= 0)
  200422. {
  200423. *(uint16*) dest = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  200424. dest += dstStrideBytes;
  200425. }
  200426. }
  200427. }
  200428. static void convertInt24ToFloat (const char* src,
  200429. float* dest,
  200430. const int srcStrideBytes,
  200431. int numSamples,
  200432. const bool littleEndian) throw()
  200433. {
  200434. const double g = 1.0 / 0x7fffff;
  200435. if (littleEndian)
  200436. {
  200437. while (--numSamples >= 0)
  200438. {
  200439. *dest++ = (float) (g * littleEndian24Bit (src));
  200440. src += srcStrideBytes;
  200441. }
  200442. }
  200443. else
  200444. {
  200445. while (--numSamples >= 0)
  200446. {
  200447. *dest++ = (float) (g * bigEndian24Bit (src));
  200448. src += srcStrideBytes;
  200449. }
  200450. }
  200451. }
  200452. static void convertFloatToInt24 (const float* src,
  200453. char* dest,
  200454. const int dstStrideBytes,
  200455. int numSamples,
  200456. const bool littleEndian) throw()
  200457. {
  200458. const double maxVal = (double) 0x7fffff;
  200459. if (littleEndian)
  200460. {
  200461. while (--numSamples >= 0)
  200462. {
  200463. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  200464. dest += dstStrideBytes;
  200465. }
  200466. }
  200467. else
  200468. {
  200469. while (--numSamples >= 0)
  200470. {
  200471. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  200472. dest += dstStrideBytes;
  200473. }
  200474. }
  200475. }
  200476. static void convertInt32ToFloat (const char* src,
  200477. float* dest,
  200478. const int srcStrideBytes,
  200479. int numSamples,
  200480. const bool littleEndian) throw()
  200481. {
  200482. const double g = 1.0 / 0x7fffffff;
  200483. if (littleEndian)
  200484. {
  200485. while (--numSamples >= 0)
  200486. {
  200487. *dest++ = (float) (g * (int) littleEndianInt (src));
  200488. src += srcStrideBytes;
  200489. }
  200490. }
  200491. else
  200492. {
  200493. while (--numSamples >= 0)
  200494. {
  200495. *dest++ = (float) (g * (int) bigEndianInt (src));
  200496. src += srcStrideBytes;
  200497. }
  200498. }
  200499. }
  200500. static void convertFloatToInt32 (const float* src,
  200501. char* dest,
  200502. const int dstStrideBytes,
  200503. int numSamples,
  200504. const bool littleEndian) throw()
  200505. {
  200506. const double maxVal = (double) 0x7fffffff;
  200507. if (littleEndian)
  200508. {
  200509. while (--numSamples >= 0)
  200510. {
  200511. *(uint32*) dest = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  200512. dest += dstStrideBytes;
  200513. }
  200514. }
  200515. else
  200516. {
  200517. while (--numSamples >= 0)
  200518. {
  200519. *(uint32*) dest = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  200520. dest += dstStrideBytes;
  200521. }
  200522. }
  200523. }
  200524. static void typeToFormatParameters (const long type,
  200525. int& bitDepth,
  200526. int& byteStride,
  200527. bool& formatIsFloat,
  200528. bool& littleEndian) throw()
  200529. {
  200530. bitDepth = 0;
  200531. littleEndian = false;
  200532. formatIsFloat = false;
  200533. switch (type)
  200534. {
  200535. case ASIOSTInt16MSB:
  200536. case ASIOSTInt16LSB:
  200537. case ASIOSTInt32MSB16:
  200538. case ASIOSTInt32LSB16:
  200539. bitDepth = 16; break;
  200540. case ASIOSTFloat32MSB:
  200541. case ASIOSTFloat32LSB:
  200542. formatIsFloat = true;
  200543. bitDepth = 32; break;
  200544. case ASIOSTInt32MSB:
  200545. case ASIOSTInt32LSB:
  200546. bitDepth = 32; break;
  200547. case ASIOSTInt24MSB:
  200548. case ASIOSTInt24LSB:
  200549. case ASIOSTInt32MSB24:
  200550. case ASIOSTInt32LSB24:
  200551. case ASIOSTInt32MSB18:
  200552. case ASIOSTInt32MSB20:
  200553. case ASIOSTInt32LSB18:
  200554. case ASIOSTInt32LSB20:
  200555. bitDepth = 24; break;
  200556. case ASIOSTFloat64MSB:
  200557. case ASIOSTFloat64LSB:
  200558. default:
  200559. bitDepth = 64;
  200560. break;
  200561. }
  200562. switch (type)
  200563. {
  200564. case ASIOSTInt16MSB:
  200565. case ASIOSTInt32MSB16:
  200566. case ASIOSTFloat32MSB:
  200567. case ASIOSTFloat64MSB:
  200568. case ASIOSTInt32MSB:
  200569. case ASIOSTInt32MSB18:
  200570. case ASIOSTInt32MSB20:
  200571. case ASIOSTInt32MSB24:
  200572. case ASIOSTInt24MSB:
  200573. littleEndian = false; break;
  200574. case ASIOSTInt16LSB:
  200575. case ASIOSTInt32LSB16:
  200576. case ASIOSTFloat32LSB:
  200577. case ASIOSTFloat64LSB:
  200578. case ASIOSTInt32LSB:
  200579. case ASIOSTInt32LSB18:
  200580. case ASIOSTInt32LSB20:
  200581. case ASIOSTInt32LSB24:
  200582. case ASIOSTInt24LSB:
  200583. littleEndian = true; break;
  200584. default:
  200585. break;
  200586. }
  200587. switch (type)
  200588. {
  200589. case ASIOSTInt16LSB:
  200590. case ASIOSTInt16MSB:
  200591. byteStride = 2; break;
  200592. case ASIOSTInt24LSB:
  200593. case ASIOSTInt24MSB:
  200594. byteStride = 3; break;
  200595. case ASIOSTInt32MSB16:
  200596. case ASIOSTInt32LSB16:
  200597. case ASIOSTInt32MSB:
  200598. case ASIOSTInt32MSB18:
  200599. case ASIOSTInt32MSB20:
  200600. case ASIOSTInt32MSB24:
  200601. case ASIOSTInt32LSB:
  200602. case ASIOSTInt32LSB18:
  200603. case ASIOSTInt32LSB20:
  200604. case ASIOSTInt32LSB24:
  200605. case ASIOSTFloat32LSB:
  200606. case ASIOSTFloat32MSB:
  200607. byteStride = 4; break;
  200608. case ASIOSTFloat64MSB:
  200609. case ASIOSTFloat64LSB:
  200610. byteStride = 8; break;
  200611. default:
  200612. break;
  200613. }
  200614. }
  200615. };
  200616. class ASIOAudioIODeviceType : public AudioIODeviceType
  200617. {
  200618. public:
  200619. ASIOAudioIODeviceType()
  200620. : AudioIODeviceType (T("ASIO")),
  200621. classIds (2),
  200622. hasScanned (false)
  200623. {
  200624. CoInitialize (0);
  200625. }
  200626. ~ASIOAudioIODeviceType()
  200627. {
  200628. }
  200629. void scanForDevices()
  200630. {
  200631. hasScanned = true;
  200632. deviceNames.clear();
  200633. classIds.clear();
  200634. HKEY hk = 0;
  200635. int index = 0;
  200636. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  200637. {
  200638. for (;;)
  200639. {
  200640. char name [256];
  200641. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  200642. {
  200643. addDriverInfo (name, hk);
  200644. }
  200645. else
  200646. {
  200647. break;
  200648. }
  200649. }
  200650. RegCloseKey (hk);
  200651. }
  200652. }
  200653. const StringArray getDeviceNames (const bool /*wantInputNames*/) const
  200654. {
  200655. jassert (hasScanned); // need to call scanForDevices() before doing this
  200656. return deviceNames;
  200657. }
  200658. int getDefaultDeviceIndex (const bool) const
  200659. {
  200660. jassert (hasScanned); // need to call scanForDevices() before doing this
  200661. for (int i = deviceNames.size(); --i >= 0;)
  200662. if (deviceNames[i].containsIgnoreCase (T("asio4all")))
  200663. return i; // asio4all is a safe choice for a default..
  200664. #if JUCE_DEBUG
  200665. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase (T("digidesign")))
  200666. return 1; // (the digi m-box driver crashes the app when you run
  200667. // it in the debugger, which can be a bit annoying)
  200668. #endif
  200669. return 0;
  200670. }
  200671. static int findFreeSlot()
  200672. {
  200673. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  200674. if (currentASIODev[i] == 0)
  200675. return i;
  200676. jassertfalse; // unfortunately you can only have a finite number
  200677. // of ASIO devices open at the same time..
  200678. return -1;
  200679. }
  200680. int getIndexOfDevice (AudioIODevice* d, const bool /*asInput*/) const
  200681. {
  200682. jassert (hasScanned); // need to call scanForDevices() before doing this
  200683. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  200684. }
  200685. bool hasSeparateInputsAndOutputs() const { return false; }
  200686. AudioIODevice* createDevice (const String& outputDeviceName,
  200687. const String& inputDeviceName)
  200688. {
  200689. jassert (inputDeviceName == outputDeviceName);
  200690. (void) inputDeviceName;
  200691. jassert (hasScanned); // need to call scanForDevices() before doing this
  200692. const int index = deviceNames.indexOf (outputDeviceName);
  200693. if (index >= 0)
  200694. {
  200695. const int freeSlot = findFreeSlot();
  200696. if (freeSlot >= 0)
  200697. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot);
  200698. }
  200699. return 0;
  200700. }
  200701. juce_UseDebuggingNewOperator
  200702. private:
  200703. StringArray deviceNames;
  200704. OwnedArray <CLSID> classIds;
  200705. bool hasScanned;
  200706. static bool checkClassIsOk (const String& classId)
  200707. {
  200708. HKEY hk = 0;
  200709. bool ok = false;
  200710. if (RegOpenKeyA (HKEY_CLASSES_ROOT, "clsid", &hk) == ERROR_SUCCESS)
  200711. {
  200712. int index = 0;
  200713. for (;;)
  200714. {
  200715. char buf [512];
  200716. if (RegEnumKeyA (hk, index++, buf, 512) == ERROR_SUCCESS)
  200717. {
  200718. if (classId.equalsIgnoreCase (buf))
  200719. {
  200720. HKEY subKey, pathKey;
  200721. if (RegOpenKeyExA (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  200722. {
  200723. if (RegOpenKeyExA (subKey, "InprocServer32", 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  200724. {
  200725. char pathName [600];
  200726. DWORD dtype = REG_SZ;
  200727. DWORD dsize = sizeof (pathName);
  200728. if (RegQueryValueExA (pathKey, 0, 0, &dtype,
  200729. (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  200730. {
  200731. OFSTRUCT of;
  200732. zerostruct (of);
  200733. of.cBytes = sizeof (of);
  200734. ok = (OpenFile (String (pathName), &of, OF_EXIST) != 0);
  200735. }
  200736. RegCloseKey (pathKey);
  200737. }
  200738. RegCloseKey (subKey);
  200739. }
  200740. break;
  200741. }
  200742. }
  200743. else
  200744. {
  200745. break;
  200746. }
  200747. }
  200748. RegCloseKey (hk);
  200749. }
  200750. return ok;
  200751. }
  200752. void addDriverInfo (const String& keyName, HKEY hk)
  200753. {
  200754. HKEY subKey;
  200755. if (RegOpenKeyExA (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  200756. {
  200757. char buf [256];
  200758. DWORD dtype = REG_SZ;
  200759. DWORD dsize = sizeof (buf);
  200760. zeromem (buf, dsize);
  200761. if (RegQueryValueExA (subKey, "clsid", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  200762. {
  200763. if (dsize > 0 && checkClassIsOk (buf))
  200764. {
  200765. wchar_t classIdStr [130];
  200766. MultiByteToWideChar (CP_ACP, 0, buf, -1, classIdStr, 128);
  200767. String deviceName;
  200768. CLSID classId;
  200769. if (CLSIDFromString ((LPOLESTR) classIdStr, &classId) == S_OK)
  200770. {
  200771. dtype = REG_SZ;
  200772. dsize = sizeof (buf);
  200773. if (RegQueryValueExA (subKey, "description", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  200774. deviceName = buf;
  200775. else
  200776. deviceName = keyName;
  200777. log (T("found ") + deviceName);
  200778. deviceNames.add (deviceName);
  200779. classIds.add (new CLSID (classId));
  200780. }
  200781. }
  200782. RegCloseKey (subKey);
  200783. }
  200784. }
  200785. }
  200786. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  200787. const ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  200788. };
  200789. AudioIODeviceType* juce_createASIOAudioIODeviceType()
  200790. {
  200791. return new ASIOAudioIODeviceType();
  200792. }
  200793. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  200794. void* guid)
  200795. {
  200796. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  200797. if (freeSlot < 0)
  200798. return 0;
  200799. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot);
  200800. }
  200801. END_JUCE_NAMESPACE
  200802. #undef log
  200803. #endif
  200804. /********* End of inlined file: juce_win32_ASIO.cpp *********/
  200805. /********* Start of inlined file: juce_win32_AudioCDReader.cpp *********/
  200806. #ifdef _MSC_VER
  200807. #pragma warning (disable: 4514)
  200808. #pragma warning (push)
  200809. #endif
  200810. #include <stddef.h>
  200811. #if JUCE_USE_CDBURNER
  200812. // you'll need the Platform SDK for these headers - if you don't have it and don't
  200813. // need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  200814. // flag in juce_Config.h to avoid these includes.
  200815. #include <imapi.h>
  200816. #include <imapierror.h>
  200817. #endif
  200818. BEGIN_JUCE_NAMESPACE
  200819. #ifdef _MSC_VER
  200820. #pragma warning (pop)
  200821. #endif
  200822. //***************************************************************************
  200823. // %%% TARGET STATUS VALUES %%%
  200824. //***************************************************************************
  200825. #define STATUS_GOOD 0x00 // Status Good
  200826. #define STATUS_CHKCOND 0x02 // Check Condition
  200827. #define STATUS_CONDMET 0x04 // Condition Met
  200828. #define STATUS_BUSY 0x08 // Busy
  200829. #define STATUS_INTERM 0x10 // Intermediate
  200830. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  200831. #define STATUS_RESCONF 0x18 // Reservation conflict
  200832. #define STATUS_COMTERM 0x22 // Command Terminated
  200833. #define STATUS_QFULL 0x28 // Queue full
  200834. //***************************************************************************
  200835. // %%% SCSI MISCELLANEOUS EQUATES %%%
  200836. //***************************************************************************
  200837. #define MAXLUN 7 // Maximum Logical Unit Id
  200838. #define MAXTARG 7 // Maximum Target Id
  200839. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  200840. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  200841. //***************************************************************************
  200842. // %%% Commands for all Device Types %%%
  200843. //***************************************************************************
  200844. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  200845. #define SCSI_COMPARE 0x39 // Compare (O)
  200846. #define SCSI_COPY 0x18 // Copy (O)
  200847. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  200848. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  200849. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  200850. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  200851. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  200852. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  200853. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  200854. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  200855. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  200856. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  200857. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  200858. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  200859. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  200860. //***************************************************************************
  200861. // %%% Commands Unique to Direct Access Devices %%%
  200862. //***************************************************************************
  200863. #define SCSI_COMPARE 0x39 // Compare (O)
  200864. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  200865. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  200866. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  200867. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  200868. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  200869. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  200870. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  200871. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  200872. #define SCSI_READ_LONG 0x3E // Read Long (O)
  200873. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  200874. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  200875. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  200876. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  200877. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  200878. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  200879. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  200880. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  200881. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  200882. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  200883. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  200884. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  200885. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  200886. #define SCSI_VERIFY 0x2F // Verify (O)
  200887. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  200888. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  200889. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  200890. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  200891. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  200892. //***************************************************************************
  200893. // %%% Commands Unique to Sequential Access Devices %%%
  200894. //***************************************************************************
  200895. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  200896. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  200897. #define SCSI_LOCATE 0x2B // Locate (O)
  200898. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  200899. #define SCSI_READ_POS 0x34 // Read Position (O)
  200900. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  200901. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  200902. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  200903. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  200904. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  200905. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  200906. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  200907. //***************************************************************************
  200908. // %%% Commands Unique to Printer Devices %%%
  200909. //***************************************************************************
  200910. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  200911. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  200912. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  200913. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  200914. //***************************************************************************
  200915. // %%% Commands Unique to Processor Devices %%%
  200916. //***************************************************************************
  200917. #define SCSI_RECEIVE 0x08 // Receive (O)
  200918. #define SCSI_SEND 0x0A // Send (O)
  200919. //***************************************************************************
  200920. // %%% Commands Unique to Write-Once Devices %%%
  200921. //***************************************************************************
  200922. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  200923. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  200924. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  200925. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  200926. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  200927. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  200928. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  200929. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  200930. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  200931. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  200932. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  200933. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  200934. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  200935. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  200936. //***************************************************************************
  200937. // %%% Commands Unique to CD-ROM Devices %%%
  200938. //***************************************************************************
  200939. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  200940. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  200941. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  200942. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  200943. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  200944. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  200945. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  200946. #define SCSI_READHEADER 0x44 // Read Header (O)
  200947. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  200948. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  200949. //***************************************************************************
  200950. // %%% Commands Unique to Scanner Devices %%%
  200951. //***************************************************************************
  200952. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  200953. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  200954. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  200955. #define SCSI_SCAN 0x1B // Scan (O)
  200956. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  200957. //***************************************************************************
  200958. // %%% Commands Unique to Optical Memory Devices %%%
  200959. //***************************************************************************
  200960. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  200961. //***************************************************************************
  200962. // %%% Commands Unique to Medium Changer Devices %%%
  200963. //***************************************************************************
  200964. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  200965. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  200966. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  200967. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  200968. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  200969. //***************************************************************************
  200970. // %%% Commands Unique to Communication Devices %%%
  200971. //***************************************************************************
  200972. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  200973. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  200974. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  200975. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  200976. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  200977. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  200978. //***************************************************************************
  200979. // %%% Request Sense Data Format %%%
  200980. //***************************************************************************
  200981. typedef struct {
  200982. BYTE ErrorCode; // Error Code (70H or 71H)
  200983. BYTE SegmentNum; // Number of current segment descriptor
  200984. BYTE SenseKey; // Sense Key(See bit definitions too)
  200985. BYTE InfoByte0; // Information MSB
  200986. BYTE InfoByte1; // Information MID
  200987. BYTE InfoByte2; // Information MID
  200988. BYTE InfoByte3; // Information LSB
  200989. BYTE AddSenLen; // Additional Sense Length
  200990. BYTE ComSpecInf0; // Command Specific Information MSB
  200991. BYTE ComSpecInf1; // Command Specific Information MID
  200992. BYTE ComSpecInf2; // Command Specific Information MID
  200993. BYTE ComSpecInf3; // Command Specific Information LSB
  200994. BYTE AddSenseCode; // Additional Sense Code
  200995. BYTE AddSenQual; // Additional Sense Code Qualifier
  200996. BYTE FieldRepUCode; // Field Replaceable Unit Code
  200997. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  200998. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  200999. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  201000. BYTE AddSenseBytes; // Additional Sense Bytes
  201001. } SENSE_DATA_FMT;
  201002. //***************************************************************************
  201003. // %%% REQUEST SENSE ERROR CODE %%%
  201004. //***************************************************************************
  201005. #define SERROR_CURRENT 0x70 // Current Errors
  201006. #define SERROR_DEFERED 0x71 // Deferred Errors
  201007. //***************************************************************************
  201008. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  201009. //***************************************************************************
  201010. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  201011. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  201012. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  201013. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  201014. //***************************************************************************
  201015. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  201016. //***************************************************************************
  201017. #define KEY_NOSENSE 0x00 // No Sense
  201018. #define KEY_RECERROR 0x01 // Recovered Error
  201019. #define KEY_NOTREADY 0x02 // Not Ready
  201020. #define KEY_MEDIUMERR 0x03 // Medium Error
  201021. #define KEY_HARDERROR 0x04 // Hardware Error
  201022. #define KEY_ILLGLREQ 0x05 // Illegal Request
  201023. #define KEY_UNITATT 0x06 // Unit Attention
  201024. #define KEY_DATAPROT 0x07 // Data Protect
  201025. #define KEY_BLANKCHK 0x08 // Blank Check
  201026. #define KEY_VENDSPEC 0x09 // Vendor Specific
  201027. #define KEY_COPYABORT 0x0A // Copy Abort
  201028. #define KEY_EQUAL 0x0C // Equal (Search)
  201029. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  201030. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  201031. #define KEY_RESERVED 0x0F // Reserved
  201032. //***************************************************************************
  201033. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  201034. //***************************************************************************
  201035. #define DTYPE_DASD 0x00 // Disk Device
  201036. #define DTYPE_SEQD 0x01 // Tape Device
  201037. #define DTYPE_PRNT 0x02 // Printer
  201038. #define DTYPE_PROC 0x03 // Processor
  201039. #define DTYPE_WORM 0x04 // Write-once read-multiple
  201040. #define DTYPE_CROM 0x05 // CD-ROM device
  201041. #define DTYPE_SCAN 0x06 // Scanner device
  201042. #define DTYPE_OPTI 0x07 // Optical memory device
  201043. #define DTYPE_JUKE 0x08 // Medium Changer device
  201044. #define DTYPE_COMM 0x09 // Communications device
  201045. #define DTYPE_RESL 0x0A // Reserved (low)
  201046. #define DTYPE_RESH 0x1E // Reserved (high)
  201047. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  201048. //***************************************************************************
  201049. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  201050. //***************************************************************************
  201051. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  201052. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  201053. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  201054. #define ANSI_RESLO 0x3 // Reserved (low)
  201055. #define ANSI_RESHI 0x7 // Reserved (high)
  201056. typedef struct
  201057. {
  201058. USHORT Length;
  201059. UCHAR ScsiStatus;
  201060. UCHAR PathId;
  201061. UCHAR TargetId;
  201062. UCHAR Lun;
  201063. UCHAR CdbLength;
  201064. UCHAR SenseInfoLength;
  201065. UCHAR DataIn;
  201066. ULONG DataTransferLength;
  201067. ULONG TimeOutValue;
  201068. ULONG DataBufferOffset;
  201069. ULONG SenseInfoOffset;
  201070. UCHAR Cdb[16];
  201071. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  201072. typedef struct
  201073. {
  201074. USHORT Length;
  201075. UCHAR ScsiStatus;
  201076. UCHAR PathId;
  201077. UCHAR TargetId;
  201078. UCHAR Lun;
  201079. UCHAR CdbLength;
  201080. UCHAR SenseInfoLength;
  201081. UCHAR DataIn;
  201082. ULONG DataTransferLength;
  201083. ULONG TimeOutValue;
  201084. PVOID DataBuffer;
  201085. ULONG SenseInfoOffset;
  201086. UCHAR Cdb[16];
  201087. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  201088. typedef struct
  201089. {
  201090. SCSI_PASS_THROUGH_DIRECT spt;
  201091. ULONG Filler;
  201092. UCHAR ucSenseBuf[32];
  201093. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  201094. typedef struct
  201095. {
  201096. ULONG Length;
  201097. UCHAR PortNumber;
  201098. UCHAR PathId;
  201099. UCHAR TargetId;
  201100. UCHAR Lun;
  201101. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  201102. #define METHOD_BUFFERED 0
  201103. #define METHOD_IN_DIRECT 1
  201104. #define METHOD_OUT_DIRECT 2
  201105. #define METHOD_NEITHER 3
  201106. #define FILE_ANY_ACCESS 0
  201107. #ifndef FILE_READ_ACCESS
  201108. #define FILE_READ_ACCESS (0x0001)
  201109. #endif
  201110. #ifndef FILE_WRITE_ACCESS
  201111. #define FILE_WRITE_ACCESS (0x0002)
  201112. #endif
  201113. #define IOCTL_SCSI_BASE 0x00000004
  201114. #define SCSI_IOCTL_DATA_OUT 0
  201115. #define SCSI_IOCTL_DATA_IN 1
  201116. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  201117. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  201118. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  201119. )
  201120. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  201121. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  201122. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  201123. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  201124. #define SENSE_LEN 14
  201125. #define SRB_DIR_SCSI 0x00
  201126. #define SRB_POSTING 0x01
  201127. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  201128. #define SRB_DIR_IN 0x08
  201129. #define SRB_DIR_OUT 0x10
  201130. #define SRB_EVENT_NOTIFY 0x40
  201131. #define RESIDUAL_COUNT_SUPPORTED 0x02
  201132. #define MAX_SRB_TIMEOUT 1080001u
  201133. #define DEFAULT_SRB_TIMEOUT 1080001u
  201134. #define SC_HA_INQUIRY 0x00
  201135. #define SC_GET_DEV_TYPE 0x01
  201136. #define SC_EXEC_SCSI_CMD 0x02
  201137. #define SC_ABORT_SRB 0x03
  201138. #define SC_RESET_DEV 0x04
  201139. #define SC_SET_HA_PARMS 0x05
  201140. #define SC_GET_DISK_INFO 0x06
  201141. #define SC_RESCAN_SCSI_BUS 0x07
  201142. #define SC_GETSET_TIMEOUTS 0x08
  201143. #define SS_PENDING 0x00
  201144. #define SS_COMP 0x01
  201145. #define SS_ABORTED 0x02
  201146. #define SS_ABORT_FAIL 0x03
  201147. #define SS_ERR 0x04
  201148. #define SS_INVALID_CMD 0x80
  201149. #define SS_INVALID_HA 0x81
  201150. #define SS_NO_DEVICE 0x82
  201151. #define SS_INVALID_SRB 0xE0
  201152. #define SS_OLD_MANAGER 0xE1
  201153. #define SS_BUFFER_ALIGN 0xE1
  201154. #define SS_ILLEGAL_MODE 0xE2
  201155. #define SS_NO_ASPI 0xE3
  201156. #define SS_FAILED_INIT 0xE4
  201157. #define SS_ASPI_IS_BUSY 0xE5
  201158. #define SS_BUFFER_TO_BIG 0xE6
  201159. #define SS_BUFFER_TOO_BIG 0xE6
  201160. #define SS_MISMATCHED_COMPONENTS 0xE7
  201161. #define SS_NO_ADAPTERS 0xE8
  201162. #define SS_INSUFFICIENT_RESOURCES 0xE9
  201163. #define SS_ASPI_IS_SHUTDOWN 0xEA
  201164. #define SS_BAD_INSTALL 0xEB
  201165. #define HASTAT_OK 0x00
  201166. #define HASTAT_SEL_TO 0x11
  201167. #define HASTAT_DO_DU 0x12
  201168. #define HASTAT_BUS_FREE 0x13
  201169. #define HASTAT_PHASE_ERR 0x14
  201170. #define HASTAT_TIMEOUT 0x09
  201171. #define HASTAT_COMMAND_TIMEOUT 0x0B
  201172. #define HASTAT_MESSAGE_REJECT 0x0D
  201173. #define HASTAT_BUS_RESET 0x0E
  201174. #define HASTAT_PARITY_ERROR 0x0F
  201175. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  201176. #define PACKED
  201177. #pragma pack(1)
  201178. typedef struct
  201179. {
  201180. BYTE SRB_Cmd;
  201181. BYTE SRB_Status;
  201182. BYTE SRB_HaID;
  201183. BYTE SRB_Flags;
  201184. DWORD SRB_Hdr_Rsvd;
  201185. BYTE HA_Count;
  201186. BYTE HA_SCSI_ID;
  201187. BYTE HA_ManagerId[16];
  201188. BYTE HA_Identifier[16];
  201189. BYTE HA_Unique[16];
  201190. WORD HA_Rsvd1;
  201191. BYTE pad[20];
  201192. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  201193. typedef struct
  201194. {
  201195. BYTE SRB_Cmd;
  201196. BYTE SRB_Status;
  201197. BYTE SRB_HaID;
  201198. BYTE SRB_Flags;
  201199. DWORD SRB_Hdr_Rsvd;
  201200. BYTE SRB_Target;
  201201. BYTE SRB_Lun;
  201202. BYTE SRB_DeviceType;
  201203. BYTE SRB_Rsvd1;
  201204. BYTE pad[68];
  201205. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  201206. typedef struct
  201207. {
  201208. BYTE SRB_Cmd;
  201209. BYTE SRB_Status;
  201210. BYTE SRB_HaID;
  201211. BYTE SRB_Flags;
  201212. DWORD SRB_Hdr_Rsvd;
  201213. BYTE SRB_Target;
  201214. BYTE SRB_Lun;
  201215. WORD SRB_Rsvd1;
  201216. DWORD SRB_BufLen;
  201217. BYTE FAR *SRB_BufPointer;
  201218. BYTE SRB_SenseLen;
  201219. BYTE SRB_CDBLen;
  201220. BYTE SRB_HaStat;
  201221. BYTE SRB_TargStat;
  201222. VOID FAR *SRB_PostProc;
  201223. BYTE SRB_Rsvd2[20];
  201224. BYTE CDBByte[16];
  201225. BYTE SenseArea[SENSE_LEN+2];
  201226. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  201227. typedef struct
  201228. {
  201229. BYTE SRB_Cmd;
  201230. BYTE SRB_Status;
  201231. BYTE SRB_HaId;
  201232. BYTE SRB_Flags;
  201233. DWORD SRB_Hdr_Rsvd;
  201234. } PACKED SRB, *PSRB, FAR *LPSRB;
  201235. #pragma pack()
  201236. struct CDDeviceInfo
  201237. {
  201238. char vendor[9];
  201239. char productId[17];
  201240. char rev[5];
  201241. char vendorSpec[21];
  201242. BYTE ha;
  201243. BYTE tgt;
  201244. BYTE lun;
  201245. char scsiDriveLetter; // will be 0 if not using scsi
  201246. };
  201247. class CDReadBuffer
  201248. {
  201249. public:
  201250. int startFrame;
  201251. int numFrames;
  201252. int dataStartOffset;
  201253. int dataLength;
  201254. BYTE* buffer;
  201255. int bufferSize;
  201256. int index;
  201257. bool wantsIndex;
  201258. CDReadBuffer (const int numberOfFrames)
  201259. : startFrame (0),
  201260. numFrames (0),
  201261. dataStartOffset (0),
  201262. dataLength (0),
  201263. index (0),
  201264. wantsIndex (false)
  201265. {
  201266. bufferSize = 2352 * numberOfFrames;
  201267. buffer = (BYTE*) malloc (bufferSize);
  201268. }
  201269. ~CDReadBuffer()
  201270. {
  201271. free (buffer);
  201272. }
  201273. bool isZero() const
  201274. {
  201275. BYTE* p = buffer + dataStartOffset;
  201276. for (int i = dataLength; --i >= 0;)
  201277. if (*p++ != 0)
  201278. return false;
  201279. return true;
  201280. }
  201281. };
  201282. class CDDeviceHandle;
  201283. class CDController
  201284. {
  201285. public:
  201286. CDController();
  201287. virtual ~CDController();
  201288. virtual bool read (CDReadBuffer* t) = 0;
  201289. virtual void shutDown();
  201290. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  201291. int getLastIndex();
  201292. public:
  201293. bool initialised;
  201294. CDDeviceHandle* deviceInfo;
  201295. int framesToCheck, framesOverlap;
  201296. void prepare (SRB_ExecSCSICmd& s);
  201297. void perform (SRB_ExecSCSICmd& s);
  201298. void setPaused (bool paused);
  201299. };
  201300. #pragma pack(1)
  201301. struct TOCTRACK
  201302. {
  201303. BYTE rsvd;
  201304. BYTE ADR;
  201305. BYTE trackNumber;
  201306. BYTE rsvd2;
  201307. BYTE addr[4];
  201308. };
  201309. struct TOC
  201310. {
  201311. WORD tocLen;
  201312. BYTE firstTrack;
  201313. BYTE lastTrack;
  201314. TOCTRACK tracks[100];
  201315. };
  201316. #pragma pack()
  201317. enum
  201318. {
  201319. READTYPE_ANY = 0,
  201320. READTYPE_ATAPI1 = 1,
  201321. READTYPE_ATAPI2 = 2,
  201322. READTYPE_READ6 = 3,
  201323. READTYPE_READ10 = 4,
  201324. READTYPE_READ_D8 = 5,
  201325. READTYPE_READ_D4 = 6,
  201326. READTYPE_READ_D4_1 = 7,
  201327. READTYPE_READ10_2 = 8
  201328. };
  201329. class CDDeviceHandle
  201330. {
  201331. public:
  201332. CDDeviceHandle (const CDDeviceInfo* const device)
  201333. : scsiHandle (0),
  201334. readType (READTYPE_ANY),
  201335. controller (0)
  201336. {
  201337. memcpy (&info, device, sizeof (info));
  201338. }
  201339. ~CDDeviceHandle()
  201340. {
  201341. if (controller != 0)
  201342. {
  201343. controller->shutDown();
  201344. delete controller;
  201345. }
  201346. if (scsiHandle != 0)
  201347. CloseHandle (scsiHandle);
  201348. }
  201349. bool readTOC (TOC* lpToc, bool useMSF);
  201350. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  201351. void openDrawer (bool shouldBeOpen);
  201352. CDDeviceInfo info;
  201353. HANDLE scsiHandle;
  201354. BYTE readType;
  201355. private:
  201356. CDController* controller;
  201357. bool testController (const int readType,
  201358. CDController* const newController,
  201359. CDReadBuffer* const bufferToUse);
  201360. };
  201361. DWORD (*fGetASPI32SupportInfo)(void);
  201362. DWORD (*fSendASPI32Command)(LPSRB);
  201363. static HINSTANCE winAspiLib = 0;
  201364. static bool usingScsi = false;
  201365. static bool initialised = false;
  201366. static bool InitialiseCDRipper()
  201367. {
  201368. if (! initialised)
  201369. {
  201370. initialised = true;
  201371. OSVERSIONINFO info;
  201372. info.dwOSVersionInfoSize = sizeof (info);
  201373. GetVersionEx (&info);
  201374. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  201375. if (! usingScsi)
  201376. {
  201377. fGetASPI32SupportInfo = 0;
  201378. fSendASPI32Command = 0;
  201379. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  201380. if (winAspiLib != 0)
  201381. {
  201382. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  201383. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  201384. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  201385. return false;
  201386. }
  201387. else
  201388. {
  201389. usingScsi = true;
  201390. }
  201391. }
  201392. }
  201393. return true;
  201394. }
  201395. static void DeinitialiseCDRipper()
  201396. {
  201397. if (winAspiLib != 0)
  201398. {
  201399. fGetASPI32SupportInfo = 0;
  201400. fSendASPI32Command = 0;
  201401. FreeLibrary (winAspiLib);
  201402. winAspiLib = 0;
  201403. }
  201404. initialised = false;
  201405. }
  201406. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  201407. {
  201408. TCHAR devicePath[8];
  201409. devicePath[0] = '\\';
  201410. devicePath[1] = '\\';
  201411. devicePath[2] = '.';
  201412. devicePath[3] = '\\';
  201413. devicePath[4] = driveLetter;
  201414. devicePath[5] = ':';
  201415. devicePath[6] = 0;
  201416. OSVERSIONINFO info;
  201417. info.dwOSVersionInfoSize = sizeof (info);
  201418. GetVersionEx (&info);
  201419. DWORD flags = GENERIC_READ;
  201420. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  201421. flags = GENERIC_READ | GENERIC_WRITE;
  201422. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  201423. if (h == INVALID_HANDLE_VALUE)
  201424. {
  201425. flags ^= GENERIC_WRITE;
  201426. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  201427. }
  201428. return h;
  201429. }
  201430. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  201431. const char driveLetter,
  201432. HANDLE& deviceHandle,
  201433. const bool retryOnFailure = true)
  201434. {
  201435. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  201436. zerostruct (s);
  201437. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  201438. s.spt.CdbLength = srb->SRB_CDBLen;
  201439. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  201440. ? SCSI_IOCTL_DATA_IN
  201441. : ((srb->SRB_Flags & SRB_DIR_OUT)
  201442. ? SCSI_IOCTL_DATA_OUT
  201443. : SCSI_IOCTL_DATA_UNSPECIFIED));
  201444. s.spt.DataTransferLength = srb->SRB_BufLen;
  201445. s.spt.TimeOutValue = 5;
  201446. s.spt.DataBuffer = srb->SRB_BufPointer;
  201447. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  201448. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  201449. srb->SRB_Status = SS_ERR;
  201450. srb->SRB_TargStat = 0x0004;
  201451. DWORD bytesReturned = 0;
  201452. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  201453. &s, sizeof (s),
  201454. &s, sizeof (s),
  201455. &bytesReturned, 0) != 0)
  201456. {
  201457. srb->SRB_Status = SS_COMP;
  201458. }
  201459. else if (retryOnFailure)
  201460. {
  201461. const DWORD error = GetLastError();
  201462. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  201463. {
  201464. if (error != ERROR_INVALID_HANDLE)
  201465. CloseHandle (deviceHandle);
  201466. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  201467. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  201468. }
  201469. }
  201470. return srb->SRB_Status;
  201471. }
  201472. // Controller types..
  201473. class ControllerType1 : public CDController
  201474. {
  201475. public:
  201476. ControllerType1() {}
  201477. ~ControllerType1() {}
  201478. bool read (CDReadBuffer* rb)
  201479. {
  201480. if (rb->numFrames * 2352 > rb->bufferSize)
  201481. return false;
  201482. SRB_ExecSCSICmd s;
  201483. prepare (s);
  201484. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201485. s.SRB_BufLen = rb->bufferSize;
  201486. s.SRB_BufPointer = rb->buffer;
  201487. s.SRB_CDBLen = 12;
  201488. s.CDBByte[0] = 0xBE;
  201489. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  201490. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  201491. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  201492. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  201493. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  201494. perform (s);
  201495. if (s.SRB_Status != SS_COMP)
  201496. return false;
  201497. rb->dataLength = rb->numFrames * 2352;
  201498. rb->dataStartOffset = 0;
  201499. return true;
  201500. }
  201501. };
  201502. class ControllerType2 : public CDController
  201503. {
  201504. public:
  201505. ControllerType2() {}
  201506. ~ControllerType2() {}
  201507. void shutDown()
  201508. {
  201509. if (initialised)
  201510. {
  201511. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  201512. SRB_ExecSCSICmd s;
  201513. prepare (s);
  201514. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  201515. s.SRB_BufLen = 0x0C;
  201516. s.SRB_BufPointer = bufPointer;
  201517. s.SRB_CDBLen = 6;
  201518. s.CDBByte[0] = 0x15;
  201519. s.CDBByte[4] = 0x0C;
  201520. perform (s);
  201521. }
  201522. }
  201523. bool init()
  201524. {
  201525. SRB_ExecSCSICmd s;
  201526. s.SRB_Status = SS_ERR;
  201527. if (deviceInfo->readType == READTYPE_READ10_2)
  201528. {
  201529. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  201530. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  201531. for (int i = 0; i < 2; ++i)
  201532. {
  201533. prepare (s);
  201534. s.SRB_Flags = SRB_EVENT_NOTIFY;
  201535. s.SRB_BufLen = 0x14;
  201536. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  201537. s.SRB_CDBLen = 6;
  201538. s.CDBByte[0] = 0x15;
  201539. s.CDBByte[1] = 0x10;
  201540. s.CDBByte[4] = 0x14;
  201541. perform (s);
  201542. if (s.SRB_Status != SS_COMP)
  201543. return false;
  201544. }
  201545. }
  201546. else
  201547. {
  201548. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  201549. prepare (s);
  201550. s.SRB_Flags = SRB_EVENT_NOTIFY;
  201551. s.SRB_BufLen = 0x0C;
  201552. s.SRB_BufPointer = bufPointer;
  201553. s.SRB_CDBLen = 6;
  201554. s.CDBByte[0] = 0x15;
  201555. s.CDBByte[4] = 0x0C;
  201556. perform (s);
  201557. }
  201558. return s.SRB_Status == SS_COMP;
  201559. }
  201560. bool read (CDReadBuffer* rb)
  201561. {
  201562. if (rb->numFrames * 2352 > rb->bufferSize)
  201563. return false;
  201564. if (!initialised)
  201565. {
  201566. initialised = init();
  201567. if (!initialised)
  201568. return false;
  201569. }
  201570. SRB_ExecSCSICmd s;
  201571. prepare (s);
  201572. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201573. s.SRB_BufLen = rb->bufferSize;
  201574. s.SRB_BufPointer = rb->buffer;
  201575. s.SRB_CDBLen = 10;
  201576. s.CDBByte[0] = 0x28;
  201577. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  201578. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  201579. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  201580. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  201581. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  201582. perform (s);
  201583. if (s.SRB_Status != SS_COMP)
  201584. return false;
  201585. rb->dataLength = rb->numFrames * 2352;
  201586. rb->dataStartOffset = 0;
  201587. return true;
  201588. }
  201589. };
  201590. class ControllerType3 : public CDController
  201591. {
  201592. public:
  201593. ControllerType3() {}
  201594. ~ControllerType3() {}
  201595. bool read (CDReadBuffer* rb)
  201596. {
  201597. if (rb->numFrames * 2352 > rb->bufferSize)
  201598. return false;
  201599. if (!initialised)
  201600. {
  201601. setPaused (false);
  201602. initialised = true;
  201603. }
  201604. SRB_ExecSCSICmd s;
  201605. prepare (s);
  201606. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201607. s.SRB_BufLen = rb->numFrames * 2352;
  201608. s.SRB_BufPointer = rb->buffer;
  201609. s.SRB_CDBLen = 12;
  201610. s.CDBByte[0] = 0xD8;
  201611. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  201612. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  201613. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  201614. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  201615. perform (s);
  201616. if (s.SRB_Status != SS_COMP)
  201617. return false;
  201618. rb->dataLength = rb->numFrames * 2352;
  201619. rb->dataStartOffset = 0;
  201620. return true;
  201621. }
  201622. };
  201623. class ControllerType4 : public CDController
  201624. {
  201625. public:
  201626. ControllerType4() {}
  201627. ~ControllerType4() {}
  201628. bool selectD4Mode()
  201629. {
  201630. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  201631. SRB_ExecSCSICmd s;
  201632. prepare (s);
  201633. s.SRB_Flags = SRB_EVENT_NOTIFY;
  201634. s.SRB_CDBLen = 6;
  201635. s.SRB_BufLen = 12;
  201636. s.SRB_BufPointer = bufPointer;
  201637. s.CDBByte[0] = 0x15;
  201638. s.CDBByte[1] = 0x10;
  201639. s.CDBByte[4] = 0x08;
  201640. perform (s);
  201641. return s.SRB_Status == SS_COMP;
  201642. }
  201643. bool read (CDReadBuffer* rb)
  201644. {
  201645. if (rb->numFrames * 2352 > rb->bufferSize)
  201646. return false;
  201647. if (!initialised)
  201648. {
  201649. setPaused (true);
  201650. if (deviceInfo->readType == READTYPE_READ_D4_1)
  201651. selectD4Mode();
  201652. initialised = true;
  201653. }
  201654. SRB_ExecSCSICmd s;
  201655. prepare (s);
  201656. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201657. s.SRB_BufLen = rb->bufferSize;
  201658. s.SRB_BufPointer = rb->buffer;
  201659. s.SRB_CDBLen = 10;
  201660. s.CDBByte[0] = 0xD4;
  201661. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  201662. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  201663. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  201664. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  201665. perform (s);
  201666. if (s.SRB_Status != SS_COMP)
  201667. return false;
  201668. rb->dataLength = rb->numFrames * 2352;
  201669. rb->dataStartOffset = 0;
  201670. return true;
  201671. }
  201672. };
  201673. CDController::CDController() : initialised (false)
  201674. {
  201675. }
  201676. CDController::~CDController()
  201677. {
  201678. }
  201679. void CDController::prepare (SRB_ExecSCSICmd& s)
  201680. {
  201681. zerostruct (s);
  201682. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201683. s.SRB_HaID = deviceInfo->info.ha;
  201684. s.SRB_Target = deviceInfo->info.tgt;
  201685. s.SRB_Lun = deviceInfo->info.lun;
  201686. s.SRB_SenseLen = SENSE_LEN;
  201687. }
  201688. void CDController::perform (SRB_ExecSCSICmd& s)
  201689. {
  201690. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201691. s.SRB_PostProc = (void*)event;
  201692. ResetEvent (event);
  201693. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  201694. deviceInfo->info.scsiDriveLetter,
  201695. deviceInfo->scsiHandle)
  201696. : fSendASPI32Command ((LPSRB)&s);
  201697. if (status == SS_PENDING)
  201698. WaitForSingleObject (event, 4000);
  201699. CloseHandle (event);
  201700. }
  201701. void CDController::setPaused (bool paused)
  201702. {
  201703. SRB_ExecSCSICmd s;
  201704. prepare (s);
  201705. s.SRB_Flags = SRB_EVENT_NOTIFY;
  201706. s.SRB_CDBLen = 10;
  201707. s.CDBByte[0] = 0x4B;
  201708. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  201709. perform (s);
  201710. }
  201711. void CDController::shutDown()
  201712. {
  201713. }
  201714. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  201715. {
  201716. if (overlapBuffer != 0)
  201717. {
  201718. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  201719. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  201720. if (doJitter
  201721. && overlapBuffer->startFrame > 0
  201722. && overlapBuffer->numFrames > 0
  201723. && overlapBuffer->dataLength > 0)
  201724. {
  201725. const int numFrames = rb->numFrames;
  201726. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  201727. {
  201728. rb->startFrame -= framesOverlap;
  201729. if (framesToCheck < framesOverlap
  201730. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  201731. rb->numFrames += framesOverlap;
  201732. }
  201733. else
  201734. {
  201735. overlapBuffer->dataLength = 0;
  201736. overlapBuffer->startFrame = 0;
  201737. overlapBuffer->numFrames = 0;
  201738. }
  201739. }
  201740. if (! read (rb))
  201741. return false;
  201742. if (doJitter)
  201743. {
  201744. const int checkLen = framesToCheck * 2352;
  201745. const int maxToCheck = rb->dataLength - checkLen;
  201746. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  201747. return true;
  201748. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  201749. bool found = false;
  201750. for (int i = 0; i < maxToCheck; ++i)
  201751. {
  201752. if (!memcmp (p, rb->buffer + i, checkLen))
  201753. {
  201754. i += checkLen;
  201755. rb->dataStartOffset = i;
  201756. rb->dataLength -= i;
  201757. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  201758. found = true;
  201759. break;
  201760. }
  201761. }
  201762. rb->numFrames = rb->dataLength / 2352;
  201763. rb->dataLength = 2352 * rb->numFrames;
  201764. if (!found)
  201765. return false;
  201766. }
  201767. if (canDoJitter)
  201768. {
  201769. memcpy (overlapBuffer->buffer,
  201770. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  201771. 2352 * framesToCheck);
  201772. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  201773. overlapBuffer->numFrames = framesToCheck;
  201774. overlapBuffer->dataLength = 2352 * framesToCheck;
  201775. overlapBuffer->dataStartOffset = 0;
  201776. }
  201777. else
  201778. {
  201779. overlapBuffer->startFrame = 0;
  201780. overlapBuffer->numFrames = 0;
  201781. overlapBuffer->dataLength = 0;
  201782. }
  201783. return true;
  201784. }
  201785. else
  201786. {
  201787. return read (rb);
  201788. }
  201789. }
  201790. int CDController::getLastIndex()
  201791. {
  201792. char qdata[100];
  201793. SRB_ExecSCSICmd s;
  201794. prepare (s);
  201795. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201796. s.SRB_BufLen = sizeof (qdata);
  201797. s.SRB_BufPointer = (BYTE*)qdata;
  201798. s.SRB_CDBLen = 12;
  201799. s.CDBByte[0] = 0x42;
  201800. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  201801. s.CDBByte[2] = 64;
  201802. s.CDBByte[3] = 1; // get current position
  201803. s.CDBByte[7] = 0;
  201804. s.CDBByte[8] = (BYTE)sizeof (qdata);
  201805. perform (s);
  201806. if (s.SRB_Status == SS_COMP)
  201807. return qdata[7];
  201808. return 0;
  201809. }
  201810. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  201811. {
  201812. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201813. SRB_ExecSCSICmd s;
  201814. zerostruct (s);
  201815. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201816. s.SRB_HaID = info.ha;
  201817. s.SRB_Target = info.tgt;
  201818. s.SRB_Lun = info.lun;
  201819. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201820. s.SRB_BufLen = 0x324;
  201821. s.SRB_BufPointer = (BYTE*)lpToc;
  201822. s.SRB_SenseLen = 0x0E;
  201823. s.SRB_CDBLen = 0x0A;
  201824. s.SRB_PostProc = (void*)event;
  201825. s.CDBByte[0] = 0x43;
  201826. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  201827. s.CDBByte[7] = 0x03;
  201828. s.CDBByte[8] = 0x24;
  201829. ResetEvent (event);
  201830. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  201831. : fSendASPI32Command ((LPSRB)&s);
  201832. if (status == SS_PENDING)
  201833. WaitForSingleObject (event, 4000);
  201834. CloseHandle (event);
  201835. return (s.SRB_Status == SS_COMP);
  201836. }
  201837. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  201838. CDReadBuffer* const overlapBuffer)
  201839. {
  201840. if (controller == 0)
  201841. {
  201842. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  201843. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  201844. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  201845. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  201846. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  201847. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  201848. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  201849. }
  201850. buffer->index = 0;
  201851. if ((controller != 0)
  201852. && controller->readAudio (buffer, overlapBuffer))
  201853. {
  201854. if (buffer->wantsIndex)
  201855. buffer->index = controller->getLastIndex();
  201856. return true;
  201857. }
  201858. return false;
  201859. }
  201860. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  201861. {
  201862. if (shouldBeOpen)
  201863. {
  201864. if (controller != 0)
  201865. {
  201866. controller->shutDown();
  201867. delete controller;
  201868. controller = 0;
  201869. }
  201870. if (scsiHandle != 0)
  201871. {
  201872. CloseHandle (scsiHandle);
  201873. scsiHandle = 0;
  201874. }
  201875. }
  201876. SRB_ExecSCSICmd s;
  201877. zerostruct (s);
  201878. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201879. s.SRB_HaID = info.ha;
  201880. s.SRB_Target = info.tgt;
  201881. s.SRB_Lun = info.lun;
  201882. s.SRB_SenseLen = SENSE_LEN;
  201883. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201884. s.SRB_BufLen = 0;
  201885. s.SRB_BufPointer = 0;
  201886. s.SRB_CDBLen = 12;
  201887. s.CDBByte[0] = 0x1b;
  201888. s.CDBByte[1] = (BYTE)(info.lun << 5);
  201889. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  201890. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201891. s.SRB_PostProc = (void*)event;
  201892. ResetEvent (event);
  201893. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  201894. : fSendASPI32Command ((LPSRB)&s);
  201895. if (status == SS_PENDING)
  201896. WaitForSingleObject (event, 4000);
  201897. CloseHandle (event);
  201898. }
  201899. bool CDDeviceHandle::testController (const int type,
  201900. CDController* const newController,
  201901. CDReadBuffer* const rb)
  201902. {
  201903. controller = newController;
  201904. readType = (BYTE)type;
  201905. controller->deviceInfo = this;
  201906. controller->framesToCheck = 1;
  201907. controller->framesOverlap = 3;
  201908. bool passed = false;
  201909. memset (rb->buffer, 0xcd, rb->bufferSize);
  201910. if (controller->read (rb))
  201911. {
  201912. passed = true;
  201913. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  201914. int wrong = 0;
  201915. for (int i = rb->dataLength / 4; --i >= 0;)
  201916. {
  201917. if (*p++ == (int) 0xcdcdcdcd)
  201918. {
  201919. if (++wrong == 4)
  201920. {
  201921. passed = false;
  201922. break;
  201923. }
  201924. }
  201925. else
  201926. {
  201927. wrong = 0;
  201928. }
  201929. }
  201930. }
  201931. if (! passed)
  201932. {
  201933. controller->shutDown();
  201934. delete controller;
  201935. controller = 0;
  201936. }
  201937. return passed;
  201938. }
  201939. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  201940. {
  201941. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201942. const int bufSize = 128;
  201943. BYTE buffer[bufSize];
  201944. zeromem (buffer, bufSize);
  201945. SRB_ExecSCSICmd s;
  201946. zerostruct (s);
  201947. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201948. s.SRB_HaID = ha;
  201949. s.SRB_Target = tgt;
  201950. s.SRB_Lun = lun;
  201951. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201952. s.SRB_BufLen = bufSize;
  201953. s.SRB_BufPointer = buffer;
  201954. s.SRB_SenseLen = SENSE_LEN;
  201955. s.SRB_CDBLen = 6;
  201956. s.SRB_PostProc = (void*)event;
  201957. s.CDBByte[0] = SCSI_INQUIRY;
  201958. s.CDBByte[4] = 100;
  201959. ResetEvent (event);
  201960. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  201961. WaitForSingleObject (event, 4000);
  201962. CloseHandle (event);
  201963. if (s.SRB_Status == SS_COMP)
  201964. {
  201965. memcpy (dev->vendor, &buffer[8], 8);
  201966. memcpy (dev->productId, &buffer[16], 16);
  201967. memcpy (dev->rev, &buffer[32], 4);
  201968. memcpy (dev->vendorSpec, &buffer[36], 20);
  201969. }
  201970. }
  201971. static int FindCDDevices (CDDeviceInfo* const list,
  201972. int maxItems)
  201973. {
  201974. int count = 0;
  201975. if (usingScsi)
  201976. {
  201977. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  201978. {
  201979. TCHAR drivePath[8];
  201980. drivePath[0] = driveLetter;
  201981. drivePath[1] = ':';
  201982. drivePath[2] = '\\';
  201983. drivePath[3] = 0;
  201984. if (GetDriveType (drivePath) == DRIVE_CDROM)
  201985. {
  201986. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  201987. if (h != INVALID_HANDLE_VALUE)
  201988. {
  201989. BYTE buffer[100], passThroughStruct[1024];
  201990. zeromem (buffer, sizeof (buffer));
  201991. zeromem (passThroughStruct, sizeof (passThroughStruct));
  201992. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  201993. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  201994. p->spt.CdbLength = 6;
  201995. p->spt.SenseInfoLength = 24;
  201996. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  201997. p->spt.DataTransferLength = 100;
  201998. p->spt.TimeOutValue = 2;
  201999. p->spt.DataBuffer = buffer;
  202000. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  202001. p->spt.Cdb[0] = 0x12;
  202002. p->spt.Cdb[4] = 100;
  202003. DWORD bytesReturned = 0;
  202004. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  202005. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  202006. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  202007. &bytesReturned, 0) != 0)
  202008. {
  202009. zeromem (&list[count], sizeof (CDDeviceInfo));
  202010. list[count].scsiDriveLetter = driveLetter;
  202011. memcpy (list[count].vendor, &buffer[8], 8);
  202012. memcpy (list[count].productId, &buffer[16], 16);
  202013. memcpy (list[count].rev, &buffer[32], 4);
  202014. memcpy (list[count].vendorSpec, &buffer[36], 20);
  202015. zeromem (passThroughStruct, sizeof (passThroughStruct));
  202016. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  202017. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  202018. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  202019. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  202020. &bytesReturned, 0) != 0)
  202021. {
  202022. list[count].ha = scsiAddr->PortNumber;
  202023. list[count].tgt = scsiAddr->TargetId;
  202024. list[count].lun = scsiAddr->Lun;
  202025. ++count;
  202026. }
  202027. }
  202028. CloseHandle (h);
  202029. }
  202030. }
  202031. }
  202032. }
  202033. else
  202034. {
  202035. const DWORD d = fGetASPI32SupportInfo();
  202036. BYTE status = HIBYTE (LOWORD (d));
  202037. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  202038. return 0;
  202039. const int numAdapters = LOBYTE (LOWORD (d));
  202040. for (BYTE ha = 0; ha < numAdapters; ++ha)
  202041. {
  202042. SRB_HAInquiry s;
  202043. zerostruct (s);
  202044. s.SRB_Cmd = SC_HA_INQUIRY;
  202045. s.SRB_HaID = ha;
  202046. fSendASPI32Command ((LPSRB)&s);
  202047. if (s.SRB_Status == SS_COMP)
  202048. {
  202049. maxItems = (int)s.HA_Unique[3];
  202050. if (maxItems == 0)
  202051. maxItems = 8;
  202052. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  202053. {
  202054. for (BYTE lun = 0; lun < 8; ++lun)
  202055. {
  202056. SRB_GDEVBlock sb;
  202057. zerostruct (sb);
  202058. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  202059. sb.SRB_HaID = ha;
  202060. sb.SRB_Target = tgt;
  202061. sb.SRB_Lun = lun;
  202062. fSendASPI32Command ((LPSRB) &sb);
  202063. if (sb.SRB_Status == SS_COMP
  202064. && sb.SRB_DeviceType == DTYPE_CROM)
  202065. {
  202066. zeromem (&list[count], sizeof (CDDeviceInfo));
  202067. list[count].ha = ha;
  202068. list[count].tgt = tgt;
  202069. list[count].lun = lun;
  202070. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  202071. ++count;
  202072. }
  202073. }
  202074. }
  202075. }
  202076. }
  202077. }
  202078. return count;
  202079. }
  202080. static int ripperUsers = 0;
  202081. static bool initialisedOk = false;
  202082. class DeinitialiseTimer : private Timer,
  202083. private DeletedAtShutdown
  202084. {
  202085. DeinitialiseTimer (const DeinitialiseTimer&);
  202086. const DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  202087. public:
  202088. DeinitialiseTimer()
  202089. {
  202090. startTimer (4000);
  202091. }
  202092. ~DeinitialiseTimer()
  202093. {
  202094. if (--ripperUsers == 0)
  202095. DeinitialiseCDRipper();
  202096. }
  202097. void timerCallback()
  202098. {
  202099. delete this;
  202100. }
  202101. juce_UseDebuggingNewOperator
  202102. };
  202103. static void incUserCount()
  202104. {
  202105. if (ripperUsers++ == 0)
  202106. initialisedOk = InitialiseCDRipper();
  202107. }
  202108. static void decUserCount()
  202109. {
  202110. new DeinitialiseTimer();
  202111. }
  202112. struct CDDeviceWrapper
  202113. {
  202114. CDDeviceHandle* cdH;
  202115. CDReadBuffer* overlapBuffer;
  202116. bool jitter;
  202117. };
  202118. static int getAddressOf (const TOCTRACK* const t)
  202119. {
  202120. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  202121. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  202122. }
  202123. static int getMSFAddressOf (const TOCTRACK* const t)
  202124. {
  202125. return 60 * t->addr[1] + t->addr[2];
  202126. }
  202127. static const int samplesPerFrame = 44100 / 75;
  202128. static const int bytesPerFrame = samplesPerFrame * 4;
  202129. const StringArray AudioCDReader::getAvailableCDNames()
  202130. {
  202131. StringArray results;
  202132. incUserCount();
  202133. if (initialisedOk)
  202134. {
  202135. CDDeviceInfo list[8];
  202136. const int num = FindCDDevices (list, 8);
  202137. decUserCount();
  202138. for (int i = 0; i < num; ++i)
  202139. {
  202140. String s;
  202141. if (list[i].scsiDriveLetter > 0)
  202142. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << T(": ");
  202143. s << String (list[i].vendor).trim()
  202144. << T(" ") << String (list[i].productId).trim()
  202145. << T(" ") << String (list[i].rev).trim();
  202146. results.add (s);
  202147. }
  202148. }
  202149. return results;
  202150. }
  202151. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  202152. {
  202153. SRB_GDEVBlock s;
  202154. zerostruct (s);
  202155. s.SRB_Cmd = SC_GET_DEV_TYPE;
  202156. s.SRB_HaID = device->ha;
  202157. s.SRB_Target = device->tgt;
  202158. s.SRB_Lun = device->lun;
  202159. if (usingScsi)
  202160. {
  202161. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  202162. if (h != INVALID_HANDLE_VALUE)
  202163. {
  202164. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  202165. cdh->scsiHandle = h;
  202166. return cdh;
  202167. }
  202168. }
  202169. else
  202170. {
  202171. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  202172. && s.SRB_DeviceType == DTYPE_CROM)
  202173. {
  202174. return new CDDeviceHandle (device);
  202175. }
  202176. }
  202177. return 0;
  202178. }
  202179. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  202180. {
  202181. incUserCount();
  202182. if (initialisedOk)
  202183. {
  202184. CDDeviceInfo list[8];
  202185. const int num = FindCDDevices (list, 8);
  202186. if (((unsigned int) deviceIndex) < (unsigned int) num)
  202187. {
  202188. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  202189. if (handle != 0)
  202190. {
  202191. CDDeviceWrapper* const d = new CDDeviceWrapper();
  202192. d->cdH = handle;
  202193. d->overlapBuffer = new CDReadBuffer(3);
  202194. return new AudioCDReader (d);
  202195. }
  202196. }
  202197. }
  202198. decUserCount();
  202199. return 0;
  202200. }
  202201. AudioCDReader::AudioCDReader (void* handle_)
  202202. : AudioFormatReader (0, T("CD Audio")),
  202203. handle (handle_),
  202204. indexingEnabled (false),
  202205. lastIndex (0),
  202206. firstFrameInBuffer (0),
  202207. samplesInBuffer (0)
  202208. {
  202209. jassert (handle_ != 0);
  202210. refreshTrackLengths();
  202211. sampleRate = 44100.0;
  202212. bitsPerSample = 16;
  202213. lengthInSamples = getPositionOfTrackStart (numTracks);
  202214. numChannels = 2;
  202215. usesFloatingPointData = false;
  202216. buffer.setSize (4 * bytesPerFrame, true);
  202217. }
  202218. AudioCDReader::~AudioCDReader()
  202219. {
  202220. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  202221. delete device->cdH;
  202222. delete device->overlapBuffer;
  202223. delete device;
  202224. decUserCount();
  202225. }
  202226. bool AudioCDReader::read (int** destSamples,
  202227. int64 startSampleInFile,
  202228. int numSamples)
  202229. {
  202230. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  202231. bool ok = true;
  202232. int offset = 0;
  202233. if (startSampleInFile < 0)
  202234. {
  202235. int* l = destSamples[0];
  202236. int* r = destSamples[1];
  202237. numSamples += (int) startSampleInFile;
  202238. offset -= (int) startSampleInFile;
  202239. while (++startSampleInFile <= 0)
  202240. {
  202241. *l++ = 0;
  202242. if (r != 0)
  202243. *r++ = 0;
  202244. }
  202245. }
  202246. while (numSamples > 0)
  202247. {
  202248. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  202249. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  202250. if (startSampleInFile >= bufferStartSample
  202251. && startSampleInFile < bufferEndSample)
  202252. {
  202253. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  202254. int* const l = destSamples[0] + offset;
  202255. int* const r = destSamples[1] + offset;
  202256. const short* src = (const short*) buffer.getData();
  202257. src += 2 * (startSampleInFile - bufferStartSample);
  202258. for (int i = 0; i < toDo; ++i)
  202259. {
  202260. l[i] = src [i << 1] << 16;
  202261. if (r != 0)
  202262. r[i] = src [(i << 1) + 1] << 16;
  202263. }
  202264. offset += toDo;
  202265. startSampleInFile += toDo;
  202266. numSamples -= toDo;
  202267. }
  202268. else
  202269. {
  202270. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  202271. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  202272. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  202273. {
  202274. device->overlapBuffer->dataLength = 0;
  202275. device->overlapBuffer->startFrame = 0;
  202276. device->overlapBuffer->numFrames = 0;
  202277. device->jitter = false;
  202278. }
  202279. firstFrameInBuffer = frameNeeded;
  202280. lastIndex = 0;
  202281. CDReadBuffer readBuffer (framesInBuffer + 4);
  202282. readBuffer.wantsIndex = indexingEnabled;
  202283. int i;
  202284. for (i = 5; --i >= 0;)
  202285. {
  202286. readBuffer.startFrame = frameNeeded;
  202287. readBuffer.numFrames = framesInBuffer;
  202288. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  202289. break;
  202290. else
  202291. device->overlapBuffer->dataLength = 0;
  202292. }
  202293. if (i >= 0)
  202294. {
  202295. memcpy ((char*) buffer.getData(),
  202296. readBuffer.buffer + readBuffer.dataStartOffset,
  202297. readBuffer.dataLength);
  202298. samplesInBuffer = readBuffer.dataLength >> 2;
  202299. lastIndex = readBuffer.index;
  202300. }
  202301. else
  202302. {
  202303. int* l = destSamples[0] + offset;
  202304. int* r = destSamples[1] + offset;
  202305. while (--numSamples >= 0)
  202306. {
  202307. *l++ = 0;
  202308. if (r != 0)
  202309. *r++ = 0;
  202310. }
  202311. // sometimes the read fails for just the very last couple of blocks, so
  202312. // we'll ignore and errors in the last half-second of the disk..
  202313. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  202314. break;
  202315. }
  202316. }
  202317. }
  202318. return ok;
  202319. }
  202320. bool AudioCDReader::isCDStillPresent() const
  202321. {
  202322. TOC toc;
  202323. zerostruct (toc);
  202324. return ((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false);
  202325. }
  202326. int AudioCDReader::getNumTracks() const
  202327. {
  202328. return numTracks;
  202329. }
  202330. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  202331. {
  202332. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  202333. : 0;
  202334. }
  202335. void AudioCDReader::refreshTrackLengths()
  202336. {
  202337. zeromem (trackStarts, sizeof (trackStarts));
  202338. zeromem (audioTracks, sizeof (audioTracks));
  202339. TOC toc;
  202340. zerostruct (toc);
  202341. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  202342. {
  202343. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  202344. for (int i = 0; i <= numTracks; ++i)
  202345. {
  202346. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  202347. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  202348. }
  202349. }
  202350. else
  202351. {
  202352. numTracks = 0;
  202353. }
  202354. }
  202355. bool AudioCDReader::isTrackAudio (int trackNum) const
  202356. {
  202357. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  202358. : false;
  202359. }
  202360. void AudioCDReader::enableIndexScanning (bool b)
  202361. {
  202362. indexingEnabled = b;
  202363. }
  202364. int AudioCDReader::getLastIndex() const
  202365. {
  202366. return lastIndex;
  202367. }
  202368. const int framesPerIndexRead = 4;
  202369. int AudioCDReader::getIndexAt (int samplePos)
  202370. {
  202371. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  202372. const int frameNeeded = samplePos / samplesPerFrame;
  202373. device->overlapBuffer->dataLength = 0;
  202374. device->overlapBuffer->startFrame = 0;
  202375. device->overlapBuffer->numFrames = 0;
  202376. device->jitter = false;
  202377. firstFrameInBuffer = 0;
  202378. lastIndex = 0;
  202379. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  202380. readBuffer.wantsIndex = true;
  202381. int i;
  202382. for (i = 5; --i >= 0;)
  202383. {
  202384. readBuffer.startFrame = frameNeeded;
  202385. readBuffer.numFrames = framesPerIndexRead;
  202386. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  202387. break;
  202388. }
  202389. if (i >= 0)
  202390. return readBuffer.index;
  202391. return -1;
  202392. }
  202393. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  202394. {
  202395. Array <int> indexes;
  202396. const int trackStart = getPositionOfTrackStart (trackNumber);
  202397. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  202398. bool needToScan = true;
  202399. if (trackEnd - trackStart > 20 * 44100)
  202400. {
  202401. // check the end of the track for indexes before scanning the whole thing
  202402. needToScan = false;
  202403. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  202404. bool seenAnIndex = false;
  202405. while (pos <= trackEnd - samplesPerFrame)
  202406. {
  202407. const int index = getIndexAt (pos);
  202408. if (index == 0)
  202409. {
  202410. // lead-out, so skip back a bit if we've not found any indexes yet..
  202411. if (seenAnIndex)
  202412. break;
  202413. pos -= 44100 * 5;
  202414. if (pos < trackStart)
  202415. break;
  202416. }
  202417. else
  202418. {
  202419. if (index > 0)
  202420. seenAnIndex = true;
  202421. if (index > 1)
  202422. {
  202423. needToScan = true;
  202424. break;
  202425. }
  202426. pos += samplesPerFrame * framesPerIndexRead;
  202427. }
  202428. }
  202429. }
  202430. if (needToScan)
  202431. {
  202432. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  202433. int pos = trackStart;
  202434. int last = -1;
  202435. while (pos < trackEnd - samplesPerFrame * 10)
  202436. {
  202437. const int frameNeeded = pos / samplesPerFrame;
  202438. device->overlapBuffer->dataLength = 0;
  202439. device->overlapBuffer->startFrame = 0;
  202440. device->overlapBuffer->numFrames = 0;
  202441. device->jitter = false;
  202442. firstFrameInBuffer = 0;
  202443. CDReadBuffer readBuffer (4);
  202444. readBuffer.wantsIndex = true;
  202445. int i;
  202446. for (i = 5; --i >= 0;)
  202447. {
  202448. readBuffer.startFrame = frameNeeded;
  202449. readBuffer.numFrames = framesPerIndexRead;
  202450. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  202451. break;
  202452. }
  202453. if (i < 0)
  202454. break;
  202455. if (readBuffer.index > last && readBuffer.index > 1)
  202456. {
  202457. last = readBuffer.index;
  202458. indexes.add (pos);
  202459. }
  202460. pos += samplesPerFrame * framesPerIndexRead;
  202461. }
  202462. indexes.removeValue (trackStart);
  202463. }
  202464. return indexes;
  202465. }
  202466. int AudioCDReader::getCDDBId()
  202467. {
  202468. refreshTrackLengths();
  202469. if (numTracks > 0)
  202470. {
  202471. TOC toc;
  202472. zerostruct (toc);
  202473. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  202474. {
  202475. int n = 0;
  202476. for (int i = numTracks; --i >= 0;)
  202477. {
  202478. int j = getMSFAddressOf (&toc.tracks[i]);
  202479. while (j > 0)
  202480. {
  202481. n += (j % 10);
  202482. j /= 10;
  202483. }
  202484. }
  202485. if (n != 0)
  202486. {
  202487. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  202488. - getMSFAddressOf (&toc.tracks[0]);
  202489. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  202490. }
  202491. }
  202492. }
  202493. return 0;
  202494. }
  202495. void AudioCDReader::ejectDisk()
  202496. {
  202497. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  202498. }
  202499. #if JUCE_USE_CDBURNER
  202500. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  202501. {
  202502. CoInitialize (0);
  202503. IDiscMaster* dm;
  202504. IDiscRecorder* result = 0;
  202505. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  202506. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  202507. IID_IDiscMaster,
  202508. (void**) &dm)))
  202509. {
  202510. if (SUCCEEDED (dm->Open()))
  202511. {
  202512. IEnumDiscRecorders* drEnum = 0;
  202513. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  202514. {
  202515. IDiscRecorder* dr = 0;
  202516. DWORD dummy;
  202517. int index = 0;
  202518. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  202519. {
  202520. if (indexToOpen == index)
  202521. {
  202522. result = dr;
  202523. break;
  202524. }
  202525. else if (list != 0)
  202526. {
  202527. BSTR path;
  202528. if (SUCCEEDED (dr->GetPath (&path)))
  202529. list->add ((const WCHAR*) path);
  202530. }
  202531. ++index;
  202532. dr->Release();
  202533. }
  202534. drEnum->Release();
  202535. }
  202536. /*if (redbookFormat != 0)
  202537. {
  202538. IEnumDiscMasterFormats* mfEnum;
  202539. if (SUCCEEDED (dm->EnumDiscMasterFormats (&mfEnum)))
  202540. {
  202541. IID formatIID;
  202542. DWORD dummy;
  202543. while (mfEnum->Next (1, &formatIID, &dummy) == S_OK)
  202544. {
  202545. }
  202546. mfEnum->Release();
  202547. }
  202548. redbookFormat
  202549. }*/
  202550. if (master == 0)
  202551. dm->Close();
  202552. }
  202553. if (master != 0)
  202554. *master = dm;
  202555. else
  202556. dm->Release();
  202557. }
  202558. return result;
  202559. }
  202560. const StringArray AudioCDBurner::findAvailableDevices()
  202561. {
  202562. StringArray devs;
  202563. enumCDBurners (&devs, -1, 0);
  202564. return devs;
  202565. }
  202566. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  202567. {
  202568. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  202569. if (b->internal == 0)
  202570. deleteAndZero (b);
  202571. return b;
  202572. }
  202573. class CDBurnerInfo : public IDiscMasterProgressEvents
  202574. {
  202575. public:
  202576. CDBurnerInfo()
  202577. : refCount (1),
  202578. progress (0),
  202579. shouldCancel (false),
  202580. listener (0)
  202581. {
  202582. }
  202583. ~CDBurnerInfo()
  202584. {
  202585. }
  202586. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  202587. {
  202588. if (result == 0)
  202589. return E_POINTER;
  202590. if (id == IID_IUnknown || id == IID_IDiscMasterProgressEvents)
  202591. {
  202592. AddRef();
  202593. *result = this;
  202594. return S_OK;
  202595. }
  202596. *result = 0;
  202597. return E_NOINTERFACE;
  202598. }
  202599. ULONG __stdcall AddRef() { return ++refCount; }
  202600. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  202601. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  202602. {
  202603. if (listener != 0 && ! shouldCancel)
  202604. shouldCancel = listener->audioCDBurnProgress (progress);
  202605. *pbCancel = shouldCancel;
  202606. return S_OK;
  202607. }
  202608. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  202609. {
  202610. progress = nCompleted / (float) nTotal;
  202611. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  202612. return E_NOTIMPL;
  202613. }
  202614. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  202615. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  202616. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  202617. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  202618. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  202619. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  202620. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  202621. IDiscMaster* discMaster;
  202622. IDiscRecorder* discRecorder;
  202623. IRedbookDiscMaster* redbook;
  202624. AudioCDBurner::BurnProgressListener* listener;
  202625. float progress;
  202626. bool shouldCancel;
  202627. private:
  202628. int refCount;
  202629. };
  202630. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  202631. : internal (0)
  202632. {
  202633. IDiscMaster* discMaster;
  202634. IDiscRecorder* dr = enumCDBurners (0, deviceIndex, &discMaster);
  202635. if (dr != 0)
  202636. {
  202637. IRedbookDiscMaster* redbook;
  202638. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  202639. hr = discMaster->SetActiveDiscRecorder (dr);
  202640. CDBurnerInfo* const info = new CDBurnerInfo();
  202641. internal = info;
  202642. info->discMaster = discMaster;
  202643. info->discRecorder = dr;
  202644. info->redbook = redbook;
  202645. }
  202646. }
  202647. AudioCDBurner::~AudioCDBurner()
  202648. {
  202649. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  202650. if (info != 0)
  202651. {
  202652. info->discRecorder->Close();
  202653. info->redbook->Release();
  202654. info->discRecorder->Release();
  202655. info->discMaster->Release();
  202656. info->Release();
  202657. }
  202658. }
  202659. bool AudioCDBurner::isDiskPresent() const
  202660. {
  202661. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  202662. HRESULT hr = info->discRecorder->OpenExclusive();
  202663. long type, flags;
  202664. hr = info->discRecorder->QueryMediaType (&type, &flags);
  202665. info->discRecorder->Close();
  202666. return hr == S_OK && type != 0 && (flags & MEDIA_WRITABLE) != 0;
  202667. }
  202668. int AudioCDBurner::getNumAvailableAudioBlocks() const
  202669. {
  202670. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  202671. long blocksFree = 0;
  202672. info->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  202673. return blocksFree;
  202674. }
  202675. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener,
  202676. const bool ejectDiscAfterwards,
  202677. const bool performFakeBurnForTesting)
  202678. {
  202679. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  202680. info->listener = listener;
  202681. info->progress = 0;
  202682. info->shouldCancel = false;
  202683. UINT_PTR cookie;
  202684. HRESULT hr = info->discMaster->ProgressAdvise (info, &cookie);
  202685. hr = info->discMaster->RecordDisc (performFakeBurnForTesting,
  202686. ejectDiscAfterwards);
  202687. String error;
  202688. if (hr != S_OK)
  202689. {
  202690. const char* e = "Couldn't open or write to the CD device";
  202691. if (hr == IMAPI_E_USERABORT)
  202692. e = "User cancelled the write operation";
  202693. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  202694. e = "No Disk present";
  202695. error = e;
  202696. }
  202697. info->discMaster->ProgressUnadvise (cookie);
  202698. info->listener = 0;
  202699. return error;
  202700. }
  202701. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamples)
  202702. {
  202703. if (source == 0)
  202704. return false;
  202705. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  202706. long bytesPerBlock;
  202707. HRESULT hr = info->redbook->GetAudioBlockSize (&bytesPerBlock);
  202708. const int samplesPerBlock = bytesPerBlock / 4;
  202709. bool ok = true;
  202710. hr = info->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  202711. byte* const buffer = (byte*) juce_malloc (bytesPerBlock);
  202712. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  202713. int samplesDone = 0;
  202714. source->prepareToPlay (samplesPerBlock, 44100.0);
  202715. while (ok)
  202716. {
  202717. {
  202718. AudioSourceChannelInfo info;
  202719. info.buffer = &sourceBuffer;
  202720. info.numSamples = samplesPerBlock;
  202721. info.startSample = 0;
  202722. sourceBuffer.clear();
  202723. source->getNextAudioBlock (info);
  202724. }
  202725. zeromem (buffer, bytesPerBlock);
  202726. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  202727. buffer, samplesPerBlock, 4);
  202728. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  202729. buffer + 2, samplesPerBlock, 4);
  202730. hr = info->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  202731. if (hr != S_OK)
  202732. ok = false;
  202733. samplesDone += samplesPerBlock;
  202734. if (samplesDone >= numSamples)
  202735. break;
  202736. }
  202737. juce_free (buffer);
  202738. hr = info->redbook->CloseAudioTrack();
  202739. delete source;
  202740. return ok && hr == S_OK;
  202741. }
  202742. #endif
  202743. END_JUCE_NAMESPACE
  202744. /********* End of inlined file: juce_win32_AudioCDReader.cpp *********/
  202745. /********* Start of inlined file: juce_win32_DirectSound.cpp *********/
  202746. extern "C"
  202747. {
  202748. // Declare just the minimum number of interfaces for the DSound objects that we need..
  202749. typedef struct typeDSBUFFERDESC
  202750. {
  202751. DWORD dwSize;
  202752. DWORD dwFlags;
  202753. DWORD dwBufferBytes;
  202754. DWORD dwReserved;
  202755. LPWAVEFORMATEX lpwfxFormat;
  202756. GUID guid3DAlgorithm;
  202757. } DSBUFFERDESC;
  202758. struct IDirectSoundBuffer;
  202759. #undef INTERFACE
  202760. #define INTERFACE IDirectSound
  202761. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  202762. {
  202763. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  202764. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  202765. STDMETHOD_(ULONG,Release) (THIS) PURE;
  202766. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  202767. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  202768. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  202769. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  202770. STDMETHOD(Compact) (THIS) PURE;
  202771. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  202772. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  202773. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  202774. };
  202775. #undef INTERFACE
  202776. #define INTERFACE IDirectSoundBuffer
  202777. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  202778. {
  202779. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  202780. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  202781. STDMETHOD_(ULONG,Release) (THIS) PURE;
  202782. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  202783. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  202784. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  202785. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  202786. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  202787. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  202788. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  202789. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  202790. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  202791. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  202792. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  202793. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  202794. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  202795. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  202796. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  202797. STDMETHOD(Stop) (THIS) PURE;
  202798. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  202799. STDMETHOD(Restore) (THIS) PURE;
  202800. };
  202801. typedef struct typeDSCBUFFERDESC
  202802. {
  202803. DWORD dwSize;
  202804. DWORD dwFlags;
  202805. DWORD dwBufferBytes;
  202806. DWORD dwReserved;
  202807. LPWAVEFORMATEX lpwfxFormat;
  202808. } DSCBUFFERDESC;
  202809. struct IDirectSoundCaptureBuffer;
  202810. #undef INTERFACE
  202811. #define INTERFACE IDirectSoundCapture
  202812. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  202813. {
  202814. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  202815. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  202816. STDMETHOD_(ULONG,Release) (THIS) PURE;
  202817. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  202818. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  202819. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  202820. };
  202821. #undef INTERFACE
  202822. #define INTERFACE IDirectSoundCaptureBuffer
  202823. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  202824. {
  202825. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  202826. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  202827. STDMETHOD_(ULONG,Release) (THIS) PURE;
  202828. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  202829. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  202830. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  202831. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  202832. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  202833. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  202834. STDMETHOD(Start) (THIS_ DWORD) PURE;
  202835. STDMETHOD(Stop) (THIS) PURE;
  202836. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  202837. };
  202838. };
  202839. BEGIN_JUCE_NAMESPACE
  202840. static const String getDSErrorMessage (HRESULT hr)
  202841. {
  202842. const char* result = 0;
  202843. switch (hr)
  202844. {
  202845. case MAKE_HRESULT(1, 0x878, 10):
  202846. result = "Device already allocated";
  202847. break;
  202848. case MAKE_HRESULT(1, 0x878, 30):
  202849. result = "Control unavailable";
  202850. break;
  202851. case E_INVALIDARG:
  202852. result = "Invalid parameter";
  202853. break;
  202854. case MAKE_HRESULT(1, 0x878, 50):
  202855. result = "Invalid call";
  202856. break;
  202857. case E_FAIL:
  202858. result = "Generic error";
  202859. break;
  202860. case MAKE_HRESULT(1, 0x878, 70):
  202861. result = "Priority level error";
  202862. break;
  202863. case E_OUTOFMEMORY:
  202864. result = "Out of memory";
  202865. break;
  202866. case MAKE_HRESULT(1, 0x878, 100):
  202867. result = "Bad format";
  202868. break;
  202869. case E_NOTIMPL:
  202870. result = "Unsupported function";
  202871. break;
  202872. case MAKE_HRESULT(1, 0x878, 120):
  202873. result = "No driver";
  202874. break;
  202875. case MAKE_HRESULT(1, 0x878, 130):
  202876. result = "Already initialised";
  202877. break;
  202878. case CLASS_E_NOAGGREGATION:
  202879. result = "No aggregation";
  202880. break;
  202881. case MAKE_HRESULT(1, 0x878, 150):
  202882. result = "Buffer lost";
  202883. break;
  202884. case MAKE_HRESULT(1, 0x878, 160):
  202885. result = "Another app has priority";
  202886. break;
  202887. case MAKE_HRESULT(1, 0x878, 170):
  202888. result = "Uninitialised";
  202889. break;
  202890. case E_NOINTERFACE:
  202891. result = "No interface";
  202892. break;
  202893. case S_OK:
  202894. result = "No error";
  202895. break;
  202896. default:
  202897. return "Unknown error: " + String ((int) hr);
  202898. }
  202899. return result;
  202900. }
  202901. #define DS_DEBUGGING 1
  202902. #ifdef DS_DEBUGGING
  202903. #define CATCH JUCE_CATCH_EXCEPTION
  202904. #undef log
  202905. #define log(a) Logger::writeToLog(a);
  202906. #undef logError
  202907. #define logError(a) logDSError(a, __LINE__);
  202908. static void logDSError (HRESULT hr, int lineNum)
  202909. {
  202910. if (hr != S_OK)
  202911. {
  202912. String error ("DS error at line ");
  202913. error << lineNum << T(" - ") << getDSErrorMessage (hr);
  202914. log (error);
  202915. }
  202916. }
  202917. #else
  202918. #define CATCH JUCE_CATCH_ALL
  202919. #define log(a)
  202920. #define logError(a)
  202921. #endif
  202922. #define DSOUND_FUNCTION(functionName, params) \
  202923. typedef HRESULT (WINAPI *type##functionName) params; \
  202924. static type##functionName ds##functionName = 0;
  202925. #define DSOUND_FUNCTION_LOAD(functionName) \
  202926. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  202927. jassert (ds##functionName != 0);
  202928. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  202929. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  202930. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  202931. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  202932. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  202933. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  202934. static void initialiseDSoundFunctions()
  202935. {
  202936. if (dsDirectSoundCreate == 0)
  202937. {
  202938. HMODULE h = LoadLibraryA ("dsound.dll");
  202939. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  202940. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  202941. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  202942. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  202943. }
  202944. }
  202945. class DSoundInternalOutChannel
  202946. {
  202947. String name;
  202948. LPGUID guid;
  202949. int sampleRate, bufferSizeSamples;
  202950. float* leftBuffer;
  202951. float* rightBuffer;
  202952. IDirectSound* pDirectSound;
  202953. IDirectSoundBuffer* pOutputBuffer;
  202954. DWORD writeOffset;
  202955. int totalBytesPerBuffer;
  202956. int bytesPerBuffer;
  202957. unsigned int lastPlayCursor;
  202958. public:
  202959. int bitDepth;
  202960. bool doneFlag;
  202961. DSoundInternalOutChannel (const String& name_,
  202962. LPGUID guid_,
  202963. int rate,
  202964. int bufferSize,
  202965. float* left,
  202966. float* right)
  202967. : name (name_),
  202968. guid (guid_),
  202969. sampleRate (rate),
  202970. bufferSizeSamples (bufferSize),
  202971. leftBuffer (left),
  202972. rightBuffer (right),
  202973. pDirectSound (0),
  202974. pOutputBuffer (0),
  202975. bitDepth (16)
  202976. {
  202977. }
  202978. ~DSoundInternalOutChannel()
  202979. {
  202980. close();
  202981. }
  202982. void close()
  202983. {
  202984. HRESULT hr;
  202985. if (pOutputBuffer != 0)
  202986. {
  202987. JUCE_TRY
  202988. {
  202989. log (T("closing dsound out: ") + name);
  202990. hr = pOutputBuffer->Stop();
  202991. logError (hr);
  202992. }
  202993. CATCH
  202994. JUCE_TRY
  202995. {
  202996. hr = pOutputBuffer->Release();
  202997. logError (hr);
  202998. }
  202999. CATCH
  203000. pOutputBuffer = 0;
  203001. }
  203002. if (pDirectSound != 0)
  203003. {
  203004. JUCE_TRY
  203005. {
  203006. hr = pDirectSound->Release();
  203007. logError (hr);
  203008. }
  203009. CATCH
  203010. pDirectSound = 0;
  203011. }
  203012. }
  203013. const String open()
  203014. {
  203015. log (T("opening dsound out device: ") + name
  203016. + T(" rate=") + String (sampleRate)
  203017. + T(" bits=") + String (bitDepth)
  203018. + T(" buf=") + String (bufferSizeSamples));
  203019. pDirectSound = 0;
  203020. pOutputBuffer = 0;
  203021. writeOffset = 0;
  203022. String error;
  203023. HRESULT hr = E_NOINTERFACE;
  203024. if (dsDirectSoundCreate != 0)
  203025. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  203026. if (hr == S_OK)
  203027. {
  203028. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  203029. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  203030. const int numChannels = 2;
  203031. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  203032. logError (hr);
  203033. if (hr == S_OK)
  203034. {
  203035. IDirectSoundBuffer* pPrimaryBuffer;
  203036. DSBUFFERDESC primaryDesc;
  203037. zerostruct (primaryDesc);
  203038. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  203039. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  203040. primaryDesc.dwBufferBytes = 0;
  203041. primaryDesc.lpwfxFormat = 0;
  203042. log ("opening dsound out step 2");
  203043. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  203044. logError (hr);
  203045. if (hr == S_OK)
  203046. {
  203047. WAVEFORMATEX wfFormat;
  203048. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  203049. wfFormat.nChannels = (unsigned short) numChannels;
  203050. wfFormat.nSamplesPerSec = sampleRate;
  203051. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  203052. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  203053. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  203054. wfFormat.cbSize = 0;
  203055. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  203056. logError (hr);
  203057. if (hr == S_OK)
  203058. {
  203059. DSBUFFERDESC secondaryDesc;
  203060. zerostruct (secondaryDesc);
  203061. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  203062. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  203063. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  203064. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  203065. secondaryDesc.lpwfxFormat = &wfFormat;
  203066. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  203067. logError (hr);
  203068. if (hr == S_OK)
  203069. {
  203070. log ("opening dsound out step 3");
  203071. DWORD dwDataLen;
  203072. unsigned char* pDSBuffData;
  203073. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  203074. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  203075. logError (hr);
  203076. if (hr == S_OK)
  203077. {
  203078. zeromem (pDSBuffData, dwDataLen);
  203079. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  203080. if (hr == S_OK)
  203081. {
  203082. hr = pOutputBuffer->SetCurrentPosition (0);
  203083. if (hr == S_OK)
  203084. {
  203085. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  203086. if (hr == S_OK)
  203087. return String::empty;
  203088. }
  203089. }
  203090. }
  203091. }
  203092. }
  203093. }
  203094. }
  203095. }
  203096. error = getDSErrorMessage (hr);
  203097. close();
  203098. return error;
  203099. }
  203100. void synchronisePosition()
  203101. {
  203102. if (pOutputBuffer != 0)
  203103. {
  203104. DWORD playCursor;
  203105. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  203106. }
  203107. }
  203108. bool service()
  203109. {
  203110. if (pOutputBuffer == 0)
  203111. return true;
  203112. DWORD playCursor, writeCursor;
  203113. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  203114. if (hr != S_OK)
  203115. {
  203116. logError (hr);
  203117. jassertfalse
  203118. return true;
  203119. }
  203120. int playWriteGap = writeCursor - playCursor;
  203121. if (playWriteGap < 0)
  203122. playWriteGap += totalBytesPerBuffer;
  203123. int bytesEmpty = playCursor - writeOffset;
  203124. if (bytesEmpty < 0)
  203125. bytesEmpty += totalBytesPerBuffer;
  203126. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  203127. {
  203128. writeOffset = writeCursor;
  203129. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  203130. }
  203131. if (bytesEmpty >= bytesPerBuffer)
  203132. {
  203133. LPBYTE lpbuf1 = 0;
  203134. LPBYTE lpbuf2 = 0;
  203135. DWORD dwSize1 = 0;
  203136. DWORD dwSize2 = 0;
  203137. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  203138. bytesPerBuffer,
  203139. (void**) &lpbuf1, &dwSize1,
  203140. (void**) &lpbuf2, &dwSize2, 0);
  203141. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  203142. {
  203143. pOutputBuffer->Restore();
  203144. hr = pOutputBuffer->Lock (writeOffset,
  203145. bytesPerBuffer,
  203146. (void**) &lpbuf1, &dwSize1,
  203147. (void**) &lpbuf2, &dwSize2, 0);
  203148. }
  203149. if (hr == S_OK)
  203150. {
  203151. if (bitDepth == 16)
  203152. {
  203153. const float gainL = 32767.0f;
  203154. const float gainR = 32767.0f;
  203155. int* dest = (int*)lpbuf1;
  203156. const float* left = leftBuffer;
  203157. const float* right = rightBuffer;
  203158. int samples1 = dwSize1 >> 2;
  203159. int samples2 = dwSize2 >> 2;
  203160. if (left == 0)
  203161. {
  203162. while (--samples1 >= 0)
  203163. {
  203164. int r = roundFloatToInt (gainR * *right++);
  203165. if (r < -32768)
  203166. r = -32768;
  203167. else if (r > 32767)
  203168. r = 32767;
  203169. *dest++ = (r << 16);
  203170. }
  203171. dest = (int*)lpbuf2;
  203172. while (--samples2 >= 0)
  203173. {
  203174. int r = roundFloatToInt (gainR * *right++);
  203175. if (r < -32768)
  203176. r = -32768;
  203177. else if (r > 32767)
  203178. r = 32767;
  203179. *dest++ = (r << 16);
  203180. }
  203181. }
  203182. else if (right == 0)
  203183. {
  203184. while (--samples1 >= 0)
  203185. {
  203186. int l = roundFloatToInt (gainL * *left++);
  203187. if (l < -32768)
  203188. l = -32768;
  203189. else if (l > 32767)
  203190. l = 32767;
  203191. l &= 0xffff;
  203192. *dest++ = l;
  203193. }
  203194. dest = (int*)lpbuf2;
  203195. while (--samples2 >= 0)
  203196. {
  203197. int l = roundFloatToInt (gainL * *left++);
  203198. if (l < -32768)
  203199. l = -32768;
  203200. else if (l > 32767)
  203201. l = 32767;
  203202. l &= 0xffff;
  203203. *dest++ = l;
  203204. }
  203205. }
  203206. else
  203207. {
  203208. while (--samples1 >= 0)
  203209. {
  203210. int l = roundFloatToInt (gainL * *left++);
  203211. if (l < -32768)
  203212. l = -32768;
  203213. else if (l > 32767)
  203214. l = 32767;
  203215. l &= 0xffff;
  203216. int r = roundFloatToInt (gainR * *right++);
  203217. if (r < -32768)
  203218. r = -32768;
  203219. else if (r > 32767)
  203220. r = 32767;
  203221. *dest++ = (r << 16) | l;
  203222. }
  203223. dest = (int*)lpbuf2;
  203224. while (--samples2 >= 0)
  203225. {
  203226. int l = roundFloatToInt (gainL * *left++);
  203227. if (l < -32768)
  203228. l = -32768;
  203229. else if (l > 32767)
  203230. l = 32767;
  203231. l &= 0xffff;
  203232. int r = roundFloatToInt (gainR * *right++);
  203233. if (r < -32768)
  203234. r = -32768;
  203235. else if (r > 32767)
  203236. r = 32767;
  203237. *dest++ = (r << 16) | l;
  203238. }
  203239. }
  203240. }
  203241. else
  203242. {
  203243. jassertfalse
  203244. }
  203245. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  203246. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  203247. }
  203248. else
  203249. {
  203250. jassertfalse
  203251. logError (hr);
  203252. }
  203253. bytesEmpty -= bytesPerBuffer;
  203254. return true;
  203255. }
  203256. else
  203257. {
  203258. return false;
  203259. }
  203260. }
  203261. };
  203262. struct DSoundInternalInChannel
  203263. {
  203264. String name;
  203265. LPGUID guid;
  203266. int sampleRate, bufferSizeSamples;
  203267. float* leftBuffer;
  203268. float* rightBuffer;
  203269. IDirectSound* pDirectSound;
  203270. IDirectSoundCapture* pDirectSoundCapture;
  203271. IDirectSoundCaptureBuffer* pInputBuffer;
  203272. public:
  203273. unsigned int readOffset;
  203274. int bytesPerBuffer, totalBytesPerBuffer;
  203275. int bitDepth;
  203276. bool doneFlag;
  203277. DSoundInternalInChannel (const String& name_,
  203278. LPGUID guid_,
  203279. int rate,
  203280. int bufferSize,
  203281. float* left,
  203282. float* right)
  203283. : name (name_),
  203284. guid (guid_),
  203285. sampleRate (rate),
  203286. bufferSizeSamples (bufferSize),
  203287. leftBuffer (left),
  203288. rightBuffer (right),
  203289. pDirectSound (0),
  203290. pDirectSoundCapture (0),
  203291. pInputBuffer (0),
  203292. bitDepth (16)
  203293. {
  203294. }
  203295. ~DSoundInternalInChannel()
  203296. {
  203297. close();
  203298. }
  203299. void close()
  203300. {
  203301. HRESULT hr;
  203302. if (pInputBuffer != 0)
  203303. {
  203304. JUCE_TRY
  203305. {
  203306. log (T("closing dsound in: ") + name);
  203307. hr = pInputBuffer->Stop();
  203308. logError (hr);
  203309. }
  203310. CATCH
  203311. JUCE_TRY
  203312. {
  203313. hr = pInputBuffer->Release();
  203314. logError (hr);
  203315. }
  203316. CATCH
  203317. pInputBuffer = 0;
  203318. }
  203319. if (pDirectSoundCapture != 0)
  203320. {
  203321. JUCE_TRY
  203322. {
  203323. hr = pDirectSoundCapture->Release();
  203324. logError (hr);
  203325. }
  203326. CATCH
  203327. pDirectSoundCapture = 0;
  203328. }
  203329. if (pDirectSound != 0)
  203330. {
  203331. JUCE_TRY
  203332. {
  203333. hr = pDirectSound->Release();
  203334. logError (hr);
  203335. }
  203336. CATCH
  203337. pDirectSound = 0;
  203338. }
  203339. }
  203340. const String open()
  203341. {
  203342. log (T("opening dsound in device: ") + name
  203343. + T(" rate=") + String (sampleRate) + T(" bits=") + String (bitDepth) + T(" buf=") + String (bufferSizeSamples));
  203344. pDirectSound = 0;
  203345. pDirectSoundCapture = 0;
  203346. pInputBuffer = 0;
  203347. readOffset = 0;
  203348. totalBytesPerBuffer = 0;
  203349. String error;
  203350. HRESULT hr = E_NOINTERFACE;
  203351. if (dsDirectSoundCaptureCreate != 0)
  203352. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  203353. logError (hr);
  203354. if (hr == S_OK)
  203355. {
  203356. const int numChannels = 2;
  203357. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  203358. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  203359. WAVEFORMATEX wfFormat;
  203360. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  203361. wfFormat.nChannels = (unsigned short)numChannels;
  203362. wfFormat.nSamplesPerSec = sampleRate;
  203363. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  203364. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  203365. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  203366. wfFormat.cbSize = 0;
  203367. DSCBUFFERDESC captureDesc;
  203368. zerostruct (captureDesc);
  203369. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  203370. captureDesc.dwFlags = 0;
  203371. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  203372. captureDesc.lpwfxFormat = &wfFormat;
  203373. log (T("opening dsound in step 2"));
  203374. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  203375. logError (hr);
  203376. if (hr == S_OK)
  203377. {
  203378. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  203379. logError (hr);
  203380. if (hr == S_OK)
  203381. return String::empty;
  203382. }
  203383. }
  203384. error = getDSErrorMessage (hr);
  203385. close();
  203386. return error;
  203387. }
  203388. void synchronisePosition()
  203389. {
  203390. if (pInputBuffer != 0)
  203391. {
  203392. DWORD capturePos;
  203393. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  203394. }
  203395. }
  203396. bool service()
  203397. {
  203398. if (pInputBuffer == 0)
  203399. return true;
  203400. DWORD capturePos, readPos;
  203401. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  203402. logError (hr);
  203403. if (hr != S_OK)
  203404. return true;
  203405. int bytesFilled = readPos - readOffset;
  203406. if (bytesFilled < 0)
  203407. bytesFilled += totalBytesPerBuffer;
  203408. if (bytesFilled >= bytesPerBuffer)
  203409. {
  203410. LPBYTE lpbuf1 = 0;
  203411. LPBYTE lpbuf2 = 0;
  203412. DWORD dwsize1 = 0;
  203413. DWORD dwsize2 = 0;
  203414. HRESULT hr = pInputBuffer->Lock (readOffset,
  203415. bytesPerBuffer,
  203416. (void**) &lpbuf1, &dwsize1,
  203417. (void**) &lpbuf2, &dwsize2, 0);
  203418. if (hr == S_OK)
  203419. {
  203420. if (bitDepth == 16)
  203421. {
  203422. const float g = 1.0f / 32768.0f;
  203423. float* destL = leftBuffer;
  203424. float* destR = rightBuffer;
  203425. int samples1 = dwsize1 >> 2;
  203426. int samples2 = dwsize2 >> 2;
  203427. const short* src = (const short*)lpbuf1;
  203428. if (destL == 0)
  203429. {
  203430. while (--samples1 >= 0)
  203431. {
  203432. ++src;
  203433. *destR++ = *src++ * g;
  203434. }
  203435. src = (const short*)lpbuf2;
  203436. while (--samples2 >= 0)
  203437. {
  203438. ++src;
  203439. *destR++ = *src++ * g;
  203440. }
  203441. }
  203442. else if (destR == 0)
  203443. {
  203444. while (--samples1 >= 0)
  203445. {
  203446. *destL++ = *src++ * g;
  203447. ++src;
  203448. }
  203449. src = (const short*)lpbuf2;
  203450. while (--samples2 >= 0)
  203451. {
  203452. *destL++ = *src++ * g;
  203453. ++src;
  203454. }
  203455. }
  203456. else
  203457. {
  203458. while (--samples1 >= 0)
  203459. {
  203460. *destL++ = *src++ * g;
  203461. *destR++ = *src++ * g;
  203462. }
  203463. src = (const short*)lpbuf2;
  203464. while (--samples2 >= 0)
  203465. {
  203466. *destL++ = *src++ * g;
  203467. *destR++ = *src++ * g;
  203468. }
  203469. }
  203470. }
  203471. else
  203472. {
  203473. jassertfalse
  203474. }
  203475. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  203476. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  203477. }
  203478. else
  203479. {
  203480. logError (hr);
  203481. jassertfalse
  203482. }
  203483. bytesFilled -= bytesPerBuffer;
  203484. return true;
  203485. }
  203486. else
  203487. {
  203488. return false;
  203489. }
  203490. }
  203491. };
  203492. class DSoundAudioIODevice : public AudioIODevice,
  203493. public Thread
  203494. {
  203495. public:
  203496. DSoundAudioIODevice (const String& deviceName,
  203497. const int outputDeviceIndex_,
  203498. const int inputDeviceIndex_)
  203499. : AudioIODevice (deviceName, "DirectSound"),
  203500. Thread ("Juce DSound"),
  203501. isOpen_ (false),
  203502. isStarted (false),
  203503. outputDeviceIndex (outputDeviceIndex_),
  203504. inputDeviceIndex (inputDeviceIndex_),
  203505. inChans (4),
  203506. outChans (4),
  203507. numInputBuffers (0),
  203508. numOutputBuffers (0),
  203509. totalSamplesOut (0),
  203510. sampleRate (0.0),
  203511. inputBuffers (0),
  203512. outputBuffers (0),
  203513. callback (0),
  203514. bufferSizeSamples (0)
  203515. {
  203516. if (outputDeviceIndex_ >= 0)
  203517. {
  203518. outChannels.add (TRANS("Left"));
  203519. outChannels.add (TRANS("Right"));
  203520. }
  203521. if (inputDeviceIndex_ >= 0)
  203522. {
  203523. inChannels.add (TRANS("Left"));
  203524. inChannels.add (TRANS("Right"));
  203525. }
  203526. }
  203527. ~DSoundAudioIODevice()
  203528. {
  203529. close();
  203530. }
  203531. const StringArray getOutputChannelNames()
  203532. {
  203533. return outChannels;
  203534. }
  203535. const StringArray getInputChannelNames()
  203536. {
  203537. return inChannels;
  203538. }
  203539. int getNumSampleRates()
  203540. {
  203541. return 4;
  203542. }
  203543. double getSampleRate (int index)
  203544. {
  203545. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  203546. return samps [jlimit (0, 3, index)];
  203547. }
  203548. int getNumBufferSizesAvailable()
  203549. {
  203550. return 50;
  203551. }
  203552. int getBufferSizeSamples (int index)
  203553. {
  203554. int n = 64;
  203555. for (int i = 0; i < index; ++i)
  203556. n += (n < 512) ? 32
  203557. : ((n < 1024) ? 64
  203558. : ((n < 2048) ? 128 : 256));
  203559. return n;
  203560. }
  203561. int getDefaultBufferSize()
  203562. {
  203563. return 2560;
  203564. }
  203565. const String open (const BitArray& inputChannels,
  203566. const BitArray& outputChannels,
  203567. double sampleRate,
  203568. int bufferSizeSamples)
  203569. {
  203570. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  203571. isOpen_ = lastError.isEmpty();
  203572. return lastError;
  203573. }
  203574. void close()
  203575. {
  203576. stop();
  203577. if (isOpen_)
  203578. {
  203579. closeDevice();
  203580. isOpen_ = false;
  203581. }
  203582. }
  203583. bool isOpen()
  203584. {
  203585. return isOpen_ && isThreadRunning();
  203586. }
  203587. int getCurrentBufferSizeSamples()
  203588. {
  203589. return bufferSizeSamples;
  203590. }
  203591. double getCurrentSampleRate()
  203592. {
  203593. return sampleRate;
  203594. }
  203595. int getCurrentBitDepth()
  203596. {
  203597. int i, bits = 256;
  203598. for (i = inChans.size(); --i >= 0;)
  203599. bits = jmin (bits, inChans[i]->bitDepth);
  203600. for (i = outChans.size(); --i >= 0;)
  203601. bits = jmin (bits, outChans[i]->bitDepth);
  203602. if (bits > 32)
  203603. bits = 16;
  203604. return bits;
  203605. }
  203606. const BitArray getActiveOutputChannels() const
  203607. {
  203608. return enabledOutputs;
  203609. }
  203610. const BitArray getActiveInputChannels() const
  203611. {
  203612. return enabledInputs;
  203613. }
  203614. int getOutputLatencyInSamples()
  203615. {
  203616. return (int) (getCurrentBufferSizeSamples() * 1.5);
  203617. }
  203618. int getInputLatencyInSamples()
  203619. {
  203620. return getOutputLatencyInSamples();
  203621. }
  203622. void start (AudioIODeviceCallback* call)
  203623. {
  203624. if (isOpen_ && call != 0 && ! isStarted)
  203625. {
  203626. if (! isThreadRunning())
  203627. {
  203628. // something gone wrong and the thread's stopped..
  203629. isOpen_ = false;
  203630. return;
  203631. }
  203632. call->audioDeviceAboutToStart (this);
  203633. const ScopedLock sl (startStopLock);
  203634. callback = call;
  203635. isStarted = true;
  203636. }
  203637. }
  203638. void stop()
  203639. {
  203640. if (isStarted)
  203641. {
  203642. AudioIODeviceCallback* const callbackLocal = callback;
  203643. {
  203644. const ScopedLock sl (startStopLock);
  203645. isStarted = false;
  203646. }
  203647. if (callbackLocal != 0)
  203648. callbackLocal->audioDeviceStopped();
  203649. }
  203650. }
  203651. bool isPlaying()
  203652. {
  203653. return isStarted && isOpen_ && isThreadRunning();
  203654. }
  203655. const String getLastError()
  203656. {
  203657. return lastError;
  203658. }
  203659. juce_UseDebuggingNewOperator
  203660. StringArray inChannels, outChannels;
  203661. int outputDeviceIndex, inputDeviceIndex;
  203662. private:
  203663. bool isOpen_;
  203664. bool isStarted;
  203665. String lastError;
  203666. OwnedArray <DSoundInternalInChannel> inChans;
  203667. OwnedArray <DSoundInternalOutChannel> outChans;
  203668. WaitableEvent startEvent;
  203669. int numInputBuffers, numOutputBuffers, bufferSizeSamples;
  203670. int volatile totalSamplesOut;
  203671. int64 volatile lastBlockTime;
  203672. double sampleRate;
  203673. BitArray enabledInputs, enabledOutputs;
  203674. float** inputBuffers;
  203675. float** outputBuffers;
  203676. AudioIODeviceCallback* callback;
  203677. CriticalSection startStopLock;
  203678. DSoundAudioIODevice (const DSoundAudioIODevice&);
  203679. const DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  203680. const String openDevice (const BitArray& inputChannels,
  203681. const BitArray& outputChannels,
  203682. double sampleRate_,
  203683. int bufferSizeSamples_);
  203684. void closeDevice()
  203685. {
  203686. isStarted = false;
  203687. stopThread (5000);
  203688. inChans.clear();
  203689. outChans.clear();
  203690. int i;
  203691. for (i = 0; i < numInputBuffers; ++i)
  203692. juce_free (inputBuffers[i]);
  203693. delete[] inputBuffers;
  203694. inputBuffers = 0;
  203695. numInputBuffers = 0;
  203696. for (i = 0; i < numOutputBuffers; ++i)
  203697. juce_free (outputBuffers[i]);
  203698. delete[] outputBuffers;
  203699. outputBuffers = 0;
  203700. numOutputBuffers = 0;
  203701. }
  203702. void resync()
  203703. {
  203704. int i;
  203705. for (i = outChans.size(); --i >= 0;)
  203706. outChans.getUnchecked(i)->close();
  203707. for (i = inChans.size(); --i >= 0;)
  203708. inChans.getUnchecked(i)->close();
  203709. if (threadShouldExit())
  203710. return;
  203711. // boost our priority while opening the devices to try to get better sync between them
  203712. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  203713. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  203714. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  203715. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  203716. for (i = outChans.size(); --i >= 0;)
  203717. outChans.getUnchecked(i)->open();
  203718. for (i = inChans.size(); --i >= 0;)
  203719. inChans.getUnchecked(i)->open();
  203720. if (! threadShouldExit())
  203721. {
  203722. sleep (5);
  203723. for (i = 0; i < outChans.size(); ++i)
  203724. outChans.getUnchecked(i)->synchronisePosition();
  203725. for (i = 0; i < inChans.size(); ++i)
  203726. inChans.getUnchecked(i)->synchronisePosition();
  203727. }
  203728. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  203729. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  203730. }
  203731. public:
  203732. void run()
  203733. {
  203734. while (! threadShouldExit())
  203735. {
  203736. if (wait (100))
  203737. break;
  203738. }
  203739. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  203740. const int maxTimeMS = jmax (5, 3 * latencyMs);
  203741. while (! threadShouldExit())
  203742. {
  203743. int numToDo = 0;
  203744. uint32 startTime = Time::getMillisecondCounter();
  203745. int i;
  203746. for (i = inChans.size(); --i >= 0;)
  203747. {
  203748. inChans.getUnchecked(i)->doneFlag = false;
  203749. ++numToDo;
  203750. }
  203751. for (i = outChans.size(); --i >= 0;)
  203752. {
  203753. outChans.getUnchecked(i)->doneFlag = false;
  203754. ++numToDo;
  203755. }
  203756. if (numToDo > 0)
  203757. {
  203758. const int maxCount = 3;
  203759. int count = maxCount;
  203760. for (;;)
  203761. {
  203762. for (i = inChans.size(); --i >= 0;)
  203763. {
  203764. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  203765. if ((! in->doneFlag) && in->service())
  203766. {
  203767. in->doneFlag = true;
  203768. --numToDo;
  203769. }
  203770. }
  203771. for (i = outChans.size(); --i >= 0;)
  203772. {
  203773. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  203774. if ((! out->doneFlag) && out->service())
  203775. {
  203776. out->doneFlag = true;
  203777. --numToDo;
  203778. }
  203779. }
  203780. if (numToDo <= 0)
  203781. break;
  203782. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  203783. {
  203784. resync();
  203785. break;
  203786. }
  203787. if (--count <= 0)
  203788. {
  203789. Sleep (1);
  203790. count = maxCount;
  203791. }
  203792. if (threadShouldExit())
  203793. return;
  203794. }
  203795. }
  203796. else
  203797. {
  203798. sleep (1);
  203799. }
  203800. const ScopedLock sl (startStopLock);
  203801. if (isStarted)
  203802. {
  203803. JUCE_TRY
  203804. {
  203805. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  203806. numInputBuffers,
  203807. outputBuffers,
  203808. numOutputBuffers,
  203809. bufferSizeSamples);
  203810. }
  203811. JUCE_CATCH_EXCEPTION
  203812. totalSamplesOut += bufferSizeSamples;
  203813. }
  203814. else
  203815. {
  203816. for (i = 0; i < numOutputBuffers; ++i)
  203817. if (outputBuffers[i] != 0)
  203818. zeromem (outputBuffers[i], bufferSizeSamples * sizeof (float));
  203819. totalSamplesOut = 0;
  203820. sleep (1);
  203821. }
  203822. }
  203823. }
  203824. };
  203825. class DSoundAudioIODeviceType : public AudioIODeviceType
  203826. {
  203827. public:
  203828. DSoundAudioIODeviceType()
  203829. : AudioIODeviceType (T("DirectSound")),
  203830. hasScanned (false)
  203831. {
  203832. initialiseDSoundFunctions();
  203833. }
  203834. ~DSoundAudioIODeviceType()
  203835. {
  203836. }
  203837. void scanForDevices()
  203838. {
  203839. hasScanned = true;
  203840. outputDeviceNames.clear();
  203841. outputGuids.clear();
  203842. inputDeviceNames.clear();
  203843. inputGuids.clear();
  203844. if (dsDirectSoundEnumerateW != 0)
  203845. {
  203846. dsDirectSoundEnumerateW (outputEnumProcW, this);
  203847. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  203848. }
  203849. }
  203850. const StringArray getDeviceNames (const bool wantInputNames) const
  203851. {
  203852. jassert (hasScanned); // need to call scanForDevices() before doing this
  203853. return wantInputNames ? inputDeviceNames
  203854. : outputDeviceNames;
  203855. }
  203856. int getDefaultDeviceIndex (const bool /*forInput*/) const
  203857. {
  203858. jassert (hasScanned); // need to call scanForDevices() before doing this
  203859. return 0;
  203860. }
  203861. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  203862. {
  203863. jassert (hasScanned); // need to call scanForDevices() before doing this
  203864. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  203865. if (d == 0)
  203866. return -1;
  203867. return asInput ? d->inputDeviceIndex
  203868. : d->outputDeviceIndex;
  203869. }
  203870. bool hasSeparateInputsAndOutputs() const { return true; }
  203871. AudioIODevice* createDevice (const String& outputDeviceName,
  203872. const String& inputDeviceName)
  203873. {
  203874. jassert (hasScanned); // need to call scanForDevices() before doing this
  203875. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  203876. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  203877. if (outputIndex >= 0 || inputIndex >= 0)
  203878. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  203879. : inputDeviceName,
  203880. outputIndex, inputIndex);
  203881. return 0;
  203882. }
  203883. juce_UseDebuggingNewOperator
  203884. StringArray outputDeviceNames;
  203885. OwnedArray <GUID> outputGuids;
  203886. StringArray inputDeviceNames;
  203887. OwnedArray <GUID> inputGuids;
  203888. private:
  203889. bool hasScanned;
  203890. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  203891. {
  203892. desc = desc.trim();
  203893. if (desc.isNotEmpty())
  203894. {
  203895. const String origDesc (desc);
  203896. int n = 2;
  203897. while (outputDeviceNames.contains (desc))
  203898. desc = origDesc + T(" (") + String (n++) + T(")");
  203899. outputDeviceNames.add (desc);
  203900. if (lpGUID != 0)
  203901. outputGuids.add (new GUID (*lpGUID));
  203902. else
  203903. outputGuids.add (0);
  203904. }
  203905. return TRUE;
  203906. }
  203907. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  203908. {
  203909. return ((DSoundAudioIODeviceType*) object)
  203910. ->outputEnumProc (lpGUID, String (description));
  203911. }
  203912. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  203913. {
  203914. return ((DSoundAudioIODeviceType*) object)
  203915. ->outputEnumProc (lpGUID, String (description));
  203916. }
  203917. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  203918. {
  203919. desc = desc.trim();
  203920. if (desc.isNotEmpty())
  203921. {
  203922. const String origDesc (desc);
  203923. int n = 2;
  203924. while (inputDeviceNames.contains (desc))
  203925. desc = origDesc + T(" (") + String (n++) + T(")");
  203926. inputDeviceNames.add (desc);
  203927. if (lpGUID != 0)
  203928. inputGuids.add (new GUID (*lpGUID));
  203929. else
  203930. inputGuids.add (0);
  203931. }
  203932. return TRUE;
  203933. }
  203934. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  203935. {
  203936. return ((DSoundAudioIODeviceType*) object)
  203937. ->inputEnumProc (lpGUID, String (description));
  203938. }
  203939. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  203940. {
  203941. return ((DSoundAudioIODeviceType*) object)
  203942. ->inputEnumProc (lpGUID, String (description));
  203943. }
  203944. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  203945. const DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  203946. };
  203947. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  203948. {
  203949. return new DSoundAudioIODeviceType();
  203950. }
  203951. const String DSoundAudioIODevice::openDevice (const BitArray& inputChannels,
  203952. const BitArray& outputChannels,
  203953. double sampleRate_,
  203954. int bufferSizeSamples_)
  203955. {
  203956. closeDevice();
  203957. totalSamplesOut = 0;
  203958. sampleRate = sampleRate_;
  203959. if (bufferSizeSamples_ <= 0)
  203960. bufferSizeSamples_ = 960; // use as a default size if none is set.
  203961. bufferSizeSamples = bufferSizeSamples_ & ~7;
  203962. DSoundAudioIODeviceType dlh;
  203963. dlh.scanForDevices();
  203964. enabledInputs = inputChannels;
  203965. enabledInputs.setRange (inChannels.size(),
  203966. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  203967. false);
  203968. numInputBuffers = enabledInputs.countNumberOfSetBits();
  203969. inputBuffers = new float* [numInputBuffers + 2];
  203970. zeromem (inputBuffers, sizeof (float*) * numInputBuffers + 2);
  203971. int i, numIns = 0;
  203972. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  203973. {
  203974. float* left = 0;
  203975. float* right = 0;
  203976. if (enabledInputs[i])
  203977. left = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  203978. if (enabledInputs[i + 1])
  203979. right = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  203980. if (left != 0 || right != 0)
  203981. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  203982. dlh.inputGuids [inputDeviceIndex],
  203983. (int) sampleRate, bufferSizeSamples,
  203984. left, right));
  203985. }
  203986. enabledOutputs = outputChannels;
  203987. enabledOutputs.setRange (outChannels.size(),
  203988. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  203989. false);
  203990. numOutputBuffers = enabledOutputs.countNumberOfSetBits();
  203991. outputBuffers = new float* [numOutputBuffers + 2];
  203992. zeromem (outputBuffers, sizeof (float*) * numOutputBuffers + 2);
  203993. int numOuts = 0;
  203994. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  203995. {
  203996. float* left = 0;
  203997. float* right = 0;
  203998. if (enabledOutputs[i])
  203999. left = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  204000. if (enabledOutputs[i + 1])
  204001. right = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  204002. if (left != 0 || right != 0)
  204003. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  204004. dlh.outputGuids [outputDeviceIndex],
  204005. (int) sampleRate, bufferSizeSamples,
  204006. left, right));
  204007. }
  204008. String error;
  204009. // boost our priority while opening the devices to try to get better sync between them
  204010. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  204011. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  204012. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  204013. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  204014. for (i = 0; i < outChans.size(); ++i)
  204015. {
  204016. error = outChans[i]->open();
  204017. if (error.isNotEmpty())
  204018. {
  204019. error = T("Error opening ") + dlh.outputDeviceNames[i]
  204020. + T(": \"") + error + T("\"");
  204021. break;
  204022. }
  204023. }
  204024. if (error.isEmpty())
  204025. {
  204026. for (i = 0; i < inChans.size(); ++i)
  204027. {
  204028. error = inChans[i]->open();
  204029. if (error.isNotEmpty())
  204030. {
  204031. error = T("Error opening ") + dlh.inputDeviceNames[i]
  204032. + T(": \"") + error + T("\"");
  204033. break;
  204034. }
  204035. }
  204036. }
  204037. if (error.isEmpty())
  204038. {
  204039. totalSamplesOut = 0;
  204040. for (i = 0; i < outChans.size(); ++i)
  204041. outChans.getUnchecked(i)->synchronisePosition();
  204042. for (i = 0; i < inChans.size(); ++i)
  204043. inChans.getUnchecked(i)->synchronisePosition();
  204044. startThread (9);
  204045. sleep (10);
  204046. notify();
  204047. }
  204048. else
  204049. {
  204050. log (error);
  204051. }
  204052. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  204053. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  204054. return error;
  204055. }
  204056. #undef log
  204057. END_JUCE_NAMESPACE
  204058. /********* End of inlined file: juce_win32_DirectSound.cpp *********/
  204059. /********* Start of inlined file: juce_win32_FileChooser.cpp *********/
  204060. #ifdef _MSC_VER
  204061. #pragma warning (disable: 4514)
  204062. #pragma warning (push)
  204063. #endif
  204064. #include <shlobj.h>
  204065. BEGIN_JUCE_NAMESPACE
  204066. #ifdef _MSC_VER
  204067. #pragma warning (pop)
  204068. #endif
  204069. static const void* defaultDirPath = 0;
  204070. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  204071. static Component* currentExtraFileWin = 0;
  204072. static bool areThereAnyAlwaysOnTopWindows()
  204073. {
  204074. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  204075. {
  204076. Component* c = Desktop::getInstance().getComponent (i);
  204077. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  204078. return true;
  204079. }
  204080. return false;
  204081. }
  204082. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  204083. {
  204084. if (msg == BFFM_INITIALIZED)
  204085. {
  204086. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  204087. }
  204088. else if (msg == BFFM_VALIDATEFAILEDW)
  204089. {
  204090. returnedString = (LPCWSTR) lParam;
  204091. }
  204092. else if (msg == BFFM_VALIDATEFAILEDA)
  204093. {
  204094. returnedString = (const char*) lParam;
  204095. }
  204096. return 0;
  204097. }
  204098. void juce_setWindowStyleBit (HWND h, int styleType, int feature, bool bitIsSet);
  204099. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  204100. {
  204101. if (currentExtraFileWin != 0)
  204102. {
  204103. if (uiMsg == WM_INITDIALOG)
  204104. {
  204105. HWND dialogH = GetParent (hdlg);
  204106. jassert (dialogH != 0);
  204107. if (dialogH == 0)
  204108. dialogH = hdlg;
  204109. RECT r, cr;
  204110. GetWindowRect (dialogH, &r);
  204111. GetClientRect (dialogH, &cr);
  204112. SetWindowPos (dialogH, 0,
  204113. r.left, r.top,
  204114. currentExtraFileWin->getWidth() + jmax (150, r.right - r.left),
  204115. jmax (150, r.bottom - r.top),
  204116. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  204117. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  204118. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  204119. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  204120. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  204121. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  204122. }
  204123. else if (uiMsg == WM_NOTIFY)
  204124. {
  204125. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  204126. if (ofn->hdr.code == CDN_SELCHANGE)
  204127. {
  204128. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  204129. if (comp != 0)
  204130. {
  204131. TCHAR path [MAX_PATH * 2];
  204132. path[0] = 0;
  204133. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  204134. const String fn ((const WCHAR*) path);
  204135. comp->selectedFileChanged (File (fn));
  204136. }
  204137. }
  204138. }
  204139. }
  204140. return 0;
  204141. }
  204142. class FPComponentHolder : public Component
  204143. {
  204144. public:
  204145. FPComponentHolder()
  204146. {
  204147. setVisible (true);
  204148. setOpaque (true);
  204149. }
  204150. ~FPComponentHolder()
  204151. {
  204152. }
  204153. void paint (Graphics& g)
  204154. {
  204155. g.fillAll (Colours::lightgrey);
  204156. }
  204157. private:
  204158. FPComponentHolder (const FPComponentHolder&);
  204159. const FPComponentHolder& operator= (const FPComponentHolder&);
  204160. };
  204161. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  204162. const String& title,
  204163. const File& currentFileOrDirectory,
  204164. const String& filter,
  204165. bool selectsDirectory,
  204166. bool isSaveDialogue,
  204167. bool warnAboutOverwritingExistingFiles,
  204168. bool selectMultipleFiles,
  204169. FilePreviewComponent* extraInfoComponent)
  204170. {
  204171. const int numCharsAvailable = 32768;
  204172. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  204173. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  204174. int fnameIdx = 0;
  204175. JUCE_TRY
  204176. {
  204177. // use a modal window as the parent for this dialog box
  204178. // to block input from other app windows
  204179. const Rectangle mainMon (Desktop::getInstance().getMainMonitorArea());
  204180. Component w (String::empty);
  204181. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  204182. mainMon.getY() + mainMon.getHeight() / 4,
  204183. 0, 0);
  204184. w.setOpaque (true);
  204185. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  204186. w.addToDesktop (0);
  204187. if (extraInfoComponent == 0)
  204188. w.enterModalState();
  204189. String initialDir;
  204190. if (currentFileOrDirectory.isDirectory())
  204191. {
  204192. initialDir = currentFileOrDirectory.getFullPathName();
  204193. }
  204194. else
  204195. {
  204196. currentFileOrDirectory.getFileName().copyToBuffer (fname, numCharsAvailable);
  204197. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  204198. }
  204199. if (currentExtraFileWin->isValidComponent())
  204200. {
  204201. jassertfalse
  204202. return;
  204203. }
  204204. if (selectsDirectory)
  204205. {
  204206. LPITEMIDLIST list = 0;
  204207. filenameSpace.fillWith (0);
  204208. {
  204209. BROWSEINFO bi;
  204210. zerostruct (bi);
  204211. bi.hwndOwner = (HWND) w.getWindowHandle();
  204212. bi.pszDisplayName = fname;
  204213. bi.lpszTitle = title;
  204214. bi.lpfn = browseCallbackProc;
  204215. #ifdef BIF_USENEWUI
  204216. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  204217. #else
  204218. bi.ulFlags = 0x50;
  204219. #endif
  204220. defaultDirPath = (const WCHAR*) initialDir;
  204221. list = SHBrowseForFolder (&bi);
  204222. if (! SHGetPathFromIDListW (list, fname))
  204223. {
  204224. fname[0] = 0;
  204225. returnedString = String::empty;
  204226. }
  204227. }
  204228. LPMALLOC al;
  204229. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  204230. al->Free (list);
  204231. defaultDirPath = 0;
  204232. if (returnedString.isNotEmpty())
  204233. {
  204234. const String stringFName (fname);
  204235. results.add (new File (File (stringFName).getSiblingFile (returnedString)));
  204236. returnedString = String::empty;
  204237. return;
  204238. }
  204239. }
  204240. else
  204241. {
  204242. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  204243. if (warnAboutOverwritingExistingFiles)
  204244. flags |= OFN_OVERWRITEPROMPT;
  204245. if (selectMultipleFiles)
  204246. flags |= OFN_ALLOWMULTISELECT;
  204247. if (extraInfoComponent != 0)
  204248. {
  204249. flags |= OFN_ENABLEHOOK;
  204250. currentExtraFileWin = new FPComponentHolder();
  204251. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  204252. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  204253. extraInfoComponent->getHeight());
  204254. currentExtraFileWin->addToDesktop (0);
  204255. currentExtraFileWin->enterModalState();
  204256. }
  204257. {
  204258. WCHAR filters [1024];
  204259. zeromem (filters, sizeof (filters));
  204260. filter.copyToBuffer (filters, 1024);
  204261. filter.copyToBuffer (filters + filter.length() + 1,
  204262. 1022 - filter.length());
  204263. OPENFILENAMEW of;
  204264. zerostruct (of);
  204265. #ifdef OPENFILENAME_SIZE_VERSION_400W
  204266. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  204267. #else
  204268. of.lStructSize = sizeof (of);
  204269. #endif
  204270. of.hwndOwner = (HWND) w.getWindowHandle();
  204271. of.lpstrFilter = filters;
  204272. of.nFilterIndex = 1;
  204273. of.lpstrFile = fname;
  204274. of.nMaxFile = numCharsAvailable;
  204275. of.lpstrInitialDir = initialDir;
  204276. of.lpstrTitle = title;
  204277. of.Flags = flags;
  204278. if (extraInfoComponent != 0)
  204279. of.lpfnHook = &openCallback;
  204280. if (isSaveDialogue)
  204281. {
  204282. if (! GetSaveFileName (&of))
  204283. fname[0] = 0;
  204284. else
  204285. fnameIdx = of.nFileOffset;
  204286. }
  204287. else
  204288. {
  204289. if (! GetOpenFileName (&of))
  204290. fname[0] = 0;
  204291. else
  204292. fnameIdx = of.nFileOffset;
  204293. }
  204294. }
  204295. }
  204296. }
  204297. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  204298. catch (...)
  204299. {
  204300. fname[0] = 0;
  204301. }
  204302. #endif
  204303. deleteAndZero (currentExtraFileWin);
  204304. const WCHAR* const files = fname;
  204305. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  204306. {
  204307. const WCHAR* filename = files + fnameIdx;
  204308. while (*filename != 0)
  204309. {
  204310. const String filepath (String (files) + T("\\") + String (filename));
  204311. results.add (new File (filepath));
  204312. filename += CharacterFunctions::length (filename) + 1;
  204313. }
  204314. }
  204315. else if (files[0] != 0)
  204316. {
  204317. results.add (new File (files));
  204318. }
  204319. }
  204320. END_JUCE_NAMESPACE
  204321. /********* End of inlined file: juce_win32_FileChooser.cpp *********/
  204322. /********* Start of inlined file: juce_win32_Fonts.cpp *********/
  204323. BEGIN_JUCE_NAMESPACE
  204324. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  204325. NEWTEXTMETRICEXW*,
  204326. int type,
  204327. LPARAM lParam)
  204328. {
  204329. if (lpelfe != 0 && type == TRUETYPE_FONTTYPE)
  204330. {
  204331. const String fontName (lpelfe->elfLogFont.lfFaceName);
  204332. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters (T("@")));
  204333. }
  204334. return 1;
  204335. }
  204336. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  204337. NEWTEXTMETRICEXW*,
  204338. int type,
  204339. LPARAM lParam)
  204340. {
  204341. if (lpelfe != 0
  204342. && ((type & (DEVICE_FONTTYPE | RASTER_FONTTYPE)) == 0))
  204343. {
  204344. LOGFONTW lf;
  204345. zerostruct (lf);
  204346. lf.lfWeight = FW_DONTCARE;
  204347. lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;
  204348. lf.lfQuality = DEFAULT_QUALITY;
  204349. lf.lfCharSet = DEFAULT_CHARSET;
  204350. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204351. lf.lfPitchAndFamily = FF_DONTCARE;
  204352. const String fontName (lpelfe->elfLogFont.lfFaceName);
  204353. fontName.copyToBuffer (lf.lfFaceName, LF_FACESIZE - 1);
  204354. HDC dc = CreateCompatibleDC (0);
  204355. EnumFontFamiliesEx (dc, &lf,
  204356. (FONTENUMPROCW) &wfontEnum2,
  204357. lParam, 0);
  204358. DeleteDC (dc);
  204359. }
  204360. return 1;
  204361. }
  204362. const StringArray Font::findAllTypefaceNames() throw()
  204363. {
  204364. StringArray results;
  204365. HDC dc = CreateCompatibleDC (0);
  204366. {
  204367. LOGFONTW lf;
  204368. zerostruct (lf);
  204369. lf.lfWeight = FW_DONTCARE;
  204370. lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;
  204371. lf.lfQuality = DEFAULT_QUALITY;
  204372. lf.lfCharSet = DEFAULT_CHARSET;
  204373. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204374. lf.lfPitchAndFamily = FF_DONTCARE;
  204375. lf.lfFaceName[0] = 0;
  204376. EnumFontFamiliesEx (dc, &lf,
  204377. (FONTENUMPROCW) &wfontEnum1,
  204378. (LPARAM) &results, 0);
  204379. }
  204380. DeleteDC (dc);
  204381. results.sort (true);
  204382. return results;
  204383. }
  204384. extern bool juce_IsRunningInWine() throw();
  204385. void Font::getDefaultFontNames (String& defaultSans,
  204386. String& defaultSerif,
  204387. String& defaultFixed) throw()
  204388. {
  204389. if (juce_IsRunningInWine())
  204390. {
  204391. // If we're running in Wine, then use fonts that might be available on Linux..
  204392. defaultSans = "Bitstream Vera Sans";
  204393. defaultSerif = "Bitstream Vera Serif";
  204394. defaultFixed = "Bitstream Vera Sans Mono";
  204395. }
  204396. else
  204397. {
  204398. defaultSans = "Verdana";
  204399. defaultSerif = "Times";
  204400. defaultFixed = "Lucida Console";
  204401. }
  204402. }
  204403. class FontDCHolder : private DeletedAtShutdown
  204404. {
  204405. HDC dc;
  204406. String fontName;
  204407. KERNINGPAIR* kps;
  204408. int numKPs;
  204409. bool bold, italic;
  204410. int size;
  204411. FontDCHolder (const FontDCHolder&);
  204412. const FontDCHolder& operator= (const FontDCHolder&);
  204413. public:
  204414. HFONT fontH;
  204415. FontDCHolder() throw()
  204416. : dc (0),
  204417. kps (0),
  204418. numKPs (0),
  204419. bold (false),
  204420. italic (false),
  204421. size (0)
  204422. {
  204423. }
  204424. ~FontDCHolder() throw()
  204425. {
  204426. if (dc != 0)
  204427. {
  204428. DeleteDC (dc);
  204429. DeleteObject (fontH);
  204430. juce_free (kps);
  204431. }
  204432. clearSingletonInstance();
  204433. }
  204434. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  204435. HDC loadFont (const String& fontName_,
  204436. const bool bold_,
  204437. const bool italic_,
  204438. const int size_) throw()
  204439. {
  204440. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  204441. {
  204442. fontName = fontName_;
  204443. bold = bold_;
  204444. italic = italic_;
  204445. size = size_;
  204446. if (dc != 0)
  204447. {
  204448. DeleteDC (dc);
  204449. DeleteObject (fontH);
  204450. juce_free (kps);
  204451. kps = 0;
  204452. }
  204453. fontH = 0;
  204454. dc = CreateCompatibleDC (0);
  204455. SetMapperFlags (dc, 0);
  204456. SetMapMode (dc, MM_TEXT);
  204457. LOGFONTW lfw;
  204458. zerostruct (lfw);
  204459. lfw.lfCharSet = DEFAULT_CHARSET;
  204460. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  204461. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  204462. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  204463. lfw.lfQuality = PROOF_QUALITY;
  204464. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  204465. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  204466. fontName.copyToBuffer (lfw.lfFaceName, LF_FACESIZE - 1);
  204467. lfw.lfHeight = size > 0 ? size : -256;
  204468. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  204469. if (standardSizedFont != 0)
  204470. {
  204471. if (SelectObject (dc, standardSizedFont) != 0)
  204472. {
  204473. fontH = standardSizedFont;
  204474. if (size == 0)
  204475. {
  204476. OUTLINETEXTMETRIC otm;
  204477. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  204478. {
  204479. lfw.lfHeight = -(int) otm.otmEMSquare;
  204480. fontH = CreateFontIndirect (&lfw);
  204481. SelectObject (dc, fontH);
  204482. DeleteObject (standardSizedFont);
  204483. }
  204484. }
  204485. }
  204486. else
  204487. {
  204488. jassertfalse
  204489. }
  204490. }
  204491. else
  204492. {
  204493. jassertfalse
  204494. }
  204495. }
  204496. return dc;
  204497. }
  204498. KERNINGPAIR* getKerningPairs (int& numKPs_) throw()
  204499. {
  204500. if (kps == 0)
  204501. {
  204502. numKPs = GetKerningPairs (dc, 0, 0);
  204503. kps = (KERNINGPAIR*) juce_calloc (sizeof (KERNINGPAIR) * numKPs);
  204504. GetKerningPairs (dc, numKPs, kps);
  204505. }
  204506. numKPs_ = numKPs;
  204507. return kps;
  204508. }
  204509. };
  204510. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  204511. static bool addGlyphToTypeface (HDC dc,
  204512. juce_wchar character,
  204513. Typeface& dest,
  204514. bool addKerning)
  204515. {
  204516. Path destShape;
  204517. GLYPHMETRICS gm;
  204518. float height;
  204519. BOOL ok = false;
  204520. {
  204521. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  204522. WORD index = 0;
  204523. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  204524. && index == 0xffff)
  204525. {
  204526. return false;
  204527. }
  204528. }
  204529. TEXTMETRIC tm;
  204530. ok = GetTextMetrics (dc, &tm);
  204531. height = (float) tm.tmHeight;
  204532. if (! ok)
  204533. {
  204534. dest.addGlyph (character, destShape, 0);
  204535. return true;
  204536. }
  204537. const float scaleX = 1.0f / height;
  204538. const float scaleY = -1.0f / height;
  204539. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  204540. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  204541. &gm, 0, 0, &identityMatrix);
  204542. if (bufSize > 0)
  204543. {
  204544. char* const data = (char*) juce_malloc (bufSize);
  204545. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  204546. bufSize, data, &identityMatrix);
  204547. const TTPOLYGONHEADER* pheader = (TTPOLYGONHEADER*) data;
  204548. while ((char*) pheader < data + bufSize)
  204549. {
  204550. #define remapX(v) (scaleX * (v).x.value)
  204551. #define remapY(v) (scaleY * (v).y.value)
  204552. float x = remapX (pheader->pfxStart);
  204553. float y = remapY (pheader->pfxStart);
  204554. destShape.startNewSubPath (x, y);
  204555. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  204556. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  204557. while ((const char*) curve < curveEnd)
  204558. {
  204559. if (curve->wType == TT_PRIM_LINE)
  204560. {
  204561. for (int i = 0; i < curve->cpfx; ++i)
  204562. {
  204563. x = remapX (curve->apfx [i]);
  204564. y = remapY (curve->apfx [i]);
  204565. destShape.lineTo (x, y);
  204566. }
  204567. }
  204568. else if (curve->wType == TT_PRIM_QSPLINE)
  204569. {
  204570. for (int i = 0; i < curve->cpfx - 1; ++i)
  204571. {
  204572. const float x2 = remapX (curve->apfx [i]);
  204573. const float y2 = remapY (curve->apfx [i]);
  204574. float x3, y3;
  204575. if (i < curve->cpfx - 2)
  204576. {
  204577. x3 = 0.5f * (x2 + remapX (curve->apfx [i + 1]));
  204578. y3 = 0.5f * (y2 + remapY (curve->apfx [i + 1]));
  204579. }
  204580. else
  204581. {
  204582. x3 = remapX (curve->apfx [i + 1]);
  204583. y3 = remapY (curve->apfx [i + 1]);
  204584. }
  204585. destShape.quadraticTo (x2, y2, x3, y3);
  204586. x = x3;
  204587. y = y3;
  204588. }
  204589. }
  204590. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  204591. }
  204592. pheader = (const TTPOLYGONHEADER*) curve;
  204593. destShape.closeSubPath();
  204594. }
  204595. juce_free (data);
  204596. }
  204597. dest.addGlyph (character, destShape, gm.gmCellIncX / height);
  204598. if (addKerning)
  204599. {
  204600. int numKPs;
  204601. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  204602. for (int i = 0; i < numKPs; ++i)
  204603. {
  204604. if (kps[i].wFirst == character)
  204605. {
  204606. dest.addKerningPair (kps[i].wFirst,
  204607. kps[i].wSecond,
  204608. kps[i].iKernAmount / height);
  204609. }
  204610. }
  204611. }
  204612. return true;
  204613. }
  204614. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  204615. {
  204616. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), 0);
  204617. return addGlyphToTypeface (dc, character, *this, true);
  204618. }
  204619. /*Image* Typeface::renderGlyphToImage (juce_wchar character, float& topLeftX, float& topLeftY)
  204620. {
  204621. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), hintingSize);
  204622. int bufSize;
  204623. GLYPHMETRICS gm;
  204624. const UINT format = GGO_GRAY2_BITMAP;
  204625. const int shift = 6;
  204626. if (wGetGlyphOutlineW != 0)
  204627. bufSize = wGetGlyphOutlineW (dc, character, format, &gm, 0, 0, &identityMatrix);
  204628. else
  204629. bufSize = GetGlyphOutline (dc, character, format, &gm, 0, 0, &identityMatrix);
  204630. Image* im = new Image (Image::SingleChannel, jmax (1, gm.gmBlackBoxX), jmax (1, gm.gmBlackBoxY), true);
  204631. if (bufSize > 0)
  204632. {
  204633. topLeftX = (float) gm.gmptGlyphOrigin.x;
  204634. topLeftY = (float) -gm.gmptGlyphOrigin.y;
  204635. uint8* const data = (uint8*) juce_calloc (bufSize);
  204636. if (wGetGlyphOutlineW != 0)
  204637. wGetGlyphOutlineW (dc, character, format, &gm, bufSize, data, &identityMatrix);
  204638. else
  204639. GetGlyphOutline (dc, character, format, &gm, bufSize, data, &identityMatrix);
  204640. const int stride = ((gm.gmBlackBoxX + 3) & ~3);
  204641. for (int y = gm.gmBlackBoxY; --y >= 0;)
  204642. {
  204643. for (int x = gm.gmBlackBoxX; --x >= 0;)
  204644. {
  204645. const int level = data [x + y * stride] << shift;
  204646. if (level > 0)
  204647. im->setPixelAt (x, y, Colour ((uint8) 0xff, (uint8) 0xff, (uint8) 0xff, (uint8) jmin (0xff, level)));
  204648. }
  204649. }
  204650. juce_free (data);
  204651. }
  204652. return im;
  204653. }*/
  204654. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  204655. bool bold,
  204656. bool italic,
  204657. bool addAllGlyphsToFont) throw()
  204658. {
  204659. clear();
  204660. HDC dc = FontDCHolder::getInstance()->loadFont (fontName, bold, italic, 0);
  204661. float height;
  204662. int firstChar, lastChar;
  204663. {
  204664. TEXTMETRIC tm;
  204665. GetTextMetrics (dc, &tm);
  204666. height = (float) tm.tmHeight;
  204667. firstChar = tm.tmFirstChar;
  204668. lastChar = tm.tmLastChar;
  204669. setAscent (tm.tmAscent / height);
  204670. setDefaultCharacter (tm.tmDefaultChar);
  204671. }
  204672. setName (fontName);
  204673. setBold (bold);
  204674. setItalic (italic);
  204675. if (addAllGlyphsToFont)
  204676. {
  204677. for (int character = firstChar; character <= lastChar; ++character)
  204678. addGlyphToTypeface (dc, (juce_wchar) character, *this, false);
  204679. int numKPs;
  204680. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  204681. for (int i = 0; i < numKPs; ++i)
  204682. {
  204683. addKerningPair (kps[i].wFirst,
  204684. kps[i].wSecond,
  204685. kps[i].iKernAmount / height);
  204686. }
  204687. }
  204688. }
  204689. END_JUCE_NAMESPACE
  204690. /********* End of inlined file: juce_win32_Fonts.cpp *********/
  204691. /********* Start of inlined file: juce_win32_Messaging.cpp *********/
  204692. BEGIN_JUCE_NAMESPACE
  204693. static const unsigned int specialId = WM_APP + 0x4400;
  204694. static const unsigned int broadcastId = WM_APP + 0x4403;
  204695. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  204696. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  204697. HWND juce_messageWindowHandle = 0;
  204698. extern long improbableWindowNumber; // defined in windowing.cpp
  204699. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  204700. const UINT message,
  204701. const WPARAM wParam,
  204702. const LPARAM lParam) throw()
  204703. {
  204704. JUCE_TRY
  204705. {
  204706. if (h == juce_messageWindowHandle)
  204707. {
  204708. if (message == specialCallbackId)
  204709. {
  204710. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  204711. return (LRESULT) (*func) ((void*) lParam);
  204712. }
  204713. else if (message == specialId)
  204714. {
  204715. // these are trapped early in the dispatch call, but must also be checked
  204716. // here in case there are windows modal dialog boxes doing their own
  204717. // dispatch loop and not calling our version
  204718. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  204719. return 0;
  204720. }
  204721. else if (message == broadcastId)
  204722. {
  204723. String* const messageString = (String*) lParam;
  204724. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  204725. delete messageString;
  204726. return 0;
  204727. }
  204728. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  204729. {
  204730. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  204731. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  204732. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  204733. return 0;
  204734. }
  204735. }
  204736. }
  204737. JUCE_CATCH_EXCEPTION
  204738. return DefWindowProc (h, message, wParam, lParam);
  204739. }
  204740. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  204741. {
  204742. MSG m;
  204743. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  204744. return false;
  204745. if (GetMessage (&m, (HWND) 0, 0, 0) > 0)
  204746. {
  204747. if (m.message == specialId
  204748. && m.hwnd == juce_messageWindowHandle)
  204749. {
  204750. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  204751. }
  204752. else
  204753. {
  204754. if (GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber
  204755. && (m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN))
  204756. {
  204757. // if it's someone else's window being clicked on, and the focus is
  204758. // currently on a juce window, pass the kb focus over..
  204759. HWND currentFocus = GetFocus();
  204760. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  204761. SetFocus (m.hwnd);
  204762. }
  204763. TranslateMessage (&m);
  204764. DispatchMessage (&m);
  204765. }
  204766. }
  204767. return true;
  204768. }
  204769. bool juce_postMessageToSystemQueue (void* message)
  204770. {
  204771. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  204772. }
  204773. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  204774. void* userData)
  204775. {
  204776. if (MessageManager::getInstance()->isThisTheMessageThread())
  204777. {
  204778. return (*callback) (userData);
  204779. }
  204780. else
  204781. {
  204782. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  204783. // deadlock because the message manager is blocked from running, and can't
  204784. // call your function..
  204785. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  204786. return (void*) SendMessage (juce_messageWindowHandle,
  204787. specialCallbackId,
  204788. (WPARAM) callback,
  204789. (LPARAM) userData);
  204790. }
  204791. }
  204792. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  204793. {
  204794. if (hwnd != juce_messageWindowHandle)
  204795. (reinterpret_cast <VoidArray*> (lParam))->add ((void*) hwnd);
  204796. return TRUE;
  204797. }
  204798. void MessageManager::broadcastMessage (const String& value) throw()
  204799. {
  204800. VoidArray windows;
  204801. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  204802. const String localCopy (value);
  204803. COPYDATASTRUCT data;
  204804. data.dwData = broadcastId;
  204805. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  204806. data.lpData = (void*) (const juce_wchar*) localCopy;
  204807. for (int i = windows.size(); --i >= 0;)
  204808. {
  204809. HWND hwnd = (HWND) windows.getUnchecked(i);
  204810. TCHAR windowName [64]; // no need to read longer strings than this
  204811. GetWindowText (hwnd, windowName, 64);
  204812. windowName [63] = 0;
  204813. if (String (windowName) == String (messageWindowName))
  204814. {
  204815. DWORD_PTR result;
  204816. SendMessageTimeout (hwnd, WM_COPYDATA,
  204817. (WPARAM) juce_messageWindowHandle,
  204818. (LPARAM) &data,
  204819. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  204820. 8000,
  204821. &result);
  204822. }
  204823. }
  204824. }
  204825. static const String getMessageWindowClassName()
  204826. {
  204827. // this name has to be different for each app/dll instance because otherwise
  204828. // poor old Win32 can get a bit confused (even despite it not being a process-global
  204829. // window class).
  204830. static int number = 0;
  204831. if (number == 0)
  204832. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  204833. return T("JUCEcs_") + String (number);
  204834. }
  204835. void MessageManager::doPlatformSpecificInitialisation()
  204836. {
  204837. OleInitialize (0);
  204838. const String className (getMessageWindowClassName());
  204839. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204840. WNDCLASSEX wc;
  204841. zerostruct (wc);
  204842. wc.cbSize = sizeof (wc);
  204843. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  204844. wc.cbWndExtra = 4;
  204845. wc.hInstance = hmod;
  204846. wc.lpszClassName = className;
  204847. RegisterClassEx (&wc);
  204848. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  204849. messageWindowName,
  204850. 0, 0, 0, 0, 0, 0, 0,
  204851. hmod, 0);
  204852. }
  204853. void MessageManager::doPlatformSpecificShutdown()
  204854. {
  204855. DestroyWindow (juce_messageWindowHandle);
  204856. UnregisterClass (getMessageWindowClassName(), 0);
  204857. OleUninitialize();
  204858. }
  204859. END_JUCE_NAMESPACE
  204860. /********* End of inlined file: juce_win32_Messaging.cpp *********/
  204861. /********* Start of inlined file: juce_win32_Midi.cpp *********/
  204862. BEGIN_JUCE_NAMESPACE
  204863. #if JUCE_MSVC
  204864. #pragma warning (disable: 4312)
  204865. #endif
  204866. using ::free;
  204867. static const int midiBufferSize = 1024 * 10;
  204868. static const int numInHeaders = 32;
  204869. static const int inBufferSize = 256;
  204870. static Array <void*, CriticalSection> activeMidiThreads;
  204871. class MidiInThread : public Thread
  204872. {
  204873. public:
  204874. MidiInThread (MidiInput* const input_,
  204875. MidiInputCallback* const callback_)
  204876. : Thread ("Juce Midi"),
  204877. hIn (0),
  204878. input (input_),
  204879. callback (callback_),
  204880. isStarted (false),
  204881. startTime (0),
  204882. pendingLength(0)
  204883. {
  204884. for (int i = numInHeaders; --i >= 0;)
  204885. {
  204886. zeromem (&hdr[i], sizeof (MIDIHDR));
  204887. hdr[i].lpData = inData[i];
  204888. hdr[i].dwBufferLength = inBufferSize;
  204889. }
  204890. };
  204891. ~MidiInThread()
  204892. {
  204893. stop();
  204894. if (hIn != 0)
  204895. {
  204896. int count = 5;
  204897. while (--count >= 0)
  204898. {
  204899. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  204900. break;
  204901. Sleep (20);
  204902. }
  204903. }
  204904. }
  204905. void handle (const uint32 message, const uint32 timeStamp) throw()
  204906. {
  204907. const int byte = message & 0xff;
  204908. if (byte < 0x80)
  204909. return;
  204910. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  204911. const double time = timeStampToTime (timeStamp);
  204912. lock.enter();
  204913. if (pendingLength < midiBufferSize - 12)
  204914. {
  204915. char* const p = pending + pendingLength;
  204916. *(double*) p = time;
  204917. *(uint32*) (p + 8) = numBytes;
  204918. *(uint32*) (p + 12) = message;
  204919. pendingLength += 12 + numBytes;
  204920. }
  204921. else
  204922. {
  204923. jassertfalse // midi buffer overflow! You might need to increase the size..
  204924. }
  204925. lock.exit();
  204926. notify();
  204927. }
  204928. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp) throw()
  204929. {
  204930. const int num = hdr->dwBytesRecorded;
  204931. if (num > 0)
  204932. {
  204933. const double time = timeStampToTime (timeStamp);
  204934. lock.enter();
  204935. if (pendingLength < midiBufferSize - (8 + num))
  204936. {
  204937. char* const p = pending + pendingLength;
  204938. *(double*) p = time;
  204939. *(uint32*) (p + 8) = num;
  204940. memcpy (p + 12, hdr->lpData, num);
  204941. pendingLength += 12 + num;
  204942. }
  204943. else
  204944. {
  204945. jassertfalse // midi buffer overflow! You might need to increase the size..
  204946. }
  204947. lock.exit();
  204948. notify();
  204949. }
  204950. }
  204951. void writeBlock (const int i) throw()
  204952. {
  204953. hdr[i].dwBytesRecorded = 0;
  204954. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  204955. jassert (res == MMSYSERR_NOERROR);
  204956. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  204957. jassert (res == MMSYSERR_NOERROR);
  204958. }
  204959. void run()
  204960. {
  204961. MemoryBlock pendingCopy (64);
  204962. while (! threadShouldExit())
  204963. {
  204964. for (int i = 0; i < numInHeaders; ++i)
  204965. {
  204966. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  204967. {
  204968. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  204969. (void) res;
  204970. jassert (res == MMSYSERR_NOERROR);
  204971. writeBlock (i);
  204972. }
  204973. }
  204974. lock.enter();
  204975. int len = pendingLength;
  204976. if (len > 0)
  204977. {
  204978. pendingCopy.ensureSize (len);
  204979. pendingCopy.copyFrom (pending, 0, len);
  204980. pendingLength = 0;
  204981. }
  204982. lock.exit();
  204983. //xxx needs to figure out if blocks are broken up or not
  204984. if (len == 0)
  204985. {
  204986. wait (500);
  204987. }
  204988. else
  204989. {
  204990. const char* p = (const char*) pendingCopy.getData();
  204991. while (len > 0)
  204992. {
  204993. const double time = *(const double*) p;
  204994. const int messageLen = *(const int*) (p + 8);
  204995. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  204996. callback->handleIncomingMidiMessage (input, message);
  204997. p += 12 + messageLen;
  204998. len -= 12 + messageLen;
  204999. }
  205000. }
  205001. }
  205002. }
  205003. void start() throw()
  205004. {
  205005. jassert (hIn != 0);
  205006. if (hIn != 0 && ! isStarted)
  205007. {
  205008. stop();
  205009. activeMidiThreads.addIfNotAlreadyThere (this);
  205010. int i;
  205011. for (i = 0; i < numInHeaders; ++i)
  205012. writeBlock (i);
  205013. startTime = Time::getMillisecondCounter();
  205014. MMRESULT res = midiInStart (hIn);
  205015. jassert (res == MMSYSERR_NOERROR);
  205016. if (res == MMSYSERR_NOERROR)
  205017. {
  205018. isStarted = true;
  205019. pendingLength = 0;
  205020. startThread (6);
  205021. }
  205022. }
  205023. }
  205024. void stop() throw()
  205025. {
  205026. if (isStarted)
  205027. {
  205028. stopThread (5000);
  205029. midiInReset (hIn);
  205030. midiInStop (hIn);
  205031. activeMidiThreads.removeValue (this);
  205032. lock.enter();
  205033. lock.exit();
  205034. for (int i = numInHeaders; --i >= 0;)
  205035. {
  205036. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  205037. {
  205038. int c = 10;
  205039. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  205040. Sleep (20);
  205041. jassert (c >= 0);
  205042. }
  205043. }
  205044. isStarted = false;
  205045. pendingLength = 0;
  205046. }
  205047. }
  205048. juce_UseDebuggingNewOperator
  205049. HMIDIIN hIn;
  205050. private:
  205051. MidiInput* input;
  205052. MidiInputCallback* callback;
  205053. bool isStarted;
  205054. uint32 startTime;
  205055. CriticalSection lock;
  205056. MIDIHDR hdr [numInHeaders];
  205057. char inData [numInHeaders] [inBufferSize];
  205058. int pendingLength;
  205059. char pending [midiBufferSize];
  205060. double timeStampToTime (uint32 timeStamp) throw()
  205061. {
  205062. timeStamp += startTime;
  205063. const uint32 now = Time::getMillisecondCounter();
  205064. if (timeStamp > now)
  205065. {
  205066. if (timeStamp > now + 2)
  205067. --startTime;
  205068. timeStamp = now;
  205069. }
  205070. return 0.001 * timeStamp;
  205071. }
  205072. MidiInThread (const MidiInThread&);
  205073. const MidiInThread& operator= (const MidiInThread&);
  205074. };
  205075. static void CALLBACK midiInCallback (HMIDIIN,
  205076. UINT uMsg,
  205077. DWORD_PTR dwInstance,
  205078. DWORD_PTR midiMessage,
  205079. DWORD_PTR timeStamp)
  205080. {
  205081. MidiInThread* const thread = (MidiInThread*) dwInstance;
  205082. if (thread != 0 && activeMidiThreads.contains (thread))
  205083. {
  205084. if (uMsg == MIM_DATA)
  205085. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  205086. else if (uMsg == MIM_LONGDATA)
  205087. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  205088. }
  205089. }
  205090. const StringArray MidiInput::getDevices()
  205091. {
  205092. StringArray s;
  205093. const int num = midiInGetNumDevs();
  205094. for (int i = 0; i < num; ++i)
  205095. {
  205096. MIDIINCAPS mc;
  205097. zerostruct (mc);
  205098. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  205099. s.add (String (mc.szPname, sizeof (mc.szPname)));
  205100. }
  205101. return s;
  205102. }
  205103. int MidiInput::getDefaultDeviceIndex()
  205104. {
  205105. return 0;
  205106. }
  205107. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  205108. {
  205109. if (callback == 0)
  205110. return 0;
  205111. UINT deviceId = MIDI_MAPPER;
  205112. int n = 0;
  205113. String name;
  205114. const int num = midiInGetNumDevs();
  205115. for (int i = 0; i < num; ++i)
  205116. {
  205117. MIDIINCAPS mc;
  205118. zerostruct (mc);
  205119. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  205120. {
  205121. if (index == n)
  205122. {
  205123. deviceId = i;
  205124. name = String (mc.szPname, sizeof (mc.szPname));
  205125. break;
  205126. }
  205127. ++n;
  205128. }
  205129. }
  205130. MidiInput* const in = new MidiInput (name);
  205131. MidiInThread* const thread = new MidiInThread (in, callback);
  205132. HMIDIIN h;
  205133. HRESULT err = midiInOpen (&h, deviceId,
  205134. (DWORD_PTR) &midiInCallback,
  205135. (DWORD_PTR) thread,
  205136. CALLBACK_FUNCTION);
  205137. if (err == MMSYSERR_NOERROR)
  205138. {
  205139. thread->hIn = h;
  205140. in->internal = (void*) thread;
  205141. return in;
  205142. }
  205143. else
  205144. {
  205145. delete in;
  205146. delete thread;
  205147. return 0;
  205148. }
  205149. }
  205150. MidiInput::MidiInput (const String& name_)
  205151. : name (name_),
  205152. internal (0)
  205153. {
  205154. }
  205155. MidiInput::~MidiInput()
  205156. {
  205157. if (internal != 0)
  205158. {
  205159. MidiInThread* const thread = (MidiInThread*) internal;
  205160. delete thread;
  205161. }
  205162. }
  205163. void MidiInput::start()
  205164. {
  205165. ((MidiInThread*) internal)->start();
  205166. }
  205167. void MidiInput::stop()
  205168. {
  205169. ((MidiInThread*) internal)->stop();
  205170. }
  205171. struct MidiOutHandle
  205172. {
  205173. int refCount;
  205174. UINT deviceId;
  205175. HMIDIOUT handle;
  205176. juce_UseDebuggingNewOperator
  205177. };
  205178. static VoidArray handles (4);
  205179. const StringArray MidiOutput::getDevices()
  205180. {
  205181. StringArray s;
  205182. const int num = midiOutGetNumDevs();
  205183. for (int i = 0; i < num; ++i)
  205184. {
  205185. MIDIOUTCAPS mc;
  205186. zerostruct (mc);
  205187. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  205188. s.add (String (mc.szPname, sizeof (mc.szPname)));
  205189. }
  205190. return s;
  205191. }
  205192. int MidiOutput::getDefaultDeviceIndex()
  205193. {
  205194. const int num = midiOutGetNumDevs();
  205195. int n = 0;
  205196. for (int i = 0; i < num; ++i)
  205197. {
  205198. MIDIOUTCAPS mc;
  205199. zerostruct (mc);
  205200. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  205201. {
  205202. if ((mc.wTechnology & MOD_MAPPER) != 0)
  205203. return n;
  205204. ++n;
  205205. }
  205206. }
  205207. return 0;
  205208. }
  205209. MidiOutput* MidiOutput::openDevice (int index)
  205210. {
  205211. UINT deviceId = MIDI_MAPPER;
  205212. const int num = midiOutGetNumDevs();
  205213. int i, n = 0;
  205214. for (i = 0; i < num; ++i)
  205215. {
  205216. MIDIOUTCAPS mc;
  205217. zerostruct (mc);
  205218. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  205219. {
  205220. // use the microsoft sw synth as a default - best not to allow deviceId
  205221. // to be MIDI_MAPPER, or else device sharing breaks
  205222. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase (T("microsoft")))
  205223. deviceId = i;
  205224. if (index == n)
  205225. {
  205226. deviceId = i;
  205227. break;
  205228. }
  205229. ++n;
  205230. }
  205231. }
  205232. for (i = handles.size(); --i >= 0;)
  205233. {
  205234. MidiOutHandle* const han = (MidiOutHandle*) handles.getUnchecked(i);
  205235. if (han != 0 && han->deviceId == deviceId)
  205236. {
  205237. han->refCount++;
  205238. MidiOutput* const out = new MidiOutput();
  205239. out->internal = (void*) han;
  205240. return out;
  205241. }
  205242. }
  205243. for (i = 4; --i >= 0;)
  205244. {
  205245. HMIDIOUT h = 0;
  205246. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  205247. if (res == MMSYSERR_NOERROR)
  205248. {
  205249. MidiOutHandle* const han = new MidiOutHandle();
  205250. han->deviceId = deviceId;
  205251. han->refCount = 1;
  205252. han->handle = h;
  205253. handles.add (han);
  205254. MidiOutput* const out = new MidiOutput();
  205255. out->internal = (void*) han;
  205256. return out;
  205257. }
  205258. else if (res == MMSYSERR_ALLOCATED)
  205259. {
  205260. Sleep (100);
  205261. }
  205262. else
  205263. {
  205264. break;
  205265. }
  205266. }
  205267. return 0;
  205268. }
  205269. MidiOutput::~MidiOutput()
  205270. {
  205271. MidiOutHandle* const h = (MidiOutHandle*) internal;
  205272. if (handles.contains ((void*) h) && --(h->refCount) == 0)
  205273. {
  205274. midiOutClose (h->handle);
  205275. handles.removeValue ((void*) h);
  205276. delete h;
  205277. }
  205278. }
  205279. void MidiOutput::reset()
  205280. {
  205281. const MidiOutHandle* const h = (MidiOutHandle*) internal;
  205282. midiOutReset (h->handle);
  205283. }
  205284. bool MidiOutput::getVolume (float& leftVol,
  205285. float& rightVol)
  205286. {
  205287. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  205288. DWORD n;
  205289. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  205290. {
  205291. const unsigned short* const nn = (const unsigned short*) &n;
  205292. rightVol = nn[0] / (float) 0xffff;
  205293. leftVol = nn[1] / (float) 0xffff;
  205294. return true;
  205295. }
  205296. else
  205297. {
  205298. rightVol = leftVol = 1.0f;
  205299. return false;
  205300. }
  205301. }
  205302. void MidiOutput::setVolume (float leftVol,
  205303. float rightVol)
  205304. {
  205305. const MidiOutHandle* const handle = (MidiOutHandle*) internal;
  205306. DWORD n;
  205307. unsigned short* const nn = (unsigned short*) &n;
  205308. nn[0] = (unsigned short) jlimit (0, 0xffff, (int)(rightVol * 0xffff));
  205309. nn[1] = (unsigned short) jlimit (0, 0xffff, (int)(leftVol * 0xffff));
  205310. midiOutSetVolume (handle->handle, n);
  205311. }
  205312. void MidiOutput::sendMessageNow (const MidiMessage& message)
  205313. {
  205314. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  205315. if (message.getRawDataSize() > 3
  205316. || message.isSysEx())
  205317. {
  205318. MIDIHDR h;
  205319. zerostruct (h);
  205320. h.lpData = (char*) message.getRawData();
  205321. h.dwBufferLength = message.getRawDataSize();
  205322. h.dwBytesRecorded = message.getRawDataSize();
  205323. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  205324. {
  205325. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  205326. if (res == MMSYSERR_NOERROR)
  205327. {
  205328. while ((h.dwFlags & MHDR_DONE) == 0)
  205329. Sleep (1);
  205330. int count = 500; // 1 sec timeout
  205331. while (--count >= 0)
  205332. {
  205333. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  205334. if (res == MIDIERR_STILLPLAYING)
  205335. Sleep (2);
  205336. else
  205337. break;
  205338. }
  205339. }
  205340. }
  205341. }
  205342. else
  205343. {
  205344. midiOutShortMsg (handle->handle,
  205345. *(unsigned int*) message.getRawData());
  205346. }
  205347. }
  205348. END_JUCE_NAMESPACE
  205349. /********* End of inlined file: juce_win32_Midi.cpp *********/
  205350. /********* Start of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  205351. #ifdef _MSC_VER
  205352. #pragma warning (disable: 4514)
  205353. #pragma warning (push)
  205354. #endif
  205355. #include <comutil.h>
  205356. #include <Exdisp.h>
  205357. #include <exdispid.h>
  205358. #ifdef _MSC_VER
  205359. #pragma warning (pop)
  205360. #pragma warning (disable: 4312 4244)
  205361. #endif
  205362. BEGIN_JUCE_NAMESPACE
  205363. class WebBrowserComponentInternal : public ActiveXControlComponent
  205364. {
  205365. public:
  205366. WebBrowserComponentInternal()
  205367. : browser (0),
  205368. connectionPoint (0),
  205369. adviseCookie (0)
  205370. {
  205371. }
  205372. ~WebBrowserComponentInternal()
  205373. {
  205374. if (connectionPoint != 0)
  205375. connectionPoint->Unadvise (adviseCookie);
  205376. if (browser != 0)
  205377. browser->Release();
  205378. }
  205379. void createBrowser()
  205380. {
  205381. createControl (&CLSID_WebBrowser);
  205382. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  205383. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  205384. if (connectionPointContainer != 0)
  205385. {
  205386. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  205387. &connectionPoint);
  205388. if (connectionPoint != 0)
  205389. {
  205390. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  205391. jassert (owner != 0);
  205392. EventHandler* handler = new EventHandler (owner);
  205393. connectionPoint->Advise (handler, &adviseCookie);
  205394. }
  205395. }
  205396. }
  205397. void goToURL (const String& url,
  205398. const StringArray* headers,
  205399. const MemoryBlock* postData)
  205400. {
  205401. if (browser != 0)
  205402. {
  205403. LPSAFEARRAY sa = 0;
  205404. _variant_t flags, frame, postDataVar, headersVar;
  205405. if (headers != 0)
  205406. headersVar = (const tchar*) headers->joinIntoString ("\r\n");
  205407. if (postData != 0 && postData->getSize() > 0)
  205408. {
  205409. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  205410. if (sa != 0)
  205411. {
  205412. void* data = 0;
  205413. SafeArrayAccessData (sa, &data);
  205414. jassert (data != 0);
  205415. if (data != 0)
  205416. {
  205417. postData->copyTo (data, 0, postData->getSize());
  205418. SafeArrayUnaccessData (sa);
  205419. VARIANT postDataVar2;
  205420. VariantInit (&postDataVar2);
  205421. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  205422. V_ARRAY (&postDataVar2) = sa;
  205423. postDataVar = postDataVar2;
  205424. }
  205425. }
  205426. }
  205427. browser->Navigate ((BSTR) (const OLECHAR*) url,
  205428. &flags, &frame,
  205429. &postDataVar, &headersVar);
  205430. if (sa != 0)
  205431. SafeArrayDestroy (sa);
  205432. }
  205433. }
  205434. IWebBrowser2* browser;
  205435. juce_UseDebuggingNewOperator
  205436. private:
  205437. IConnectionPoint* connectionPoint;
  205438. DWORD adviseCookie;
  205439. class EventHandler : public IDispatch
  205440. {
  205441. public:
  205442. EventHandler (WebBrowserComponent* owner_)
  205443. : owner (owner_),
  205444. refCount (0)
  205445. {
  205446. }
  205447. ~EventHandler()
  205448. {
  205449. }
  205450. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  205451. {
  205452. if (id == IID_IUnknown || id == IID_IDispatch || id == DIID_DWebBrowserEvents2)
  205453. {
  205454. AddRef();
  205455. *result = this;
  205456. return S_OK;
  205457. }
  205458. *result = 0;
  205459. return E_NOINTERFACE;
  205460. }
  205461. ULONG __stdcall AddRef() { return ++refCount; }
  205462. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  205463. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  205464. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  205465. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  205466. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  205467. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  205468. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  205469. UINT __RPC_FAR* /*puArgErr*/)
  205470. {
  205471. switch (dispIdMember)
  205472. {
  205473. case DISPID_BEFORENAVIGATE2:
  205474. {
  205475. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  205476. String url;
  205477. if ((vurl->vt & VT_BYREF) != 0)
  205478. url = *vurl->pbstrVal;
  205479. else
  205480. url = vurl->bstrVal;
  205481. *pDispParams->rgvarg->pboolVal
  205482. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  205483. : VARIANT_TRUE;
  205484. return S_OK;
  205485. }
  205486. default:
  205487. break;
  205488. }
  205489. return E_NOTIMPL;
  205490. }
  205491. juce_UseDebuggingNewOperator
  205492. private:
  205493. WebBrowserComponent* const owner;
  205494. int refCount;
  205495. EventHandler (const EventHandler&);
  205496. const EventHandler& operator= (const EventHandler&);
  205497. };
  205498. };
  205499. WebBrowserComponent::WebBrowserComponent()
  205500. : browser (0),
  205501. blankPageShown (false)
  205502. {
  205503. setOpaque (true);
  205504. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  205505. }
  205506. WebBrowserComponent::~WebBrowserComponent()
  205507. {
  205508. delete browser;
  205509. }
  205510. void WebBrowserComponent::goToURL (const String& url,
  205511. const StringArray* headers,
  205512. const MemoryBlock* postData)
  205513. {
  205514. lastURL = url;
  205515. lastHeaders.clear();
  205516. if (headers != 0)
  205517. lastHeaders = *headers;
  205518. lastPostData.setSize (0);
  205519. if (postData != 0)
  205520. lastPostData = *postData;
  205521. blankPageShown = false;
  205522. browser->goToURL (url, headers, postData);
  205523. }
  205524. void WebBrowserComponent::stop()
  205525. {
  205526. if (browser->browser != 0)
  205527. browser->browser->Stop();
  205528. }
  205529. void WebBrowserComponent::goBack()
  205530. {
  205531. lastURL = String::empty;
  205532. blankPageShown = false;
  205533. if (browser->browser != 0)
  205534. browser->browser->GoBack();
  205535. }
  205536. void WebBrowserComponent::goForward()
  205537. {
  205538. lastURL = String::empty;
  205539. if (browser->browser != 0)
  205540. browser->browser->GoForward();
  205541. }
  205542. void WebBrowserComponent::paint (Graphics& g)
  205543. {
  205544. if (browser->browser == 0)
  205545. g.fillAll (Colours::white);
  205546. }
  205547. void WebBrowserComponent::checkWindowAssociation()
  205548. {
  205549. if (isShowing())
  205550. {
  205551. if (browser->browser == 0 && getPeer() != 0)
  205552. {
  205553. browser->createBrowser();
  205554. reloadLastURL();
  205555. }
  205556. else
  205557. {
  205558. if (blankPageShown)
  205559. goBack();
  205560. }
  205561. }
  205562. else
  205563. {
  205564. if (browser != 0 && ! blankPageShown)
  205565. {
  205566. // when the component becomes invisible, some stuff like flash
  205567. // carries on playing audio, so we need to force it onto a blank
  205568. // page to avoid this..
  205569. blankPageShown = true;
  205570. browser->goToURL ("about:blank", 0, 0);
  205571. }
  205572. }
  205573. }
  205574. void WebBrowserComponent::reloadLastURL()
  205575. {
  205576. if (lastURL.isNotEmpty())
  205577. {
  205578. goToURL (lastURL, &lastHeaders, &lastPostData);
  205579. lastURL = String::empty;
  205580. }
  205581. }
  205582. void WebBrowserComponent::parentHierarchyChanged()
  205583. {
  205584. checkWindowAssociation();
  205585. }
  205586. void WebBrowserComponent::moved()
  205587. {
  205588. }
  205589. void WebBrowserComponent::resized()
  205590. {
  205591. browser->setSize (getWidth(), getHeight());
  205592. }
  205593. void WebBrowserComponent::visibilityChanged()
  205594. {
  205595. checkWindowAssociation();
  205596. }
  205597. bool WebBrowserComponent::pageAboutToLoad (const String&)
  205598. {
  205599. return true;
  205600. }
  205601. END_JUCE_NAMESPACE
  205602. /********* End of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  205603. /********* Start of inlined file: juce_win32_Windowing.cpp *********/
  205604. #ifdef _MSC_VER
  205605. #pragma warning (disable: 4514)
  205606. #pragma warning (push)
  205607. #endif
  205608. #include <float.h>
  205609. #include <windowsx.h>
  205610. #include <shlobj.h>
  205611. #if JUCE_OPENGL
  205612. #include <gl/gl.h>
  205613. #endif
  205614. #ifdef _MSC_VER
  205615. #pragma warning (pop)
  205616. #pragma warning (disable: 4312 4244)
  205617. #endif
  205618. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  205619. // these are in the windows SDK, but need to be repeated here for GCC..
  205620. #ifndef GET_APPCOMMAND_LPARAM
  205621. #define FAPPCOMMAND_MASK 0xF000
  205622. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  205623. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  205624. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  205625. #define APPCOMMAND_MEDIA_STOP 13
  205626. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  205627. #define WM_APPCOMMAND 0x0319
  205628. #endif
  205629. BEGIN_JUCE_NAMESPACE
  205630. extern void juce_repeatLastProcessPriority() throw(); // in juce_win32_Threads.cpp
  205631. extern void juce_CheckCurrentlyFocusedTopLevelWindow() throw(); // in juce_TopLevelWindow.cpp
  205632. extern bool juce_IsRunningInWine() throw();
  205633. #ifndef ULW_ALPHA
  205634. #define ULW_ALPHA 0x00000002
  205635. #endif
  205636. #ifndef AC_SRC_ALPHA
  205637. #define AC_SRC_ALPHA 0x01
  205638. #endif
  205639. #define DEBUG_REPAINT_TIMES 0
  205640. static HPALETTE palette = 0;
  205641. static bool createPaletteIfNeeded = true;
  205642. static bool shouldDeactivateTitleBar = true;
  205643. static bool screenSaverAllowed = true;
  205644. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  205645. #define WM_TRAYNOTIFY WM_USER + 100
  205646. using ::abs;
  205647. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  205648. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  205649. bool Desktop::canUseSemiTransparentWindows() throw()
  205650. {
  205651. if (updateLayeredWindow == 0)
  205652. {
  205653. if (! juce_IsRunningInWine())
  205654. {
  205655. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  205656. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  205657. }
  205658. }
  205659. return updateLayeredWindow != 0;
  205660. }
  205661. #undef DefWindowProc
  205662. #define DefWindowProc DefWindowProcW
  205663. const int extendedKeyModifier = 0x10000;
  205664. const int KeyPress::spaceKey = VK_SPACE;
  205665. const int KeyPress::returnKey = VK_RETURN;
  205666. const int KeyPress::escapeKey = VK_ESCAPE;
  205667. const int KeyPress::backspaceKey = VK_BACK;
  205668. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  205669. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  205670. const int KeyPress::tabKey = VK_TAB;
  205671. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  205672. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  205673. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  205674. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  205675. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  205676. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  205677. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  205678. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  205679. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  205680. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  205681. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  205682. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  205683. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  205684. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  205685. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  205686. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  205687. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  205688. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  205689. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  205690. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  205691. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  205692. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  205693. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  205694. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  205695. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  205696. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  205697. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  205698. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  205699. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  205700. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  205701. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  205702. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  205703. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  205704. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  205705. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  205706. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  205707. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  205708. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  205709. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  205710. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  205711. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  205712. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  205713. const int KeyPress::playKey = 0x30000;
  205714. const int KeyPress::stopKey = 0x30001;
  205715. const int KeyPress::fastForwardKey = 0x30002;
  205716. const int KeyPress::rewindKey = 0x30003;
  205717. class WindowsBitmapImage : public Image
  205718. {
  205719. public:
  205720. HBITMAP hBitmap;
  205721. BITMAPV4HEADER bitmapInfo;
  205722. HDC hdc;
  205723. unsigned char* bitmapData;
  205724. WindowsBitmapImage (const PixelFormat format_,
  205725. const int w, const int h, const bool clearImage)
  205726. : Image (format_, w, h)
  205727. {
  205728. jassert (format_ == RGB || format_ == ARGB);
  205729. pixelStride = (format_ == RGB) ? 3 : 4;
  205730. zerostruct (bitmapInfo);
  205731. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  205732. bitmapInfo.bV4Width = w;
  205733. bitmapInfo.bV4Height = h;
  205734. bitmapInfo.bV4Planes = 1;
  205735. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  205736. if (format_ == ARGB)
  205737. {
  205738. bitmapInfo.bV4AlphaMask = 0xff000000;
  205739. bitmapInfo.bV4RedMask = 0xff0000;
  205740. bitmapInfo.bV4GreenMask = 0xff00;
  205741. bitmapInfo.bV4BlueMask = 0xff;
  205742. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  205743. }
  205744. else
  205745. {
  205746. bitmapInfo.bV4V4Compression = BI_RGB;
  205747. }
  205748. lineStride = -((w * pixelStride + 3) & ~3);
  205749. HDC dc = GetDC (0);
  205750. hdc = CreateCompatibleDC (dc);
  205751. ReleaseDC (0, dc);
  205752. SetMapMode (hdc, MM_TEXT);
  205753. hBitmap = CreateDIBSection (hdc,
  205754. (BITMAPINFO*) &(bitmapInfo),
  205755. DIB_RGB_COLORS,
  205756. (void**) &bitmapData,
  205757. 0, 0);
  205758. SelectObject (hdc, hBitmap);
  205759. if (format_ == ARGB && clearImage)
  205760. zeromem (bitmapData, abs (h * lineStride));
  205761. imageData = bitmapData - (lineStride * (h - 1));
  205762. }
  205763. ~WindowsBitmapImage()
  205764. {
  205765. DeleteDC (hdc);
  205766. DeleteObject (hBitmap);
  205767. imageData = 0; // to stop the base class freeing this
  205768. }
  205769. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  205770. const int x, const int y,
  205771. const RectangleList& maskedRegion) throw()
  205772. {
  205773. static HDRAWDIB hdd = 0;
  205774. static bool needToCreateDrawDib = true;
  205775. if (needToCreateDrawDib)
  205776. {
  205777. needToCreateDrawDib = false;
  205778. HDC dc = GetDC (0);
  205779. const int n = GetDeviceCaps (dc, BITSPIXEL);
  205780. ReleaseDC (0, dc);
  205781. // only open if we're not palettised
  205782. if (n > 8)
  205783. hdd = DrawDibOpen();
  205784. }
  205785. if (createPaletteIfNeeded)
  205786. {
  205787. HDC dc = GetDC (0);
  205788. const int n = GetDeviceCaps (dc, BITSPIXEL);
  205789. ReleaseDC (0, dc);
  205790. if (n <= 8)
  205791. palette = CreateHalftonePalette (dc);
  205792. createPaletteIfNeeded = false;
  205793. }
  205794. if (palette != 0)
  205795. {
  205796. SelectPalette (dc, palette, FALSE);
  205797. RealizePalette (dc);
  205798. SetStretchBltMode (dc, HALFTONE);
  205799. }
  205800. SetMapMode (dc, MM_TEXT);
  205801. if (transparent)
  205802. {
  205803. POINT p, pos;
  205804. SIZE size;
  205805. RECT windowBounds;
  205806. GetWindowRect (hwnd, &windowBounds);
  205807. p.x = -x;
  205808. p.y = -y;
  205809. pos.x = windowBounds.left;
  205810. pos.y = windowBounds.top;
  205811. size.cx = windowBounds.right - windowBounds.left;
  205812. size.cy = windowBounds.bottom - windowBounds.top;
  205813. BLENDFUNCTION bf;
  205814. bf.AlphaFormat = AC_SRC_ALPHA;
  205815. bf.BlendFlags = 0;
  205816. bf.BlendOp = AC_SRC_OVER;
  205817. bf.SourceConstantAlpha = 0xff;
  205818. if (! maskedRegion.isEmpty())
  205819. {
  205820. for (RectangleList::Iterator i (maskedRegion); i.next();)
  205821. {
  205822. const Rectangle& r = *i.getRectangle();
  205823. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  205824. }
  205825. }
  205826. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  205827. }
  205828. else
  205829. {
  205830. int savedDC = 0;
  205831. if (! maskedRegion.isEmpty())
  205832. {
  205833. savedDC = SaveDC (dc);
  205834. for (RectangleList::Iterator i (maskedRegion); i.next();)
  205835. {
  205836. const Rectangle& r = *i.getRectangle();
  205837. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  205838. }
  205839. }
  205840. const int w = getWidth();
  205841. const int h = getHeight();
  205842. if (hdd == 0)
  205843. {
  205844. StretchDIBits (dc,
  205845. x, y, w, h,
  205846. 0, 0, w, h,
  205847. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  205848. DIB_RGB_COLORS, SRCCOPY);
  205849. }
  205850. else
  205851. {
  205852. DrawDibDraw (hdd, dc, x, y, -1, -1,
  205853. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  205854. 0, 0, w, h, 0);
  205855. }
  205856. if (! maskedRegion.isEmpty())
  205857. RestoreDC (dc, savedDC);
  205858. }
  205859. }
  205860. juce_UseDebuggingNewOperator
  205861. private:
  205862. WindowsBitmapImage (const WindowsBitmapImage&);
  205863. const WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  205864. };
  205865. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  205866. static int currentModifiers = 0;
  205867. static int modifiersAtLastCallback = 0;
  205868. static void updateKeyModifiers() throw()
  205869. {
  205870. currentModifiers &= ~(ModifierKeys::shiftModifier
  205871. | ModifierKeys::ctrlModifier
  205872. | ModifierKeys::altModifier);
  205873. if ((GetKeyState (VK_SHIFT) & 0x8000) != 0)
  205874. currentModifiers |= ModifierKeys::shiftModifier;
  205875. if ((GetKeyState (VK_CONTROL) & 0x8000) != 0)
  205876. currentModifiers |= ModifierKeys::ctrlModifier;
  205877. if ((GetKeyState (VK_MENU) & 0x8000) != 0)
  205878. currentModifiers |= ModifierKeys::altModifier;
  205879. if ((GetKeyState (VK_RMENU) & 0x8000) != 0)
  205880. currentModifiers &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  205881. }
  205882. void ModifierKeys::updateCurrentModifiers() throw()
  205883. {
  205884. currentModifierFlags = currentModifiers;
  205885. }
  205886. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  205887. {
  205888. SHORT k = (SHORT) keyCode;
  205889. if ((keyCode & extendedKeyModifier) == 0
  205890. && (k >= (SHORT) T('a') && k <= (SHORT) T('z')))
  205891. k += (SHORT) T('A') - (SHORT) T('a');
  205892. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  205893. (SHORT) '+', VK_OEM_PLUS,
  205894. (SHORT) '-', VK_OEM_MINUS,
  205895. (SHORT) '.', VK_OEM_PERIOD,
  205896. (SHORT) ';', VK_OEM_1,
  205897. (SHORT) ':', VK_OEM_1,
  205898. (SHORT) '/', VK_OEM_2,
  205899. (SHORT) '?', VK_OEM_2,
  205900. (SHORT) '[', VK_OEM_4,
  205901. (SHORT) ']', VK_OEM_6 };
  205902. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  205903. if (k == translatedValues [i])
  205904. k = translatedValues [i + 1];
  205905. return (GetKeyState (k) & 0x8000) != 0;
  205906. }
  205907. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  205908. {
  205909. updateKeyModifiers();
  205910. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  205911. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0)
  205912. currentModifiers |= ModifierKeys::leftButtonModifier;
  205913. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0)
  205914. currentModifiers |= ModifierKeys::rightButtonModifier;
  205915. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0)
  205916. currentModifiers |= ModifierKeys::middleButtonModifier;
  205917. return ModifierKeys (currentModifiers);
  205918. }
  205919. static int64 getMouseEventTime() throw()
  205920. {
  205921. static int64 eventTimeOffset = 0;
  205922. static DWORD lastMessageTime = 0;
  205923. const DWORD thisMessageTime = GetMessageTime();
  205924. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  205925. {
  205926. lastMessageTime = thisMessageTime;
  205927. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  205928. }
  205929. return eventTimeOffset + thisMessageTime;
  205930. }
  205931. class Win32ComponentPeer : public ComponentPeer
  205932. {
  205933. public:
  205934. Win32ComponentPeer (Component* const component,
  205935. const int windowStyleFlags)
  205936. : ComponentPeer (component, windowStyleFlags),
  205937. dontRepaint (false),
  205938. fullScreen (false),
  205939. isDragging (false),
  205940. isMouseOver (false),
  205941. hasCreatedCaret (false),
  205942. currentWindowIcon (0),
  205943. taskBarIcon (0),
  205944. dropTarget (0)
  205945. {
  205946. MessageManager::getInstance()
  205947. ->callFunctionOnMessageThread (&createWindowCallback, (void*) this);
  205948. setTitle (component->getName());
  205949. if ((windowStyleFlags & windowHasDropShadow) != 0
  205950. && Desktop::canUseSemiTransparentWindows())
  205951. {
  205952. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  205953. if (shadower != 0)
  205954. shadower->setOwner (component);
  205955. }
  205956. else
  205957. {
  205958. shadower = 0;
  205959. }
  205960. }
  205961. ~Win32ComponentPeer()
  205962. {
  205963. setTaskBarIcon (0);
  205964. deleteAndZero (shadower);
  205965. // do this before the next bit to avoid messages arriving for this window
  205966. // before it's destroyed
  205967. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  205968. MessageManager::getInstance()
  205969. ->callFunctionOnMessageThread (&destroyWindowCallback, (void*) hwnd);
  205970. if (currentWindowIcon != 0)
  205971. DestroyIcon (currentWindowIcon);
  205972. if (dropTarget != 0)
  205973. {
  205974. dropTarget->Release();
  205975. dropTarget = 0;
  205976. }
  205977. }
  205978. void* getNativeHandle() const
  205979. {
  205980. return (void*) hwnd;
  205981. }
  205982. void setVisible (bool shouldBeVisible)
  205983. {
  205984. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  205985. if (shouldBeVisible)
  205986. InvalidateRect (hwnd, 0, 0);
  205987. else
  205988. lastPaintTime = 0;
  205989. }
  205990. void setTitle (const String& title)
  205991. {
  205992. SetWindowText (hwnd, title);
  205993. }
  205994. void setPosition (int x, int y)
  205995. {
  205996. offsetWithinParent (x, y);
  205997. SetWindowPos (hwnd, 0,
  205998. x - windowBorder.getLeft(),
  205999. y - windowBorder.getTop(),
  206000. 0, 0,
  206001. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206002. }
  206003. void repaintNowIfTransparent()
  206004. {
  206005. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206006. handlePaintMessage();
  206007. }
  206008. void updateBorderSize()
  206009. {
  206010. WINDOWINFO info;
  206011. info.cbSize = sizeof (info);
  206012. if (GetWindowInfo (hwnd, &info))
  206013. {
  206014. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  206015. info.rcClient.left - info.rcWindow.left,
  206016. info.rcWindow.bottom - info.rcClient.bottom,
  206017. info.rcWindow.right - info.rcClient.right);
  206018. }
  206019. }
  206020. void setSize (int w, int h)
  206021. {
  206022. SetWindowPos (hwnd, 0, 0, 0,
  206023. w + windowBorder.getLeftAndRight(),
  206024. h + windowBorder.getTopAndBottom(),
  206025. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206026. updateBorderSize();
  206027. repaintNowIfTransparent();
  206028. }
  206029. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  206030. {
  206031. fullScreen = isNowFullScreen;
  206032. offsetWithinParent (x, y);
  206033. SetWindowPos (hwnd, 0,
  206034. x - windowBorder.getLeft(),
  206035. y - windowBorder.getTop(),
  206036. w + windowBorder.getLeftAndRight(),
  206037. h + windowBorder.getTopAndBottom(),
  206038. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206039. updateBorderSize();
  206040. repaintNowIfTransparent();
  206041. }
  206042. void getBounds (int& x, int& y, int& w, int& h) const
  206043. {
  206044. RECT r;
  206045. GetWindowRect (hwnd, &r);
  206046. x = r.left;
  206047. y = r.top;
  206048. w = r.right - x;
  206049. h = r.bottom - y;
  206050. HWND parentH = GetParent (hwnd);
  206051. if (parentH != 0)
  206052. {
  206053. GetWindowRect (parentH, &r);
  206054. x -= r.left;
  206055. y -= r.top;
  206056. }
  206057. x += windowBorder.getLeft();
  206058. y += windowBorder.getTop();
  206059. w -= windowBorder.getLeftAndRight();
  206060. h -= windowBorder.getTopAndBottom();
  206061. }
  206062. int getScreenX() const
  206063. {
  206064. RECT r;
  206065. GetWindowRect (hwnd, &r);
  206066. return r.left + windowBorder.getLeft();
  206067. }
  206068. int getScreenY() const
  206069. {
  206070. RECT r;
  206071. GetWindowRect (hwnd, &r);
  206072. return r.top + windowBorder.getTop();
  206073. }
  206074. void relativePositionToGlobal (int& x, int& y)
  206075. {
  206076. RECT r;
  206077. GetWindowRect (hwnd, &r);
  206078. x += r.left + windowBorder.getLeft();
  206079. y += r.top + windowBorder.getTop();
  206080. }
  206081. void globalPositionToRelative (int& x, int& y)
  206082. {
  206083. RECT r;
  206084. GetWindowRect (hwnd, &r);
  206085. x -= r.left + windowBorder.getLeft();
  206086. y -= r.top + windowBorder.getTop();
  206087. }
  206088. void setMinimised (bool shouldBeMinimised)
  206089. {
  206090. if (shouldBeMinimised != isMinimised())
  206091. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  206092. }
  206093. bool isMinimised() const
  206094. {
  206095. WINDOWPLACEMENT wp;
  206096. wp.length = sizeof (WINDOWPLACEMENT);
  206097. GetWindowPlacement (hwnd, &wp);
  206098. return wp.showCmd == SW_SHOWMINIMIZED;
  206099. }
  206100. void setFullScreen (bool shouldBeFullScreen)
  206101. {
  206102. setMinimised (false);
  206103. if (fullScreen != shouldBeFullScreen)
  206104. {
  206105. fullScreen = shouldBeFullScreen;
  206106. const ComponentDeletionWatcher deletionChecker (component);
  206107. if (! fullScreen)
  206108. {
  206109. const Rectangle boundsCopy (lastNonFullscreenBounds);
  206110. if (hasTitleBar())
  206111. ShowWindow (hwnd, SW_SHOWNORMAL);
  206112. if (! boundsCopy.isEmpty())
  206113. {
  206114. setBounds (boundsCopy.getX(),
  206115. boundsCopy.getY(),
  206116. boundsCopy.getWidth(),
  206117. boundsCopy.getHeight(),
  206118. false);
  206119. }
  206120. }
  206121. else
  206122. {
  206123. if (hasTitleBar())
  206124. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  206125. else
  206126. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  206127. }
  206128. if (! deletionChecker.hasBeenDeleted())
  206129. handleMovedOrResized();
  206130. }
  206131. }
  206132. bool isFullScreen() const
  206133. {
  206134. if (! hasTitleBar())
  206135. return fullScreen;
  206136. WINDOWPLACEMENT wp;
  206137. wp.length = sizeof (wp);
  206138. GetWindowPlacement (hwnd, &wp);
  206139. return wp.showCmd == SW_SHOWMAXIMIZED;
  206140. }
  206141. bool contains (int x, int y, bool trueIfInAChildWindow) const
  206142. {
  206143. RECT r;
  206144. GetWindowRect (hwnd, &r);
  206145. POINT p;
  206146. p.x = x + r.left + windowBorder.getLeft();
  206147. p.y = y + r.top + windowBorder.getTop();
  206148. HWND w = WindowFromPoint (p);
  206149. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  206150. }
  206151. const BorderSize getFrameSize() const
  206152. {
  206153. return windowBorder;
  206154. }
  206155. bool setAlwaysOnTop (bool alwaysOnTop)
  206156. {
  206157. const bool oldDeactivate = shouldDeactivateTitleBar;
  206158. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206159. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  206160. 0, 0, 0, 0,
  206161. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206162. shouldDeactivateTitleBar = oldDeactivate;
  206163. if (shadower != 0)
  206164. shadower->componentBroughtToFront (*component);
  206165. return true;
  206166. }
  206167. void toFront (bool makeActive)
  206168. {
  206169. setMinimised (false);
  206170. const bool oldDeactivate = shouldDeactivateTitleBar;
  206171. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206172. MessageManager::getInstance()
  206173. ->callFunctionOnMessageThread (makeActive ? &toFrontCallback1
  206174. : &toFrontCallback2,
  206175. (void*) hwnd);
  206176. shouldDeactivateTitleBar = oldDeactivate;
  206177. if (! makeActive)
  206178. {
  206179. // in this case a broughttofront call won't have occured, so do it now..
  206180. handleBroughtToFront();
  206181. }
  206182. }
  206183. void toBehind (ComponentPeer* other)
  206184. {
  206185. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  206186. jassert (otherPeer != 0); // wrong type of window?
  206187. if (otherPeer != 0)
  206188. {
  206189. setMinimised (false);
  206190. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  206191. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206192. }
  206193. }
  206194. bool isFocused() const
  206195. {
  206196. return MessageManager::getInstance()
  206197. ->callFunctionOnMessageThread (&getFocusCallback, 0) == (void*) hwnd;
  206198. }
  206199. void grabFocus()
  206200. {
  206201. const bool oldDeactivate = shouldDeactivateTitleBar;
  206202. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206203. MessageManager::getInstance()
  206204. ->callFunctionOnMessageThread (&setFocusCallback, (void*) hwnd);
  206205. shouldDeactivateTitleBar = oldDeactivate;
  206206. }
  206207. void textInputRequired (int /*x*/, int /*y*/)
  206208. {
  206209. if (! hasCreatedCaret)
  206210. {
  206211. hasCreatedCaret = true;
  206212. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  206213. }
  206214. ShowCaret (hwnd);
  206215. SetCaretPos (0, 0);
  206216. }
  206217. void repaint (int x, int y, int w, int h)
  206218. {
  206219. const RECT r = { x, y, x + w, y + h };
  206220. InvalidateRect (hwnd, &r, FALSE);
  206221. }
  206222. void performAnyPendingRepaintsNow()
  206223. {
  206224. MSG m;
  206225. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  206226. DispatchMessage (&m);
  206227. }
  206228. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  206229. {
  206230. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  206231. return (Win32ComponentPeer*) GetWindowLongPtr (h, 8);
  206232. return 0;
  206233. }
  206234. void setTaskBarIcon (const Image* const image)
  206235. {
  206236. if (image != 0)
  206237. {
  206238. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  206239. if (taskBarIcon == 0)
  206240. {
  206241. taskBarIcon = new NOTIFYICONDATA();
  206242. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  206243. taskBarIcon->hWnd = (HWND) hwnd;
  206244. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  206245. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  206246. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  206247. taskBarIcon->hIcon = hicon;
  206248. taskBarIcon->szTip[0] = 0;
  206249. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  206250. }
  206251. else
  206252. {
  206253. HICON oldIcon = taskBarIcon->hIcon;
  206254. taskBarIcon->hIcon = hicon;
  206255. taskBarIcon->uFlags = NIF_ICON;
  206256. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206257. DestroyIcon (oldIcon);
  206258. }
  206259. DestroyIcon (hicon);
  206260. }
  206261. else if (taskBarIcon != 0)
  206262. {
  206263. taskBarIcon->uFlags = 0;
  206264. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  206265. DestroyIcon (taskBarIcon->hIcon);
  206266. deleteAndZero (taskBarIcon);
  206267. }
  206268. }
  206269. void setTaskBarIconToolTip (const String& toolTip) const
  206270. {
  206271. if (taskBarIcon != 0)
  206272. {
  206273. taskBarIcon->uFlags = NIF_TIP;
  206274. toolTip.copyToBuffer (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  206275. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206276. }
  206277. }
  206278. juce_UseDebuggingNewOperator
  206279. bool dontRepaint;
  206280. private:
  206281. HWND hwnd;
  206282. DropShadower* shadower;
  206283. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  206284. BorderSize windowBorder;
  206285. HICON currentWindowIcon;
  206286. NOTIFYICONDATA* taskBarIcon;
  206287. IDropTarget* dropTarget;
  206288. class TemporaryImage : public Timer
  206289. {
  206290. public:
  206291. TemporaryImage()
  206292. : image (0)
  206293. {
  206294. }
  206295. ~TemporaryImage()
  206296. {
  206297. delete image;
  206298. }
  206299. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  206300. {
  206301. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  206302. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  206303. {
  206304. delete image;
  206305. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  206306. }
  206307. startTimer (3000);
  206308. return image;
  206309. }
  206310. void timerCallback()
  206311. {
  206312. stopTimer();
  206313. deleteAndZero (image);
  206314. }
  206315. private:
  206316. WindowsBitmapImage* image;
  206317. TemporaryImage (const TemporaryImage&);
  206318. const TemporaryImage& operator= (const TemporaryImage&);
  206319. };
  206320. TemporaryImage offscreenImageGenerator;
  206321. class WindowClassHolder : public DeletedAtShutdown
  206322. {
  206323. public:
  206324. WindowClassHolder()
  206325. : windowClassName ("JUCE_")
  206326. {
  206327. // this name has to be different for each app/dll instance because otherwise
  206328. // poor old Win32 can get a bit confused (even despite it not being a process-global
  206329. // window class).
  206330. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  206331. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  206332. TCHAR moduleFile [1024];
  206333. moduleFile[0] = 0;
  206334. GetModuleFileName (moduleHandle, moduleFile, 1024);
  206335. WORD iconNum = 0;
  206336. WNDCLASSEX wcex;
  206337. wcex.cbSize = sizeof (wcex);
  206338. wcex.style = CS_OWNDC;
  206339. wcex.lpfnWndProc = (WNDPROC) windowProc;
  206340. wcex.lpszClassName = windowClassName;
  206341. wcex.cbClsExtra = 0;
  206342. wcex.cbWndExtra = 32;
  206343. wcex.hInstance = moduleHandle;
  206344. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  206345. iconNum = 1;
  206346. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  206347. wcex.hCursor = 0;
  206348. wcex.hbrBackground = 0;
  206349. wcex.lpszMenuName = 0;
  206350. RegisterClassEx (&wcex);
  206351. }
  206352. ~WindowClassHolder()
  206353. {
  206354. if (ComponentPeer::getNumPeers() == 0)
  206355. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  206356. clearSingletonInstance();
  206357. }
  206358. String windowClassName;
  206359. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  206360. };
  206361. static void* createWindowCallback (void* userData)
  206362. {
  206363. ((Win32ComponentPeer*) userData)->createWindow();
  206364. return 0;
  206365. }
  206366. void createWindow()
  206367. {
  206368. DWORD exstyle = WS_EX_ACCEPTFILES;
  206369. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  206370. if (hasTitleBar())
  206371. {
  206372. type |= WS_OVERLAPPED;
  206373. exstyle |= WS_EX_APPWINDOW;
  206374. if ((styleFlags & windowHasCloseButton) != 0)
  206375. {
  206376. type |= WS_SYSMENU;
  206377. }
  206378. else
  206379. {
  206380. // annoyingly, windows won't let you have a min/max button without a close button
  206381. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  206382. }
  206383. if ((styleFlags & windowIsResizable) != 0)
  206384. type |= WS_THICKFRAME;
  206385. }
  206386. else
  206387. {
  206388. type |= WS_POPUP | WS_SYSMENU;
  206389. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  206390. exstyle |= WS_EX_TOOLWINDOW;
  206391. else
  206392. exstyle |= WS_EX_APPWINDOW;
  206393. }
  206394. if ((styleFlags & windowHasMinimiseButton) != 0)
  206395. type |= WS_MINIMIZEBOX;
  206396. if ((styleFlags & windowHasMaximiseButton) != 0)
  206397. type |= WS_MAXIMIZEBOX;
  206398. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  206399. exstyle |= WS_EX_TRANSPARENT;
  206400. if ((styleFlags & windowIsSemiTransparent) != 0
  206401. && Desktop::canUseSemiTransparentWindows())
  206402. exstyle |= WS_EX_LAYERED;
  206403. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  206404. if (hwnd != 0)
  206405. {
  206406. SetWindowLongPtr (hwnd, 0, 0);
  206407. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  206408. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  206409. if (dropTarget == 0)
  206410. dropTarget = new JuceDropTarget (this);
  206411. RegisterDragDrop (hwnd, dropTarget);
  206412. updateBorderSize();
  206413. // Calling this function here is (for some reason) necessary to make Windows
  206414. // correctly enable the menu items that we specify in the wm_initmenu message.
  206415. GetSystemMenu (hwnd, false);
  206416. }
  206417. else
  206418. {
  206419. jassertfalse
  206420. }
  206421. }
  206422. static void* destroyWindowCallback (void* handle)
  206423. {
  206424. RevokeDragDrop ((HWND) handle);
  206425. DestroyWindow ((HWND) handle);
  206426. return 0;
  206427. }
  206428. static void* toFrontCallback1 (void* h)
  206429. {
  206430. SetForegroundWindow ((HWND) h);
  206431. return 0;
  206432. }
  206433. static void* toFrontCallback2 (void* h)
  206434. {
  206435. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206436. return 0;
  206437. }
  206438. static void* setFocusCallback (void* h)
  206439. {
  206440. SetFocus ((HWND) h);
  206441. return 0;
  206442. }
  206443. static void* getFocusCallback (void*)
  206444. {
  206445. return (void*) GetFocus();
  206446. }
  206447. void offsetWithinParent (int& x, int& y) const
  206448. {
  206449. if (isTransparent())
  206450. {
  206451. HWND parentHwnd = GetParent (hwnd);
  206452. if (parentHwnd != 0)
  206453. {
  206454. RECT parentRect;
  206455. GetWindowRect (parentHwnd, &parentRect);
  206456. x += parentRect.left;
  206457. y += parentRect.top;
  206458. }
  206459. }
  206460. }
  206461. bool isTransparent() const
  206462. {
  206463. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  206464. }
  206465. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  206466. void setIcon (const Image& newIcon)
  206467. {
  206468. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  206469. if (hicon != 0)
  206470. {
  206471. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  206472. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  206473. if (currentWindowIcon != 0)
  206474. DestroyIcon (currentWindowIcon);
  206475. currentWindowIcon = hicon;
  206476. }
  206477. }
  206478. void handlePaintMessage()
  206479. {
  206480. #if DEBUG_REPAINT_TIMES
  206481. const double paintStart = Time::getMillisecondCounterHiRes();
  206482. #endif
  206483. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  206484. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  206485. PAINTSTRUCT paintStruct;
  206486. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  206487. // message and become re-entrant, but that's OK
  206488. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  206489. // corrupt the image it's using to paint into, so do a check here.
  206490. static bool reentrant = false;
  206491. if (reentrant)
  206492. {
  206493. DeleteObject (rgn);
  206494. EndPaint (hwnd, &paintStruct);
  206495. return;
  206496. }
  206497. reentrant = true;
  206498. // this is the rectangle to update..
  206499. int x = paintStruct.rcPaint.left;
  206500. int y = paintStruct.rcPaint.top;
  206501. int w = paintStruct.rcPaint.right - x;
  206502. int h = paintStruct.rcPaint.bottom - y;
  206503. const bool transparent = isTransparent();
  206504. if (transparent)
  206505. {
  206506. // it's not possible to have a transparent window with a title bar at the moment!
  206507. jassert (! hasTitleBar());
  206508. RECT r;
  206509. GetWindowRect (hwnd, &r);
  206510. x = y = 0;
  206511. w = r.right - r.left;
  206512. h = r.bottom - r.top;
  206513. }
  206514. if (w > 0 && h > 0)
  206515. {
  206516. clearMaskedRegion();
  206517. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  206518. LowLevelGraphicsSoftwareRenderer context (*offscreenImage);
  206519. RectangleList* const contextClip = context.getRawClipRegion();
  206520. contextClip->clear();
  206521. context.setOrigin (-x, -y);
  206522. bool needToPaintAll = true;
  206523. if (regionType == COMPLEXREGION && ! transparent)
  206524. {
  206525. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  206526. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  206527. DeleteObject (clipRgn);
  206528. char rgnData [8192];
  206529. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  206530. if (res > 0 && res <= sizeof (rgnData))
  206531. {
  206532. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  206533. if (hdr->iType == RDH_RECTANGLES
  206534. && hdr->rcBound.right - hdr->rcBound.left >= w
  206535. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  206536. {
  206537. needToPaintAll = false;
  206538. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  206539. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  206540. while (--num >= 0)
  206541. {
  206542. // (need to move this one pixel to the left because of a win32 bug)
  206543. const int cx = jmax (x, rects->left - 1);
  206544. const int cy = rects->top;
  206545. const int cw = rects->right - cx;
  206546. const int ch = rects->bottom - rects->top;
  206547. if (cx + cw - x <= w && cy + ch - y <= h)
  206548. {
  206549. contextClip->addWithoutMerging (Rectangle (cx - x, cy - y, cw, ch));
  206550. }
  206551. else
  206552. {
  206553. needToPaintAll = true;
  206554. break;
  206555. }
  206556. ++rects;
  206557. }
  206558. }
  206559. }
  206560. }
  206561. if (needToPaintAll)
  206562. {
  206563. contextClip->clear();
  206564. contextClip->addWithoutMerging (Rectangle (0, 0, w, h));
  206565. }
  206566. if (transparent)
  206567. {
  206568. RectangleList::Iterator i (*contextClip);
  206569. while (i.next())
  206570. {
  206571. const Rectangle& r = *i.getRectangle();
  206572. offscreenImage->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  206573. }
  206574. }
  206575. // if the component's not opaque, this won't draw properly unless the platform can support this
  206576. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  206577. updateCurrentModifiers();
  206578. handlePaint (context);
  206579. if (! dontRepaint)
  206580. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  206581. }
  206582. DeleteObject (rgn);
  206583. EndPaint (hwnd, &paintStruct);
  206584. reentrant = false;
  206585. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  206586. _fpreset(); // because some graphics cards can unmask FP exceptions
  206587. #endif
  206588. lastPaintTime = Time::getMillisecondCounter();
  206589. #if DEBUG_REPAINT_TIMES
  206590. const double elapsed = Time::getMillisecondCounterHiRes() - paintStart;
  206591. Logger::outputDebugString (T("repaint time: ") + String (elapsed, 2));
  206592. #endif
  206593. }
  206594. void doMouseMove (const int x, const int y)
  206595. {
  206596. static uint32 lastMouseTime = 0;
  206597. // this can be set to throttle the mouse-messages to less than a
  206598. // certain number per second, as things can get unresponsive
  206599. // if each drag or move callback has to do a lot of work.
  206600. const int maxMouseMovesPerSecond = 60;
  206601. const int64 mouseEventTime = getMouseEventTime();
  206602. if (! isMouseOver)
  206603. {
  206604. isMouseOver = true;
  206605. TRACKMOUSEEVENT tme;
  206606. tme.cbSize = sizeof (tme);
  206607. tme.dwFlags = TME_LEAVE;
  206608. tme.hwndTrack = hwnd;
  206609. tme.dwHoverTime = 0;
  206610. if (! TrackMouseEvent (&tme))
  206611. {
  206612. jassertfalse;
  206613. }
  206614. updateKeyModifiers();
  206615. handleMouseEnter (x, y, mouseEventTime);
  206616. }
  206617. else if (! isDragging)
  206618. {
  206619. if (((unsigned int) x) < (unsigned int) component->getWidth()
  206620. && ((unsigned int) y) < (unsigned int) component->getHeight())
  206621. {
  206622. RECT r;
  206623. GetWindowRect (hwnd, &r);
  206624. POINT p;
  206625. p.x = x + r.left + windowBorder.getLeft();
  206626. p.y = y + r.top + windowBorder.getTop();
  206627. if (WindowFromPoint (p) == hwnd)
  206628. {
  206629. const uint32 now = Time::getMillisecondCounter();
  206630. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  206631. {
  206632. lastMouseTime = now;
  206633. handleMouseMove (x, y, mouseEventTime);
  206634. }
  206635. }
  206636. }
  206637. }
  206638. else
  206639. {
  206640. const uint32 now = Time::getMillisecondCounter();
  206641. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  206642. {
  206643. lastMouseTime = now;
  206644. handleMouseDrag (x, y, mouseEventTime);
  206645. }
  206646. }
  206647. }
  206648. void doMouseDown (const int x, const int y, const WPARAM wParam)
  206649. {
  206650. if (GetCapture() != hwnd)
  206651. SetCapture (hwnd);
  206652. doMouseMove (x, y);
  206653. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  206654. if ((wParam & MK_LBUTTON) != 0)
  206655. currentModifiers |= ModifierKeys::leftButtonModifier;
  206656. if ((wParam & MK_RBUTTON) != 0)
  206657. currentModifiers |= ModifierKeys::rightButtonModifier;
  206658. if ((wParam & MK_MBUTTON) != 0)
  206659. currentModifiers |= ModifierKeys::middleButtonModifier;
  206660. updateKeyModifiers();
  206661. isDragging = true;
  206662. handleMouseDown (x, y, getMouseEventTime());
  206663. }
  206664. void doMouseUp (const int x, const int y, const WPARAM wParam)
  206665. {
  206666. int numButtons = 0;
  206667. if ((wParam & MK_LBUTTON) != 0)
  206668. ++numButtons;
  206669. if ((wParam & MK_RBUTTON) != 0)
  206670. ++numButtons;
  206671. if ((wParam & MK_MBUTTON) != 0)
  206672. ++numButtons;
  206673. const int oldModifiers = currentModifiers;
  206674. // update the currentmodifiers only after the callback, so the callback
  206675. // knows which button was released.
  206676. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  206677. if ((wParam & MK_LBUTTON) != 0)
  206678. currentModifiers |= ModifierKeys::leftButtonModifier;
  206679. if ((wParam & MK_RBUTTON) != 0)
  206680. currentModifiers |= ModifierKeys::rightButtonModifier;
  206681. if ((wParam & MK_MBUTTON) != 0)
  206682. currentModifiers |= ModifierKeys::middleButtonModifier;
  206683. updateKeyModifiers();
  206684. isDragging = false;
  206685. // release the mouse capture if the user's not still got a button down
  206686. if (numButtons == 0 && hwnd == GetCapture())
  206687. ReleaseCapture();
  206688. handleMouseUp (oldModifiers, x, y, getMouseEventTime());
  206689. }
  206690. void doCaptureChanged()
  206691. {
  206692. if (isDragging)
  206693. {
  206694. RECT wr;
  206695. GetWindowRect (hwnd, &wr);
  206696. const DWORD mp = GetMessagePos();
  206697. doMouseUp (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  206698. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  206699. getMouseEventTime());
  206700. }
  206701. }
  206702. void doMouseExit()
  206703. {
  206704. if (isMouseOver)
  206705. {
  206706. isMouseOver = false;
  206707. RECT wr;
  206708. GetWindowRect (hwnd, &wr);
  206709. const DWORD mp = GetMessagePos();
  206710. handleMouseExit (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  206711. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  206712. getMouseEventTime());
  206713. }
  206714. }
  206715. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  206716. {
  206717. updateKeyModifiers();
  206718. const int amount = jlimit (-1000, 1000, (int) (0.75f * (short) HIWORD (wParam)));
  206719. handleMouseWheel (isVertical ? 0 : amount,
  206720. isVertical ? amount : 0,
  206721. getMouseEventTime());
  206722. }
  206723. void sendModifierKeyChangeIfNeeded()
  206724. {
  206725. if (modifiersAtLastCallback != currentModifiers)
  206726. {
  206727. modifiersAtLastCallback = currentModifiers;
  206728. handleModifierKeysChange();
  206729. }
  206730. }
  206731. bool doKeyUp (const WPARAM key)
  206732. {
  206733. updateKeyModifiers();
  206734. switch (key)
  206735. {
  206736. case VK_SHIFT:
  206737. case VK_CONTROL:
  206738. case VK_MENU:
  206739. case VK_CAPITAL:
  206740. case VK_LWIN:
  206741. case VK_RWIN:
  206742. case VK_APPS:
  206743. case VK_NUMLOCK:
  206744. case VK_SCROLL:
  206745. case VK_LSHIFT:
  206746. case VK_RSHIFT:
  206747. case VK_LCONTROL:
  206748. case VK_LMENU:
  206749. case VK_RCONTROL:
  206750. case VK_RMENU:
  206751. sendModifierKeyChangeIfNeeded();
  206752. }
  206753. return handleKeyUpOrDown();
  206754. }
  206755. bool doKeyDown (const WPARAM key)
  206756. {
  206757. updateKeyModifiers();
  206758. bool used = false;
  206759. switch (key)
  206760. {
  206761. case VK_SHIFT:
  206762. case VK_LSHIFT:
  206763. case VK_RSHIFT:
  206764. case VK_CONTROL:
  206765. case VK_LCONTROL:
  206766. case VK_RCONTROL:
  206767. case VK_MENU:
  206768. case VK_LMENU:
  206769. case VK_RMENU:
  206770. case VK_LWIN:
  206771. case VK_RWIN:
  206772. case VK_CAPITAL:
  206773. case VK_NUMLOCK:
  206774. case VK_SCROLL:
  206775. case VK_APPS:
  206776. sendModifierKeyChangeIfNeeded();
  206777. break;
  206778. case VK_LEFT:
  206779. case VK_RIGHT:
  206780. case VK_UP:
  206781. case VK_DOWN:
  206782. case VK_PRIOR:
  206783. case VK_NEXT:
  206784. case VK_HOME:
  206785. case VK_END:
  206786. case VK_DELETE:
  206787. case VK_INSERT:
  206788. case VK_F1:
  206789. case VK_F2:
  206790. case VK_F3:
  206791. case VK_F4:
  206792. case VK_F5:
  206793. case VK_F6:
  206794. case VK_F7:
  206795. case VK_F8:
  206796. case VK_F9:
  206797. case VK_F10:
  206798. case VK_F11:
  206799. case VK_F12:
  206800. case VK_F13:
  206801. case VK_F14:
  206802. case VK_F15:
  206803. case VK_F16:
  206804. used = handleKeyUpOrDown();
  206805. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  206806. break;
  206807. case VK_ADD:
  206808. case VK_SUBTRACT:
  206809. case VK_MULTIPLY:
  206810. case VK_DIVIDE:
  206811. case VK_SEPARATOR:
  206812. case VK_DECIMAL:
  206813. used = handleKeyUpOrDown();
  206814. break;
  206815. default:
  206816. used = handleKeyUpOrDown();
  206817. {
  206818. MSG msg;
  206819. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  206820. {
  206821. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  206822. // manually generate the key-press event that matches this key-down.
  206823. const UINT keyChar = MapVirtualKey (key, 2);
  206824. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  206825. }
  206826. }
  206827. break;
  206828. }
  206829. return used;
  206830. }
  206831. bool doKeyChar (int key, const LPARAM flags)
  206832. {
  206833. updateKeyModifiers();
  206834. juce_wchar textChar = (juce_wchar) key;
  206835. const int virtualScanCode = (flags >> 16) & 0xff;
  206836. if (key >= '0' && key <= '9')
  206837. {
  206838. switch (virtualScanCode) // check for a numeric keypad scan-code
  206839. {
  206840. case 0x52:
  206841. case 0x4f:
  206842. case 0x50:
  206843. case 0x51:
  206844. case 0x4b:
  206845. case 0x4c:
  206846. case 0x4d:
  206847. case 0x47:
  206848. case 0x48:
  206849. case 0x49:
  206850. key = (key - '0') + KeyPress::numberPad0;
  206851. break;
  206852. default:
  206853. break;
  206854. }
  206855. }
  206856. else
  206857. {
  206858. // convert the scan code to an unmodified character code..
  206859. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  206860. UINT keyChar = MapVirtualKey (virtualKey, 2);
  206861. keyChar = LOWORD (keyChar);
  206862. if (keyChar != 0)
  206863. key = (int) keyChar;
  206864. // avoid sending junk text characters for some control-key combinations
  206865. if (textChar < ' ' && (currentModifiers & (ModifierKeys::ctrlModifier | ModifierKeys::altModifier)) != 0)
  206866. textChar = 0;
  206867. }
  206868. return handleKeyPress (key, textChar);
  206869. }
  206870. bool doAppCommand (const LPARAM lParam)
  206871. {
  206872. int key = 0;
  206873. switch (GET_APPCOMMAND_LPARAM (lParam))
  206874. {
  206875. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  206876. key = KeyPress::playKey;
  206877. break;
  206878. case APPCOMMAND_MEDIA_STOP:
  206879. key = KeyPress::stopKey;
  206880. break;
  206881. case APPCOMMAND_MEDIA_NEXTTRACK:
  206882. key = KeyPress::fastForwardKey;
  206883. break;
  206884. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  206885. key = KeyPress::rewindKey;
  206886. break;
  206887. }
  206888. if (key != 0)
  206889. {
  206890. updateKeyModifiers();
  206891. if (hwnd == GetActiveWindow())
  206892. {
  206893. handleKeyPress (key, 0);
  206894. return true;
  206895. }
  206896. }
  206897. return false;
  206898. }
  206899. class JuceDropTarget : public IDropTarget
  206900. {
  206901. public:
  206902. JuceDropTarget (Win32ComponentPeer* const owner_)
  206903. : owner (owner_),
  206904. refCount (1)
  206905. {
  206906. }
  206907. virtual ~JuceDropTarget()
  206908. {
  206909. jassert (refCount == 0);
  206910. }
  206911. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  206912. {
  206913. if (id == IID_IUnknown || id == IID_IDropTarget)
  206914. {
  206915. AddRef();
  206916. *result = this;
  206917. return S_OK;
  206918. }
  206919. *result = 0;
  206920. return E_NOINTERFACE;
  206921. }
  206922. ULONG __stdcall AddRef() { return ++refCount; }
  206923. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  206924. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206925. {
  206926. updateFileList (pDataObject);
  206927. int x = mousePos.x, y = mousePos.y;
  206928. owner->globalPositionToRelative (x, y);
  206929. owner->handleFileDragMove (files, x, y);
  206930. *pdwEffect = DROPEFFECT_COPY;
  206931. return S_OK;
  206932. }
  206933. HRESULT __stdcall DragLeave()
  206934. {
  206935. owner->handleFileDragExit (files);
  206936. return S_OK;
  206937. }
  206938. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206939. {
  206940. int x = mousePos.x, y = mousePos.y;
  206941. owner->globalPositionToRelative (x, y);
  206942. owner->handleFileDragMove (files, x, y);
  206943. *pdwEffect = DROPEFFECT_COPY;
  206944. return S_OK;
  206945. }
  206946. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206947. {
  206948. updateFileList (pDataObject);
  206949. int x = mousePos.x, y = mousePos.y;
  206950. owner->globalPositionToRelative (x, y);
  206951. owner->handleFileDragDrop (files, x, y);
  206952. *pdwEffect = DROPEFFECT_COPY;
  206953. return S_OK;
  206954. }
  206955. private:
  206956. Win32ComponentPeer* const owner;
  206957. int refCount;
  206958. StringArray files;
  206959. void updateFileList (IDataObject* const pDataObject)
  206960. {
  206961. files.clear();
  206962. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206963. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206964. if (pDataObject->GetData (&format, &medium) == S_OK)
  206965. {
  206966. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  206967. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  206968. unsigned int i = 0;
  206969. if (pDropFiles->fWide)
  206970. {
  206971. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  206972. for (;;)
  206973. {
  206974. unsigned int len = 0;
  206975. while (i + len < totalLen && fname [i + len] != 0)
  206976. ++len;
  206977. if (len == 0)
  206978. break;
  206979. files.add (String (fname + i, len));
  206980. i += len + 1;
  206981. }
  206982. }
  206983. else
  206984. {
  206985. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  206986. for (;;)
  206987. {
  206988. unsigned int len = 0;
  206989. while (i + len < totalLen && fname [i + len] != 0)
  206990. ++len;
  206991. if (len == 0)
  206992. break;
  206993. files.add (String (fname + i, len));
  206994. i += len + 1;
  206995. }
  206996. }
  206997. GlobalUnlock (medium.hGlobal);
  206998. }
  206999. }
  207000. JuceDropTarget (const JuceDropTarget&);
  207001. const JuceDropTarget& operator= (const JuceDropTarget&);
  207002. };
  207003. void doSettingChange()
  207004. {
  207005. Desktop::getInstance().refreshMonitorSizes();
  207006. if (fullScreen && ! isMinimised())
  207007. {
  207008. const Rectangle r (component->getParentMonitorArea());
  207009. SetWindowPos (hwnd, 0,
  207010. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  207011. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  207012. }
  207013. }
  207014. public:
  207015. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207016. {
  207017. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  207018. if (peer != 0)
  207019. return peer->peerWindowProc (h, message, wParam, lParam);
  207020. return DefWindowProc (h, message, wParam, lParam);
  207021. }
  207022. private:
  207023. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207024. {
  207025. {
  207026. const MessageManagerLock messLock;
  207027. if (isValidPeer (this))
  207028. {
  207029. switch (message)
  207030. {
  207031. case WM_NCHITTEST:
  207032. if (hasTitleBar())
  207033. break;
  207034. return HTCLIENT;
  207035. case WM_PAINT:
  207036. handlePaintMessage();
  207037. return 0;
  207038. case WM_NCPAINT:
  207039. if (wParam != 1)
  207040. handlePaintMessage();
  207041. if (hasTitleBar())
  207042. break;
  207043. return 0;
  207044. case WM_ERASEBKGND:
  207045. case WM_NCCALCSIZE:
  207046. if (hasTitleBar())
  207047. break;
  207048. return 1;
  207049. case WM_MOUSEMOVE:
  207050. doMouseMove (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  207051. return 0;
  207052. case WM_MOUSELEAVE:
  207053. doMouseExit();
  207054. return 0;
  207055. case WM_LBUTTONDOWN:
  207056. case WM_MBUTTONDOWN:
  207057. case WM_RBUTTONDOWN:
  207058. doMouseDown (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  207059. return 0;
  207060. case WM_LBUTTONUP:
  207061. case WM_MBUTTONUP:
  207062. case WM_RBUTTONUP:
  207063. doMouseUp (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  207064. return 0;
  207065. case WM_CAPTURECHANGED:
  207066. doCaptureChanged();
  207067. return 0;
  207068. case WM_NCMOUSEMOVE:
  207069. if (hasTitleBar())
  207070. break;
  207071. return 0;
  207072. case 0x020A: /* WM_MOUSEWHEEL */
  207073. doMouseWheel (wParam, true);
  207074. return 0;
  207075. case 0x020E: /* WM_MOUSEHWHEEL */
  207076. doMouseWheel (wParam, false);
  207077. return 0;
  207078. case WM_WINDOWPOSCHANGING:
  207079. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  207080. {
  207081. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  207082. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  207083. {
  207084. if (constrainer != 0)
  207085. {
  207086. const Rectangle current (component->getX() - windowBorder.getLeft(),
  207087. component->getY() - windowBorder.getTop(),
  207088. component->getWidth() + windowBorder.getLeftAndRight(),
  207089. component->getHeight() + windowBorder.getTopAndBottom());
  207090. constrainer->checkBounds (wp->x, wp->y, wp->cx, wp->cy,
  207091. current,
  207092. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207093. wp->y != current.getY() && wp->y + wp->cy == current.getBottom(),
  207094. wp->x != current.getX() && wp->x + wp->cx == current.getRight(),
  207095. wp->y == current.getY() && wp->y + wp->cy != current.getBottom(),
  207096. wp->x == current.getX() && wp->x + wp->cx != current.getRight());
  207097. }
  207098. }
  207099. }
  207100. return 0;
  207101. case WM_WINDOWPOSCHANGED:
  207102. handleMovedOrResized();
  207103. if (dontRepaint)
  207104. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  207105. else
  207106. return 0;
  207107. case WM_KEYDOWN:
  207108. case WM_SYSKEYDOWN:
  207109. if (doKeyDown (wParam))
  207110. return 0;
  207111. break;
  207112. case WM_KEYUP:
  207113. case WM_SYSKEYUP:
  207114. if (doKeyUp (wParam))
  207115. return 0;
  207116. break;
  207117. case WM_CHAR:
  207118. if (doKeyChar ((int) wParam, lParam))
  207119. return 0;
  207120. break;
  207121. case WM_APPCOMMAND:
  207122. if (doAppCommand (lParam))
  207123. return TRUE;
  207124. break;
  207125. case WM_SETFOCUS:
  207126. updateKeyModifiers();
  207127. handleFocusGain();
  207128. break;
  207129. case WM_KILLFOCUS:
  207130. if (hasCreatedCaret)
  207131. {
  207132. hasCreatedCaret = false;
  207133. DestroyCaret();
  207134. }
  207135. handleFocusLoss();
  207136. break;
  207137. case WM_ACTIVATEAPP:
  207138. // Windows does weird things to process priority when you swap apps,
  207139. // so this forces an update when the app is brought to the front
  207140. if (wParam != FALSE)
  207141. juce_repeatLastProcessPriority();
  207142. juce_CheckCurrentlyFocusedTopLevelWindow();
  207143. modifiersAtLastCallback = -1;
  207144. return 0;
  207145. case WM_ACTIVATE:
  207146. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  207147. {
  207148. modifiersAtLastCallback = -1;
  207149. updateKeyModifiers();
  207150. if (isMinimised())
  207151. {
  207152. component->repaint();
  207153. handleMovedOrResized();
  207154. if (! isValidMessageListener())
  207155. return 0;
  207156. }
  207157. if (LOWORD (wParam) == WA_CLICKACTIVE
  207158. && component->isCurrentlyBlockedByAnotherModalComponent())
  207159. {
  207160. int mx, my;
  207161. component->getMouseXYRelative (mx, my);
  207162. Component* const underMouse = component->getComponentAt (mx, my);
  207163. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  207164. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  207165. return 0;
  207166. }
  207167. handleBroughtToFront();
  207168. return 0;
  207169. }
  207170. break;
  207171. case WM_NCACTIVATE:
  207172. // while a temporary window is being shown, prevent Windows from deactivating the
  207173. // title bars of our main windows.
  207174. if (wParam == 0 && ! shouldDeactivateTitleBar)
  207175. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  207176. break;
  207177. case WM_MOUSEACTIVATE:
  207178. if (! component->getMouseClickGrabsKeyboardFocus())
  207179. return MA_NOACTIVATE;
  207180. break;
  207181. case WM_SHOWWINDOW:
  207182. if (wParam != 0)
  207183. handleBroughtToFront();
  207184. break;
  207185. case WM_CLOSE:
  207186. handleUserClosingWindow();
  207187. return 0;
  207188. case WM_QUIT:
  207189. JUCEApplication::quit();
  207190. return 0;
  207191. case WM_TRAYNOTIFY:
  207192. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207193. {
  207194. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  207195. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207196. {
  207197. Component* const current = Component::getCurrentlyModalComponent();
  207198. if (current != 0)
  207199. current->inputAttemptWhenModal();
  207200. }
  207201. }
  207202. else
  207203. {
  207204. const int oldModifiers = currentModifiers;
  207205. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  207206. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  207207. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  207208. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  207209. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  207210. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  207211. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  207212. {
  207213. SetFocus (hwnd);
  207214. SetForegroundWindow (hwnd);
  207215. component->mouseDown (e);
  207216. }
  207217. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207218. {
  207219. e.mods = ModifierKeys (oldModifiers);
  207220. component->mouseUp (e);
  207221. }
  207222. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207223. {
  207224. e.mods = ModifierKeys (oldModifiers);
  207225. component->mouseDoubleClick (e);
  207226. }
  207227. else if (lParam == WM_MOUSEMOVE)
  207228. {
  207229. component->mouseMove (e);
  207230. }
  207231. }
  207232. break;
  207233. case WM_SYNCPAINT:
  207234. return 0;
  207235. case WM_PALETTECHANGED:
  207236. InvalidateRect (h, 0, 0);
  207237. break;
  207238. case WM_DISPLAYCHANGE:
  207239. InvalidateRect (h, 0, 0);
  207240. createPaletteIfNeeded = true;
  207241. // intentional fall-through...
  207242. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  207243. doSettingChange();
  207244. break;
  207245. case WM_INITMENU:
  207246. if (! hasTitleBar())
  207247. {
  207248. if (isFullScreen())
  207249. {
  207250. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  207251. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  207252. }
  207253. else if (! isMinimised())
  207254. {
  207255. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  207256. }
  207257. }
  207258. break;
  207259. case WM_SYSCOMMAND:
  207260. switch (wParam & 0xfff0)
  207261. {
  207262. case SC_CLOSE:
  207263. if (hasTitleBar())
  207264. {
  207265. PostMessage (h, WM_CLOSE, 0, 0);
  207266. return 0;
  207267. }
  207268. break;
  207269. case SC_KEYMENU:
  207270. if (hasTitleBar() && h == GetCapture())
  207271. ReleaseCapture();
  207272. break;
  207273. case SC_MAXIMIZE:
  207274. setFullScreen (true);
  207275. return 0;
  207276. case SC_MINIMIZE:
  207277. if (! hasTitleBar())
  207278. {
  207279. setMinimised (true);
  207280. return 0;
  207281. }
  207282. break;
  207283. case SC_RESTORE:
  207284. if (hasTitleBar())
  207285. {
  207286. if (isFullScreen())
  207287. {
  207288. setFullScreen (false);
  207289. return 0;
  207290. }
  207291. }
  207292. else
  207293. {
  207294. if (isMinimised())
  207295. setMinimised (false);
  207296. else if (isFullScreen())
  207297. setFullScreen (false);
  207298. return 0;
  207299. }
  207300. break;
  207301. case SC_MONITORPOWER:
  207302. case SC_SCREENSAVE:
  207303. if (! screenSaverAllowed)
  207304. return 0;
  207305. break;
  207306. }
  207307. break;
  207308. case WM_NCLBUTTONDOWN:
  207309. case WM_NCRBUTTONDOWN:
  207310. case WM_NCMBUTTONDOWN:
  207311. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207312. {
  207313. Component* const current = Component::getCurrentlyModalComponent();
  207314. if (current != 0)
  207315. current->inputAttemptWhenModal();
  207316. }
  207317. break;
  207318. //case WM_IME_STARTCOMPOSITION;
  207319. // return 0;
  207320. case WM_GETDLGCODE:
  207321. return DLGC_WANTALLKEYS;
  207322. default:
  207323. break;
  207324. }
  207325. }
  207326. }
  207327. // (the message manager lock exits before calling this, to avoid deadlocks if
  207328. // this calls into non-juce windows)
  207329. return DefWindowProc (h, message, wParam, lParam);
  207330. }
  207331. Win32ComponentPeer (const Win32ComponentPeer&);
  207332. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  207333. };
  207334. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  207335. {
  207336. return new Win32ComponentPeer (this, styleFlags);
  207337. }
  207338. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  207339. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  207340. {
  207341. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  207342. if (wp != 0)
  207343. wp->setTaskBarIcon (&newImage);
  207344. }
  207345. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  207346. {
  207347. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  207348. if (wp != 0)
  207349. wp->setTaskBarIconToolTip (tooltip);
  207350. }
  207351. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  207352. {
  207353. DWORD val = GetWindowLong (h, styleType);
  207354. if (bitIsSet)
  207355. val |= feature;
  207356. else
  207357. val &= ~feature;
  207358. SetWindowLongPtr (h, styleType, val);
  207359. SetWindowPos (h, 0, 0, 0, 0, 0,
  207360. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  207361. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  207362. }
  207363. bool Process::isForegroundProcess() throw()
  207364. {
  207365. HWND fg = GetForegroundWindow();
  207366. if (fg == 0)
  207367. return true;
  207368. DWORD processId = 0;
  207369. GetWindowThreadProcessId (fg, &processId);
  207370. return processId == GetCurrentProcessId();
  207371. }
  207372. void Desktop::getMousePosition (int& x, int& y) throw()
  207373. {
  207374. POINT mousePos;
  207375. GetCursorPos (&mousePos);
  207376. x = mousePos.x;
  207377. y = mousePos.y;
  207378. }
  207379. void Desktop::setMousePosition (int x, int y) throw()
  207380. {
  207381. SetCursorPos (x, y);
  207382. }
  207383. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  207384. {
  207385. screenSaverAllowed = isEnabled;
  207386. }
  207387. bool Desktop::isScreenSaverEnabled() throw()
  207388. {
  207389. return screenSaverAllowed;
  207390. }
  207391. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  207392. {
  207393. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  207394. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  207395. return TRUE;
  207396. }
  207397. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  207398. {
  207399. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  207400. // make sure the first in the list is the main monitor
  207401. for (int i = 1; i < monitorCoords.size(); ++i)
  207402. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  207403. monitorCoords.swap (i, 0);
  207404. if (monitorCoords.size() == 0)
  207405. {
  207406. RECT r;
  207407. GetWindowRect (GetDesktopWindow(), &r);
  207408. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207409. }
  207410. if (clipToWorkArea)
  207411. {
  207412. // clip the main monitor to the active non-taskbar area
  207413. RECT r;
  207414. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  207415. Rectangle& screen = monitorCoords.getReference (0);
  207416. screen.setPosition (jmax (screen.getX(), r.left),
  207417. jmax (screen.getY(), r.top));
  207418. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  207419. jmin (screen.getBottom(), r.bottom) - screen.getY());
  207420. }
  207421. }
  207422. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  207423. {
  207424. Image* im = 0;
  207425. if (bitmap != 0)
  207426. {
  207427. BITMAP bm;
  207428. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  207429. && bm.bmWidth > 0 && bm.bmHeight > 0)
  207430. {
  207431. HDC tempDC = GetDC (0);
  207432. HDC dc = CreateCompatibleDC (tempDC);
  207433. ReleaseDC (0, tempDC);
  207434. SelectObject (dc, bitmap);
  207435. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  207436. for (int y = bm.bmHeight; --y >= 0;)
  207437. {
  207438. for (int x = bm.bmWidth; --x >= 0;)
  207439. {
  207440. COLORREF col = GetPixel (dc, x, y);
  207441. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  207442. (uint8) GetGValue (col),
  207443. (uint8) GetBValue (col)));
  207444. }
  207445. }
  207446. DeleteDC (dc);
  207447. }
  207448. }
  207449. return im;
  207450. }
  207451. static Image* createImageFromHICON (HICON icon) throw()
  207452. {
  207453. ICONINFO info;
  207454. if (GetIconInfo (icon, &info))
  207455. {
  207456. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  207457. if (mask == 0)
  207458. return 0;
  207459. Image* const image = createImageFromHBITMAP (info.hbmColor);
  207460. if (image == 0)
  207461. return mask;
  207462. for (int y = image->getHeight(); --y >= 0;)
  207463. {
  207464. for (int x = image->getWidth(); --x >= 0;)
  207465. {
  207466. const float brightness = mask->getPixelAt (x, y).getBrightness();
  207467. if (brightness > 0.0f)
  207468. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  207469. }
  207470. }
  207471. delete mask;
  207472. return image;
  207473. }
  207474. return 0;
  207475. }
  207476. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  207477. {
  207478. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  207479. ICONINFO info;
  207480. info.fIcon = isIcon;
  207481. info.xHotspot = hotspotX;
  207482. info.yHotspot = hotspotY;
  207483. info.hbmMask = mask;
  207484. HICON hi = 0;
  207485. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  207486. {
  207487. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  207488. Graphics g (bitmap);
  207489. g.drawImageAt (&image, 0, 0);
  207490. info.hbmColor = bitmap.hBitmap;
  207491. hi = CreateIconIndirect (&info);
  207492. }
  207493. else
  207494. {
  207495. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  207496. HDC colDC = CreateCompatibleDC (GetDC (0));
  207497. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  207498. SelectObject (colDC, colour);
  207499. SelectObject (alphaDC, mask);
  207500. for (int y = image.getHeight(); --y >= 0;)
  207501. {
  207502. for (int x = image.getWidth(); --x >= 0;)
  207503. {
  207504. const Colour c (image.getPixelAt (x, y));
  207505. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  207506. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  207507. }
  207508. }
  207509. DeleteDC (colDC);
  207510. DeleteDC (alphaDC);
  207511. info.hbmColor = colour;
  207512. hi = CreateIconIndirect (&info);
  207513. DeleteObject (colour);
  207514. }
  207515. DeleteObject (mask);
  207516. return hi;
  207517. }
  207518. Image* juce_createIconForFile (const File& file)
  207519. {
  207520. Image* image = 0;
  207521. TCHAR filename [1024];
  207522. file.getFullPathName().copyToBuffer (filename, 1023);
  207523. WORD iconNum = 0;
  207524. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  207525. filename, &iconNum);
  207526. if (icon != 0)
  207527. {
  207528. image = createImageFromHICON (icon);
  207529. DestroyIcon (icon);
  207530. }
  207531. return image;
  207532. }
  207533. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  207534. {
  207535. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  207536. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  207537. const Image* im = &image;
  207538. Image* newIm = 0;
  207539. if (image.getWidth() > maxW || image.getHeight() > maxH)
  207540. {
  207541. im = newIm = image.createCopy (maxW, maxH);
  207542. hotspotX = (hotspotX * maxW) / image.getWidth();
  207543. hotspotY = (hotspotY * maxH) / image.getHeight();
  207544. }
  207545. void* cursorH = 0;
  207546. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  207547. if (os == SystemStats::WinXP)
  207548. {
  207549. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  207550. }
  207551. else
  207552. {
  207553. const int stride = (maxW + 7) >> 3;
  207554. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  207555. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  207556. int index = 0;
  207557. for (int y = 0; y < maxH; ++y)
  207558. {
  207559. for (int x = 0; x < maxW; ++x)
  207560. {
  207561. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  207562. const Colour pixelColour (im->getPixelAt (x, y));
  207563. if (pixelColour.getAlpha() < 127)
  207564. andPlane [index + (x >> 3)] |= bit;
  207565. else if (pixelColour.getBrightness() >= 0.5f)
  207566. xorPlane [index + (x >> 3)] |= bit;
  207567. }
  207568. index += stride;
  207569. }
  207570. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  207571. juce_free (andPlane);
  207572. juce_free (xorPlane);
  207573. }
  207574. delete newIm;
  207575. return cursorH;
  207576. }
  207577. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  207578. {
  207579. if (cursorHandle != 0 && ! isStandard)
  207580. DestroyCursor ((HCURSOR) cursorHandle);
  207581. }
  207582. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  207583. {
  207584. LPCTSTR cursorName = IDC_ARROW;
  207585. switch (type)
  207586. {
  207587. case MouseCursor::NormalCursor:
  207588. cursorName = IDC_ARROW;
  207589. break;
  207590. case MouseCursor::NoCursor:
  207591. return 0;
  207592. case MouseCursor::DraggingHandCursor:
  207593. {
  207594. static void* dragHandCursor = 0;
  207595. if (dragHandCursor == 0)
  207596. {
  207597. static const unsigned char dragHandData[] =
  207598. { 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,
  207599. 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,
  207600. 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 };
  207601. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  207602. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  207603. delete image;
  207604. }
  207605. return dragHandCursor;
  207606. }
  207607. case MouseCursor::WaitCursor:
  207608. cursorName = IDC_WAIT;
  207609. break;
  207610. case MouseCursor::IBeamCursor:
  207611. cursorName = IDC_IBEAM;
  207612. break;
  207613. case MouseCursor::PointingHandCursor:
  207614. cursorName = MAKEINTRESOURCE(32649);
  207615. break;
  207616. case MouseCursor::LeftRightResizeCursor:
  207617. case MouseCursor::LeftEdgeResizeCursor:
  207618. case MouseCursor::RightEdgeResizeCursor:
  207619. cursorName = IDC_SIZEWE;
  207620. break;
  207621. case MouseCursor::UpDownResizeCursor:
  207622. case MouseCursor::TopEdgeResizeCursor:
  207623. case MouseCursor::BottomEdgeResizeCursor:
  207624. cursorName = IDC_SIZENS;
  207625. break;
  207626. case MouseCursor::TopLeftCornerResizeCursor:
  207627. case MouseCursor::BottomRightCornerResizeCursor:
  207628. cursorName = IDC_SIZENWSE;
  207629. break;
  207630. case MouseCursor::TopRightCornerResizeCursor:
  207631. case MouseCursor::BottomLeftCornerResizeCursor:
  207632. cursorName = IDC_SIZENESW;
  207633. break;
  207634. case MouseCursor::UpDownLeftRightResizeCursor:
  207635. cursorName = IDC_SIZEALL;
  207636. break;
  207637. case MouseCursor::CrosshairCursor:
  207638. cursorName = IDC_CROSS;
  207639. break;
  207640. case MouseCursor::CopyingCursor:
  207641. // can't seem to find one of these in the win32 list..
  207642. break;
  207643. }
  207644. HCURSOR cursorH = LoadCursor (0, cursorName);
  207645. if (cursorH == 0)
  207646. cursorH = LoadCursor (0, IDC_ARROW);
  207647. return (void*) cursorH;
  207648. }
  207649. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  207650. {
  207651. SetCursor ((HCURSOR) getHandle());
  207652. }
  207653. void MouseCursor::showInAllWindows() const throw()
  207654. {
  207655. showInWindow (0);
  207656. }
  207657. class JuceDropSource : public IDropSource
  207658. {
  207659. int refCount;
  207660. public:
  207661. JuceDropSource()
  207662. : refCount (1)
  207663. {
  207664. }
  207665. virtual ~JuceDropSource()
  207666. {
  207667. jassert (refCount == 0);
  207668. }
  207669. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207670. {
  207671. if (id == IID_IUnknown || id == IID_IDropSource)
  207672. {
  207673. AddRef();
  207674. *result = this;
  207675. return S_OK;
  207676. }
  207677. *result = 0;
  207678. return E_NOINTERFACE;
  207679. }
  207680. ULONG __stdcall AddRef() { return ++refCount; }
  207681. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  207682. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  207683. {
  207684. if (escapePressed)
  207685. return DRAGDROP_S_CANCEL;
  207686. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  207687. return DRAGDROP_S_DROP;
  207688. return S_OK;
  207689. }
  207690. HRESULT __stdcall GiveFeedback (DWORD)
  207691. {
  207692. return DRAGDROP_S_USEDEFAULTCURSORS;
  207693. }
  207694. };
  207695. class JuceEnumFormatEtc : public IEnumFORMATETC
  207696. {
  207697. public:
  207698. JuceEnumFormatEtc (const FORMATETC* const format_)
  207699. : refCount (1),
  207700. format (format_),
  207701. index (0)
  207702. {
  207703. }
  207704. virtual ~JuceEnumFormatEtc()
  207705. {
  207706. jassert (refCount == 0);
  207707. }
  207708. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207709. {
  207710. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  207711. {
  207712. AddRef();
  207713. *result = this;
  207714. return S_OK;
  207715. }
  207716. *result = 0;
  207717. return E_NOINTERFACE;
  207718. }
  207719. ULONG __stdcall AddRef() { return ++refCount; }
  207720. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  207721. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  207722. {
  207723. if (result == 0)
  207724. return E_POINTER;
  207725. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  207726. newOne->index = index;
  207727. *result = newOne;
  207728. return S_OK;
  207729. }
  207730. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  207731. {
  207732. if (pceltFetched != 0)
  207733. *pceltFetched = 0;
  207734. else if (celt != 1)
  207735. return S_FALSE;
  207736. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  207737. {
  207738. copyFormatEtc (lpFormatEtc [0], *format);
  207739. ++index;
  207740. if (pceltFetched != 0)
  207741. *pceltFetched = 1;
  207742. return S_OK;
  207743. }
  207744. return S_FALSE;
  207745. }
  207746. HRESULT __stdcall Skip (ULONG celt)
  207747. {
  207748. if (index + (int) celt >= 1)
  207749. return S_FALSE;
  207750. index += celt;
  207751. return S_OK;
  207752. }
  207753. HRESULT __stdcall Reset()
  207754. {
  207755. index = 0;
  207756. return S_OK;
  207757. }
  207758. private:
  207759. int refCount;
  207760. const FORMATETC* const format;
  207761. int index;
  207762. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  207763. {
  207764. dest = source;
  207765. if (source.ptd != 0)
  207766. {
  207767. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  207768. *(dest.ptd) = *(source.ptd);
  207769. }
  207770. }
  207771. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  207772. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  207773. };
  207774. class JuceDataObject : public IDataObject
  207775. {
  207776. JuceDropSource* const dropSource;
  207777. const FORMATETC* const format;
  207778. const STGMEDIUM* const medium;
  207779. int refCount;
  207780. JuceDataObject (const JuceDataObject&);
  207781. const JuceDataObject& operator= (const JuceDataObject&);
  207782. public:
  207783. JuceDataObject (JuceDropSource* const dropSource_,
  207784. const FORMATETC* const format_,
  207785. const STGMEDIUM* const medium_)
  207786. : dropSource (dropSource_),
  207787. format (format_),
  207788. medium (medium_),
  207789. refCount (1)
  207790. {
  207791. }
  207792. virtual ~JuceDataObject()
  207793. {
  207794. jassert (refCount == 0);
  207795. }
  207796. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207797. {
  207798. if (id == IID_IUnknown || id == IID_IDataObject)
  207799. {
  207800. AddRef();
  207801. *result = this;
  207802. return S_OK;
  207803. }
  207804. *result = 0;
  207805. return E_NOINTERFACE;
  207806. }
  207807. ULONG __stdcall AddRef() { return ++refCount; }
  207808. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  207809. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  207810. {
  207811. if (pFormatEtc->tymed == format->tymed
  207812. && pFormatEtc->cfFormat == format->cfFormat
  207813. && pFormatEtc->dwAspect == format->dwAspect)
  207814. {
  207815. pMedium->tymed = format->tymed;
  207816. pMedium->pUnkForRelease = 0;
  207817. if (format->tymed == TYMED_HGLOBAL)
  207818. {
  207819. const SIZE_T len = GlobalSize (medium->hGlobal);
  207820. void* const src = GlobalLock (medium->hGlobal);
  207821. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  207822. memcpy (dst, src, len);
  207823. GlobalUnlock (medium->hGlobal);
  207824. pMedium->hGlobal = dst;
  207825. return S_OK;
  207826. }
  207827. }
  207828. return DV_E_FORMATETC;
  207829. }
  207830. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  207831. {
  207832. if (f == 0)
  207833. return E_INVALIDARG;
  207834. if (f->tymed == format->tymed
  207835. && f->cfFormat == format->cfFormat
  207836. && f->dwAspect == format->dwAspect)
  207837. return S_OK;
  207838. return DV_E_FORMATETC;
  207839. }
  207840. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  207841. {
  207842. pFormatEtcOut->ptd = 0;
  207843. return E_NOTIMPL;
  207844. }
  207845. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  207846. {
  207847. if (result == 0)
  207848. return E_POINTER;
  207849. if (direction == DATADIR_GET)
  207850. {
  207851. *result = new JuceEnumFormatEtc (format);
  207852. return S_OK;
  207853. }
  207854. *result = 0;
  207855. return E_NOTIMPL;
  207856. }
  207857. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  207858. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  207859. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  207860. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  207861. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  207862. };
  207863. static HDROP createHDrop (const StringArray& fileNames) throw()
  207864. {
  207865. int totalChars = 0;
  207866. for (int i = fileNames.size(); --i >= 0;)
  207867. totalChars += fileNames[i].length() + 1;
  207868. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  207869. sizeof (DROPFILES)
  207870. + sizeof (WCHAR) * (totalChars + 2));
  207871. if (hDrop != 0)
  207872. {
  207873. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  207874. pDropFiles->pFiles = sizeof (DROPFILES);
  207875. pDropFiles->fWide = true;
  207876. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  207877. for (int i = 0; i < fileNames.size(); ++i)
  207878. {
  207879. fileNames[i].copyToBuffer (fname, 2048);
  207880. fname += fileNames[i].length() + 1;
  207881. }
  207882. *fname = 0;
  207883. GlobalUnlock (hDrop);
  207884. }
  207885. return hDrop;
  207886. }
  207887. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  207888. {
  207889. JuceDropSource* const source = new JuceDropSource();
  207890. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  207891. DWORD effect;
  207892. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  207893. data->Release();
  207894. source->Release();
  207895. return res == DRAGDROP_S_DROP;
  207896. }
  207897. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  207898. {
  207899. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207900. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207901. medium.hGlobal = createHDrop (files);
  207902. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  207903. : DROPEFFECT_COPY);
  207904. }
  207905. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  207906. {
  207907. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207908. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207909. const int numChars = text.length();
  207910. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  207911. char* d = (char*) GlobalLock (medium.hGlobal);
  207912. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  207913. format.cfFormat = CF_UNICODETEXT;
  207914. GlobalUnlock (medium.hGlobal);
  207915. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  207916. }
  207917. #if JUCE_OPENGL
  207918. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  207919. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  207920. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  207921. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  207922. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  207923. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  207924. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  207925. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  207926. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  207927. #define WGL_ACCELERATION_ARB 0x2003
  207928. #define WGL_SWAP_METHOD_ARB 0x2007
  207929. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  207930. #define WGL_PIXEL_TYPE_ARB 0x2013
  207931. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  207932. #define WGL_COLOR_BITS_ARB 0x2014
  207933. #define WGL_RED_BITS_ARB 0x2015
  207934. #define WGL_GREEN_BITS_ARB 0x2017
  207935. #define WGL_BLUE_BITS_ARB 0x2019
  207936. #define WGL_ALPHA_BITS_ARB 0x201B
  207937. #define WGL_DEPTH_BITS_ARB 0x2022
  207938. #define WGL_STENCIL_BITS_ARB 0x2023
  207939. #define WGL_FULL_ACCELERATION_ARB 0x2027
  207940. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  207941. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  207942. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  207943. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  207944. #define WGL_STEREO_ARB 0x2012
  207945. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  207946. #define WGL_SAMPLES_ARB 0x2042
  207947. #define WGL_TYPE_RGBA_ARB 0x202B
  207948. static void getWglExtensions (HDC dc, StringArray& result) throw()
  207949. {
  207950. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  207951. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  207952. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  207953. else
  207954. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  207955. }
  207956. class WindowedGLContext : public OpenGLContext
  207957. {
  207958. public:
  207959. WindowedGLContext (Component* const component_,
  207960. HGLRC contextToShareWith,
  207961. const OpenGLPixelFormat& pixelFormat)
  207962. : renderContext (0),
  207963. nativeWindow (0),
  207964. dc (0),
  207965. component (component_)
  207966. {
  207967. jassert (component != 0);
  207968. createNativeWindow();
  207969. // Use a default pixel format that should be supported everywhere
  207970. PIXELFORMATDESCRIPTOR pfd;
  207971. zerostruct (pfd);
  207972. pfd.nSize = sizeof (pfd);
  207973. pfd.nVersion = 1;
  207974. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  207975. pfd.iPixelType = PFD_TYPE_RGBA;
  207976. pfd.cColorBits = 24;
  207977. pfd.cDepthBits = 16;
  207978. const int format = ChoosePixelFormat (dc, &pfd);
  207979. if (format != 0)
  207980. SetPixelFormat (dc, format, &pfd);
  207981. renderContext = wglCreateContext (dc);
  207982. makeActive();
  207983. setPixelFormat (pixelFormat);
  207984. if (contextToShareWith != 0 && renderContext != 0)
  207985. wglShareLists (contextToShareWith, renderContext);
  207986. }
  207987. ~WindowedGLContext()
  207988. {
  207989. makeInactive();
  207990. wglDeleteContext (renderContext);
  207991. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  207992. delete nativeWindow;
  207993. }
  207994. bool makeActive() const throw()
  207995. {
  207996. jassert (renderContext != 0);
  207997. return wglMakeCurrent (dc, renderContext) != 0;
  207998. }
  207999. bool makeInactive() const throw()
  208000. {
  208001. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  208002. }
  208003. bool isActive() const throw()
  208004. {
  208005. return wglGetCurrentContext() == renderContext;
  208006. }
  208007. const OpenGLPixelFormat getPixelFormat() const
  208008. {
  208009. OpenGLPixelFormat pf;
  208010. makeActive();
  208011. StringArray availableExtensions;
  208012. getWglExtensions (dc, availableExtensions);
  208013. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  208014. return pf;
  208015. }
  208016. void* getRawContext() const throw()
  208017. {
  208018. return renderContext;
  208019. }
  208020. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  208021. {
  208022. makeActive();
  208023. PIXELFORMATDESCRIPTOR pfd;
  208024. zerostruct (pfd);
  208025. pfd.nSize = sizeof (pfd);
  208026. pfd.nVersion = 1;
  208027. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  208028. pfd.iPixelType = PFD_TYPE_RGBA;
  208029. pfd.iLayerType = PFD_MAIN_PLANE;
  208030. pfd.cColorBits = pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits;
  208031. pfd.cRedBits = pixelFormat.redBits;
  208032. pfd.cGreenBits = pixelFormat.greenBits;
  208033. pfd.cBlueBits = pixelFormat.blueBits;
  208034. pfd.cAlphaBits = pixelFormat.alphaBits;
  208035. pfd.cDepthBits = pixelFormat.depthBufferBits;
  208036. pfd.cStencilBits = pixelFormat.stencilBufferBits;
  208037. pfd.cAccumBits = pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  208038. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits;
  208039. pfd.cAccumRedBits = pixelFormat.accumulationBufferRedBits;
  208040. pfd.cAccumGreenBits = pixelFormat.accumulationBufferGreenBits;
  208041. pfd.cAccumBlueBits = pixelFormat.accumulationBufferBlueBits;
  208042. pfd.cAccumAlphaBits = pixelFormat.accumulationBufferAlphaBits;
  208043. int format = 0;
  208044. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  208045. StringArray availableExtensions;
  208046. getWglExtensions (dc, availableExtensions);
  208047. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208048. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  208049. {
  208050. int attributes[64];
  208051. int n = 0;
  208052. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  208053. attributes[n++] = GL_TRUE;
  208054. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  208055. attributes[n++] = GL_TRUE;
  208056. attributes[n++] = WGL_ACCELERATION_ARB;
  208057. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  208058. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  208059. attributes[n++] = GL_TRUE;
  208060. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  208061. attributes[n++] = WGL_TYPE_RGBA_ARB;
  208062. attributes[n++] = WGL_COLOR_BITS_ARB;
  208063. attributes[n++] = pfd.cColorBits;
  208064. attributes[n++] = WGL_RED_BITS_ARB;
  208065. attributes[n++] = pixelFormat.redBits;
  208066. attributes[n++] = WGL_GREEN_BITS_ARB;
  208067. attributes[n++] = pixelFormat.greenBits;
  208068. attributes[n++] = WGL_BLUE_BITS_ARB;
  208069. attributes[n++] = pixelFormat.blueBits;
  208070. attributes[n++] = WGL_ALPHA_BITS_ARB;
  208071. attributes[n++] = pixelFormat.alphaBits;
  208072. attributes[n++] = WGL_DEPTH_BITS_ARB;
  208073. attributes[n++] = pixelFormat.depthBufferBits;
  208074. if (pixelFormat.stencilBufferBits > 0)
  208075. {
  208076. attributes[n++] = WGL_STENCIL_BITS_ARB;
  208077. attributes[n++] = pixelFormat.stencilBufferBits;
  208078. }
  208079. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  208080. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  208081. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  208082. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  208083. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  208084. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  208085. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208086. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  208087. if (availableExtensions.contains ("WGL_ARB_multisample")
  208088. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  208089. {
  208090. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  208091. attributes[n++] = 1;
  208092. attributes[n++] = WGL_SAMPLES_ARB;
  208093. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  208094. }
  208095. attributes[n++] = 0;
  208096. UINT formatsCount;
  208097. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  208098. (void) ok;
  208099. jassert (ok);
  208100. }
  208101. else
  208102. {
  208103. format = ChoosePixelFormat (dc, &pfd);
  208104. }
  208105. if (format != 0)
  208106. {
  208107. makeInactive();
  208108. // win32 can't change the pixel format of a window, so need to delete the
  208109. // old one and create a new one..
  208110. jassert (nativeWindow != 0);
  208111. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208112. delete nativeWindow;
  208113. createNativeWindow();
  208114. if (SetPixelFormat (dc, format, &pfd))
  208115. {
  208116. wglDeleteContext (renderContext);
  208117. renderContext = wglCreateContext (dc);
  208118. jassert (renderContext != 0);
  208119. return renderContext != 0;
  208120. }
  208121. }
  208122. return false;
  208123. }
  208124. void updateWindowPosition (int x, int y, int w, int h, int)
  208125. {
  208126. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  208127. x, y, w, h,
  208128. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  208129. }
  208130. void repaint()
  208131. {
  208132. int x, y, w, h;
  208133. nativeWindow->getBounds (x, y, w, h);
  208134. nativeWindow->repaint (0, 0, w, h);
  208135. }
  208136. void swapBuffers()
  208137. {
  208138. SwapBuffers (dc);
  208139. }
  208140. bool setSwapInterval (const int numFramesPerSwap)
  208141. {
  208142. makeActive();
  208143. StringArray availableExtensions;
  208144. getWglExtensions (dc, availableExtensions);
  208145. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  208146. return availableExtensions.contains ("WGL_EXT_swap_control")
  208147. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  208148. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  208149. }
  208150. int getSwapInterval() const
  208151. {
  208152. makeActive();
  208153. StringArray availableExtensions;
  208154. getWglExtensions (dc, availableExtensions);
  208155. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  208156. if (availableExtensions.contains ("WGL_EXT_swap_control")
  208157. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  208158. return wglGetSwapIntervalEXT();
  208159. return 0;
  208160. }
  208161. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  208162. {
  208163. jassert (isActive());
  208164. StringArray availableExtensions;
  208165. getWglExtensions (dc, availableExtensions);
  208166. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208167. int numTypes = 0;
  208168. if (availableExtensions.contains("WGL_ARB_pixel_format")
  208169. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208170. {
  208171. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  208172. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  208173. jassertfalse
  208174. }
  208175. else
  208176. {
  208177. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  208178. }
  208179. OpenGLPixelFormat pf;
  208180. for (int i = 0; i < numTypes; ++i)
  208181. {
  208182. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  208183. {
  208184. bool alreadyListed = false;
  208185. for (int j = results.size(); --j >= 0;)
  208186. if (pf == *results.getUnchecked(j))
  208187. alreadyListed = true;
  208188. if (! alreadyListed)
  208189. results.add (new OpenGLPixelFormat (pf));
  208190. }
  208191. }
  208192. }
  208193. juce_UseDebuggingNewOperator
  208194. HGLRC renderContext;
  208195. private:
  208196. Win32ComponentPeer* nativeWindow;
  208197. Component* const component;
  208198. HDC dc;
  208199. void createNativeWindow()
  208200. {
  208201. nativeWindow = new Win32ComponentPeer (component, 0);
  208202. nativeWindow->dontRepaint = true;
  208203. nativeWindow->setVisible (true);
  208204. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  208205. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  208206. if (peer != 0)
  208207. {
  208208. SetParent (hwnd, (HWND) peer->getNativeHandle());
  208209. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  208210. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  208211. }
  208212. dc = GetDC (hwnd);
  208213. }
  208214. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  208215. OpenGLPixelFormat& result,
  208216. const StringArray& availableExtensions) const throw()
  208217. {
  208218. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208219. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208220. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208221. {
  208222. int attributes[32];
  208223. int numAttributes = 0;
  208224. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  208225. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  208226. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  208227. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  208228. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  208229. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  208230. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  208231. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  208232. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  208233. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  208234. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  208235. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  208236. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  208237. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  208238. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208239. if (availableExtensions.contains ("WGL_ARB_multisample"))
  208240. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  208241. int values[32];
  208242. zeromem (values, sizeof (values));
  208243. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  208244. {
  208245. int n = 0;
  208246. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  208247. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  208248. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  208249. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  208250. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  208251. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  208252. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  208253. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  208254. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  208255. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  208256. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  208257. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  208258. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  208259. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  208260. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  208261. result.fullSceneAntiAliasingNumSamples = values[n++]; // WGL_SAMPLES_ARB
  208262. return isValidFormat;
  208263. }
  208264. else
  208265. {
  208266. jassertfalse
  208267. }
  208268. }
  208269. else
  208270. {
  208271. PIXELFORMATDESCRIPTOR pfd;
  208272. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  208273. {
  208274. result.redBits = pfd.cRedBits;
  208275. result.greenBits = pfd.cGreenBits;
  208276. result.blueBits = pfd.cBlueBits;
  208277. result.alphaBits = pfd.cAlphaBits;
  208278. result.depthBufferBits = pfd.cDepthBits;
  208279. result.stencilBufferBits = pfd.cStencilBits;
  208280. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  208281. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  208282. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  208283. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  208284. result.fullSceneAntiAliasingNumSamples = 0;
  208285. return true;
  208286. }
  208287. else
  208288. {
  208289. jassertfalse
  208290. }
  208291. }
  208292. return false;
  208293. }
  208294. WindowedGLContext (const WindowedGLContext&);
  208295. const WindowedGLContext& operator= (const WindowedGLContext&);
  208296. };
  208297. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  208298. const OpenGLPixelFormat& pixelFormat,
  208299. const OpenGLContext* const contextToShareWith)
  208300. {
  208301. WindowedGLContext* c = new WindowedGLContext (component,
  208302. contextToShareWith != 0 ? (HGLRC) contextToShareWith->getRawContext() : 0,
  208303. pixelFormat);
  208304. if (c->renderContext == 0)
  208305. deleteAndZero (c);
  208306. return c;
  208307. }
  208308. void juce_glViewport (const int w, const int h)
  208309. {
  208310. glViewport (0, 0, w, h);
  208311. }
  208312. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  208313. OwnedArray <OpenGLPixelFormat>& results)
  208314. {
  208315. Component tempComp;
  208316. {
  208317. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  208318. wc.makeActive();
  208319. wc.findAlternativeOpenGLPixelFormats (results);
  208320. }
  208321. }
  208322. #endif
  208323. class JuceIStorage : public IStorage
  208324. {
  208325. int refCount;
  208326. public:
  208327. JuceIStorage() : refCount (1) {}
  208328. virtual ~JuceIStorage()
  208329. {
  208330. jassert (refCount == 0);
  208331. }
  208332. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  208333. {
  208334. if (id == IID_IUnknown || id == IID_IStorage)
  208335. {
  208336. AddRef();
  208337. *result = this;
  208338. return S_OK;
  208339. }
  208340. *result = 0;
  208341. return E_NOINTERFACE;
  208342. }
  208343. ULONG __stdcall AddRef() { return ++refCount; }
  208344. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  208345. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208346. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208347. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  208348. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  208349. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  208350. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  208351. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  208352. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  208353. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  208354. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  208355. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  208356. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  208357. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  208358. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  208359. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  208360. juce_UseDebuggingNewOperator
  208361. };
  208362. class JuceOleInPlaceFrame : public IOleInPlaceFrame
  208363. {
  208364. int refCount;
  208365. HWND window;
  208366. public:
  208367. JuceOleInPlaceFrame (HWND window_)
  208368. : refCount (1),
  208369. window (window_)
  208370. {
  208371. }
  208372. virtual ~JuceOleInPlaceFrame()
  208373. {
  208374. jassert (refCount == 0);
  208375. }
  208376. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  208377. {
  208378. if (id == IID_IUnknown || id == IID_IOleInPlaceFrame)
  208379. {
  208380. AddRef();
  208381. *result = this;
  208382. return S_OK;
  208383. }
  208384. *result = 0;
  208385. return E_NOINTERFACE;
  208386. }
  208387. ULONG __stdcall AddRef() { return ++refCount; }
  208388. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  208389. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208390. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208391. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  208392. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208393. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208394. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  208395. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  208396. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  208397. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  208398. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  208399. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  208400. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  208401. juce_UseDebuggingNewOperator
  208402. };
  208403. class JuceIOleInPlaceSite : public IOleInPlaceSite
  208404. {
  208405. int refCount;
  208406. HWND window;
  208407. JuceOleInPlaceFrame* frame;
  208408. public:
  208409. JuceIOleInPlaceSite (HWND window_)
  208410. : refCount (1),
  208411. window (window_)
  208412. {
  208413. frame = new JuceOleInPlaceFrame (window);
  208414. }
  208415. virtual ~JuceIOleInPlaceSite()
  208416. {
  208417. jassert (refCount == 0);
  208418. frame->Release();
  208419. }
  208420. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  208421. {
  208422. if (id == IID_IUnknown || id == IID_IOleInPlaceSite)
  208423. {
  208424. AddRef();
  208425. *result = this;
  208426. return S_OK;
  208427. }
  208428. *result = 0;
  208429. return E_NOINTERFACE;
  208430. }
  208431. ULONG __stdcall AddRef() { return ++refCount; }
  208432. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  208433. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208434. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208435. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  208436. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  208437. HRESULT __stdcall OnUIActivate() { return S_OK; }
  208438. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  208439. {
  208440. frame->AddRef();
  208441. *lplpFrame = frame;
  208442. *lplpDoc = 0;
  208443. lpFrameInfo->fMDIApp = FALSE;
  208444. lpFrameInfo->hwndFrame = window;
  208445. lpFrameInfo->haccel = 0;
  208446. lpFrameInfo->cAccelEntries = 0;
  208447. return S_OK;
  208448. }
  208449. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  208450. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  208451. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  208452. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  208453. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  208454. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  208455. juce_UseDebuggingNewOperator
  208456. };
  208457. class JuceIOleClientSite : public IOleClientSite
  208458. {
  208459. int refCount;
  208460. JuceIOleInPlaceSite* inplaceSite;
  208461. public:
  208462. JuceIOleClientSite (HWND window)
  208463. : refCount (1)
  208464. {
  208465. inplaceSite = new JuceIOleInPlaceSite (window);
  208466. }
  208467. virtual ~JuceIOleClientSite()
  208468. {
  208469. jassert (refCount == 0);
  208470. inplaceSite->Release();
  208471. }
  208472. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  208473. {
  208474. if (id == IID_IUnknown || id == IID_IOleClientSite)
  208475. {
  208476. AddRef();
  208477. *result = this;
  208478. return S_OK;
  208479. }
  208480. else if (id == IID_IOleInPlaceSite)
  208481. {
  208482. inplaceSite->AddRef();
  208483. *result = inplaceSite;
  208484. return S_OK;
  208485. }
  208486. *result = 0;
  208487. return E_NOINTERFACE;
  208488. }
  208489. ULONG __stdcall AddRef() { return ++refCount; }
  208490. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  208491. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  208492. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  208493. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  208494. HRESULT __stdcall ShowObject() { return S_OK; }
  208495. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  208496. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  208497. juce_UseDebuggingNewOperator
  208498. };
  208499. class ActiveXControlData : public ComponentMovementWatcher
  208500. {
  208501. ActiveXControlComponent* const owner;
  208502. bool wasShowing;
  208503. public:
  208504. HWND controlHWND;
  208505. IStorage* storage;
  208506. IOleClientSite* clientSite;
  208507. IOleObject* control;
  208508. ActiveXControlData (HWND hwnd,
  208509. ActiveXControlComponent* const owner_)
  208510. : ComponentMovementWatcher (owner_),
  208511. owner (owner_),
  208512. wasShowing (owner_ != 0 && owner_->isShowing()),
  208513. controlHWND (0),
  208514. storage (new JuceIStorage()),
  208515. clientSite (new JuceIOleClientSite (hwnd)),
  208516. control (0)
  208517. {
  208518. }
  208519. ~ActiveXControlData()
  208520. {
  208521. if (control != 0)
  208522. {
  208523. control->Close (OLECLOSE_NOSAVE);
  208524. control->Release();
  208525. }
  208526. clientSite->Release();
  208527. storage->Release();
  208528. }
  208529. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  208530. {
  208531. Component* const topComp = owner->getTopLevelComponent();
  208532. if (topComp->getPeer() != 0)
  208533. {
  208534. int x = 0, y = 0;
  208535. owner->relativePositionToOtherComponent (topComp, x, y);
  208536. owner->setControlBounds (Rectangle (x, y, owner->getWidth(), owner->getHeight()));
  208537. }
  208538. }
  208539. void componentPeerChanged()
  208540. {
  208541. const bool isShowingNow = owner->isShowing();
  208542. if (wasShowing != isShowingNow)
  208543. {
  208544. wasShowing = isShowingNow;
  208545. owner->setControlVisible (isShowingNow);
  208546. }
  208547. }
  208548. void componentVisibilityChanged (Component&)
  208549. {
  208550. componentPeerChanged();
  208551. }
  208552. static bool doesWindowMatch (const ActiveXControlComponent* const ax, HWND hwnd)
  208553. {
  208554. return ((ActiveXControlData*) ax->control) != 0
  208555. && ((ActiveXControlData*) ax->control)->controlHWND == hwnd;
  208556. }
  208557. };
  208558. static VoidArray activeXComps;
  208559. static HWND getHWND (const ActiveXControlComponent* const component)
  208560. {
  208561. HWND hwnd = 0;
  208562. const IID iid = IID_IOleWindow;
  208563. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  208564. if (window != 0)
  208565. {
  208566. window->GetWindow (&hwnd);
  208567. window->Release();
  208568. }
  208569. return hwnd;
  208570. }
  208571. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  208572. {
  208573. RECT activeXRect, peerRect;
  208574. GetWindowRect (hwnd, &activeXRect);
  208575. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  208576. const int mx = GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left;
  208577. const int my = GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top;
  208578. const int64 mouseEventTime = getMouseEventTime();
  208579. const int oldModifiers = currentModifiers;
  208580. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  208581. switch (message)
  208582. {
  208583. case WM_MOUSEMOVE:
  208584. if (ModifierKeys (currentModifiers).isAnyMouseButtonDown())
  208585. peer->handleMouseDrag (mx, my, mouseEventTime);
  208586. else
  208587. peer->handleMouseMove (mx, my, mouseEventTime);
  208588. break;
  208589. case WM_LBUTTONDOWN:
  208590. case WM_MBUTTONDOWN:
  208591. case WM_RBUTTONDOWN:
  208592. peer->handleMouseDown (mx, my, mouseEventTime);
  208593. break;
  208594. case WM_LBUTTONUP:
  208595. case WM_MBUTTONUP:
  208596. case WM_RBUTTONUP:
  208597. peer->handleMouseUp (oldModifiers, mx, my, mouseEventTime);
  208598. break;
  208599. default:
  208600. break;
  208601. }
  208602. }
  208603. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  208604. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  208605. {
  208606. for (int i = activeXComps.size(); --i >= 0;)
  208607. {
  208608. const ActiveXControlComponent* const ax = (const ActiveXControlComponent*) activeXComps.getUnchecked(i);
  208609. if (ActiveXControlData::doesWindowMatch (ax, hwnd))
  208610. {
  208611. switch (message)
  208612. {
  208613. case WM_MOUSEMOVE:
  208614. case WM_LBUTTONDOWN:
  208615. case WM_MBUTTONDOWN:
  208616. case WM_RBUTTONDOWN:
  208617. case WM_LBUTTONUP:
  208618. case WM_MBUTTONUP:
  208619. case WM_RBUTTONUP:
  208620. case WM_LBUTTONDBLCLK:
  208621. case WM_MBUTTONDBLCLK:
  208622. case WM_RBUTTONDBLCLK:
  208623. if (ax->isShowing())
  208624. {
  208625. ComponentPeer* const peer = ax->getPeer();
  208626. if (peer != 0)
  208627. {
  208628. offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  208629. if (! ax->areMouseEventsAllowed())
  208630. return 0;
  208631. }
  208632. }
  208633. break;
  208634. default:
  208635. break;
  208636. }
  208637. return CallWindowProc ((WNDPROC) (ax->originalWndProc), hwnd, message, wParam, lParam);
  208638. }
  208639. }
  208640. return DefWindowProc (hwnd, message, wParam, lParam);
  208641. }
  208642. ActiveXControlComponent::ActiveXControlComponent()
  208643. : originalWndProc (0),
  208644. control (0),
  208645. mouseEventsAllowed (true)
  208646. {
  208647. activeXComps.add (this);
  208648. }
  208649. ActiveXControlComponent::~ActiveXControlComponent()
  208650. {
  208651. deleteControl();
  208652. activeXComps.removeValue (this);
  208653. }
  208654. void ActiveXControlComponent::paint (Graphics& g)
  208655. {
  208656. if (control == 0)
  208657. g.fillAll (Colours::lightgrey);
  208658. }
  208659. bool ActiveXControlComponent::createControl (const void* controlIID)
  208660. {
  208661. deleteControl();
  208662. ComponentPeer* const peer = getPeer();
  208663. // the component must have already been added to a real window when you call this!
  208664. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  208665. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  208666. {
  208667. int x = 0, y = 0;
  208668. relativePositionToOtherComponent (getTopLevelComponent(), x, y);
  208669. HWND hwnd = (HWND) peer->getNativeHandle();
  208670. ActiveXControlData* const info = new ActiveXControlData (hwnd, this);
  208671. HRESULT hr;
  208672. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  208673. info->clientSite, info->storage,
  208674. (void**) &(info->control))) == S_OK)
  208675. {
  208676. info->control->SetHostNames (L"Juce", 0);
  208677. if (OleSetContainedObject (info->control, TRUE) == S_OK)
  208678. {
  208679. RECT rect;
  208680. rect.left = x;
  208681. rect.top = y;
  208682. rect.right = x + getWidth();
  208683. rect.bottom = y + getHeight();
  208684. if (info->control->DoVerb (OLEIVERB_SHOW, 0, info->clientSite, 0, hwnd, &rect) == S_OK)
  208685. {
  208686. control = info;
  208687. setControlBounds (Rectangle (x, y, getWidth(), getHeight()));
  208688. info->controlHWND = getHWND (this);
  208689. if (info->controlHWND != 0)
  208690. {
  208691. originalWndProc = (void*) GetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC);
  208692. SetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC, (LONG_PTR) activeXHookWndProc);
  208693. }
  208694. return true;
  208695. }
  208696. }
  208697. }
  208698. delete info;
  208699. }
  208700. return false;
  208701. }
  208702. void ActiveXControlComponent::deleteControl()
  208703. {
  208704. ActiveXControlData* const info = (ActiveXControlData*) control;
  208705. if (info != 0)
  208706. {
  208707. delete info;
  208708. control = 0;
  208709. originalWndProc = 0;
  208710. }
  208711. }
  208712. void* ActiveXControlComponent::queryInterface (const void* iid) const
  208713. {
  208714. ActiveXControlData* const info = (ActiveXControlData*) control;
  208715. void* result = 0;
  208716. if (info != 0 && info->control != 0
  208717. && info->control->QueryInterface (*(const IID*) iid, &result) == S_OK)
  208718. return result;
  208719. return 0;
  208720. }
  208721. void ActiveXControlComponent::setControlBounds (const Rectangle& newBounds) const
  208722. {
  208723. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  208724. if (hwnd != 0)
  208725. MoveWindow (hwnd, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  208726. }
  208727. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  208728. {
  208729. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  208730. if (hwnd != 0)
  208731. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  208732. }
  208733. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  208734. {
  208735. mouseEventsAllowed = eventsCanReachControl;
  208736. }
  208737. END_JUCE_NAMESPACE
  208738. /********* End of inlined file: juce_win32_Windowing.cpp *********/
  208739. #endif
  208740. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  208741. // Auto-links to various win32 libs that are needed by library calls..
  208742. #pragma comment(lib, "kernel32.lib")
  208743. #pragma comment(lib, "user32.lib")
  208744. #pragma comment(lib, "shell32.lib")
  208745. #pragma comment(lib, "gdi32.lib")
  208746. #pragma comment(lib, "vfw32.lib")
  208747. #pragma comment(lib, "comdlg32.lib")
  208748. #pragma comment(lib, "winmm.lib")
  208749. #pragma comment(lib, "wininet.lib")
  208750. #pragma comment(lib, "ole32.lib")
  208751. #pragma comment(lib, "advapi32.lib")
  208752. #pragma comment(lib, "ws2_32.lib")
  208753. #pragma comment(lib, "comsupp.lib")
  208754. #if JUCE_OPENGL
  208755. #pragma comment(lib, "OpenGL32.Lib")
  208756. #pragma comment(lib, "GlU32.Lib")
  208757. #endif
  208758. #if JUCE_QUICKTIME
  208759. #pragma comment (lib, "QTMLClient.lib")
  208760. #endif
  208761. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  208762. #endif
  208763. //==============================================================================
  208764. #if JUCE_LINUX
  208765. /********* Start of inlined file: juce_linux_Files.cpp *********/
  208766. /********* Start of inlined file: linuxincludes.h *********/
  208767. #ifndef __LINUXINCLUDES_JUCEHEADER__
  208768. #define __LINUXINCLUDES_JUCEHEADER__
  208769. // Linux Header Files:
  208770. #include <unistd.h>
  208771. #include <stdlib.h>
  208772. #include <sched.h>
  208773. #include <pthread.h>
  208774. #include <sys/time.h>
  208775. #include <errno.h>
  208776. /* Remove this macro if you're having problems compiling the cpu affinity
  208777. calls (the API for these has changed about quite a bit in various Linux
  208778. versions, and a lot of distros seem to ship with obsolete versions)
  208779. */
  208780. #ifndef SUPPORT_AFFINITIES
  208781. #define SUPPORT_AFFINITIES 1
  208782. #endif
  208783. #endif // __LINUXINCLUDES_JUCEHEADER__
  208784. /********* End of inlined file: linuxincludes.h *********/
  208785. #include <sys/stat.h>
  208786. #include <sys/dir.h>
  208787. #include <sys/ptrace.h>
  208788. #include <sys/vfs.h> // for statfs
  208789. #include <sys/wait.h>
  208790. #include <unistd.h>
  208791. #include <fnmatch.h>
  208792. #include <utime.h>
  208793. #include <pwd.h>
  208794. #include <fcntl.h>
  208795. #define U_ISOFS_SUPER_MAGIC (short) 0x9660 // linux/iso_fs.h
  208796. #define U_MSDOS_SUPER_MAGIC (short) 0x4d44 // linux/msdos_fs.h
  208797. #define U_NFS_SUPER_MAGIC (short) 0x6969 // linux/nfs_fs.h
  208798. #define U_SMB_SUPER_MAGIC (short) 0x517B // linux/smb_fs.h
  208799. BEGIN_JUCE_NAMESPACE
  208800. /*
  208801. Note that a lot of methods that you'd expect to find in this file actually
  208802. live in juce_posix_SharedCode.h!
  208803. */
  208804. /********* Start of inlined file: juce_posix_SharedCode.h *********/
  208805. /*
  208806. This file contains posix routines that are common to both the Linux and Mac builds.
  208807. It gets included directly in the cpp files for these platforms.
  208808. */
  208809. CriticalSection::CriticalSection() throw()
  208810. {
  208811. pthread_mutexattr_t atts;
  208812. pthread_mutexattr_init (&atts);
  208813. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  208814. pthread_mutex_init (&internal, &atts);
  208815. }
  208816. CriticalSection::~CriticalSection() throw()
  208817. {
  208818. pthread_mutex_destroy (&internal);
  208819. }
  208820. void CriticalSection::enter() const throw()
  208821. {
  208822. pthread_mutex_lock (&internal);
  208823. }
  208824. bool CriticalSection::tryEnter() const throw()
  208825. {
  208826. return pthread_mutex_trylock (&internal) == 0;
  208827. }
  208828. void CriticalSection::exit() const throw()
  208829. {
  208830. pthread_mutex_unlock (&internal);
  208831. }
  208832. struct EventStruct
  208833. {
  208834. pthread_cond_t condition;
  208835. pthread_mutex_t mutex;
  208836. bool triggered;
  208837. };
  208838. WaitableEvent::WaitableEvent() throw()
  208839. {
  208840. EventStruct* const es = new EventStruct();
  208841. es->triggered = false;
  208842. pthread_cond_init (&es->condition, 0);
  208843. pthread_mutex_init (&es->mutex, 0);
  208844. internal = es;
  208845. }
  208846. WaitableEvent::~WaitableEvent() throw()
  208847. {
  208848. EventStruct* const es = (EventStruct*) internal;
  208849. pthread_cond_destroy (&es->condition);
  208850. pthread_mutex_destroy (&es->mutex);
  208851. delete es;
  208852. }
  208853. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  208854. {
  208855. EventStruct* const es = (EventStruct*) internal;
  208856. bool ok = true;
  208857. pthread_mutex_lock (&es->mutex);
  208858. if (timeOutMillisecs < 0)
  208859. {
  208860. while (! es->triggered)
  208861. pthread_cond_wait (&es->condition, &es->mutex);
  208862. }
  208863. else
  208864. {
  208865. while (! es->triggered)
  208866. {
  208867. struct timeval t;
  208868. gettimeofday (&t, 0);
  208869. struct timespec time;
  208870. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  208871. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  208872. if (time.tv_nsec >= 1000000000)
  208873. {
  208874. time.tv_nsec -= 1000000000;
  208875. time.tv_sec++;
  208876. }
  208877. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  208878. {
  208879. ok = false;
  208880. break;
  208881. }
  208882. }
  208883. }
  208884. es->triggered = false;
  208885. pthread_mutex_unlock (&es->mutex);
  208886. return ok;
  208887. }
  208888. void WaitableEvent::signal() const throw()
  208889. {
  208890. EventStruct* const es = (EventStruct*) internal;
  208891. pthread_mutex_lock (&es->mutex);
  208892. es->triggered = true;
  208893. pthread_cond_broadcast (&es->condition);
  208894. pthread_mutex_unlock (&es->mutex);
  208895. }
  208896. void WaitableEvent::reset() const throw()
  208897. {
  208898. EventStruct* const es = (EventStruct*) internal;
  208899. pthread_mutex_lock (&es->mutex);
  208900. es->triggered = false;
  208901. pthread_mutex_unlock (&es->mutex);
  208902. }
  208903. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  208904. {
  208905. struct timespec time;
  208906. time.tv_sec = millisecs / 1000;
  208907. time.tv_nsec = (millisecs % 1000) * 1000000;
  208908. nanosleep (&time, 0);
  208909. }
  208910. const tchar File::separator = T('/');
  208911. const tchar* File::separatorString = T("/");
  208912. bool juce_copyFile (const String& s, const String& d) throw();
  208913. static bool juce_stat (const String& fileName, struct stat& info) throw()
  208914. {
  208915. return fileName.isNotEmpty()
  208916. && (stat (fileName.toUTF8(), &info) == 0);
  208917. }
  208918. bool juce_isDirectory (const String& fileName) throw()
  208919. {
  208920. struct stat info;
  208921. return fileName.isEmpty()
  208922. || (juce_stat (fileName, info)
  208923. && ((info.st_mode & S_IFDIR) != 0));
  208924. }
  208925. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  208926. {
  208927. if (fileName.isEmpty())
  208928. return false;
  208929. const char* const fileNameUTF8 = fileName.toUTF8();
  208930. bool exists = access (fileNameUTF8, F_OK) == 0;
  208931. if (exists && dontCountDirectories)
  208932. {
  208933. struct stat info;
  208934. const int res = stat (fileNameUTF8, &info);
  208935. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  208936. exists = false;
  208937. }
  208938. return exists;
  208939. }
  208940. int64 juce_getFileSize (const String& fileName) throw()
  208941. {
  208942. struct stat info;
  208943. return juce_stat (fileName, info) ? info.st_size : 0;
  208944. }
  208945. bool juce_canWriteToFile (const String& fileName) throw()
  208946. {
  208947. return access (fileName.toUTF8(), W_OK) == 0;
  208948. }
  208949. bool juce_deleteFile (const String& fileName) throw()
  208950. {
  208951. const char* const fileNameUTF8 = fileName.toUTF8();
  208952. if (juce_isDirectory (fileName))
  208953. return rmdir (fileNameUTF8) == 0;
  208954. else
  208955. return remove (fileNameUTF8) == 0;
  208956. }
  208957. bool juce_moveFile (const String& source, const String& dest) throw()
  208958. {
  208959. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  208960. return true;
  208961. if (juce_canWriteToFile (source)
  208962. && juce_copyFile (source, dest))
  208963. {
  208964. if (juce_deleteFile (source))
  208965. return true;
  208966. juce_deleteFile (dest);
  208967. }
  208968. return false;
  208969. }
  208970. void juce_createDirectory (const String& fileName) throw()
  208971. {
  208972. mkdir (fileName.toUTF8(), 0777);
  208973. }
  208974. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  208975. {
  208976. const char* const fileNameUTF8 = fileName.toUTF8();
  208977. int flags = O_RDONLY;
  208978. if (forWriting)
  208979. {
  208980. if (juce_fileExists (fileName, false))
  208981. {
  208982. const int f = open (fileNameUTF8, O_RDWR, 00644);
  208983. if (f != -1)
  208984. lseek (f, 0, SEEK_END);
  208985. return (void*) f;
  208986. }
  208987. else
  208988. {
  208989. flags = O_RDWR + O_CREAT;
  208990. }
  208991. }
  208992. return (void*) open (fileNameUTF8, flags, 00644);
  208993. }
  208994. void juce_fileClose (void* handle) throw()
  208995. {
  208996. if (handle != 0)
  208997. close ((int) (pointer_sized_int) handle);
  208998. }
  208999. int juce_fileRead (void* handle, void* buffer, int size) throw()
  209000. {
  209001. if (handle != 0)
  209002. return read ((int) (pointer_sized_int) handle, buffer, size);
  209003. return 0;
  209004. }
  209005. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  209006. {
  209007. if (handle != 0)
  209008. return write ((int) (pointer_sized_int) handle, buffer, size);
  209009. return 0;
  209010. }
  209011. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  209012. {
  209013. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  209014. return pos;
  209015. return -1;
  209016. }
  209017. int64 juce_fileGetPosition (void* handle) throw()
  209018. {
  209019. if (handle != 0)
  209020. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  209021. else
  209022. return -1;
  209023. }
  209024. void juce_fileFlush (void* handle) throw()
  209025. {
  209026. if (handle != 0)
  209027. fsync ((int) (pointer_sized_int) handle);
  209028. }
  209029. // if this file doesn't exist, find a parent of it that does..
  209030. static bool doStatFS (const File* file, struct statfs& result) throw()
  209031. {
  209032. File f (*file);
  209033. for (int i = 5; --i >= 0;)
  209034. {
  209035. if (f.exists())
  209036. break;
  209037. f = f.getParentDirectory();
  209038. }
  209039. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  209040. }
  209041. int64 File::getBytesFreeOnVolume() const throw()
  209042. {
  209043. int64 free_space = 0;
  209044. struct statfs buf;
  209045. if (doStatFS (this, buf))
  209046. // Note: this returns space available to non-super user
  209047. free_space = (int64) buf.f_bsize * (int64) buf.f_bavail;
  209048. return free_space;
  209049. }
  209050. const String juce_getVolumeLabel (const String& filenameOnVolume,
  209051. int& volumeSerialNumber) throw()
  209052. {
  209053. // There is no equivalent on Linux
  209054. volumeSerialNumber = 0;
  209055. return String::empty;
  209056. }
  209057. #if JUCE_64BIT
  209058. #define filedesc ((long long) internal)
  209059. #else
  209060. #define filedesc ((int) internal)
  209061. #endif
  209062. InterProcessLock::InterProcessLock (const String& name_) throw()
  209063. : internal (0),
  209064. name (name_),
  209065. reentrancyLevel (0)
  209066. {
  209067. #if JUCE_MAC
  209068. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  209069. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  209070. #else
  209071. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  209072. #endif
  209073. temp.create();
  209074. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  209075. }
  209076. InterProcessLock::~InterProcessLock() throw()
  209077. {
  209078. while (reentrancyLevel > 0)
  209079. this->exit();
  209080. close (filedesc);
  209081. }
  209082. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  209083. {
  209084. if (internal == 0)
  209085. return false;
  209086. if (reentrancyLevel != 0)
  209087. return true;
  209088. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  209089. struct flock fl;
  209090. zerostruct (fl);
  209091. fl.l_whence = SEEK_SET;
  209092. fl.l_type = F_WRLCK;
  209093. for (;;)
  209094. {
  209095. const int result = fcntl (filedesc, F_SETLK, &fl);
  209096. if (result >= 0)
  209097. {
  209098. ++reentrancyLevel;
  209099. return true;
  209100. }
  209101. if (errno != EINTR)
  209102. {
  209103. if (timeOutMillisecs == 0
  209104. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  209105. break;
  209106. Thread::sleep (10);
  209107. }
  209108. }
  209109. return false;
  209110. }
  209111. void InterProcessLock::exit() throw()
  209112. {
  209113. if (reentrancyLevel > 0 && internal != 0)
  209114. {
  209115. --reentrancyLevel;
  209116. struct flock fl;
  209117. zerostruct (fl);
  209118. fl.l_whence = SEEK_SET;
  209119. fl.l_type = F_UNLCK;
  209120. for (;;)
  209121. {
  209122. const int result = fcntl (filedesc, F_SETLKW, &fl);
  209123. if (result >= 0 || errno != EINTR)
  209124. break;
  209125. }
  209126. }
  209127. }
  209128. /********* End of inlined file: juce_posix_SharedCode.h *********/
  209129. static File executableFile;
  209130. void juce_getFileTimes (const String& fileName,
  209131. int64& modificationTime,
  209132. int64& accessTime,
  209133. int64& creationTime) throw()
  209134. {
  209135. modificationTime = 0;
  209136. accessTime = 0;
  209137. creationTime = 0;
  209138. struct stat info;
  209139. const int res = stat (fileName.toUTF8(), &info);
  209140. if (res == 0)
  209141. {
  209142. modificationTime = (int64) info.st_mtime * 1000;
  209143. accessTime = (int64) info.st_atime * 1000;
  209144. creationTime = (int64) info.st_ctime * 1000;
  209145. }
  209146. }
  209147. bool juce_setFileTimes (const String& fileName,
  209148. int64 modificationTime,
  209149. int64 accessTime,
  209150. int64 creationTime) throw()
  209151. {
  209152. struct utimbuf times;
  209153. times.actime = (time_t) (accessTime / 1000);
  209154. times.modtime = (time_t) (modificationTime / 1000);
  209155. return utime (fileName.toUTF8(), &times) == 0;
  209156. }
  209157. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  209158. {
  209159. struct stat info;
  209160. const int res = stat (fileName.toUTF8(), &info);
  209161. if (res != 0)
  209162. return false;
  209163. info.st_mode &= 0777; // Just permissions
  209164. if( isReadOnly )
  209165. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  209166. else
  209167. // Give everybody write permission?
  209168. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  209169. return chmod (fileName.toUTF8(), info.st_mode) == 0;
  209170. }
  209171. bool juce_copyFile (const String& s, const String& d) throw()
  209172. {
  209173. const File source (s), dest (d);
  209174. FileInputStream* in = source.createInputStream();
  209175. bool ok = false;
  209176. if (in != 0)
  209177. {
  209178. if (dest.deleteFile())
  209179. {
  209180. FileOutputStream* const out = dest.createOutputStream();
  209181. if (out != 0)
  209182. {
  209183. const int bytesCopied = out->writeFromInputStream (*in, -1);
  209184. delete out;
  209185. ok = (bytesCopied == source.getSize());
  209186. if (! ok)
  209187. dest.deleteFile();
  209188. }
  209189. }
  209190. delete in;
  209191. }
  209192. return ok;
  209193. }
  209194. const StringArray juce_getFileSystemRoots() throw()
  209195. {
  209196. StringArray s;
  209197. s.add (T("/"));
  209198. return s;
  209199. }
  209200. bool File::isOnCDRomDrive() const throw()
  209201. {
  209202. struct statfs buf;
  209203. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  209204. return (buf.f_type == U_ISOFS_SUPER_MAGIC);
  209205. // Assume not if this fails for some reason
  209206. return false;
  209207. }
  209208. bool File::isOnHardDisk() const throw()
  209209. {
  209210. struct statfs buf;
  209211. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  209212. {
  209213. switch (buf.f_type)
  209214. {
  209215. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  209216. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  209217. case U_NFS_SUPER_MAGIC: // Network NFS
  209218. case U_SMB_SUPER_MAGIC: // Network Samba
  209219. return false;
  209220. default:
  209221. // Assume anything else is a hard-disk (but note it could
  209222. // be a RAM disk. There isn't a good way of determining
  209223. // this for sure)
  209224. return true;
  209225. }
  209226. }
  209227. // Assume so if this fails for some reason
  209228. return true;
  209229. }
  209230. bool File::isOnRemovableDrive() const throw()
  209231. {
  209232. jassertfalse // xxx not implemented for linux!
  209233. return false;
  209234. }
  209235. bool File::isHidden() const throw()
  209236. {
  209237. return getFileName().startsWithChar (T('.'));
  209238. }
  209239. const File File::getSpecialLocation (const SpecialLocationType type)
  209240. {
  209241. switch (type)
  209242. {
  209243. case userHomeDirectory:
  209244. {
  209245. const char* homeDir = getenv ("HOME");
  209246. if (homeDir == 0)
  209247. {
  209248. struct passwd* const pw = getpwuid (getuid());
  209249. if (pw != 0)
  209250. homeDir = pw->pw_dir;
  209251. }
  209252. return File (String::fromUTF8 ((const uint8*) homeDir));
  209253. }
  209254. case userDocumentsDirectory:
  209255. case userMusicDirectory:
  209256. case userMoviesDirectory:
  209257. case userApplicationDataDirectory:
  209258. return File ("~");
  209259. case userDesktopDirectory:
  209260. return File ("~/Desktop");
  209261. case commonApplicationDataDirectory:
  209262. return File ("/var");
  209263. case globalApplicationsDirectory:
  209264. return File ("/usr");
  209265. case tempDirectory:
  209266. {
  209267. File tmp ("/var/tmp");
  209268. if (! tmp.isDirectory())
  209269. {
  209270. tmp = T("/tmp");
  209271. if (! tmp.isDirectory())
  209272. tmp = File::getCurrentWorkingDirectory();
  209273. }
  209274. return tmp;
  209275. }
  209276. case currentExecutableFile:
  209277. case currentApplicationFile:
  209278. // if this fails, it's probably because juce_setCurrentExecutableFileName()
  209279. // was never called to set the filename - this should be done by the juce
  209280. // main() function, so maybe you've hacked it to use your own custom main()?
  209281. jassert (executableFile.exists());
  209282. return executableFile;
  209283. default:
  209284. jassertfalse // unknown type?
  209285. break;
  209286. }
  209287. return File::nonexistent;
  209288. }
  209289. void juce_setCurrentExecutableFileName (const String& filename) throw()
  209290. {
  209291. executableFile = File::getCurrentWorkingDirectory().getChildFile (filename);
  209292. }
  209293. const File File::getCurrentWorkingDirectory() throw()
  209294. {
  209295. char buf [2048];
  209296. getcwd (buf, sizeof(buf));
  209297. return File (String::fromUTF8 ((const uint8*) buf));
  209298. }
  209299. bool File::setAsCurrentWorkingDirectory() const throw()
  209300. {
  209301. return chdir (getFullPathName().toUTF8()) == 0;
  209302. }
  209303. struct FindFileStruct
  209304. {
  209305. String parentDir, wildCard;
  209306. DIR* dir;
  209307. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  209308. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  209309. {
  209310. const char* const wildcardUTF8 = wildCard.toUTF8();
  209311. for (;;)
  209312. {
  209313. struct dirent* const de = readdir (dir);
  209314. if (de == 0)
  209315. break;
  209316. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  209317. {
  209318. result = String::fromUTF8 ((const uint8*) de->d_name);
  209319. const String path (parentDir + result);
  209320. if (isDir != 0 || fileSize != 0)
  209321. {
  209322. struct stat info;
  209323. const bool statOk = (stat (path.toUTF8(), &info) == 0);
  209324. if (isDir != 0)
  209325. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  209326. if (isHidden != 0)
  209327. *isHidden = (de->d_name[0] == '.');
  209328. if (fileSize != 0)
  209329. *fileSize = statOk ? info.st_size : 0;
  209330. }
  209331. if (modTime != 0 || creationTime != 0)
  209332. {
  209333. int64 m, a, c;
  209334. juce_getFileTimes (path, m, a, c);
  209335. if (modTime != 0)
  209336. *modTime = m;
  209337. if (creationTime != 0)
  209338. *creationTime = c;
  209339. }
  209340. if (isReadOnly != 0)
  209341. *isReadOnly = ! juce_canWriteToFile (path);
  209342. return true;
  209343. }
  209344. }
  209345. return false;
  209346. }
  209347. };
  209348. // returns 0 on failure
  209349. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  209350. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  209351. Time* creationTime, bool* isReadOnly) throw()
  209352. {
  209353. DIR* d = opendir (directory.toUTF8());
  209354. if (d != 0)
  209355. {
  209356. FindFileStruct* ff = new FindFileStruct();
  209357. ff->parentDir = directory;
  209358. if (!ff->parentDir.endsWithChar (File::separator))
  209359. ff->parentDir += File::separator;
  209360. ff->wildCard = wildCard;
  209361. if (wildCard == T("*.*"))
  209362. ff->wildCard = T("*");
  209363. ff->dir = d;
  209364. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  209365. {
  209366. return ff;
  209367. }
  209368. else
  209369. {
  209370. firstResultFile = String::empty;
  209371. isDir = false;
  209372. isHidden = false;
  209373. closedir (d);
  209374. delete ff;
  209375. }
  209376. }
  209377. return 0;
  209378. }
  209379. bool juce_findFileNext (void* handle, String& resultFile,
  209380. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  209381. {
  209382. FindFileStruct* const ff = (FindFileStruct*) handle;
  209383. if (ff != 0)
  209384. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  209385. return false;
  209386. }
  209387. void juce_findFileClose (void* handle) throw()
  209388. {
  209389. FindFileStruct* const ff = (FindFileStruct*) handle;
  209390. if (ff != 0)
  209391. {
  209392. closedir (ff->dir);
  209393. delete ff;
  209394. }
  209395. }
  209396. bool juce_launchFile (const String& fileName,
  209397. const String& parameters) throw()
  209398. {
  209399. String cmdString (fileName);
  209400. cmdString << " " << parameters;
  209401. if (URL::isProbablyAWebsiteURL (cmdString) || URL::isProbablyAnEmailAddress (cmdString))
  209402. {
  209403. // create a command that tries to launch a bunch of likely browsers
  209404. const char* const browserNames[] = { "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  209405. StringArray cmdLines;
  209406. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  209407. cmdLines.add (String (browserNames[i]) + T(" ") + cmdString.trim().quoted());
  209408. cmdString = cmdLines.joinIntoString (T(" || "));
  209409. }
  209410. char* const argv[4] = { "/bin/sh", "-c", (char*) cmdString.toUTF8(), 0 };
  209411. const int cpid = fork();
  209412. if (cpid == 0)
  209413. {
  209414. setsid();
  209415. // Child process
  209416. execve (argv[0], argv, environ);
  209417. exit (0);
  209418. }
  209419. return cpid >= 0;
  209420. }
  209421. END_JUCE_NAMESPACE
  209422. /********* End of inlined file: juce_linux_Files.cpp *********/
  209423. /********* Start of inlined file: juce_linux_NamedPipe.cpp *********/
  209424. /********* Start of inlined file: juce_mac_NamedPipe.cpp *********/
  209425. #include <sys/stat.h>
  209426. #include <sys/dir.h>
  209427. #include <fcntl.h>
  209428. // As well as being for the mac, this file is included by the linux build.
  209429. #if ! JUCE_MAC
  209430. #include <sys/wait.h>
  209431. #include <errno.h>
  209432. #include <unistd.h>
  209433. #endif
  209434. BEGIN_JUCE_NAMESPACE
  209435. struct NamedPipeInternal
  209436. {
  209437. String pipeInName, pipeOutName;
  209438. int pipeIn, pipeOut;
  209439. bool volatile createdPipe, blocked, stopReadOperation;
  209440. static void signalHandler (int) {}
  209441. };
  209442. void NamedPipe::cancelPendingReads()
  209443. {
  209444. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  209445. {
  209446. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  209447. intern->stopReadOperation = true;
  209448. char buffer [1] = { 0 };
  209449. ::write (intern->pipeIn, buffer, 1);
  209450. int timeout = 2000;
  209451. while (intern->blocked && --timeout >= 0)
  209452. Thread::sleep (2);
  209453. intern->stopReadOperation = false;
  209454. }
  209455. }
  209456. void NamedPipe::close()
  209457. {
  209458. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  209459. if (intern != 0)
  209460. {
  209461. internal = 0;
  209462. if (intern->pipeIn != -1)
  209463. ::close (intern->pipeIn);
  209464. if (intern->pipeOut != -1)
  209465. ::close (intern->pipeOut);
  209466. if (intern->createdPipe)
  209467. {
  209468. unlink (intern->pipeInName);
  209469. unlink (intern->pipeOutName);
  209470. }
  209471. delete intern;
  209472. }
  209473. }
  209474. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  209475. {
  209476. close();
  209477. NamedPipeInternal* const intern = new NamedPipeInternal();
  209478. internal = intern;
  209479. intern->createdPipe = createPipe;
  209480. intern->blocked = false;
  209481. intern->stopReadOperation = false;
  209482. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  209483. siginterrupt (SIGPIPE, 1);
  209484. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  209485. intern->pipeInName = pipePath + T("_in");
  209486. intern->pipeOutName = pipePath + T("_out");
  209487. intern->pipeIn = -1;
  209488. intern->pipeOut = -1;
  209489. if (createPipe)
  209490. {
  209491. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  209492. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  209493. {
  209494. delete intern;
  209495. internal = 0;
  209496. return false;
  209497. }
  209498. }
  209499. return true;
  209500. }
  209501. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  209502. {
  209503. int bytesRead = -1;
  209504. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  209505. if (intern != 0)
  209506. {
  209507. intern->blocked = true;
  209508. if (intern->pipeIn == -1)
  209509. {
  209510. if (intern->createdPipe)
  209511. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  209512. else
  209513. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  209514. if (intern->pipeIn == -1)
  209515. {
  209516. intern->blocked = false;
  209517. return -1;
  209518. }
  209519. }
  209520. bytesRead = 0;
  209521. char* p = (char*) destBuffer;
  209522. while (bytesRead < maxBytesToRead)
  209523. {
  209524. const int bytesThisTime = maxBytesToRead - bytesRead;
  209525. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  209526. if (numRead <= 0 || intern->stopReadOperation)
  209527. {
  209528. bytesRead = -1;
  209529. break;
  209530. }
  209531. bytesRead += numRead;
  209532. p += bytesRead;
  209533. }
  209534. intern->blocked = false;
  209535. }
  209536. return bytesRead;
  209537. }
  209538. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  209539. {
  209540. int bytesWritten = -1;
  209541. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  209542. if (intern != 0)
  209543. {
  209544. if (intern->pipeOut == -1)
  209545. {
  209546. if (intern->createdPipe)
  209547. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  209548. else
  209549. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  209550. if (intern->pipeOut == -1)
  209551. {
  209552. return -1;
  209553. }
  209554. }
  209555. const char* p = (const char*) sourceBuffer;
  209556. bytesWritten = 0;
  209557. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  209558. while (bytesWritten < numBytesToWrite
  209559. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  209560. {
  209561. const int bytesThisTime = numBytesToWrite - bytesWritten;
  209562. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  209563. if (numWritten <= 0)
  209564. {
  209565. bytesWritten = -1;
  209566. break;
  209567. }
  209568. bytesWritten += numWritten;
  209569. p += bytesWritten;
  209570. }
  209571. }
  209572. return bytesWritten;
  209573. }
  209574. END_JUCE_NAMESPACE
  209575. /********* End of inlined file: juce_mac_NamedPipe.cpp *********/
  209576. /********* End of inlined file: juce_linux_NamedPipe.cpp *********/
  209577. /********* Start of inlined file: juce_linux_Network.cpp *********/
  209578. #include <netdb.h>
  209579. #include <arpa/inet.h>
  209580. #include <netinet/in.h>
  209581. #include <sys/types.h>
  209582. #include <sys/ioctl.h>
  209583. #include <sys/socket.h>
  209584. #include <sys/wait.h>
  209585. #include <linux/if.h>
  209586. BEGIN_JUCE_NAMESPACE
  209587. // we'll borrow the mac's socket-based http streaming code..
  209588. /********* Start of inlined file: juce_mac_HTTPStream.h *********/
  209589. // (This file gets included by the mac + linux networking code)
  209590. /** A HTTP input stream that uses sockets.
  209591. */
  209592. class JUCE_HTTPSocketStream
  209593. {
  209594. public:
  209595. JUCE_HTTPSocketStream()
  209596. : readPosition (0),
  209597. socketHandle (-1),
  209598. levelsOfRedirection (0),
  209599. timeoutSeconds (15)
  209600. {
  209601. }
  209602. ~JUCE_HTTPSocketStream()
  209603. {
  209604. closeSocket();
  209605. }
  209606. bool open (const String& url,
  209607. const String& headers,
  209608. const MemoryBlock& postData,
  209609. const bool isPost,
  209610. URL::OpenStreamProgressCallback* callback,
  209611. void* callbackContext,
  209612. int timeOutMs)
  209613. {
  209614. closeSocket();
  209615. uint32 timeOutTime = Time::getMillisecondCounter();
  209616. if (timeOutMs == 0)
  209617. timeOutTime += 60000;
  209618. else if (timeOutMs < 0)
  209619. timeOutTime = 0xffffffff;
  209620. else
  209621. timeOutTime += timeOutMs;
  209622. String hostName, hostPath;
  209623. int hostPort;
  209624. if (! decomposeURL (url, hostName, hostPath, hostPort))
  209625. return false;
  209626. const struct hostent* host = 0;
  209627. int port = 0;
  209628. String proxyName, proxyPath;
  209629. int proxyPort = 0;
  209630. String proxyURL (getenv ("http_proxy"));
  209631. if (proxyURL.startsWithIgnoreCase (T("http://")))
  209632. {
  209633. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  209634. return false;
  209635. host = gethostbyname ((const char*) proxyName.toUTF8());
  209636. port = proxyPort;
  209637. }
  209638. else
  209639. {
  209640. host = gethostbyname ((const char*) hostName.toUTF8());
  209641. port = hostPort;
  209642. }
  209643. if (host == 0)
  209644. return false;
  209645. struct sockaddr_in address;
  209646. zerostruct (address);
  209647. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  209648. address.sin_family = host->h_addrtype;
  209649. address.sin_port = htons (port);
  209650. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  209651. if (socketHandle == -1)
  209652. return false;
  209653. int receiveBufferSize = 16384;
  209654. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  209655. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  209656. #if JUCE_MAC
  209657. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  209658. #endif
  209659. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  209660. {
  209661. closeSocket();
  209662. return false;
  209663. }
  209664. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  209665. proxyName, proxyPort,
  209666. hostPath, url,
  209667. headers, postData,
  209668. isPost));
  209669. int totalHeaderSent = 0;
  209670. while (totalHeaderSent < requestHeader.getSize())
  209671. {
  209672. if (Time::getMillisecondCounter() > timeOutTime)
  209673. {
  209674. closeSocket();
  209675. return false;
  209676. }
  209677. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  209678. if (send (socketHandle,
  209679. ((const char*) requestHeader.getData()) + totalHeaderSent,
  209680. numToSend, 0)
  209681. != numToSend)
  209682. {
  209683. closeSocket();
  209684. return false;
  209685. }
  209686. totalHeaderSent += numToSend;
  209687. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  209688. {
  209689. closeSocket();
  209690. return false;
  209691. }
  209692. }
  209693. const String responseHeader (readResponse (timeOutTime));
  209694. if (responseHeader.isNotEmpty())
  209695. {
  209696. //DBG (responseHeader);
  209697. StringArray lines;
  209698. lines.addLines (responseHeader);
  209699. // NB - using charToString() here instead of just T(" "), because that was
  209700. // causing a mysterious gcc internal compiler error...
  209701. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  209702. .substring (0, 3)
  209703. .getIntValue();
  209704. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  209705. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  209706. String location (findHeaderItem (lines, T("Location:")));
  209707. if (statusCode >= 300 && statusCode < 400
  209708. && location.isNotEmpty())
  209709. {
  209710. if (! location.startsWithIgnoreCase (T("http://")))
  209711. location = T("http://") + location;
  209712. if (levelsOfRedirection++ < 3)
  209713. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  209714. }
  209715. else
  209716. {
  209717. levelsOfRedirection = 0;
  209718. return true;
  209719. }
  209720. }
  209721. closeSocket();
  209722. return false;
  209723. }
  209724. int read (void* buffer, int bytesToRead)
  209725. {
  209726. fd_set readbits;
  209727. FD_ZERO (&readbits);
  209728. FD_SET (socketHandle, &readbits);
  209729. struct timeval tv;
  209730. tv.tv_sec = timeoutSeconds;
  209731. tv.tv_usec = 0;
  209732. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  209733. return 0; // (timeout)
  209734. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  209735. readPosition += bytesRead;
  209736. return bytesRead;
  209737. }
  209738. int readPosition;
  209739. juce_UseDebuggingNewOperator
  209740. private:
  209741. int socketHandle, levelsOfRedirection;
  209742. const int timeoutSeconds;
  209743. void closeSocket()
  209744. {
  209745. if (socketHandle >= 0)
  209746. close (socketHandle);
  209747. socketHandle = -1;
  209748. }
  209749. const MemoryBlock createRequestHeader (const String& hostName,
  209750. const int hostPort,
  209751. const String& proxyName,
  209752. const int proxyPort,
  209753. const String& hostPath,
  209754. const String& originalURL,
  209755. const String& headers,
  209756. const MemoryBlock& postData,
  209757. const bool isPost)
  209758. {
  209759. String header (isPost ? "POST " : "GET ");
  209760. if (proxyName.isEmpty())
  209761. {
  209762. header << hostPath << " HTTP/1.0\r\nHost: "
  209763. << hostName << ':' << hostPort;
  209764. }
  209765. else
  209766. {
  209767. header << originalURL << " HTTP/1.0\r\nHost: "
  209768. << proxyName << ':' << proxyPort;
  209769. }
  209770. header << "\r\nUser-Agent: JUCE/"
  209771. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  209772. << "\r\nConnection: Close\r\nContent-Length: "
  209773. << postData.getSize() << "\r\n"
  209774. << headers << "\r\n";
  209775. MemoryBlock mb;
  209776. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  209777. mb.append (postData.getData(), postData.getSize());
  209778. return mb;
  209779. }
  209780. const String readResponse (const uint32 timeOutTime)
  209781. {
  209782. int bytesRead = 0, numConsecutiveLFs = 0;
  209783. MemoryBlock buffer (1024, true);
  209784. while (numConsecutiveLFs < 2 && bytesRead < 32768
  209785. && Time::getMillisecondCounter() <= timeOutTime)
  209786. {
  209787. fd_set readbits;
  209788. FD_ZERO (&readbits);
  209789. FD_SET (socketHandle, &readbits);
  209790. struct timeval tv;
  209791. tv.tv_sec = timeoutSeconds;
  209792. tv.tv_usec = 0;
  209793. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  209794. return String::empty; // (timeout)
  209795. buffer.ensureSize (bytesRead + 8, true);
  209796. char* const dest = (char*) buffer.getData() + bytesRead;
  209797. if (recv (socketHandle, dest, 1, 0) == -1)
  209798. return String::empty;
  209799. const char lastByte = *dest;
  209800. ++bytesRead;
  209801. if (lastByte == '\n')
  209802. ++numConsecutiveLFs;
  209803. else if (lastByte != '\r')
  209804. numConsecutiveLFs = 0;
  209805. }
  209806. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  209807. if (header.startsWithIgnoreCase (T("HTTP/")))
  209808. return header.trimEnd();
  209809. return String::empty;
  209810. }
  209811. static bool decomposeURL (const String& url,
  209812. String& host, String& path, int& port)
  209813. {
  209814. if (! url.startsWithIgnoreCase (T("http://")))
  209815. return false;
  209816. const int nextSlash = url.indexOfChar (7, '/');
  209817. int nextColon = url.indexOfChar (7, ':');
  209818. if (nextColon > nextSlash && nextSlash > 0)
  209819. nextColon = -1;
  209820. if (nextColon >= 0)
  209821. {
  209822. host = url.substring (7, nextColon);
  209823. if (nextSlash >= 0)
  209824. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  209825. else
  209826. port = url.substring (nextColon + 1).getIntValue();
  209827. }
  209828. else
  209829. {
  209830. port = 80;
  209831. if (nextSlash >= 0)
  209832. host = url.substring (7, nextSlash);
  209833. else
  209834. host = url.substring (7);
  209835. }
  209836. if (nextSlash >= 0)
  209837. path = url.substring (nextSlash);
  209838. else
  209839. path = T("/");
  209840. return true;
  209841. }
  209842. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  209843. {
  209844. for (int i = 0; i < lines.size(); ++i)
  209845. if (lines[i].startsWithIgnoreCase (itemName))
  209846. return lines[i].substring (itemName.length()).trim();
  209847. return String::empty;
  209848. }
  209849. };
  209850. bool juce_isOnLine()
  209851. {
  209852. return true;
  209853. }
  209854. void* juce_openInternetFile (const String& url,
  209855. const String& headers,
  209856. const MemoryBlock& postData,
  209857. const bool isPost,
  209858. URL::OpenStreamProgressCallback* callback,
  209859. void* callbackContext,
  209860. int timeOutMs)
  209861. {
  209862. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  209863. if (s->open (url, headers, postData, isPost,
  209864. callback, callbackContext, timeOutMs))
  209865. return s;
  209866. delete s;
  209867. return 0;
  209868. }
  209869. void juce_closeInternetFile (void* handle)
  209870. {
  209871. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  209872. if (s != 0)
  209873. delete s;
  209874. }
  209875. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  209876. {
  209877. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  209878. if (s != 0)
  209879. return s->read (buffer, bytesToRead);
  209880. return 0;
  209881. }
  209882. int juce_seekInInternetFile (void* handle, int newPosition)
  209883. {
  209884. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  209885. if (s != 0)
  209886. return s->readPosition;
  209887. return 0;
  209888. }
  209889. /********* End of inlined file: juce_mac_HTTPStream.h *********/
  209890. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  209891. {
  209892. int numResults = 0;
  209893. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  209894. if (s != -1)
  209895. {
  209896. char buf [1024];
  209897. struct ifconf ifc;
  209898. ifc.ifc_len = sizeof (buf);
  209899. ifc.ifc_buf = buf;
  209900. ioctl (s, SIOCGIFCONF, &ifc);
  209901. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  209902. {
  209903. struct ifreq ifr;
  209904. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  209905. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  209906. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  209907. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  209908. && numResults < maxNum)
  209909. {
  209910. int64 a = 0;
  209911. for (int j = 6; --j >= 0;)
  209912. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data[j];
  209913. *addresses++ = a;
  209914. ++numResults;
  209915. }
  209916. }
  209917. close (s);
  209918. }
  209919. return numResults;
  209920. }
  209921. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  209922. const String& emailSubject,
  209923. const String& bodyText,
  209924. const StringArray& filesToAttach)
  209925. {
  209926. jassertfalse // xxx todo
  209927. return false;
  209928. }
  209929. END_JUCE_NAMESPACE
  209930. /********* End of inlined file: juce_linux_Network.cpp *********/
  209931. /********* Start of inlined file: juce_linux_SystemStats.cpp *********/
  209932. #include <sys/sysinfo.h>
  209933. #include <dlfcn.h>
  209934. #ifndef CPU_ISSET
  209935. #undef SUPPORT_AFFINITIES
  209936. #endif
  209937. BEGIN_JUCE_NAMESPACE
  209938. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel, int* extFeatures) throw()
  209939. {
  209940. unsigned int cpu = 0;
  209941. unsigned int ext = 0;
  209942. unsigned int family = 0;
  209943. unsigned int dummy = 0;
  209944. #if JUCE_64BIT
  209945. __asm__ ("cpuid"
  209946. : "=a" (family), "=b" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  209947. #else
  209948. __asm__ ("push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx"
  209949. : "=a" (family), "=D" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  209950. #endif
  209951. if (familyModel != 0)
  209952. *familyModel = family;
  209953. if (extFeatures != 0)
  209954. *extFeatures = ext;
  209955. return cpu;
  209956. }*/
  209957. void Logger::outputDebugString (const String& text) throw()
  209958. {
  209959. fprintf (stdout, text.toUTF8());
  209960. fprintf (stdout, "\n");
  209961. }
  209962. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  209963. {
  209964. String text;
  209965. va_list args;
  209966. va_start (args, format);
  209967. text.vprintf(format, args);
  209968. outputDebugString(text);
  209969. }
  209970. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  209971. {
  209972. return Linux;
  209973. }
  209974. const String SystemStats::getOperatingSystemName() throw()
  209975. {
  209976. return T("Linux");
  209977. }
  209978. bool SystemStats::isOperatingSystem64Bit() throw()
  209979. {
  209980. #if JUCE_64BIT
  209981. return true;
  209982. #else
  209983. //xxx not sure how to find this out?..
  209984. return false;
  209985. #endif
  209986. }
  209987. static const String getCpuInfo (const char* key, bool lastOne = false) throw()
  209988. {
  209989. String info;
  209990. char buf [256];
  209991. FILE* f = fopen ("/proc/cpuinfo", "r");
  209992. while (f != 0 && fgets (buf, sizeof(buf), f))
  209993. {
  209994. if (strncmp (buf, key, strlen (key)) == 0)
  209995. {
  209996. char* p = buf;
  209997. while (*p && *p != '\n')
  209998. ++p;
  209999. if (*p != 0)
  210000. *p = 0;
  210001. p = buf;
  210002. while (*p != 0 && *p != ':')
  210003. ++p;
  210004. if (*p != 0 && *(p + 1) != 0)
  210005. info = p + 2;
  210006. if (! lastOne)
  210007. break;
  210008. }
  210009. }
  210010. fclose (f);
  210011. return info;
  210012. }
  210013. bool SystemStats::hasMMX() throw()
  210014. {
  210015. return getCpuInfo ("flags").contains (T("mmx"));
  210016. }
  210017. bool SystemStats::hasSSE() throw()
  210018. {
  210019. return getCpuInfo ("flags").contains (T("sse"));
  210020. }
  210021. bool SystemStats::hasSSE2() throw()
  210022. {
  210023. return getCpuInfo ("flags").contains (T("sse2"));
  210024. }
  210025. bool SystemStats::has3DNow() throw()
  210026. {
  210027. return getCpuInfo ("flags").contains (T("3dnow"));
  210028. }
  210029. const String SystemStats::getCpuVendor() throw()
  210030. {
  210031. return getCpuInfo ("vendor_id");
  210032. }
  210033. int SystemStats::getCpuSpeedInMegaherz() throw()
  210034. {
  210035. const String speed (getCpuInfo ("cpu MHz"));
  210036. return (int) (speed.getFloatValue() + 0.5f);
  210037. }
  210038. int SystemStats::getMemorySizeInMegabytes() throw()
  210039. {
  210040. struct sysinfo sysi;
  210041. if (sysinfo (&sysi) == 0)
  210042. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  210043. return 0;
  210044. }
  210045. uint32 juce_millisecondsSinceStartup() throw()
  210046. {
  210047. static unsigned int calibrate = 0;
  210048. static bool calibrated = false;
  210049. timeval t;
  210050. unsigned int ret = 0;
  210051. if (! gettimeofday (&t, 0))
  210052. {
  210053. if (! calibrated)
  210054. {
  210055. struct sysinfo sysi;
  210056. if (sysinfo (&sysi) == 0)
  210057. // Safe to assume system was not brought up earlier than 1970!
  210058. calibrate = t.tv_sec - sysi.uptime;
  210059. calibrated = true;
  210060. }
  210061. ret = 1000 * (t.tv_sec - calibrate) + (t.tv_usec / 1000);
  210062. }
  210063. return ret;
  210064. }
  210065. double Time::getMillisecondCounterHiRes() throw()
  210066. {
  210067. return getHighResolutionTicks() * 0.001;
  210068. }
  210069. int64 Time::getHighResolutionTicks() throw()
  210070. {
  210071. timeval t;
  210072. if (gettimeofday (&t, 0))
  210073. return 0;
  210074. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  210075. }
  210076. int64 Time::getHighResolutionTicksPerSecond() throw()
  210077. {
  210078. // Microseconds
  210079. return 1000000;
  210080. }
  210081. bool Time::setSystemTimeToThisTime() const throw()
  210082. {
  210083. timeval t;
  210084. t.tv_sec = millisSinceEpoch % 1000000;
  210085. t.tv_usec = millisSinceEpoch - t.tv_sec;
  210086. return settimeofday (&t, NULL) ? false : true;
  210087. }
  210088. int SystemStats::getPageSize() throw()
  210089. {
  210090. static int systemPageSize = 0;
  210091. if (systemPageSize == 0)
  210092. systemPageSize = sysconf (_SC_PAGESIZE);
  210093. return systemPageSize;
  210094. }
  210095. int SystemStats::getNumCpus() throw()
  210096. {
  210097. const int lastCpu = getCpuInfo ("processor", true).getIntValue();
  210098. return lastCpu + 1;
  210099. }
  210100. void SystemStats::initialiseStats() throw()
  210101. {
  210102. // Process starts off as root when running suid
  210103. Process::lowerPrivilege();
  210104. String s (SystemStats::getJUCEVersion());
  210105. }
  210106. void PlatformUtilities::fpuReset()
  210107. {
  210108. }
  210109. END_JUCE_NAMESPACE
  210110. /********* End of inlined file: juce_linux_SystemStats.cpp *********/
  210111. /********* Start of inlined file: juce_linux_Threads.cpp *********/
  210112. #include <dlfcn.h>
  210113. #include <sys/file.h>
  210114. #include <sys/types.h>
  210115. #include <sys/ptrace.h>
  210116. BEGIN_JUCE_NAMESPACE
  210117. /*
  210118. Note that a lot of methods that you'd expect to find in this file actually
  210119. live in juce_posix_SharedCode.h!
  210120. */
  210121. #ifndef CPU_ISSET
  210122. #undef SUPPORT_AFFINITIES
  210123. #endif
  210124. void JUCE_API juce_threadEntryPoint (void*);
  210125. void* threadEntryProc (void* value) throw()
  210126. {
  210127. // New threads start off as root when running suid
  210128. Process::lowerPrivilege();
  210129. juce_threadEntryPoint (value);
  210130. return 0;
  210131. }
  210132. void* juce_createThread (void* userData) throw()
  210133. {
  210134. pthread_t handle = 0;
  210135. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  210136. {
  210137. pthread_detach (handle);
  210138. return (void*)handle;
  210139. }
  210140. return 0;
  210141. }
  210142. void juce_killThread (void* handle) throw()
  210143. {
  210144. if (handle != 0)
  210145. pthread_cancel ((pthread_t)handle);
  210146. }
  210147. void juce_setCurrentThreadName (const String& /*name*/) throw()
  210148. {
  210149. }
  210150. int Thread::getCurrentThreadId() throw()
  210151. {
  210152. return (int) pthread_self();
  210153. }
  210154. /*
  210155. * This is all a bit non-ideal... the trouble is that on Linux you
  210156. * need to call setpriority to affect the dynamic priority for
  210157. * non-realtime processes, but this requires the pid, which is not
  210158. * accessible from the pthread_t. We could get it by calling getpid
  210159. * once each thread has started, but then we would need a list of
  210160. * running threads etc etc.
  210161. * Also there is no such thing as IDLE priority on Linux.
  210162. * For the moment, map idle, low and normal process priorities to
  210163. * SCHED_OTHER, with the thread priority ignored for these classes.
  210164. * Map high priority processes to the lower half of the SCHED_RR
  210165. * range, and realtime to the upper half
  210166. */
  210167. // priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  210168. // priority of the current thread
  210169. void juce_setThreadPriority (void* handle, int priority) throw()
  210170. {
  210171. struct sched_param param;
  210172. int policy, maxp, minp, pri;
  210173. if (handle == 0)
  210174. handle = (void*) pthread_self();
  210175. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  210176. && policy != SCHED_OTHER)
  210177. {
  210178. minp = sched_get_priority_min(policy);
  210179. maxp = sched_get_priority_max(policy);
  210180. pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  210181. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  210182. // Realtime process priority
  210183. param.__sched_priority = minp + ((maxp - minp) / 2) + pri;
  210184. else
  210185. // High process priority
  210186. param.__sched_priority = minp + pri;
  210187. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  210188. pthread_setschedparam ((pthread_t) handle, policy, &param);
  210189. }
  210190. }
  210191. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  210192. {
  210193. #if SUPPORT_AFFINITIES
  210194. cpu_set_t affinity;
  210195. CPU_ZERO (&affinity);
  210196. for (int i = 0; i < 32; ++i)
  210197. if ((affinityMask & (1 << i)) != 0)
  210198. CPU_SET (i, &affinity);
  210199. /*
  210200. N.B. If this line causes a compile error, then you've probably not got the latest
  210201. version of glibc installed.
  210202. If you don't want to update your copy of glibc and don't care about cpu affinities,
  210203. then you can just disable all this stuff by removing the SUPPORT_AFFINITIES macro
  210204. from the linuxincludes.h file.
  210205. */
  210206. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  210207. sched_yield();
  210208. #else
  210209. /* affinities aren't supported because either the appropriate header files weren't found,
  210210. or the SUPPORT_AFFINITIES macro was turned off in linuxheaders.h
  210211. */
  210212. jassertfalse
  210213. #endif
  210214. }
  210215. void Thread::yield() throw()
  210216. {
  210217. sched_yield();
  210218. }
  210219. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  210220. void Process::setPriority (ProcessPriority prior)
  210221. {
  210222. struct sched_param param;
  210223. int policy, maxp, minp;
  210224. const int p = (int) prior;
  210225. if (p <= 1)
  210226. policy = SCHED_OTHER;
  210227. else
  210228. policy = SCHED_RR;
  210229. minp = sched_get_priority_min (policy);
  210230. maxp = sched_get_priority_max (policy);
  210231. if (p < 2)
  210232. param.__sched_priority = 0;
  210233. else if (p == 2 )
  210234. // Set to middle of lower realtime priority range
  210235. param.__sched_priority = minp + (maxp - minp) / 4;
  210236. else
  210237. // Set to middle of higher realtime priority range
  210238. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  210239. pthread_setschedparam (pthread_self(), policy, &param);
  210240. }
  210241. void Process::terminate()
  210242. {
  210243. exit (0);
  210244. }
  210245. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  210246. {
  210247. static char testResult = 0;
  210248. if (testResult == 0)
  210249. {
  210250. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  210251. if (testResult >= 0)
  210252. {
  210253. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  210254. testResult = 1;
  210255. }
  210256. }
  210257. return testResult < 0;
  210258. }
  210259. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  210260. {
  210261. return juce_isRunningUnderDebugger();
  210262. }
  210263. void Process::raisePrivilege()
  210264. {
  210265. // If running suid root, change effective user
  210266. // to root
  210267. if (geteuid() != 0 && getuid() == 0)
  210268. {
  210269. setreuid (geteuid(), getuid());
  210270. setregid (getegid(), getgid());
  210271. }
  210272. }
  210273. void Process::lowerPrivilege()
  210274. {
  210275. // If runing suid root, change effective user
  210276. // back to real user
  210277. if (geteuid() == 0 && getuid() != 0)
  210278. {
  210279. setreuid (geteuid(), getuid());
  210280. setregid (getegid(), getgid());
  210281. }
  210282. }
  210283. #if JUCE_BUILD_GUI_CLASSES
  210284. void* Process::loadDynamicLibrary (const String& name)
  210285. {
  210286. return dlopen ((const char*) name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  210287. }
  210288. void Process::freeDynamicLibrary (void* handle)
  210289. {
  210290. dlclose(handle);
  210291. }
  210292. void* Process::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  210293. {
  210294. return dlsym (libraryHandle, (const char*) procedureName);
  210295. }
  210296. #endif
  210297. END_JUCE_NAMESPACE
  210298. /********* End of inlined file: juce_linux_Threads.cpp *********/
  210299. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  210300. /********* Start of inlined file: juce_linux_Audio.cpp *********/
  210301. #if JUCE_BUILD_GUI_CLASSES
  210302. #if JUCE_ALSA
  210303. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  210304. not got your paths set up correctly to find its header files.
  210305. The package you need to install to get ASLA support is "libasound2-dev".
  210306. If you don't have the ALSA library and don't want to build Juce with audio support,
  210307. just disable the JUCE_ALSA flag in juce_Config.h
  210308. */
  210309. #include <alsa/asoundlib.h>
  210310. BEGIN_JUCE_NAMESPACE
  210311. static const int maxNumChans = 64;
  210312. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  210313. {
  210314. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  210315. snd_pcm_hw_params_t* hwParams;
  210316. snd_pcm_hw_params_alloca (&hwParams);
  210317. for (int i = 0; ratesToTry[i] != 0; ++i)
  210318. {
  210319. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  210320. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  210321. {
  210322. rates.addIfNotAlreadyThere (ratesToTry[i]);
  210323. }
  210324. }
  210325. }
  210326. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  210327. {
  210328. snd_pcm_hw_params_t *params;
  210329. snd_pcm_hw_params_alloca (&params);
  210330. if (snd_pcm_hw_params_any (handle, params) >= 0)
  210331. {
  210332. snd_pcm_hw_params_get_channels_min (params, minChans);
  210333. snd_pcm_hw_params_get_channels_max (params, maxChans);
  210334. }
  210335. }
  210336. static void getDeviceProperties (const String& id,
  210337. unsigned int& minChansOut,
  210338. unsigned int& maxChansOut,
  210339. unsigned int& minChansIn,
  210340. unsigned int& maxChansIn,
  210341. Array <int>& rates)
  210342. {
  210343. if (id.isEmpty())
  210344. return;
  210345. snd_ctl_t* handle;
  210346. if (snd_ctl_open (&handle, id.upToLastOccurrenceOf (T(","), false, false), SND_CTL_NONBLOCK) >= 0)
  210347. {
  210348. snd_pcm_info_t* info;
  210349. snd_pcm_info_alloca (&info);
  210350. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  210351. snd_pcm_info_set_device (info, id.fromLastOccurrenceOf (T(","), false, false).getIntValue());
  210352. snd_pcm_info_set_subdevice (info, 0);
  210353. if (snd_ctl_pcm_info (handle, info) >= 0)
  210354. {
  210355. snd_pcm_t* pcmHandle;
  210356. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  210357. {
  210358. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  210359. getDeviceSampleRates (pcmHandle, rates);
  210360. snd_pcm_close (pcmHandle);
  210361. }
  210362. }
  210363. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  210364. if (snd_ctl_pcm_info (handle, info) >= 0)
  210365. {
  210366. snd_pcm_t* pcmHandle;
  210367. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  210368. {
  210369. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  210370. if (rates.size() == 0)
  210371. getDeviceSampleRates (pcmHandle, rates);
  210372. snd_pcm_close (pcmHandle);
  210373. }
  210374. }
  210375. snd_ctl_close (handle);
  210376. }
  210377. }
  210378. class ALSADevice
  210379. {
  210380. public:
  210381. ALSADevice (const String& id,
  210382. const bool forInput)
  210383. : handle (0),
  210384. bitDepth (16),
  210385. numChannelsRunning (0),
  210386. isInput (forInput),
  210387. sampleFormat (AudioDataConverters::int16LE)
  210388. {
  210389. failed (snd_pcm_open (&handle, id,
  210390. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  210391. SND_PCM_ASYNC));
  210392. }
  210393. ~ALSADevice()
  210394. {
  210395. if (handle != 0)
  210396. snd_pcm_close (handle);
  210397. }
  210398. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  210399. {
  210400. if (handle == 0)
  210401. return false;
  210402. snd_pcm_hw_params_t* hwParams;
  210403. snd_pcm_hw_params_alloca (&hwParams);
  210404. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  210405. return false;
  210406. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  210407. isInterleaved = false;
  210408. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  210409. isInterleaved = true;
  210410. else
  210411. {
  210412. jassertfalse
  210413. return false;
  210414. }
  210415. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  210416. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  210417. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  210418. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  210419. SND_PCM_FORMAT_S24_LE, 24, AudioDataConverters::int24LE,
  210420. SND_PCM_FORMAT_S24_BE, 24, AudioDataConverters::int24BE,
  210421. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  210422. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  210423. bitDepth = 0;
  210424. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  210425. {
  210426. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  210427. {
  210428. bitDepth = formatsToTry [i + 1];
  210429. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  210430. break;
  210431. }
  210432. }
  210433. if (bitDepth == 0)
  210434. {
  210435. error = "device doesn't support a compatible PCM format";
  210436. DBG (T("ALSA error: ") + error + T("\n"));
  210437. return false;
  210438. }
  210439. int dir = 0;
  210440. unsigned int periods = 4;
  210441. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  210442. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  210443. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  210444. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  210445. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  210446. || failed (snd_pcm_hw_params (handle, hwParams)))
  210447. {
  210448. return false;
  210449. }
  210450. snd_pcm_sw_params_t* swParams;
  210451. snd_pcm_sw_params_alloca (&swParams);
  210452. if (failed (snd_pcm_sw_params_current (handle, swParams))
  210453. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  210454. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, 0))
  210455. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  210456. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, INT_MAX))
  210457. || failed (snd_pcm_sw_params (handle, swParams)))
  210458. {
  210459. return false;
  210460. }
  210461. /*
  210462. #ifdef JUCE_DEBUG
  210463. // enable this to dump the config of the devices that get opened
  210464. snd_output_t* out;
  210465. snd_output_stdio_attach (&out, stderr, 0);
  210466. snd_pcm_hw_params_dump (hwParams, out);
  210467. snd_pcm_sw_params_dump (swParams, out);
  210468. #endif
  210469. */
  210470. numChannelsRunning = numChannels;
  210471. return true;
  210472. }
  210473. bool write (float** const data, const int numSamples)
  210474. {
  210475. if (isInterleaved)
  210476. {
  210477. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  210478. float* interleaved = (float*) scratch;
  210479. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  210480. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  210481. snd_pcm_sframes_t num = snd_pcm_writei (handle, (void*) interleaved, numSamples);
  210482. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  210483. return false;
  210484. }
  210485. else
  210486. {
  210487. for (int i = 0; i < numChannelsRunning; ++i)
  210488. if (data[i] != 0)
  210489. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  210490. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  210491. if (failed (num))
  210492. {
  210493. if (num == -EPIPE)
  210494. {
  210495. if (failed (snd_pcm_prepare (handle)))
  210496. return false;
  210497. }
  210498. else if (num != -ESTRPIPE)
  210499. return false;
  210500. }
  210501. }
  210502. return true;
  210503. }
  210504. bool read (float** const data, const int numSamples)
  210505. {
  210506. if (isInterleaved)
  210507. {
  210508. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  210509. float* interleaved = (float*) scratch;
  210510. snd_pcm_sframes_t num = snd_pcm_readi (handle, (void*) interleaved, numSamples);
  210511. if (failed (num))
  210512. {
  210513. if (num == -EPIPE)
  210514. {
  210515. if (failed (snd_pcm_prepare (handle)))
  210516. return false;
  210517. }
  210518. else if (num != -ESTRPIPE)
  210519. return false;
  210520. }
  210521. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  210522. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  210523. }
  210524. else
  210525. {
  210526. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  210527. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  210528. return false;
  210529. for (int i = 0; i < numChannelsRunning; ++i)
  210530. if (data[i] != 0)
  210531. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  210532. }
  210533. return true;
  210534. }
  210535. juce_UseDebuggingNewOperator
  210536. snd_pcm_t* handle;
  210537. String error;
  210538. int bitDepth, numChannelsRunning;
  210539. private:
  210540. const bool isInput;
  210541. bool isInterleaved;
  210542. MemoryBlock scratch;
  210543. AudioDataConverters::DataFormat sampleFormat;
  210544. bool failed (const int errorNum)
  210545. {
  210546. if (errorNum >= 0)
  210547. return false;
  210548. error = snd_strerror (errorNum);
  210549. DBG (T("ALSA error: ") + error + T("\n"));
  210550. return true;
  210551. }
  210552. };
  210553. class ALSAThread : public Thread
  210554. {
  210555. public:
  210556. ALSAThread (const String& inputId_,
  210557. const String& outputId_)
  210558. : Thread ("Juce ALSA"),
  210559. sampleRate (0),
  210560. bufferSize (0),
  210561. callback (0),
  210562. inputId (inputId_),
  210563. outputId (outputId_),
  210564. outputDevice (0),
  210565. inputDevice (0),
  210566. numCallbacks (0),
  210567. totalNumInputChannels (0),
  210568. totalNumOutputChannels (0)
  210569. {
  210570. zeromem (outputChannelData, sizeof (outputChannelData));
  210571. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  210572. zeromem (inputChannelData, sizeof (inputChannelData));
  210573. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  210574. initialiseRatesAndChannels();
  210575. }
  210576. ~ALSAThread()
  210577. {
  210578. close();
  210579. }
  210580. void open (const BitArray& inputChannels,
  210581. const BitArray& outputChannels,
  210582. const double sampleRate_,
  210583. const int bufferSize_)
  210584. {
  210585. close();
  210586. error = String::empty;
  210587. sampleRate = sampleRate_;
  210588. bufferSize = bufferSize_;
  210589. currentInputChans.clear();
  210590. currentOutputChans.clear();
  210591. if (inputChannels.getHighestBit() >= 0)
  210592. {
  210593. for (int i = 0; i <= inputChannels.getHighestBit(); ++i)
  210594. {
  210595. inputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  210596. if (inputChannels[i])
  210597. {
  210598. inputChannelDataForCallback [totalNumInputChannels++] = inputChannelData [i];
  210599. currentInputChans.setBit (i);
  210600. }
  210601. }
  210602. }
  210603. if (outputChannels.getHighestBit() >= 0)
  210604. {
  210605. for (int i = 0; i <= outputChannels.getHighestBit(); ++i)
  210606. {
  210607. outputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  210608. if (outputChannels[i])
  210609. {
  210610. outputChannelDataForCallback [totalNumOutputChannels++] = outputChannelData [i];
  210611. currentOutputChans.setBit (i);
  210612. }
  210613. }
  210614. }
  210615. if (totalNumOutputChannels > 0 && outputId.isNotEmpty())
  210616. {
  210617. outputDevice = new ALSADevice (outputId, false);
  210618. if (outputDevice->error.isNotEmpty())
  210619. {
  210620. error = outputDevice->error;
  210621. deleteAndZero (outputDevice);
  210622. return;
  210623. }
  210624. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  210625. currentOutputChans.getHighestBit() + 1,
  210626. bufferSize))
  210627. {
  210628. error = outputDevice->error;
  210629. deleteAndZero (outputDevice);
  210630. return;
  210631. }
  210632. }
  210633. if (totalNumInputChannels > 0 && inputId.isNotEmpty())
  210634. {
  210635. inputDevice = new ALSADevice (inputId, true);
  210636. if (inputDevice->error.isNotEmpty())
  210637. {
  210638. error = inputDevice->error;
  210639. deleteAndZero (inputDevice);
  210640. return;
  210641. }
  210642. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  210643. currentInputChans.getHighestBit() + 1,
  210644. bufferSize))
  210645. {
  210646. error = inputDevice->error;
  210647. deleteAndZero (inputDevice);
  210648. return;
  210649. }
  210650. }
  210651. if (outputDevice == 0 && inputDevice == 0)
  210652. {
  210653. error = "no channels";
  210654. return;
  210655. }
  210656. if (outputDevice != 0 && inputDevice != 0)
  210657. {
  210658. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  210659. }
  210660. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  210661. return;
  210662. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  210663. return;
  210664. startThread (9);
  210665. int count = 1000;
  210666. while (numCallbacks == 0)
  210667. {
  210668. sleep (5);
  210669. if (--count < 0 || ! isThreadRunning())
  210670. {
  210671. error = "device didn't start";
  210672. break;
  210673. }
  210674. }
  210675. }
  210676. void close()
  210677. {
  210678. stopThread (6000);
  210679. deleteAndZero (inputDevice);
  210680. deleteAndZero (outputDevice);
  210681. for (int i = 0; i < maxNumChans; ++i)
  210682. {
  210683. juce_free (inputChannelData [i]);
  210684. juce_free (outputChannelData [i]);
  210685. }
  210686. zeromem (outputChannelData, sizeof (outputChannelData));
  210687. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  210688. zeromem (inputChannelData, sizeof (inputChannelData));
  210689. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  210690. totalNumOutputChannels = 0;
  210691. totalNumInputChannels = 0;
  210692. numCallbacks = 0;
  210693. }
  210694. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  210695. {
  210696. const ScopedLock sl (callbackLock);
  210697. callback = newCallback;
  210698. }
  210699. void run()
  210700. {
  210701. while (! threadShouldExit())
  210702. {
  210703. if (inputDevice != 0)
  210704. {
  210705. if (! inputDevice->read (inputChannelData, bufferSize))
  210706. {
  210707. DBG ("ALSA: read failure");
  210708. break;
  210709. }
  210710. }
  210711. if (threadShouldExit())
  210712. break;
  210713. {
  210714. const ScopedLock sl (callbackLock);
  210715. ++numCallbacks;
  210716. if (callback != 0)
  210717. {
  210718. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback,
  210719. totalNumInputChannels,
  210720. outputChannelDataForCallback,
  210721. totalNumOutputChannels,
  210722. bufferSize);
  210723. }
  210724. else
  210725. {
  210726. for (int i = 0; i < totalNumOutputChannels; ++i)
  210727. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  210728. }
  210729. }
  210730. if (outputDevice != 0)
  210731. {
  210732. failed (snd_pcm_wait (outputDevice->handle, 2000));
  210733. if (threadShouldExit())
  210734. break;
  210735. failed (snd_pcm_avail_update (outputDevice->handle));
  210736. if (! outputDevice->write (outputChannelData, bufferSize))
  210737. {
  210738. DBG ("ALSA: write failure");
  210739. break;
  210740. }
  210741. }
  210742. }
  210743. }
  210744. int getBitDepth() const throw()
  210745. {
  210746. if (outputDevice != 0)
  210747. return outputDevice->bitDepth;
  210748. if (inputDevice != 0)
  210749. return inputDevice->bitDepth;
  210750. return 16;
  210751. }
  210752. juce_UseDebuggingNewOperator
  210753. String error;
  210754. double sampleRate;
  210755. int bufferSize;
  210756. BitArray currentInputChans, currentOutputChans;
  210757. Array <int> sampleRates;
  210758. StringArray channelNamesOut, channelNamesIn;
  210759. AudioIODeviceCallback* callback;
  210760. private:
  210761. const String inputId, outputId;
  210762. ALSADevice* outputDevice;
  210763. ALSADevice* inputDevice;
  210764. int numCallbacks;
  210765. CriticalSection callbackLock;
  210766. float* outputChannelData [maxNumChans];
  210767. float* outputChannelDataForCallback [maxNumChans];
  210768. int totalNumInputChannels;
  210769. float* inputChannelData [maxNumChans];
  210770. float* inputChannelDataForCallback [maxNumChans];
  210771. int totalNumOutputChannels;
  210772. unsigned int minChansOut, maxChansOut;
  210773. unsigned int minChansIn, maxChansIn;
  210774. bool failed (const int errorNum) throw()
  210775. {
  210776. if (errorNum >= 0)
  210777. return false;
  210778. error = snd_strerror (errorNum);
  210779. DBG (T("ALSA error: ") + error + T("\n"));
  210780. return true;
  210781. }
  210782. void initialiseRatesAndChannels() throw()
  210783. {
  210784. sampleRates.clear();
  210785. channelNamesOut.clear();
  210786. channelNamesIn.clear();
  210787. minChansOut = 0;
  210788. maxChansOut = 0;
  210789. minChansIn = 0;
  210790. maxChansIn = 0;
  210791. unsigned int dummy = 0;
  210792. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  210793. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  210794. unsigned int i;
  210795. for (i = 0; i < maxChansOut; ++i)
  210796. channelNamesOut.add (T("channel ") + String ((int) i + 1));
  210797. for (i = 0; i < maxChansIn; ++i)
  210798. channelNamesIn.add (T("channel ") + String ((int) i + 1));
  210799. }
  210800. };
  210801. class ALSAAudioIODevice : public AudioIODevice
  210802. {
  210803. public:
  210804. ALSAAudioIODevice (const String& deviceName,
  210805. const String& inputId_,
  210806. const String& outputId_)
  210807. : AudioIODevice (deviceName, T("ALSA")),
  210808. inputId (inputId_),
  210809. outputId (outputId_),
  210810. isOpen_ (false),
  210811. isStarted (false),
  210812. internal (0)
  210813. {
  210814. internal = new ALSAThread (inputId, outputId);
  210815. }
  210816. ~ALSAAudioIODevice()
  210817. {
  210818. delete internal;
  210819. }
  210820. const StringArray getOutputChannelNames()
  210821. {
  210822. return internal->channelNamesOut;
  210823. }
  210824. const StringArray getInputChannelNames()
  210825. {
  210826. return internal->channelNamesIn;
  210827. }
  210828. int getNumSampleRates()
  210829. {
  210830. return internal->sampleRates.size();
  210831. }
  210832. double getSampleRate (int index)
  210833. {
  210834. return internal->sampleRates [index];
  210835. }
  210836. int getNumBufferSizesAvailable()
  210837. {
  210838. return 50;
  210839. }
  210840. int getBufferSizeSamples (int index)
  210841. {
  210842. int n = 16;
  210843. for (int i = 0; i < index; ++i)
  210844. n += n < 64 ? 16
  210845. : (n < 512 ? 32
  210846. : (n < 1024 ? 64
  210847. : (n < 2048 ? 128 : 256)));
  210848. return n;
  210849. }
  210850. int getDefaultBufferSize()
  210851. {
  210852. return 512;
  210853. }
  210854. const String open (const BitArray& inputChannels,
  210855. const BitArray& outputChannels,
  210856. double sampleRate,
  210857. int bufferSizeSamples)
  210858. {
  210859. close();
  210860. if (bufferSizeSamples <= 0)
  210861. bufferSizeSamples = getDefaultBufferSize();
  210862. if (sampleRate <= 0)
  210863. {
  210864. for (int i = 0; i < getNumSampleRates(); ++i)
  210865. {
  210866. if (getSampleRate (i) >= 44100)
  210867. {
  210868. sampleRate = getSampleRate (i);
  210869. break;
  210870. }
  210871. }
  210872. }
  210873. internal->open (inputChannels, outputChannels,
  210874. sampleRate, bufferSizeSamples);
  210875. isOpen_ = internal->error.isEmpty();
  210876. return internal->error;
  210877. }
  210878. void close()
  210879. {
  210880. stop();
  210881. internal->close();
  210882. isOpen_ = false;
  210883. }
  210884. bool isOpen()
  210885. {
  210886. return isOpen_;
  210887. }
  210888. int getCurrentBufferSizeSamples()
  210889. {
  210890. return internal->bufferSize;
  210891. }
  210892. double getCurrentSampleRate()
  210893. {
  210894. return internal->sampleRate;
  210895. }
  210896. int getCurrentBitDepth()
  210897. {
  210898. return internal->getBitDepth();
  210899. }
  210900. const BitArray getActiveOutputChannels() const
  210901. {
  210902. return internal->currentOutputChans;
  210903. }
  210904. const BitArray getActiveInputChannels() const
  210905. {
  210906. return internal->currentInputChans;
  210907. }
  210908. int getOutputLatencyInSamples()
  210909. {
  210910. return 0;
  210911. }
  210912. int getInputLatencyInSamples()
  210913. {
  210914. return 0;
  210915. }
  210916. void start (AudioIODeviceCallback* callback)
  210917. {
  210918. if (! isOpen_)
  210919. callback = 0;
  210920. internal->setCallback (callback);
  210921. if (callback != 0)
  210922. callback->audioDeviceAboutToStart (this);
  210923. isStarted = (callback != 0);
  210924. }
  210925. void stop()
  210926. {
  210927. AudioIODeviceCallback* const oldCallback = internal->callback;
  210928. start (0);
  210929. if (oldCallback != 0)
  210930. oldCallback->audioDeviceStopped();
  210931. }
  210932. bool isPlaying()
  210933. {
  210934. return isStarted && internal->error.isEmpty();
  210935. }
  210936. const String getLastError()
  210937. {
  210938. return internal->error;
  210939. }
  210940. String inputId, outputId;
  210941. private:
  210942. bool isOpen_, isStarted;
  210943. ALSAThread* internal;
  210944. };
  210945. class ALSAAudioIODeviceType : public AudioIODeviceType
  210946. {
  210947. public:
  210948. ALSAAudioIODeviceType()
  210949. : AudioIODeviceType (T("ALSA")),
  210950. hasScanned (false)
  210951. {
  210952. }
  210953. ~ALSAAudioIODeviceType()
  210954. {
  210955. }
  210956. void scanForDevices()
  210957. {
  210958. if (hasScanned)
  210959. return;
  210960. hasScanned = true;
  210961. inputNames.clear();
  210962. inputIds.clear();
  210963. outputNames.clear();
  210964. outputIds.clear();
  210965. snd_ctl_t* handle;
  210966. snd_ctl_card_info_t* info;
  210967. snd_ctl_card_info_alloca (&info);
  210968. int cardNum = -1;
  210969. while (outputIds.size() + inputIds.size() <= 32)
  210970. {
  210971. snd_card_next (&cardNum);
  210972. if (cardNum < 0)
  210973. break;
  210974. if (snd_ctl_open (&handle, T("hw:") + String (cardNum), SND_CTL_NONBLOCK) >= 0)
  210975. {
  210976. if (snd_ctl_card_info (handle, info) >= 0)
  210977. {
  210978. String cardId (snd_ctl_card_info_get_id (info));
  210979. if (cardId.removeCharacters (T("0123456789")).isEmpty())
  210980. cardId = String (cardNum);
  210981. int device = -1;
  210982. for (;;)
  210983. {
  210984. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  210985. break;
  210986. String id, name;
  210987. id << "hw:" << cardId << ',' << device;
  210988. bool isInput, isOutput;
  210989. if (testDevice (id, isInput, isOutput))
  210990. {
  210991. name << snd_ctl_card_info_get_name (info);
  210992. if (name.isEmpty())
  210993. name = id;
  210994. if (isInput)
  210995. {
  210996. inputNames.add (name);
  210997. inputIds.add (id);
  210998. }
  210999. if (isOutput)
  211000. {
  211001. outputNames.add (name);
  211002. outputIds.add (id);
  211003. }
  211004. }
  211005. }
  211006. }
  211007. snd_ctl_close (handle);
  211008. }
  211009. }
  211010. inputNames.appendNumbersToDuplicates (false, true);
  211011. outputNames.appendNumbersToDuplicates (false, true);
  211012. }
  211013. const StringArray getDeviceNames (const bool wantInputNames) const
  211014. {
  211015. jassert (hasScanned); // need to call scanForDevices() before doing this
  211016. return wantInputNames ? inputNames : outputNames;
  211017. }
  211018. int getDefaultDeviceIndex (const bool forInput) const
  211019. {
  211020. jassert (hasScanned); // need to call scanForDevices() before doing this
  211021. return 0;
  211022. }
  211023. bool hasSeparateInputsAndOutputs() const { return true; }
  211024. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  211025. {
  211026. jassert (hasScanned); // need to call scanForDevices() before doing this
  211027. ALSAAudioIODevice* const d = dynamic_cast <ALSAAudioIODevice*> (device);
  211028. if (d == 0)
  211029. return -1;
  211030. return asInput ? inputIds.indexOf (d->inputId)
  211031. : outputIds.indexOf (d->outputId);
  211032. }
  211033. AudioIODevice* createDevice (const String& outputDeviceName,
  211034. const String& inputDeviceName)
  211035. {
  211036. jassert (hasScanned); // need to call scanForDevices() before doing this
  211037. const int inputIndex = inputNames.indexOf (inputDeviceName);
  211038. const int outputIndex = outputNames.indexOf (outputDeviceName);
  211039. String deviceName (outputDeviceName);
  211040. if (deviceName.isEmpty())
  211041. deviceName = inputDeviceName;
  211042. if (index >= 0)
  211043. return new ALSAAudioIODevice (deviceName,
  211044. inputIds [inputIndex],
  211045. outputIds [outputIndex]);
  211046. return 0;
  211047. }
  211048. juce_UseDebuggingNewOperator
  211049. private:
  211050. StringArray inputNames, outputNames, inputIds, outputIds;
  211051. bool hasScanned;
  211052. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  211053. {
  211054. unsigned int minChansOut = 0, maxChansOut = 0;
  211055. unsigned int minChansIn = 0, maxChansIn = 0;
  211056. Array <int> rates;
  211057. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  211058. DBG (T("ALSA device: ") + id
  211059. + T(" outs=") + String ((int) minChansOut) + T("-") + String ((int) maxChansOut)
  211060. + T(" ins=") + String ((int) minChansIn) + T("-") + String ((int) maxChansIn)
  211061. + T(" rates=") + String (rates.size()));
  211062. isInput = maxChansIn > 0;
  211063. isOutput = maxChansOut > 0;
  211064. return (isInput || isOutput) && rates.size() > 0;
  211065. }
  211066. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  211067. const ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  211068. };
  211069. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  211070. {
  211071. return new ALSAAudioIODeviceType();
  211072. }
  211073. END_JUCE_NAMESPACE
  211074. #else // if ALSA is turned off..
  211075. BEGIN_JUCE_NAMESPACE
  211076. AudioIODeviceType* juce_createDefaultAudioIODeviceType() { return 0; }
  211077. END_JUCE_NAMESPACE
  211078. #endif
  211079. #endif
  211080. /********* End of inlined file: juce_linux_Audio.cpp *********/
  211081. /********* Start of inlined file: juce_linux_AudioCDReader.cpp *********/
  211082. BEGIN_JUCE_NAMESPACE
  211083. AudioCDReader::AudioCDReader()
  211084. : AudioFormatReader (0, T("CD Audio"))
  211085. {
  211086. }
  211087. const StringArray AudioCDReader::getAvailableCDNames()
  211088. {
  211089. StringArray names;
  211090. return names;
  211091. }
  211092. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  211093. {
  211094. return 0;
  211095. }
  211096. AudioCDReader::~AudioCDReader()
  211097. {
  211098. }
  211099. void AudioCDReader::refreshTrackLengths()
  211100. {
  211101. }
  211102. bool AudioCDReader::read (int** destSamples,
  211103. int64 startSampleInFile,
  211104. int numSamples)
  211105. {
  211106. return false;
  211107. }
  211108. bool AudioCDReader::isCDStillPresent() const
  211109. {
  211110. return false;
  211111. }
  211112. int AudioCDReader::getNumTracks() const
  211113. {
  211114. return 0;
  211115. }
  211116. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  211117. {
  211118. return 0;
  211119. }
  211120. bool AudioCDReader::isTrackAudio (int trackNum) const
  211121. {
  211122. return false;
  211123. }
  211124. void AudioCDReader::enableIndexScanning (bool b)
  211125. {
  211126. }
  211127. int AudioCDReader::getLastIndex() const
  211128. {
  211129. return 0;
  211130. }
  211131. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211132. {
  211133. return Array<int>();
  211134. }
  211135. int AudioCDReader::getCDDBId()
  211136. {
  211137. return 0;
  211138. }
  211139. END_JUCE_NAMESPACE
  211140. /********* End of inlined file: juce_linux_AudioCDReader.cpp *********/
  211141. /********* Start of inlined file: juce_linux_FileChooser.cpp *********/
  211142. #if JUCE_BUILD_GUI_CLASSES
  211143. BEGIN_JUCE_NAMESPACE
  211144. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  211145. const String& title,
  211146. const File& file,
  211147. const String& filters,
  211148. bool isDirectory,
  211149. bool isSave,
  211150. bool warnAboutOverwritingExistingFiles,
  211151. bool selectMultipleFiles,
  211152. FilePreviewComponent* previewComponent)
  211153. {
  211154. //xxx ain't got one!
  211155. jassertfalse
  211156. }
  211157. END_JUCE_NAMESPACE
  211158. #endif
  211159. /********* End of inlined file: juce_linux_FileChooser.cpp *********/
  211160. /********* Start of inlined file: juce_linux_Fonts.cpp *********/
  211161. #if JUCE_BUILD_GUI_CLASSES
  211162. /* Got a build error here? You'll need to install the freetype library...
  211163. The name of the package to install is "libfreetype6-dev".
  211164. */
  211165. #include <ft2build.h>
  211166. #include FT_FREETYPE_H
  211167. BEGIN_JUCE_NAMESPACE
  211168. class FreeTypeFontFace
  211169. {
  211170. public:
  211171. enum FontStyle
  211172. {
  211173. Plain = 0,
  211174. Bold = 1,
  211175. Italic = 2
  211176. };
  211177. struct FontNameIndex
  211178. {
  211179. String fileName;
  211180. int faceIndex;
  211181. };
  211182. FreeTypeFontFace (const String& familyName)
  211183. : hasSerif (false),
  211184. monospaced (false)
  211185. {
  211186. family = familyName;
  211187. }
  211188. void setFileName (const String& name,
  211189. const int faceIndex,
  211190. FontStyle style)
  211191. {
  211192. if (names[(int) style].fileName.isEmpty())
  211193. {
  211194. names[(int) style].fileName = name;
  211195. names[(int) style].faceIndex = faceIndex;
  211196. }
  211197. }
  211198. const String& getFamilyName() const throw()
  211199. {
  211200. return family;
  211201. }
  211202. const String& getFileName (int style, int* faceIndex) const throw()
  211203. {
  211204. *faceIndex = names [style].faceIndex;
  211205. return names[style].fileName;
  211206. }
  211207. void setMonospaced (bool mono) { monospaced = mono; }
  211208. bool getMonospaced () const throw() { return monospaced; }
  211209. void setSerif (const bool serif) { hasSerif = serif; }
  211210. bool getSerif () const throw() { return hasSerif; }
  211211. private:
  211212. String family;
  211213. FontNameIndex names[4];
  211214. bool hasSerif, monospaced;
  211215. };
  211216. class FreeTypeInterface : public DeletedAtShutdown
  211217. {
  211218. public:
  211219. FreeTypeInterface() throw()
  211220. : lastFace (0),
  211221. lastBold (false),
  211222. lastItalic (false)
  211223. {
  211224. if (FT_Init_FreeType (&ftLib) != 0)
  211225. {
  211226. ftLib = 0;
  211227. DBG (T("Failed to initialize FreeType"));
  211228. }
  211229. StringArray fontDirs;
  211230. fontDirs.addTokens (String (getenv ("JUCE_FONT_PATH")), T(";,"), 0);
  211231. fontDirs.removeEmptyStrings (true);
  211232. if (fontDirs.size() == 0)
  211233. {
  211234. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  211235. XmlElement* const fontsInfo = fontsConfig.getDocumentElement();
  211236. if (fontsInfo != 0)
  211237. {
  211238. forEachXmlChildElementWithTagName (*fontsInfo, e, T("dir"))
  211239. {
  211240. fontDirs.add (e->getAllSubText().trim());
  211241. }
  211242. delete fontsInfo;
  211243. }
  211244. }
  211245. if (fontDirs.size() == 0)
  211246. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  211247. for (int i = 0; i < fontDirs.size(); ++i)
  211248. enumerateFaces (fontDirs[i]);
  211249. }
  211250. ~FreeTypeInterface() throw()
  211251. {
  211252. if (lastFace != 0)
  211253. FT_Done_Face (lastFace);
  211254. if (ftLib != 0)
  211255. FT_Done_FreeType (ftLib);
  211256. clearSingletonInstance();
  211257. }
  211258. FreeTypeFontFace* findOrCreate (const String& familyName,
  211259. const bool create = false) throw()
  211260. {
  211261. for (int i = 0; i < faces.size(); i++)
  211262. if (faces[i]->getFamilyName() == familyName)
  211263. return faces[i];
  211264. if (! create)
  211265. return NULL;
  211266. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  211267. faces.add (newFace);
  211268. return newFace;
  211269. }
  211270. // Enumerate all font faces available in a given directory
  211271. void enumerateFaces (const String& path) throw()
  211272. {
  211273. File dirPath (path);
  211274. if (path.isEmpty() || ! dirPath.isDirectory())
  211275. return;
  211276. DirectoryIterator di (dirPath, true);
  211277. while (di.next())
  211278. {
  211279. File possible (di.getFile());
  211280. if (possible.hasFileExtension (T("ttf"))
  211281. || possible.hasFileExtension (T("pfb"))
  211282. || possible.hasFileExtension (T("pcf")))
  211283. {
  211284. FT_Face face;
  211285. int faceIndex = 0;
  211286. int numFaces = 0;
  211287. do
  211288. {
  211289. if (FT_New_Face (ftLib,
  211290. possible.getFullPathName(),
  211291. faceIndex,
  211292. &face) == 0)
  211293. {
  211294. if (faceIndex == 0)
  211295. numFaces = face->num_faces;
  211296. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  211297. {
  211298. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  211299. int style = (int) FreeTypeFontFace::Plain;
  211300. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  211301. style |= (int) FreeTypeFontFace::Bold;
  211302. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  211303. style |= (int) FreeTypeFontFace::Italic;
  211304. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  211305. if ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0)
  211306. newFace->setMonospaced (true);
  211307. else
  211308. newFace->setMonospaced (false);
  211309. // Surely there must be a better way to do this?
  211310. if (String (face->family_name).containsIgnoreCase (T("Sans"))
  211311. || String (face->family_name).containsIgnoreCase (T("Verdana"))
  211312. || String (face->family_name).containsIgnoreCase (T("Arial")))
  211313. {
  211314. newFace->setSerif (false);
  211315. }
  211316. else
  211317. {
  211318. newFace->setSerif (true);
  211319. }
  211320. }
  211321. FT_Done_Face (face);
  211322. }
  211323. ++faceIndex;
  211324. }
  211325. while (faceIndex < numFaces);
  211326. }
  211327. }
  211328. }
  211329. // Create a FreeType face object for a given font
  211330. FT_Face createFT_Face (const String& fontName,
  211331. const bool bold,
  211332. const bool italic) throw()
  211333. {
  211334. FT_Face face = NULL;
  211335. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  211336. {
  211337. face = lastFace;
  211338. }
  211339. else
  211340. {
  211341. if (lastFace)
  211342. {
  211343. FT_Done_Face (lastFace);
  211344. lastFace = NULL;
  211345. }
  211346. lastFontName = fontName;
  211347. lastBold = bold;
  211348. lastItalic = italic;
  211349. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  211350. if (ftFace != 0)
  211351. {
  211352. int style = (int) FreeTypeFontFace::Plain;
  211353. if (bold)
  211354. style |= (int) FreeTypeFontFace::Bold;
  211355. if (italic)
  211356. style |= (int) FreeTypeFontFace::Italic;
  211357. int faceIndex;
  211358. String fileName (ftFace->getFileName (style, &faceIndex));
  211359. if (fileName.isEmpty())
  211360. {
  211361. style ^= (int) FreeTypeFontFace::Bold;
  211362. fileName = ftFace->getFileName (style, &faceIndex);
  211363. if (fileName.isEmpty())
  211364. {
  211365. style ^= (int) FreeTypeFontFace::Bold;
  211366. style ^= (int) FreeTypeFontFace::Italic;
  211367. fileName = ftFace->getFileName (style, &faceIndex);
  211368. if (! fileName.length())
  211369. {
  211370. style ^= (int) FreeTypeFontFace::Bold;
  211371. fileName = ftFace->getFileName (style, &faceIndex);
  211372. }
  211373. }
  211374. }
  211375. if (! FT_New_Face (ftLib, (const char*) fileName, faceIndex, &lastFace))
  211376. {
  211377. face = lastFace;
  211378. // If there isn't a unicode charmap then select the first one.
  211379. if (FT_Select_Charmap (face, ft_encoding_unicode))
  211380. FT_Set_Charmap (face, face->charmaps[0]);
  211381. }
  211382. }
  211383. }
  211384. return face;
  211385. }
  211386. bool addGlyph (FT_Face face, Typeface& dest, uint32 character) throw()
  211387. {
  211388. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  211389. const float height = (float) (face->ascender - face->descender);
  211390. const float scaleX = 1.0f / height;
  211391. const float scaleY = -1.0f / height;
  211392. Path destShape;
  211393. #define CONVERTX(val) (scaleX * (val).x)
  211394. #define CONVERTY(val) (scaleY * (val).y)
  211395. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE
  211396. | FT_LOAD_NO_BITMAP
  211397. | FT_LOAD_IGNORE_TRANSFORM) != 0
  211398. || face->glyph->format != ft_glyph_format_outline)
  211399. {
  211400. return false;
  211401. }
  211402. const FT_Outline* const outline = &face->glyph->outline;
  211403. const short* const contours = outline->contours;
  211404. const char* const tags = outline->tags;
  211405. FT_Vector* const points = outline->points;
  211406. for (int c = 0; c < outline->n_contours; c++)
  211407. {
  211408. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  211409. const int endPoint = contours[c];
  211410. for (int p = startPoint; p <= endPoint; p++)
  211411. {
  211412. const float x = CONVERTX (points[p]);
  211413. const float y = CONVERTY (points[p]);
  211414. if (p == startPoint)
  211415. {
  211416. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  211417. {
  211418. float x2 = CONVERTX (points [endPoint]);
  211419. float y2 = CONVERTY (points [endPoint]);
  211420. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  211421. {
  211422. x2 = (x + x2) * 0.5f;
  211423. y2 = (y + y2) * 0.5f;
  211424. }
  211425. destShape.startNewSubPath (x2, y2);
  211426. }
  211427. else
  211428. {
  211429. destShape.startNewSubPath (x, y);
  211430. }
  211431. }
  211432. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  211433. {
  211434. if (p != startPoint)
  211435. destShape.lineTo (x, y);
  211436. }
  211437. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  211438. {
  211439. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  211440. float x2 = CONVERTX (points [nextIndex]);
  211441. float y2 = CONVERTY (points [nextIndex]);
  211442. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  211443. {
  211444. x2 = (x + x2) * 0.5f;
  211445. y2 = (y + y2) * 0.5f;
  211446. }
  211447. else
  211448. {
  211449. ++p;
  211450. }
  211451. destShape.quadraticTo (x, y, x2, y2);
  211452. }
  211453. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  211454. {
  211455. if (p >= endPoint)
  211456. return false;
  211457. const int next1 = p + 1;
  211458. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  211459. const float x2 = CONVERTX (points [next1]);
  211460. const float y2 = CONVERTY (points [next1]);
  211461. const float x3 = CONVERTX (points [next2]);
  211462. const float y3 = CONVERTY (points [next2]);
  211463. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  211464. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  211465. return false;
  211466. destShape.cubicTo (x, y, x2, y2, x3, y3);
  211467. p += 2;
  211468. }
  211469. }
  211470. destShape.closeSubPath();
  211471. }
  211472. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance/height);
  211473. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  211474. addKerning (face, dest, character, glyphIndex);
  211475. return true;
  211476. }
  211477. void addKerning (FT_Face face, Typeface& dest, const uint32 character, const uint32 glyphIndex) throw()
  211478. {
  211479. const float height = (float) (face->ascender - face->descender);
  211480. uint32 rightGlyphIndex;
  211481. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  211482. while (rightGlyphIndex != 0)
  211483. {
  211484. FT_Vector kerning;
  211485. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  211486. {
  211487. if (kerning.x != 0)
  211488. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  211489. }
  211490. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  211491. }
  211492. }
  211493. // Add a glyph to a font
  211494. bool addGlyphToFont (const uint32 character,
  211495. const tchar* fontName, bool bold, bool italic,
  211496. Typeface& dest) throw()
  211497. {
  211498. FT_Face face = createFT_Face (fontName, bold, italic);
  211499. if (face != 0)
  211500. return addGlyph (face, dest, character);
  211501. return false;
  211502. }
  211503. // Create a Typeface object for given name/style
  211504. bool createTypeface (const String& fontName,
  211505. const bool bold, const bool italic,
  211506. Typeface& dest,
  211507. const bool addAllGlyphs) throw()
  211508. {
  211509. dest.clear();
  211510. dest.setName (fontName);
  211511. dest.setBold (bold);
  211512. dest.setItalic (italic);
  211513. FT_Face face = createFT_Face (fontName, bold, italic);
  211514. if (face == 0)
  211515. {
  211516. #ifdef JUCE_DEBUG
  211517. String msg (T("Failed to create typeface: "));
  211518. msg << fontName << " " << (bold ? 'B' : ' ') << (italic ? 'I' : ' ');
  211519. DBG (msg);
  211520. #endif
  211521. return face;
  211522. }
  211523. const float height = (float) (face->ascender - face->descender);
  211524. dest.setAscent (face->ascender / height);
  211525. dest.setDefaultCharacter (L' ');
  211526. if (addAllGlyphs)
  211527. {
  211528. uint32 glyphIndex;
  211529. uint32 charCode = FT_Get_First_Char (face, &glyphIndex);
  211530. while (glyphIndex != 0)
  211531. {
  211532. addGlyph (face, dest, charCode);
  211533. charCode = FT_Get_Next_Char (face, charCode, &glyphIndex);
  211534. }
  211535. }
  211536. return true;
  211537. }
  211538. void getFamilyNames (StringArray& familyNames) const throw()
  211539. {
  211540. for (int i = 0; i < faces.size(); i++)
  211541. familyNames.add (faces[i]->getFamilyName());
  211542. }
  211543. void getMonospacedNames (StringArray& monoSpaced) const throw()
  211544. {
  211545. for (int i = 0; i < faces.size(); i++)
  211546. if (faces[i]->getMonospaced())
  211547. monoSpaced.add (faces[i]->getFamilyName());
  211548. }
  211549. void getSerifNames (StringArray& serif) const throw()
  211550. {
  211551. for (int i = 0; i < faces.size(); i++)
  211552. if (faces[i]->getSerif())
  211553. serif.add (faces[i]->getFamilyName());
  211554. }
  211555. void getSansSerifNames (StringArray& sansSerif) const throw()
  211556. {
  211557. for (int i = 0; i < faces.size(); i++)
  211558. if (! faces[i]->getSerif())
  211559. sansSerif.add (faces[i]->getFamilyName());
  211560. }
  211561. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  211562. private:
  211563. FT_Library ftLib;
  211564. FT_Face lastFace;
  211565. String lastFontName;
  211566. bool lastBold, lastItalic;
  211567. OwnedArray<FreeTypeFontFace> faces;
  211568. };
  211569. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  211570. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  211571. bool bold, bool italic,
  211572. bool addAllGlyphsToFont) throw()
  211573. {
  211574. FreeTypeInterface::getInstance()
  211575. ->createTypeface (fontName, bold, italic, *this, addAllGlyphsToFont);
  211576. }
  211577. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  211578. {
  211579. return FreeTypeInterface::getInstance()
  211580. ->addGlyphToFont (character, getName(), isBold(), isItalic(), *this);
  211581. }
  211582. const StringArray Font::findAllTypefaceNames() throw()
  211583. {
  211584. StringArray s;
  211585. FreeTypeInterface::getInstance()->getFamilyNames (s);
  211586. s.sort (true);
  211587. return s;
  211588. }
  211589. static const String pickBestFont (const StringArray& names,
  211590. const char* const choicesString)
  211591. {
  211592. StringArray choices;
  211593. choices.addTokens (String (choicesString), T(","), 0);
  211594. choices.trim();
  211595. choices.removeEmptyStrings();
  211596. int i, j;
  211597. for (j = 0; j < choices.size(); ++j)
  211598. if (names.contains (choices[j], true))
  211599. return choices[j];
  211600. for (j = 0; j < choices.size(); ++j)
  211601. for (i = 0; i < names.size(); i++)
  211602. if (names[i].startsWithIgnoreCase (choices[j]))
  211603. return names[i];
  211604. for (j = 0; j < choices.size(); ++j)
  211605. for (i = 0; i < names.size(); i++)
  211606. if (names[i].containsIgnoreCase (choices[j]))
  211607. return names[i];
  211608. return names[0];
  211609. }
  211610. static const String linux_getDefaultSansSerifFontName()
  211611. {
  211612. StringArray allFonts;
  211613. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  211614. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  211615. }
  211616. static const String linux_getDefaultSerifFontName()
  211617. {
  211618. StringArray allFonts;
  211619. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  211620. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  211621. }
  211622. static const String linux_getDefaultMonospacedFontName()
  211623. {
  211624. StringArray allFonts;
  211625. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  211626. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  211627. }
  211628. void Font::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  211629. {
  211630. defaultSans = linux_getDefaultSansSerifFontName();
  211631. defaultSerif = linux_getDefaultSerifFontName();
  211632. defaultFixed = linux_getDefaultMonospacedFontName();
  211633. }
  211634. END_JUCE_NAMESPACE
  211635. #endif
  211636. /********* End of inlined file: juce_linux_Fonts.cpp *********/
  211637. /********* Start of inlined file: juce_linux_Messaging.cpp *********/
  211638. #if JUCE_BUILD_GUI_CLASSES
  211639. #include <stdio.h>
  211640. #include <signal.h>
  211641. #include <X11/Xlib.h>
  211642. #include <X11/Xatom.h>
  211643. #include <X11/Xresource.h>
  211644. #include <X11/Xutil.h>
  211645. BEGIN_JUCE_NAMESPACE
  211646. #ifdef JUCE_DEBUG
  211647. #define JUCE_DEBUG_XERRORS 1
  211648. #endif
  211649. Display* display = 0; // This is also referenced from WindowDriver.cpp
  211650. static Window juce_messageWindowHandle = None;
  211651. #define SpecialAtom "JUCESpecialAtom"
  211652. #define BroadcastAtom "JUCEBroadcastAtom"
  211653. #define SpecialCallbackAtom "JUCESpecialCallbackAtom"
  211654. static Atom specialId;
  211655. static Atom broadcastId;
  211656. static Atom specialCallbackId;
  211657. // This is referenced from WindowDriver.cpp
  211658. XContext improbableNumber;
  211659. // Defined in WindowDriver.cpp
  211660. extern void juce_windowMessageReceive (XEvent* event);
  211661. struct MessageThreadFuncCall
  211662. {
  211663. MessageCallbackFunction* func;
  211664. void* parameter;
  211665. void* result;
  211666. CriticalSection lock;
  211667. WaitableEvent event;
  211668. };
  211669. static bool errorCondition = false;
  211670. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  211671. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  211672. // (defined in another file to avoid problems including certain headers in this one)
  211673. extern bool juce_isRunningAsApplication();
  211674. // Usually happens when client-server connection is broken
  211675. static int ioErrorHandler (Display* display)
  211676. {
  211677. DBG (T("ERROR: connection to X server broken.. terminating."));
  211678. errorCondition = true;
  211679. if (juce_isRunningAsApplication())
  211680. Process::terminate();
  211681. return 0;
  211682. }
  211683. // A protocol error has occurred
  211684. static int errorHandler (Display* display, XErrorEvent* event)
  211685. {
  211686. #ifdef JUCE_DEBUG_XERRORS
  211687. char errorStr[64] = { 0 };
  211688. char requestStr[64] = { 0 };
  211689. XGetErrorText (display, event->error_code, errorStr, 64);
  211690. XGetErrorDatabaseText (display,
  211691. "XRequest",
  211692. (const char*) String (event->request_code),
  211693. "Unknown",
  211694. requestStr,
  211695. 64);
  211696. DBG (T("ERROR: X returned ") + String (errorStr) + T(" for operation ") + String (requestStr));
  211697. #endif
  211698. return 0;
  211699. }
  211700. static bool breakIn = false;
  211701. // Breakin from keyboard
  211702. static void sig_handler (int sig)
  211703. {
  211704. if (sig == SIGINT)
  211705. {
  211706. breakIn = true;
  211707. return;
  211708. }
  211709. static bool reentrant = false;
  211710. if (reentrant == false)
  211711. {
  211712. reentrant = true;
  211713. // Illegal instruction
  211714. fflush (stdout);
  211715. Logger::outputDebugString ("ERROR: Program executed illegal instruction.. terminating");
  211716. errorCondition = true;
  211717. if (juce_isRunningAsApplication())
  211718. Process::terminate();
  211719. }
  211720. else
  211721. {
  211722. if (juce_isRunningAsApplication())
  211723. exit(0);
  211724. }
  211725. }
  211726. void MessageManager::doPlatformSpecificInitialisation()
  211727. {
  211728. // Initialise xlib for multiple thread support
  211729. static bool initThreadCalled = false;
  211730. if (! initThreadCalled)
  211731. {
  211732. if (! XInitThreads())
  211733. {
  211734. // This is fatal! Print error and closedown
  211735. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  211736. if (juce_isRunningAsApplication())
  211737. Process::terminate();
  211738. return;
  211739. }
  211740. initThreadCalled = true;
  211741. }
  211742. // This is called if the client/server connection is broken
  211743. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  211744. // This is called if a protocol error occurs
  211745. oldErrorHandler = XSetErrorHandler (errorHandler);
  211746. // Install signal handler for break-in
  211747. struct sigaction saction;
  211748. sigset_t maskSet;
  211749. sigemptyset (&maskSet);
  211750. saction.sa_handler = sig_handler;
  211751. saction.sa_mask = maskSet;
  211752. saction.sa_flags = 0;
  211753. sigaction (SIGINT, &saction, NULL);
  211754. #ifndef _DEBUG
  211755. // Setup signal handlers for various fatal errors
  211756. sigaction (SIGILL, &saction, NULL);
  211757. sigaction (SIGBUS, &saction, NULL);
  211758. sigaction (SIGFPE, &saction, NULL);
  211759. sigaction (SIGSEGV, &saction, NULL);
  211760. sigaction (SIGSYS, &saction, NULL);
  211761. #endif
  211762. String displayName (getenv ("DISPLAY"));
  211763. if (displayName.isEmpty())
  211764. displayName = T(":0.0");
  211765. display = XOpenDisplay (displayName);
  211766. if (display == 0)
  211767. {
  211768. // This is fatal! Print error and closedown
  211769. Logger::outputDebugString ("Failed to open the X display.");
  211770. if (juce_isRunningAsApplication())
  211771. Process::terminate();
  211772. return;
  211773. }
  211774. // Get defaults for various properties
  211775. int screen = DefaultScreen (display);
  211776. Window root = RootWindow (display, screen);
  211777. Visual* visual = DefaultVisual (display, screen);
  211778. // Create atoms for our ClientMessages (these cannot be deleted)
  211779. specialId = XInternAtom (display, SpecialAtom, false);
  211780. broadcastId = XInternAtom (display, BroadcastAtom, false);
  211781. specialCallbackId = XInternAtom (display, SpecialCallbackAtom, false);
  211782. // Create a context to store user data associated with Windows we
  211783. // create in WindowDriver
  211784. improbableNumber = XUniqueContext();
  211785. // We're only interested in client messages for this window
  211786. // which are always sent
  211787. XSetWindowAttributes swa;
  211788. swa.event_mask = NoEventMask;
  211789. // Create our message window (this will never be mapped)
  211790. juce_messageWindowHandle = XCreateWindow (display, root,
  211791. 0, 0, 1, 1, 0, 0, InputOnly,
  211792. visual, CWEventMask, &swa);
  211793. }
  211794. void MessageManager::doPlatformSpecificShutdown()
  211795. {
  211796. if (errorCondition == false)
  211797. {
  211798. XDestroyWindow (display, juce_messageWindowHandle);
  211799. XCloseDisplay (display);
  211800. // reset pointers
  211801. juce_messageWindowHandle = 0;
  211802. display = 0;
  211803. // Restore original error handlers
  211804. XSetIOErrorHandler (oldIOErrorHandler);
  211805. oldIOErrorHandler = 0;
  211806. XSetErrorHandler (oldErrorHandler);
  211807. oldErrorHandler = 0;
  211808. }
  211809. }
  211810. bool juce_postMessageToSystemQueue (void* message)
  211811. {
  211812. if (errorCondition)
  211813. return false;
  211814. XClientMessageEvent clientMsg;
  211815. clientMsg.display = display;
  211816. clientMsg.window = juce_messageWindowHandle;
  211817. clientMsg.type = ClientMessage;
  211818. clientMsg.format = 32;
  211819. clientMsg.message_type = specialId;
  211820. #if JUCE_64BIT
  211821. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) message) >> 32));
  211822. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (long) message);
  211823. #else
  211824. clientMsg.data.l[0] = (long) message;
  211825. #endif
  211826. XSendEvent (display, juce_messageWindowHandle, false,
  211827. NoEventMask, (XEvent*) &clientMsg);
  211828. XFlush (display); // This is necessary to ensure the event is delivered
  211829. return true;
  211830. }
  211831. void MessageManager::broadcastMessage (const String& value) throw()
  211832. {
  211833. }
  211834. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  211835. void* parameter)
  211836. {
  211837. void* retVal = 0;
  211838. if (! errorCondition)
  211839. {
  211840. if (! isThisTheMessageThread())
  211841. {
  211842. static MessageThreadFuncCall messageFuncCallContext;
  211843. const ScopedLock sl (messageFuncCallContext.lock);
  211844. XClientMessageEvent clientMsg;
  211845. clientMsg.display = display;
  211846. clientMsg.window = juce_messageWindowHandle;
  211847. clientMsg.type = ClientMessage;
  211848. clientMsg.format = 32;
  211849. clientMsg.message_type = specialCallbackId;
  211850. #if JUCE_64BIT
  211851. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) &messageFuncCallContext) >> 32));
  211852. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (uint64) &messageFuncCallContext);
  211853. #else
  211854. clientMsg.data.l[0] = (long) &messageFuncCallContext;
  211855. #endif
  211856. messageFuncCallContext.func = func;
  211857. messageFuncCallContext.parameter = parameter;
  211858. if (XSendEvent (display, juce_messageWindowHandle, false, NoEventMask, (XEvent*) &clientMsg) == 0)
  211859. return 0;
  211860. XFlush (display); // This is necessary to ensure the event is delivered
  211861. // Wait for it to complete before continuing
  211862. messageFuncCallContext.event.wait();
  211863. retVal = messageFuncCallContext.result;
  211864. }
  211865. else
  211866. {
  211867. // Just call the function directly
  211868. retVal = func (parameter);
  211869. }
  211870. }
  211871. return retVal;
  211872. }
  211873. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  211874. {
  211875. if (errorCondition)
  211876. return false;
  211877. if (breakIn)
  211878. {
  211879. errorCondition = true;
  211880. if (juce_isRunningAsApplication())
  211881. Process::terminate();
  211882. return false;
  211883. }
  211884. if (returnIfNoPendingMessages && ! XPending (display))
  211885. return false;
  211886. XEvent evt;
  211887. XNextEvent (display, &evt);
  211888. if (evt.type == ClientMessage && evt.xany.window == juce_messageWindowHandle)
  211889. {
  211890. XClientMessageEvent* const clientMsg = (XClientMessageEvent*) &evt;
  211891. if (clientMsg->format != 32)
  211892. {
  211893. jassertfalse
  211894. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received malformed client message.");
  211895. }
  211896. else
  211897. {
  211898. JUCE_TRY
  211899. {
  211900. #if JUCE_64BIT
  211901. void* const messagePtr
  211902. = (void*) ((0xffffffff00000000 & (((uint64) clientMsg->data.l[0]) << 32))
  211903. | (clientMsg->data.l[1] & 0x00000000ffffffff));
  211904. #else
  211905. void* const messagePtr = (void*) (clientMsg->data.l[0]);
  211906. #endif
  211907. if (clientMsg->message_type == specialId)
  211908. {
  211909. MessageManager::getInstance()->deliverMessage (messagePtr);
  211910. }
  211911. else if (clientMsg->message_type == specialCallbackId)
  211912. {
  211913. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) messagePtr;
  211914. MessageCallbackFunction* func = call->func;
  211915. call->result = (*func) (call->parameter);
  211916. call->event.signal();
  211917. }
  211918. else if (clientMsg->message_type == broadcastId)
  211919. {
  211920. #if 0
  211921. TCHAR buffer[8192];
  211922. zeromem (buffer, sizeof (buffer));
  211923. if (GlobalGetAtomName ((ATOM) lParam, buffer, 8192) != 0)
  211924. mq->deliverBroadcastMessage (String (buffer));
  211925. #endif
  211926. }
  211927. else
  211928. {
  211929. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received unknown client message.");
  211930. }
  211931. }
  211932. JUCE_CATCH_ALL
  211933. }
  211934. }
  211935. else if (evt.xany.window != juce_messageWindowHandle)
  211936. {
  211937. juce_windowMessageReceive (&evt);
  211938. }
  211939. return true;
  211940. }
  211941. END_JUCE_NAMESPACE
  211942. #endif
  211943. /********* End of inlined file: juce_linux_Messaging.cpp *********/
  211944. /********* Start of inlined file: juce_linux_Midi.cpp *********/
  211945. #if JUCE_BUILD_GUI_CLASSES
  211946. #if JUCE_ALSA
  211947. #include <alsa/asoundlib.h>
  211948. BEGIN_JUCE_NAMESPACE
  211949. static snd_seq_t* iterateDevices (const bool forInput,
  211950. StringArray& deviceNamesFound,
  211951. const int deviceIndexToOpen)
  211952. {
  211953. snd_seq_t* returnedHandle = 0;
  211954. snd_seq_t* seqHandle;
  211955. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  211956. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  211957. {
  211958. snd_seq_system_info_t* systemInfo;
  211959. snd_seq_client_info_t* clientInfo;
  211960. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  211961. {
  211962. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  211963. && snd_seq_client_info_malloc (&clientInfo) == 0)
  211964. {
  211965. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  211966. while (--numClients >= 0 && returnedHandle == 0)
  211967. {
  211968. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  211969. {
  211970. snd_seq_port_info_t* portInfo;
  211971. if (snd_seq_port_info_malloc (&portInfo) == 0)
  211972. {
  211973. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  211974. const int client = snd_seq_client_info_get_client (clientInfo);
  211975. snd_seq_port_info_set_client (portInfo, client);
  211976. snd_seq_port_info_set_port (portInfo, -1);
  211977. while (--numPorts >= 0)
  211978. {
  211979. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  211980. && (snd_seq_port_info_get_capability (portInfo)
  211981. & (forInput ? SND_SEQ_PORT_CAP_READ
  211982. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  211983. {
  211984. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  211985. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  211986. {
  211987. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  211988. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  211989. if (sourcePort != -1)
  211990. {
  211991. snd_seq_set_client_name (seqHandle,
  211992. forInput ? "Juce Midi Input"
  211993. : "Juce Midi Output");
  211994. const int portId
  211995. = snd_seq_create_simple_port (seqHandle,
  211996. forInput ? "Juce Midi In Port"
  211997. : "Juce Midi Out Port",
  211998. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  211999. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  212000. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  212001. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  212002. returnedHandle = seqHandle;
  212003. break;
  212004. }
  212005. }
  212006. }
  212007. }
  212008. snd_seq_port_info_free (portInfo);
  212009. }
  212010. }
  212011. }
  212012. snd_seq_client_info_free (clientInfo);
  212013. }
  212014. snd_seq_system_info_free (systemInfo);
  212015. }
  212016. if (returnedHandle == 0)
  212017. snd_seq_close (seqHandle);
  212018. }
  212019. deviceNamesFound.appendNumbersToDuplicates (true, true);
  212020. return returnedHandle;
  212021. }
  212022. static snd_seq_t* createDevice (const bool forInput,
  212023. const String& deviceNameToOpen)
  212024. {
  212025. snd_seq_t* seqHandle = 0;
  212026. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  212027. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  212028. {
  212029. snd_seq_set_client_name (seqHandle,
  212030. (const char*) (forInput ? (deviceNameToOpen + T(" Input"))
  212031. : (deviceNameToOpen + T(" Output"))));
  212032. const int portId
  212033. = snd_seq_create_simple_port (seqHandle,
  212034. forInput ? "in"
  212035. : "out",
  212036. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  212037. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  212038. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  212039. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  212040. if (portId < 0)
  212041. {
  212042. snd_seq_close (seqHandle);
  212043. seqHandle = 0;
  212044. }
  212045. }
  212046. return seqHandle;
  212047. }
  212048. class MidiOutputDevice
  212049. {
  212050. public:
  212051. MidiOutputDevice (MidiOutput* const midiOutput_,
  212052. snd_seq_t* const seqHandle_)
  212053. :
  212054. midiOutput (midiOutput_),
  212055. seqHandle (seqHandle_),
  212056. maxEventSize (16 * 1024)
  212057. {
  212058. jassert (seqHandle != 0 && midiOutput != 0);
  212059. snd_midi_event_new (maxEventSize, &midiParser);
  212060. }
  212061. ~MidiOutputDevice()
  212062. {
  212063. snd_midi_event_free (midiParser);
  212064. snd_seq_close (seqHandle);
  212065. }
  212066. void sendMessageNow (const MidiMessage& message)
  212067. {
  212068. if (message.getRawDataSize() > maxEventSize)
  212069. {
  212070. maxEventSize = message.getRawDataSize();
  212071. snd_midi_event_free (midiParser);
  212072. snd_midi_event_new (maxEventSize, &midiParser);
  212073. }
  212074. snd_seq_event_t event;
  212075. snd_seq_ev_clear (&event);
  212076. snd_midi_event_encode (midiParser,
  212077. message.getRawData(),
  212078. message.getRawDataSize(),
  212079. &event);
  212080. snd_midi_event_reset_encode (midiParser);
  212081. snd_seq_ev_set_source (&event, 0);
  212082. snd_seq_ev_set_subs (&event);
  212083. snd_seq_ev_set_direct (&event);
  212084. snd_seq_event_output_direct (seqHandle, &event);
  212085. }
  212086. juce_UseDebuggingNewOperator
  212087. private:
  212088. MidiOutput* const midiOutput;
  212089. snd_seq_t* const seqHandle;
  212090. snd_midi_event_t* midiParser;
  212091. int maxEventSize;
  212092. };
  212093. const StringArray MidiOutput::getDevices()
  212094. {
  212095. StringArray devices;
  212096. iterateDevices (false, devices, -1);
  212097. return devices;
  212098. }
  212099. int MidiOutput::getDefaultDeviceIndex()
  212100. {
  212101. return 0;
  212102. }
  212103. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  212104. {
  212105. MidiOutput* newDevice = 0;
  212106. StringArray devices;
  212107. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  212108. if (handle != 0)
  212109. {
  212110. newDevice = new MidiOutput();
  212111. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  212112. }
  212113. return newDevice;
  212114. }
  212115. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  212116. {
  212117. MidiOutput* newDevice = 0;
  212118. snd_seq_t* const handle = createDevice (false, deviceName);
  212119. if (handle != 0)
  212120. {
  212121. newDevice = new MidiOutput();
  212122. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  212123. }
  212124. return newDevice;
  212125. }
  212126. MidiOutput::~MidiOutput()
  212127. {
  212128. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  212129. delete device;
  212130. }
  212131. void MidiOutput::reset()
  212132. {
  212133. }
  212134. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212135. {
  212136. return false;
  212137. }
  212138. void MidiOutput::setVolume (float leftVol, float rightVol)
  212139. {
  212140. }
  212141. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212142. {
  212143. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  212144. }
  212145. class MidiInputThread : public Thread
  212146. {
  212147. public:
  212148. MidiInputThread (MidiInput* const midiInput_,
  212149. snd_seq_t* const seqHandle_,
  212150. MidiInputCallback* const callback_)
  212151. : Thread (T("Juce MIDI Input")),
  212152. midiInput (midiInput_),
  212153. seqHandle (seqHandle_),
  212154. callback (callback_)
  212155. {
  212156. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  212157. }
  212158. ~MidiInputThread()
  212159. {
  212160. snd_seq_close (seqHandle);
  212161. }
  212162. void run()
  212163. {
  212164. const int maxEventSize = 16 * 1024;
  212165. snd_midi_event_t* midiParser;
  212166. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  212167. {
  212168. uint8* const buffer = (uint8*) juce_malloc (maxEventSize);
  212169. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  212170. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  212171. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  212172. while (! threadShouldExit())
  212173. {
  212174. if (poll (pfd, numPfds, 500) > 0)
  212175. {
  212176. snd_seq_event_t* inputEvent = 0;
  212177. snd_seq_nonblock (seqHandle, 1);
  212178. do
  212179. {
  212180. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  212181. {
  212182. // xxx what about SYSEXes that are too big for the buffer?
  212183. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  212184. snd_midi_event_reset_decode (midiParser);
  212185. if (numBytes > 0)
  212186. {
  212187. const MidiMessage message ((const uint8*) buffer,
  212188. numBytes,
  212189. Time::getMillisecondCounter() * 0.001);
  212190. callback->handleIncomingMidiMessage (midiInput, message);
  212191. }
  212192. snd_seq_free_event (inputEvent);
  212193. }
  212194. }
  212195. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  212196. snd_seq_free_event (inputEvent);
  212197. }
  212198. }
  212199. snd_midi_event_free (midiParser);
  212200. juce_free (buffer);
  212201. }
  212202. };
  212203. juce_UseDebuggingNewOperator
  212204. private:
  212205. MidiInput* const midiInput;
  212206. snd_seq_t* const seqHandle;
  212207. MidiInputCallback* const callback;
  212208. };
  212209. MidiInput::MidiInput (const String& name_)
  212210. : name (name_),
  212211. internal (0)
  212212. {
  212213. }
  212214. MidiInput::~MidiInput()
  212215. {
  212216. stop();
  212217. MidiInputThread* const thread = (MidiInputThread*) internal;
  212218. delete thread;
  212219. }
  212220. void MidiInput::start()
  212221. {
  212222. ((MidiInputThread*) internal)->startThread();
  212223. }
  212224. void MidiInput::stop()
  212225. {
  212226. ((MidiInputThread*) internal)->stopThread (3000);
  212227. }
  212228. int MidiInput::getDefaultDeviceIndex()
  212229. {
  212230. return 0;
  212231. }
  212232. const StringArray MidiInput::getDevices()
  212233. {
  212234. StringArray devices;
  212235. iterateDevices (true, devices, -1);
  212236. return devices;
  212237. }
  212238. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  212239. {
  212240. MidiInput* newDevice = 0;
  212241. StringArray devices;
  212242. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  212243. if (handle != 0)
  212244. {
  212245. newDevice = new MidiInput (devices [deviceIndex]);
  212246. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  212247. }
  212248. return newDevice;
  212249. }
  212250. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  212251. {
  212252. MidiInput* newDevice = 0;
  212253. snd_seq_t* const handle = createDevice (true, deviceName);
  212254. if (handle != 0)
  212255. {
  212256. newDevice = new MidiInput (deviceName);
  212257. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  212258. }
  212259. return newDevice;
  212260. }
  212261. END_JUCE_NAMESPACE
  212262. #else
  212263. // (These are just stub functions if ALSA is unavailable...)
  212264. BEGIN_JUCE_NAMESPACE
  212265. const StringArray MidiOutput::getDevices() { return StringArray(); }
  212266. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  212267. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  212268. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  212269. MidiOutput::~MidiOutput() {}
  212270. void MidiOutput::reset() {}
  212271. bool MidiOutput::getVolume (float&, float&) { return false; }
  212272. void MidiOutput::setVolume (float, float) {}
  212273. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  212274. MidiInput::MidiInput (const String& name_)
  212275. : name (name_),
  212276. internal (0)
  212277. {}
  212278. MidiInput::~MidiInput() {}
  212279. void MidiInput::start() {}
  212280. void MidiInput::stop() {}
  212281. int MidiInput::getDefaultDeviceIndex() { return 0; }
  212282. const StringArray MidiInput::getDevices() { return StringArray(); }
  212283. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  212284. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  212285. END_JUCE_NAMESPACE
  212286. #endif
  212287. #endif
  212288. /********* End of inlined file: juce_linux_Midi.cpp *********/
  212289. /********* Start of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  212290. BEGIN_JUCE_NAMESPACE
  212291. /*
  212292. Sorry.. This class isn't implemented on Linux!
  212293. */
  212294. WebBrowserComponent::WebBrowserComponent()
  212295. : browser (0),
  212296. blankPageShown (false)
  212297. {
  212298. setOpaque (true);
  212299. }
  212300. WebBrowserComponent::~WebBrowserComponent()
  212301. {
  212302. }
  212303. void WebBrowserComponent::goToURL (const String& url,
  212304. const StringArray* headers,
  212305. const MemoryBlock* postData)
  212306. {
  212307. lastURL = url;
  212308. lastHeaders.clear();
  212309. if (headers != 0)
  212310. lastHeaders = *headers;
  212311. lastPostData.setSize (0);
  212312. if (postData != 0)
  212313. lastPostData = *postData;
  212314. blankPageShown = false;
  212315. }
  212316. void WebBrowserComponent::stop()
  212317. {
  212318. }
  212319. void WebBrowserComponent::goBack()
  212320. {
  212321. lastURL = String::empty;
  212322. blankPageShown = false;
  212323. }
  212324. void WebBrowserComponent::goForward()
  212325. {
  212326. lastURL = String::empty;
  212327. }
  212328. void WebBrowserComponent::paint (Graphics& g)
  212329. {
  212330. g.fillAll (Colours::white);
  212331. }
  212332. void WebBrowserComponent::checkWindowAssociation()
  212333. {
  212334. }
  212335. void WebBrowserComponent::reloadLastURL()
  212336. {
  212337. if (lastURL.isNotEmpty())
  212338. {
  212339. goToURL (lastURL, &lastHeaders, &lastPostData);
  212340. lastURL = String::empty;
  212341. }
  212342. }
  212343. void WebBrowserComponent::parentHierarchyChanged()
  212344. {
  212345. checkWindowAssociation();
  212346. }
  212347. void WebBrowserComponent::moved()
  212348. {
  212349. }
  212350. void WebBrowserComponent::resized()
  212351. {
  212352. }
  212353. void WebBrowserComponent::visibilityChanged()
  212354. {
  212355. checkWindowAssociation();
  212356. }
  212357. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  212358. {
  212359. return true;
  212360. }
  212361. END_JUCE_NAMESPACE
  212362. /********* End of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  212363. /********* Start of inlined file: juce_linux_Windowing.cpp *********/
  212364. #if JUCE_BUILD_GUI_CLASSES
  212365. #include <X11/Xlib.h>
  212366. #include <X11/Xutil.h>
  212367. #include <X11/Xatom.h>
  212368. #include <X11/Xmd.h>
  212369. #include <X11/keysym.h>
  212370. #include <X11/cursorfont.h>
  212371. #include <dlfcn.h>
  212372. #if JUCE_USE_XINERAMA
  212373. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package..
  212374. */
  212375. #include <X11/extensions/Xinerama.h>
  212376. #endif
  212377. #if JUCE_USE_XSHM
  212378. #include <X11/extensions/XShm.h>
  212379. #include <sys/shm.h>
  212380. #include <sys/ipc.h>
  212381. #endif
  212382. #if JUCE_OPENGL
  212383. /* Got an include error here?
  212384. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  212385. and "freeglut3-dev".
  212386. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  212387. want to disable it.
  212388. */
  212389. #include <GL/glx.h>
  212390. #endif
  212391. #undef KeyPress
  212392. BEGIN_JUCE_NAMESPACE
  212393. #define TAKE_FOCUS 0
  212394. #define DELETE_WINDOW 1
  212395. #define SYSTEM_TRAY_REQUEST_DOCK 0
  212396. #define SYSTEM_TRAY_BEGIN_MESSAGE 1
  212397. #define SYSTEM_TRAY_CANCEL_MESSAGE 2
  212398. static const int repaintTimerPeriod = 1000 / 100; // 100 fps maximum
  212399. static Atom wm_ChangeState = None;
  212400. static Atom wm_State = None;
  212401. static Atom wm_Protocols = None;
  212402. static Atom wm_ProtocolList [2] = { None, None };
  212403. static Atom wm_ActiveWin = None;
  212404. #define ourDndVersion 3
  212405. static Atom XA_XdndAware = None;
  212406. static Atom XA_XdndEnter = None;
  212407. static Atom XA_XdndLeave = None;
  212408. static Atom XA_XdndPosition = None;
  212409. static Atom XA_XdndStatus = None;
  212410. static Atom XA_XdndDrop = None;
  212411. static Atom XA_XdndFinished = None;
  212412. static Atom XA_XdndSelection = None;
  212413. static Atom XA_XdndProxy = None;
  212414. static Atom XA_XdndTypeList = None;
  212415. static Atom XA_XdndActionList = None;
  212416. static Atom XA_XdndActionDescription = None;
  212417. static Atom XA_XdndActionCopy = None;
  212418. static Atom XA_XdndActionMove = None;
  212419. static Atom XA_XdndActionLink = None;
  212420. static Atom XA_XdndActionAsk = None;
  212421. static Atom XA_XdndActionPrivate = None;
  212422. static Atom XA_JXSelectionWindowProperty = None;
  212423. static Atom XA_MimeTextPlain = None;
  212424. static Atom XA_MimeTextUriList = None;
  212425. static Atom XA_MimeRootDrop = None;
  212426. static XErrorHandler oldHandler = 0;
  212427. static int trappedErrorCode = 0;
  212428. extern "C" int errorTrapHandler (Display* dpy, XErrorEvent* err)
  212429. {
  212430. trappedErrorCode = err->error_code;
  212431. return 0;
  212432. }
  212433. static void trapErrors()
  212434. {
  212435. trappedErrorCode = 0;
  212436. oldHandler = XSetErrorHandler (errorTrapHandler);
  212437. }
  212438. static bool untrapErrors()
  212439. {
  212440. XSetErrorHandler (oldHandler);
  212441. return (trappedErrorCode == 0);
  212442. }
  212443. static bool isActiveApplication = false;
  212444. bool Process::isForegroundProcess() throw()
  212445. {
  212446. return isActiveApplication;
  212447. }
  212448. // (used in the messaging code, declared here for build reasons)
  212449. bool juce_isRunningAsApplication()
  212450. {
  212451. return JUCEApplication::getInstance() != 0;
  212452. }
  212453. // These are defined in juce_linux_Messaging.cpp
  212454. extern Display* display;
  212455. extern XContext improbableNumber;
  212456. static const int eventMask = NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  212457. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  212458. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  212459. static int pointerMap[5];
  212460. static int lastMousePosX = 0, lastMousePosY = 0;
  212461. enum MouseButtons
  212462. {
  212463. NoButton = 0,
  212464. LeftButton = 1,
  212465. MiddleButton = 2,
  212466. RightButton = 3,
  212467. WheelUp = 4,
  212468. WheelDown = 5
  212469. };
  212470. static void getMousePos (int& x, int& y, int& mouseMods) throw()
  212471. {
  212472. Window root, child;
  212473. int winx, winy;
  212474. unsigned int mask;
  212475. mouseMods = 0;
  212476. if (XQueryPointer (display,
  212477. RootWindow (display, DefaultScreen (display)),
  212478. &root, &child,
  212479. &x, &y, &winx, &winy, &mask) == False)
  212480. {
  212481. // Pointer not on the default screen
  212482. x = y = -1;
  212483. }
  212484. else
  212485. {
  212486. if ((mask & Button1Mask) != 0)
  212487. mouseMods |= ModifierKeys::leftButtonModifier;
  212488. if ((mask & Button2Mask) != 0)
  212489. mouseMods |= ModifierKeys::middleButtonModifier;
  212490. if ((mask & Button3Mask) != 0)
  212491. mouseMods |= ModifierKeys::rightButtonModifier;
  212492. }
  212493. }
  212494. static int AltMask = 0;
  212495. static int NumLockMask = 0;
  212496. static bool numLock = 0;
  212497. static bool capsLock = 0;
  212498. static char keyStates [32];
  212499. static void updateKeyStates (const int keycode, const bool press) throw()
  212500. {
  212501. const int keybyte = keycode >> 3;
  212502. const int keybit = (1 << (keycode & 7));
  212503. if (press)
  212504. keyStates [keybyte] |= keybit;
  212505. else
  212506. keyStates [keybyte] &= ~keybit;
  212507. }
  212508. static bool keyDown (const int keycode) throw()
  212509. {
  212510. const int keybyte = keycode >> 3;
  212511. const int keybit = (1 << (keycode & 7));
  212512. return (keyStates [keybyte] & keybit) != 0;
  212513. }
  212514. static const int extendedKeyModifier = 0x10000000;
  212515. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  212516. {
  212517. int keysym;
  212518. if (keyCode & extendedKeyModifier)
  212519. {
  212520. keysym = 0xff00 | (keyCode & 0xff);
  212521. }
  212522. else
  212523. {
  212524. keysym = keyCode;
  212525. if (keysym == (XK_Tab & 0xff)
  212526. || keysym == (XK_Return & 0xff)
  212527. || keysym == (XK_Escape & 0xff)
  212528. || keysym == (XK_BackSpace & 0xff))
  212529. {
  212530. keysym |= 0xff00;
  212531. }
  212532. }
  212533. return keyDown (XKeysymToKeycode (display, keysym));
  212534. }
  212535. // Alt and Num lock are not defined by standard X
  212536. // modifier constants: check what they're mapped to
  212537. static void getModifierMapping() throw()
  212538. {
  212539. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  212540. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  212541. AltMask = 0;
  212542. NumLockMask = 0;
  212543. XModifierKeymap* mapping = XGetModifierMapping (display);
  212544. if (mapping)
  212545. {
  212546. for (int i = 0; i < 8; i++)
  212547. {
  212548. if (mapping->modifiermap [i << 1] == altLeftCode)
  212549. AltMask = 1 << i;
  212550. else if (mapping->modifiermap [i << 1] == numLockCode)
  212551. NumLockMask = 1 << i;
  212552. }
  212553. XFreeModifiermap (mapping);
  212554. }
  212555. }
  212556. static int currentModifiers = 0;
  212557. void ModifierKeys::updateCurrentModifiers() throw()
  212558. {
  212559. currentModifierFlags = currentModifiers;
  212560. }
  212561. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  212562. {
  212563. int x, y, mouseMods;
  212564. getMousePos (x, y, mouseMods);
  212565. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  212566. currentModifiers |= mouseMods;
  212567. return ModifierKeys (currentModifiers);
  212568. }
  212569. static void updateKeyModifiers (const int status) throw()
  212570. {
  212571. currentModifiers &= ~(ModifierKeys::shiftModifier
  212572. | ModifierKeys::ctrlModifier
  212573. | ModifierKeys::altModifier);
  212574. if (status & ShiftMask)
  212575. currentModifiers |= ModifierKeys::shiftModifier;
  212576. if (status & ControlMask)
  212577. currentModifiers |= ModifierKeys::ctrlModifier;
  212578. if (status & AltMask)
  212579. currentModifiers |= ModifierKeys::altModifier;
  212580. numLock = ((status & NumLockMask) != 0);
  212581. capsLock = ((status & LockMask) != 0);
  212582. }
  212583. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  212584. {
  212585. int modifier = 0;
  212586. bool isModifier = true;
  212587. switch (sym)
  212588. {
  212589. case XK_Shift_L:
  212590. case XK_Shift_R:
  212591. modifier = ModifierKeys::shiftModifier;
  212592. break;
  212593. case XK_Control_L:
  212594. case XK_Control_R:
  212595. modifier = ModifierKeys::ctrlModifier;
  212596. break;
  212597. case XK_Alt_L:
  212598. case XK_Alt_R:
  212599. modifier = ModifierKeys::altModifier;
  212600. break;
  212601. case XK_Num_Lock:
  212602. if (press)
  212603. numLock = ! numLock;
  212604. break;
  212605. case XK_Caps_Lock:
  212606. if (press)
  212607. capsLock = ! capsLock;
  212608. break;
  212609. case XK_Scroll_Lock:
  212610. break;
  212611. default:
  212612. isModifier = false;
  212613. break;
  212614. }
  212615. if (modifier != 0)
  212616. {
  212617. if (press)
  212618. currentModifiers |= modifier;
  212619. else
  212620. currentModifiers &= ~modifier;
  212621. }
  212622. return isModifier;
  212623. }
  212624. #if JUCE_USE_XSHM
  212625. static bool isShmAvailable() throw()
  212626. {
  212627. static bool isChecked = false;
  212628. static bool isAvailable = false;
  212629. if (! isChecked)
  212630. {
  212631. isChecked = true;
  212632. int major, minor;
  212633. Bool pixmaps;
  212634. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  212635. {
  212636. trapErrors();
  212637. XShmSegmentInfo segmentInfo;
  212638. zerostruct (segmentInfo);
  212639. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  212640. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  212641. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  212642. xImage->bytes_per_line * xImage->height,
  212643. IPC_CREAT | 0777)) >= 0)
  212644. {
  212645. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  212646. if (segmentInfo.shmaddr != (void*) -1)
  212647. {
  212648. segmentInfo.readOnly = False;
  212649. xImage->data = segmentInfo.shmaddr;
  212650. XSync (display, False);
  212651. if (XShmAttach (display, &segmentInfo) != 0)
  212652. {
  212653. XSync (display, False);
  212654. XShmDetach (display, &segmentInfo);
  212655. isAvailable = true;
  212656. }
  212657. }
  212658. XFlush (display);
  212659. XDestroyImage (xImage);
  212660. shmdt (segmentInfo.shmaddr);
  212661. }
  212662. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  212663. isAvailable &= untrapErrors();
  212664. }
  212665. }
  212666. return isAvailable;
  212667. }
  212668. #endif
  212669. class XBitmapImage : public Image
  212670. {
  212671. public:
  212672. XBitmapImage (const PixelFormat format_, const int w, const int h,
  212673. const bool clearImage, const bool is16Bit_)
  212674. : Image (format_, w, h),
  212675. is16Bit (is16Bit_)
  212676. {
  212677. jassert (format_ == RGB || format_ == ARGB);
  212678. pixelStride = (format_ == RGB) ? 3 : 4;
  212679. lineStride = ((w * pixelStride + 3) & ~3);
  212680. Visual* const visual = DefaultVisual (display, DefaultScreen (display));
  212681. #if JUCE_USE_XSHM
  212682. usingXShm = false;
  212683. if ((! is16Bit) && isShmAvailable())
  212684. {
  212685. zerostruct (segmentInfo);
  212686. xImage = XShmCreateImage (display, visual, 24, ZPixmap, 0, &segmentInfo, w, h);
  212687. if (xImage != 0)
  212688. {
  212689. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  212690. xImage->bytes_per_line * xImage->height,
  212691. IPC_CREAT | 0777)) >= 0)
  212692. {
  212693. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  212694. if (segmentInfo.shmaddr != (void*) -1)
  212695. {
  212696. segmentInfo.readOnly = False;
  212697. xImage->data = segmentInfo.shmaddr;
  212698. imageData = (uint8*) segmentInfo.shmaddr;
  212699. XSync (display, False);
  212700. if (XShmAttach (display, &segmentInfo) != 0)
  212701. {
  212702. XSync (display, False);
  212703. usingXShm = true;
  212704. }
  212705. else
  212706. {
  212707. jassertfalse
  212708. }
  212709. }
  212710. else
  212711. {
  212712. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  212713. }
  212714. }
  212715. }
  212716. }
  212717. if (! usingXShm)
  212718. #endif
  212719. {
  212720. imageData = (uint8*) juce_malloc (lineStride * h);
  212721. if (format_ == ARGB && clearImage)
  212722. zeromem (imageData, h * lineStride);
  212723. xImage = (XImage*) juce_calloc (sizeof (XImage));
  212724. xImage->width = w;
  212725. xImage->height = h;
  212726. xImage->xoffset = 0;
  212727. xImage->format = ZPixmap;
  212728. xImage->data = (char*) imageData;
  212729. xImage->byte_order = ImageByteOrder (display);
  212730. xImage->bitmap_unit = BitmapUnit (display);
  212731. xImage->bitmap_bit_order = BitmapBitOrder (display);
  212732. xImage->bitmap_pad = 32;
  212733. xImage->depth = pixelStride * 8;
  212734. xImage->bytes_per_line = lineStride;
  212735. xImage->bits_per_pixel = pixelStride * 8;
  212736. xImage->red_mask = 0x00FF0000;
  212737. xImage->green_mask = 0x0000FF00;
  212738. xImage->blue_mask = 0x000000FF;
  212739. if (is16Bit)
  212740. {
  212741. const int pixelStride = 2;
  212742. const int lineStride = ((w * pixelStride + 3) & ~3);
  212743. xImage->data = (char*) juce_malloc (lineStride * h);
  212744. xImage->bitmap_pad = 16;
  212745. xImage->depth = pixelStride * 8;
  212746. xImage->bytes_per_line = lineStride;
  212747. xImage->bits_per_pixel = pixelStride * 8;
  212748. xImage->red_mask = visual->red_mask;
  212749. xImage->green_mask = visual->green_mask;
  212750. xImage->blue_mask = visual->blue_mask;
  212751. }
  212752. if (! XInitImage (xImage))
  212753. {
  212754. jassertfalse
  212755. }
  212756. }
  212757. }
  212758. ~XBitmapImage()
  212759. {
  212760. #if JUCE_USE_XSHM
  212761. if (usingXShm)
  212762. {
  212763. XShmDetach (display, &segmentInfo);
  212764. XFlush (display);
  212765. XDestroyImage (xImage);
  212766. shmdt (segmentInfo.shmaddr);
  212767. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  212768. }
  212769. else
  212770. #endif
  212771. {
  212772. juce_free (xImage->data);
  212773. xImage->data = 0;
  212774. XDestroyImage (xImage);
  212775. }
  212776. if (! is16Bit)
  212777. imageData = 0; // to stop the base class freeing this (for the 16-bit version we want it to free it)
  212778. }
  212779. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  212780. {
  212781. static GC gc = 0;
  212782. if (gc == 0)
  212783. gc = DefaultGC (display, DefaultScreen (display));
  212784. if (is16Bit)
  212785. {
  212786. const uint32 rMask = xImage->red_mask;
  212787. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  212788. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  212789. const uint32 gMask = xImage->green_mask;
  212790. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  212791. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  212792. const uint32 bMask = xImage->blue_mask;
  212793. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  212794. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  212795. int ls, ps;
  212796. const uint8* const pixels = lockPixelDataReadOnly (0, 0, getWidth(), getHeight(), ls, ps);
  212797. jassert (! isARGB())
  212798. for (int y = sy; y < sy + dh; ++y)
  212799. {
  212800. const uint8* p = pixels + y * ls + sx * ps;
  212801. for (int x = sx; x < sx + dw; ++x)
  212802. {
  212803. const PixelRGB* const pixel = (const PixelRGB*) p;
  212804. p += ps;
  212805. XPutPixel (xImage, x, y,
  212806. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  212807. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  212808. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  212809. }
  212810. }
  212811. releasePixelDataReadOnly (pixels);
  212812. }
  212813. // blit results to screen.
  212814. #if JUCE_USE_XSHM
  212815. if (usingXShm)
  212816. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, False);
  212817. else
  212818. #endif
  212819. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  212820. }
  212821. juce_UseDebuggingNewOperator
  212822. private:
  212823. XImage* xImage;
  212824. const bool is16Bit;
  212825. #if JUCE_USE_XSHM
  212826. XShmSegmentInfo segmentInfo;
  212827. bool usingXShm;
  212828. #endif
  212829. static int getShiftNeeded (const uint32 mask) throw()
  212830. {
  212831. for (int i = 32; --i >= 0;)
  212832. if (((mask >> i) & 1) != 0)
  212833. return i - 7;
  212834. jassertfalse
  212835. return 0;
  212836. }
  212837. };
  212838. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  212839. class LinuxComponentPeer : public ComponentPeer
  212840. {
  212841. public:
  212842. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  212843. : ComponentPeer (component, windowStyleFlags),
  212844. windowH (0),
  212845. parentWindow (0),
  212846. wx (0),
  212847. wy (0),
  212848. ww (0),
  212849. wh (0),
  212850. taskbarImage (0),
  212851. fullScreen (false),
  212852. entered (false),
  212853. mapped (false)
  212854. {
  212855. // it's dangerous to create a window on a thread other than the message thread..
  212856. checkMessageManagerIsLocked
  212857. repainter = new LinuxRepaintManager (this);
  212858. createWindow();
  212859. setTitle (component->getName());
  212860. }
  212861. ~LinuxComponentPeer()
  212862. {
  212863. // it's dangerous to delete a window on a thread other than the message thread..
  212864. checkMessageManagerIsLocked
  212865. deleteTaskBarIcon();
  212866. destroyWindow();
  212867. windowH = 0;
  212868. delete repainter;
  212869. }
  212870. void* getNativeHandle() const
  212871. {
  212872. return (void*) windowH;
  212873. }
  212874. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  212875. {
  212876. XPointer peer = 0;
  212877. if (! XFindContext (display, (XID) windowHandle, improbableNumber, &peer))
  212878. {
  212879. if (peer != 0 && ! ((LinuxComponentPeer*) peer)->isValidMessageListener())
  212880. peer = 0;
  212881. }
  212882. return (LinuxComponentPeer*) peer;
  212883. }
  212884. void setVisible (bool shouldBeVisible)
  212885. {
  212886. if (shouldBeVisible)
  212887. XMapWindow (display, windowH);
  212888. else
  212889. XUnmapWindow (display, windowH);
  212890. }
  212891. void setTitle (const String& title)
  212892. {
  212893. setWindowTitle (windowH, title);
  212894. }
  212895. void setPosition (int x, int y)
  212896. {
  212897. setBounds (x, y, ww, wh, false);
  212898. }
  212899. void setSize (int w, int h)
  212900. {
  212901. setBounds (wx, wy, w, h, false);
  212902. }
  212903. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  212904. {
  212905. fullScreen = isNowFullScreen;
  212906. if (windowH != 0)
  212907. {
  212908. const ComponentDeletionWatcher deletionChecker (component);
  212909. wx = x;
  212910. wy = y;
  212911. ww = jmax (1, w);
  212912. wh = jmax (1, h);
  212913. if (! mapped)
  212914. {
  212915. // Make sure the Window manager does what we want
  212916. XSizeHints* hints = XAllocSizeHints();
  212917. hints->flags = USSize | USPosition;
  212918. hints->width = ww + windowBorder.getLeftAndRight();
  212919. hints->height = wh + windowBorder.getTopAndBottom();
  212920. hints->x = wx - windowBorder.getLeft();
  212921. hints->y = wy - windowBorder.getTop();
  212922. XSetWMNormalHints (display, windowH, hints);
  212923. XFree (hints);
  212924. }
  212925. XMoveResizeWindow (display, windowH,
  212926. wx - windowBorder.getLeft(),
  212927. wy - windowBorder.getTop(),
  212928. ww + windowBorder.getLeftAndRight(),
  212929. wh + windowBorder.getTopAndBottom());
  212930. if (! deletionChecker.hasBeenDeleted())
  212931. {
  212932. updateBorderSize();
  212933. handleMovedOrResized();
  212934. }
  212935. }
  212936. }
  212937. void getBounds (int& x, int& y, int& w, int& h) const
  212938. {
  212939. x = wx;
  212940. y = wy;
  212941. w = ww;
  212942. h = wh;
  212943. }
  212944. int getScreenX() const
  212945. {
  212946. return wx;
  212947. }
  212948. int getScreenY() const
  212949. {
  212950. return wy;
  212951. }
  212952. void relativePositionToGlobal (int& x, int& y)
  212953. {
  212954. x += wx;
  212955. y += wy;
  212956. }
  212957. void globalPositionToRelative (int& x, int& y)
  212958. {
  212959. x -= wx;
  212960. y -= wy;
  212961. }
  212962. void setMinimised (bool shouldBeMinimised)
  212963. {
  212964. if (shouldBeMinimised)
  212965. {
  212966. Window root = RootWindow (display, DefaultScreen (display));
  212967. XClientMessageEvent clientMsg;
  212968. clientMsg.display = display;
  212969. clientMsg.window = windowH;
  212970. clientMsg.type = ClientMessage;
  212971. clientMsg.format = 32;
  212972. clientMsg.message_type = wm_ChangeState;
  212973. clientMsg.data.l[0] = IconicState;
  212974. XSendEvent (display, root, false,
  212975. SubstructureRedirectMask | SubstructureNotifyMask,
  212976. (XEvent*) &clientMsg);
  212977. }
  212978. else
  212979. {
  212980. setVisible (true);
  212981. }
  212982. }
  212983. bool isMinimised() const
  212984. {
  212985. bool minimised = false;
  212986. unsigned char* stateProp;
  212987. unsigned long nitems, bytesLeft;
  212988. Atom actualType;
  212989. int actualFormat;
  212990. if (XGetWindowProperty (display, windowH, wm_State, 0, 64, False,
  212991. wm_State, &actualType, &actualFormat, &nitems, &bytesLeft,
  212992. &stateProp) == Success
  212993. && actualType == wm_State
  212994. && actualFormat == 32
  212995. && nitems > 0)
  212996. {
  212997. if (((unsigned long*) stateProp)[0] == IconicState)
  212998. minimised = true;
  212999. XFree (stateProp);
  213000. }
  213001. return minimised;
  213002. }
  213003. void setFullScreen (const bool shouldBeFullScreen)
  213004. {
  213005. Rectangle r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  213006. setMinimised (false);
  213007. if (fullScreen != shouldBeFullScreen)
  213008. {
  213009. if (shouldBeFullScreen)
  213010. r = Desktop::getInstance().getMainMonitorArea();
  213011. if (! r.isEmpty())
  213012. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  213013. getComponent()->repaint();
  213014. }
  213015. }
  213016. bool isFullScreen() const
  213017. {
  213018. return fullScreen;
  213019. }
  213020. bool isChildWindowOf (Window possibleParent) const
  213021. {
  213022. Window* windowList = 0;
  213023. uint32 windowListSize = 0;
  213024. Window parent, root;
  213025. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  213026. {
  213027. if (windowList != 0)
  213028. XFree (windowList);
  213029. return parent == possibleParent;
  213030. }
  213031. return false;
  213032. }
  213033. bool isFrontWindow() const
  213034. {
  213035. Window* windowList = 0;
  213036. uint32 windowListSize = 0;
  213037. bool result = false;
  213038. Window parent, root = RootWindow (display, DefaultScreen (display));
  213039. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  213040. {
  213041. for (int i = windowListSize; --i >= 0;)
  213042. {
  213043. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  213044. if (peer != 0)
  213045. {
  213046. result = (peer == this);
  213047. break;
  213048. }
  213049. }
  213050. }
  213051. if (windowList != 0)
  213052. XFree (windowList);
  213053. return result;
  213054. }
  213055. bool contains (int x, int y, bool trueIfInAChildWindow) const
  213056. {
  213057. jassert (x >= 0 && y >= 0 && x < ww && y < wh); // should only be called for points that are actually inside the bounds
  213058. if (((unsigned int) x) >= (unsigned int) ww
  213059. || ((unsigned int) y) >= (unsigned int) wh)
  213060. return false;
  213061. bool inFront = false;
  213062. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  213063. {
  213064. Component* const c = Desktop::getInstance().getComponent (i);
  213065. if (inFront)
  213066. {
  213067. if (c->contains (x + wx - c->getScreenX(),
  213068. y + wy - c->getScreenY()))
  213069. {
  213070. return false;
  213071. }
  213072. }
  213073. else if (c == getComponent())
  213074. {
  213075. inFront = true;
  213076. }
  213077. }
  213078. if (trueIfInAChildWindow)
  213079. return true;
  213080. ::Window root, child;
  213081. unsigned int bw, depth;
  213082. int wx, wy, w, h;
  213083. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  213084. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  213085. &bw, &depth))
  213086. {
  213087. return false;
  213088. }
  213089. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  213090. return false;
  213091. return child == None;
  213092. }
  213093. const BorderSize getFrameSize() const
  213094. {
  213095. return BorderSize();
  213096. }
  213097. bool setAlwaysOnTop (bool alwaysOnTop)
  213098. {
  213099. if (windowH != 0)
  213100. {
  213101. const bool wasVisible = component->isVisible();
  213102. if (wasVisible)
  213103. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  213104. XSetWindowAttributes swa;
  213105. swa.override_redirect = alwaysOnTop ? True : False;
  213106. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  213107. if (wasVisible)
  213108. setVisible (true);
  213109. }
  213110. return true;
  213111. }
  213112. void toFront (bool makeActive)
  213113. {
  213114. if (makeActive)
  213115. {
  213116. setVisible (true);
  213117. grabFocus();
  213118. }
  213119. XEvent ev;
  213120. ev.xclient.type = ClientMessage;
  213121. ev.xclient.serial = 0;
  213122. ev.xclient.send_event = True;
  213123. ev.xclient.message_type = wm_ActiveWin;
  213124. ev.xclient.window = windowH;
  213125. ev.xclient.format = 32;
  213126. ev.xclient.data.l[0] = 2;
  213127. ev.xclient.data.l[1] = CurrentTime;
  213128. ev.xclient.data.l[2] = 0;
  213129. ev.xclient.data.l[3] = 0;
  213130. ev.xclient.data.l[4] = 0;
  213131. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  213132. False,
  213133. SubstructureRedirectMask | SubstructureNotifyMask,
  213134. &ev);
  213135. XSync (display, False);
  213136. handleBroughtToFront();
  213137. }
  213138. void toBehind (ComponentPeer* other)
  213139. {
  213140. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  213141. jassert (otherPeer != 0); // wrong type of window?
  213142. if (otherPeer != 0)
  213143. {
  213144. setMinimised (false);
  213145. Window newStack[] = { otherPeer->windowH, windowH };
  213146. XRestackWindows (display, newStack, 2);
  213147. }
  213148. }
  213149. bool isFocused() const
  213150. {
  213151. int revert;
  213152. Window focusedWindow = 0;
  213153. XGetInputFocus (display, &focusedWindow, &revert);
  213154. return focusedWindow == windowH;
  213155. }
  213156. void grabFocus()
  213157. {
  213158. XWindowAttributes atts;
  213159. if (windowH != 0
  213160. && XGetWindowAttributes (display, windowH, &atts)
  213161. && atts.map_state == IsViewable
  213162. && ! isFocused())
  213163. {
  213164. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  213165. isActiveApplication = true;
  213166. }
  213167. }
  213168. void textInputRequired (int /*x*/, int /*y*/)
  213169. {
  213170. }
  213171. void repaint (int x, int y, int w, int h)
  213172. {
  213173. if (Rectangle::intersectRectangles (x, y, w, h,
  213174. 0, 0,
  213175. getComponent()->getWidth(),
  213176. getComponent()->getHeight()))
  213177. {
  213178. repainter->repaint (x, y, w, h);
  213179. }
  213180. }
  213181. void performAnyPendingRepaintsNow()
  213182. {
  213183. repainter->performAnyPendingRepaintsNow();
  213184. }
  213185. void setIcon (const Image& newIcon)
  213186. {
  213187. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  213188. uint32* const data = (uint32*) juce_malloc (dataSize);
  213189. int index = 0;
  213190. data[index++] = newIcon.getWidth();
  213191. data[index++] = newIcon.getHeight();
  213192. for (int y = 0; y < newIcon.getHeight(); ++y)
  213193. for (int x = 0; x < newIcon.getWidth(); ++x)
  213194. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  213195. XChangeProperty (display, windowH,
  213196. XInternAtom (display, "_NET_WM_ICON", False),
  213197. XA_CARDINAL, 32, PropModeReplace,
  213198. (unsigned char*) data, dataSize);
  213199. XSync (display, False);
  213200. juce_free (data);
  213201. }
  213202. void handleWindowMessage (XEvent* event)
  213203. {
  213204. switch (event->xany.type)
  213205. {
  213206. case 2: // 'KeyPress'
  213207. {
  213208. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  213209. updateKeyStates (keyEvent->keycode, true);
  213210. char utf8 [64];
  213211. zeromem (utf8, sizeof (utf8));
  213212. KeySym sym;
  213213. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  213214. const juce_wchar unicodeChar = *(const juce_wchar*) String::fromUTF8 ((const uint8*) utf8, sizeof (utf8) - 1);
  213215. int keyCode = (int) unicodeChar;
  213216. if (keyCode < 0x20)
  213217. keyCode = XKeycodeToKeysym (display, keyEvent->keycode,
  213218. (currentModifiers & ModifierKeys::shiftModifier) != 0 ? 1 : 0);
  213219. const int oldMods = currentModifiers;
  213220. bool keyPressed = false;
  213221. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  213222. if ((sym & 0xff00) == 0xff00)
  213223. {
  213224. // Translate keypad
  213225. if (sym == XK_KP_Divide)
  213226. keyCode = XK_slash;
  213227. else if (sym == XK_KP_Multiply)
  213228. keyCode = XK_asterisk;
  213229. else if (sym == XK_KP_Subtract)
  213230. keyCode = XK_hyphen;
  213231. else if (sym == XK_KP_Add)
  213232. keyCode = XK_plus;
  213233. else if (sym == XK_KP_Enter)
  213234. keyCode = XK_Return;
  213235. else if (sym == XK_KP_Decimal)
  213236. keyCode = numLock ? XK_period : XK_Delete;
  213237. else if (sym == XK_KP_0)
  213238. keyCode = numLock ? XK_0 : XK_Insert;
  213239. else if (sym == XK_KP_1)
  213240. keyCode = numLock ? XK_1 : XK_End;
  213241. else if (sym == XK_KP_2)
  213242. keyCode = numLock ? XK_2 : XK_Down;
  213243. else if (sym == XK_KP_3)
  213244. keyCode = numLock ? XK_3 : XK_Page_Down;
  213245. else if (sym == XK_KP_4)
  213246. keyCode = numLock ? XK_4 : XK_Left;
  213247. else if (sym == XK_KP_5)
  213248. keyCode = XK_5;
  213249. else if (sym == XK_KP_6)
  213250. keyCode = numLock ? XK_6 : XK_Right;
  213251. else if (sym == XK_KP_7)
  213252. keyCode = numLock ? XK_7 : XK_Home;
  213253. else if (sym == XK_KP_8)
  213254. keyCode = numLock ? XK_8 : XK_Up;
  213255. else if (sym == XK_KP_9)
  213256. keyCode = numLock ? XK_9 : XK_Page_Up;
  213257. switch (sym)
  213258. {
  213259. case XK_Left:
  213260. case XK_Right:
  213261. case XK_Up:
  213262. case XK_Down:
  213263. case XK_Page_Up:
  213264. case XK_Page_Down:
  213265. case XK_End:
  213266. case XK_Home:
  213267. case XK_Delete:
  213268. case XK_Insert:
  213269. keyPressed = true;
  213270. keyCode = (sym & 0xff) | extendedKeyModifier;
  213271. break;
  213272. case XK_Tab:
  213273. case XK_Return:
  213274. case XK_Escape:
  213275. case XK_BackSpace:
  213276. keyPressed = true;
  213277. keyCode &= 0xff;
  213278. break;
  213279. default:
  213280. {
  213281. if (sym >= XK_F1 && sym <= XK_F16)
  213282. {
  213283. keyPressed = true;
  213284. keyCode = (sym & 0xff) | extendedKeyModifier;
  213285. }
  213286. break;
  213287. }
  213288. }
  213289. }
  213290. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  213291. keyPressed = true;
  213292. if (oldMods != currentModifiers)
  213293. handleModifierKeysChange();
  213294. if (keyDownChange)
  213295. handleKeyUpOrDown();
  213296. if (keyPressed)
  213297. handleKeyPress (keyCode, unicodeChar);
  213298. break;
  213299. }
  213300. case KeyRelease:
  213301. {
  213302. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  213303. updateKeyStates (keyEvent->keycode, false);
  213304. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  213305. const int oldMods = currentModifiers;
  213306. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  213307. if (oldMods != currentModifiers)
  213308. handleModifierKeysChange();
  213309. if (keyDownChange)
  213310. handleKeyUpOrDown();
  213311. break;
  213312. }
  213313. case ButtonPress:
  213314. {
  213315. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  213316. bool buttonMsg = false;
  213317. bool wheelUpMsg = false;
  213318. bool wheelDownMsg = false;
  213319. const int map = pointerMap [buttonPressEvent->button - Button1];
  213320. if (map == LeftButton)
  213321. {
  213322. currentModifiers |= ModifierKeys::leftButtonModifier;
  213323. buttonMsg = true;
  213324. }
  213325. else if (map == RightButton)
  213326. {
  213327. currentModifiers |= ModifierKeys::rightButtonModifier;
  213328. buttonMsg = true;
  213329. }
  213330. else if (map == MiddleButton)
  213331. {
  213332. currentModifiers |= ModifierKeys::middleButtonModifier;
  213333. buttonMsg = true;
  213334. }
  213335. else if (map == WheelUp)
  213336. {
  213337. wheelUpMsg = true;
  213338. }
  213339. else if (map == WheelDown)
  213340. {
  213341. wheelDownMsg = true;
  213342. }
  213343. updateKeyModifiers (buttonPressEvent->state);
  213344. if (buttonMsg)
  213345. {
  213346. toFront (true);
  213347. handleMouseDown (buttonPressEvent->x, buttonPressEvent->y,
  213348. getEventTime (buttonPressEvent->time));
  213349. }
  213350. else if (wheelUpMsg || wheelDownMsg)
  213351. {
  213352. handleMouseWheel (0, wheelDownMsg ? -84 : 84,
  213353. getEventTime (buttonPressEvent->time));
  213354. }
  213355. lastMousePosX = lastMousePosY = 0x100000;
  213356. break;
  213357. }
  213358. case ButtonRelease:
  213359. {
  213360. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  213361. const int oldModifiers = currentModifiers;
  213362. const int map = pointerMap [buttonRelEvent->button - Button1];
  213363. if (map == LeftButton)
  213364. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  213365. else if (map == RightButton)
  213366. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  213367. else if (map == MiddleButton)
  213368. currentModifiers &= ~ModifierKeys::middleButtonModifier;
  213369. updateKeyModifiers (buttonRelEvent->state);
  213370. handleMouseUp (oldModifiers,
  213371. buttonRelEvent->x, buttonRelEvent->y,
  213372. getEventTime (buttonRelEvent->time));
  213373. lastMousePosX = lastMousePosY = 0x100000;
  213374. break;
  213375. }
  213376. case MotionNotify:
  213377. {
  213378. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  213379. updateKeyModifiers (movedEvent->state);
  213380. int x, y, mouseMods;
  213381. getMousePos (x, y, mouseMods);
  213382. if (lastMousePosX != x || lastMousePosY != y)
  213383. {
  213384. lastMousePosX = x;
  213385. lastMousePosY = y;
  213386. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  213387. {
  213388. Window wRoot = 0, wParent = 0;
  213389. Window* wChild = 0;
  213390. unsigned int numChildren;
  213391. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  213392. if (wParent != 0
  213393. && wParent != windowH
  213394. && wParent != wRoot)
  213395. {
  213396. parentWindow = wParent;
  213397. updateBounds();
  213398. x -= getScreenX();
  213399. y -= getScreenY();
  213400. }
  213401. else
  213402. {
  213403. parentWindow = 0;
  213404. x -= getScreenX();
  213405. y -= getScreenY();
  213406. }
  213407. }
  213408. else
  213409. {
  213410. x -= getScreenX();
  213411. y -= getScreenY();
  213412. }
  213413. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0)
  213414. handleMouseMove (x, y, getEventTime (movedEvent->time));
  213415. else
  213416. handleMouseDrag (x, y, getEventTime (movedEvent->time));
  213417. }
  213418. break;
  213419. }
  213420. case EnterNotify:
  213421. {
  213422. lastMousePosX = lastMousePosY = 0x100000;
  213423. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  213424. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  213425. && ! entered)
  213426. {
  213427. updateKeyModifiers (enterEvent->state);
  213428. handleMouseEnter (enterEvent->x, enterEvent->y, getEventTime (enterEvent->time));
  213429. entered = true;
  213430. }
  213431. break;
  213432. }
  213433. case LeaveNotify:
  213434. {
  213435. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  213436. // Suppress the normal leave if we've got a pointer grab, or if
  213437. // it's a bogus one caused by clicking a mouse button when running
  213438. // in a Window manager
  213439. if (((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  213440. && leaveEvent->mode == NotifyNormal)
  213441. || leaveEvent->mode == NotifyUngrab)
  213442. {
  213443. updateKeyModifiers (leaveEvent->state);
  213444. handleMouseExit (leaveEvent->x, leaveEvent->y, getEventTime (leaveEvent->time));
  213445. entered = false;
  213446. }
  213447. break;
  213448. }
  213449. case FocusIn:
  213450. {
  213451. isActiveApplication = true;
  213452. if (isFocused())
  213453. handleFocusGain();
  213454. break;
  213455. }
  213456. case FocusOut:
  213457. {
  213458. isActiveApplication = false;
  213459. if (! isFocused())
  213460. handleFocusLoss();
  213461. break;
  213462. }
  213463. case Expose:
  213464. {
  213465. // Batch together all pending expose events
  213466. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  213467. XEvent nextEvent;
  213468. if (exposeEvent->window != windowH)
  213469. {
  213470. Window child;
  213471. XTranslateCoordinates (display, exposeEvent->window, windowH,
  213472. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  213473. &child);
  213474. }
  213475. repaint (exposeEvent->x, exposeEvent->y,
  213476. exposeEvent->width, exposeEvent->height);
  213477. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  213478. {
  213479. XPeekEvent (display, (XEvent*) &nextEvent);
  213480. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  213481. break;
  213482. XNextEvent (display, (XEvent*) &nextEvent);
  213483. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  213484. repaint (nextExposeEvent->x, nextExposeEvent->y,
  213485. nextExposeEvent->width, nextExposeEvent->height);
  213486. }
  213487. break;
  213488. }
  213489. case CirculateNotify:
  213490. case CreateNotify:
  213491. case DestroyNotify:
  213492. // Think we can ignore these
  213493. break;
  213494. case ConfigureNotify:
  213495. {
  213496. updateBounds();
  213497. updateBorderSize();
  213498. handleMovedOrResized();
  213499. // if the native title bar is dragged, need to tell any active menus, etc.
  213500. if ((styleFlags & windowHasTitleBar) != 0
  213501. && component->isCurrentlyBlockedByAnotherModalComponent())
  213502. {
  213503. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  213504. if (currentModalComp != 0)
  213505. currentModalComp->inputAttemptWhenModal();
  213506. }
  213507. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  213508. if (confEvent->window == windowH
  213509. && confEvent->above != 0
  213510. && isFrontWindow())
  213511. {
  213512. handleBroughtToFront();
  213513. }
  213514. break;
  213515. }
  213516. case ReparentNotify:
  213517. case GravityNotify:
  213518. {
  213519. parentWindow = 0;
  213520. Window wRoot = 0;
  213521. Window* wChild = 0;
  213522. unsigned int numChildren;
  213523. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  213524. if (parentWindow == windowH || parentWindow == wRoot)
  213525. parentWindow = 0;
  213526. updateBounds();
  213527. updateBorderSize();
  213528. handleMovedOrResized();
  213529. break;
  213530. }
  213531. case MapNotify:
  213532. mapped = true;
  213533. handleBroughtToFront();
  213534. break;
  213535. case UnmapNotify:
  213536. mapped = false;
  213537. break;
  213538. case MappingNotify:
  213539. {
  213540. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  213541. if (mappingEvent->request != MappingPointer)
  213542. {
  213543. // Deal with modifier/keyboard mapping
  213544. XRefreshKeyboardMapping (mappingEvent);
  213545. getModifierMapping();
  213546. }
  213547. break;
  213548. }
  213549. case ClientMessage:
  213550. {
  213551. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  213552. if (clientMsg->message_type == wm_Protocols && clientMsg->format == 32)
  213553. {
  213554. const Atom atom = (Atom) clientMsg->data.l[0];
  213555. if (atom == wm_ProtocolList [TAKE_FOCUS])
  213556. {
  213557. XWindowAttributes atts;
  213558. if (clientMsg->window != 0
  213559. && XGetWindowAttributes (display, clientMsg->window, &atts))
  213560. {
  213561. if (atts.map_state == IsViewable)
  213562. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  213563. }
  213564. }
  213565. else if (atom == wm_ProtocolList [DELETE_WINDOW])
  213566. {
  213567. handleUserClosingWindow();
  213568. }
  213569. }
  213570. else if (clientMsg->message_type == XA_XdndEnter)
  213571. {
  213572. handleDragAndDropEnter (clientMsg);
  213573. }
  213574. else if (clientMsg->message_type == XA_XdndLeave)
  213575. {
  213576. resetDragAndDrop();
  213577. }
  213578. else if (clientMsg->message_type == XA_XdndPosition)
  213579. {
  213580. handleDragAndDropPosition (clientMsg);
  213581. }
  213582. else if (clientMsg->message_type == XA_XdndDrop)
  213583. {
  213584. handleDragAndDropDrop (clientMsg);
  213585. }
  213586. else if (clientMsg->message_type == XA_XdndStatus)
  213587. {
  213588. handleDragAndDropStatus (clientMsg);
  213589. }
  213590. else if (clientMsg->message_type == XA_XdndFinished)
  213591. {
  213592. resetDragAndDrop();
  213593. }
  213594. break;
  213595. }
  213596. case SelectionNotify:
  213597. handleDragAndDropSelection (event);
  213598. break;
  213599. case SelectionClear:
  213600. case SelectionRequest:
  213601. break;
  213602. default:
  213603. break;
  213604. }
  213605. }
  213606. void showMouseCursor (Cursor cursor) throw()
  213607. {
  213608. XDefineCursor (display, windowH, cursor);
  213609. }
  213610. void setTaskBarIcon (const Image& image)
  213611. {
  213612. deleteTaskBarIcon();
  213613. taskbarImage = image.createCopy();
  213614. Screen* const screen = XDefaultScreenOfDisplay (display);
  213615. const int screenNumber = XScreenNumberOfScreen (screen);
  213616. char screenAtom[32];
  213617. snprintf (screenAtom, sizeof (screenAtom), "_NET_SYSTEM_TRAY_S%d", screenNumber);
  213618. Atom selectionAtom = XInternAtom (display, screenAtom, false);
  213619. XGrabServer (display);
  213620. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  213621. if (managerWin != None)
  213622. XSelectInput (display, managerWin, StructureNotifyMask);
  213623. XUngrabServer (display);
  213624. XFlush (display);
  213625. if (managerWin != None)
  213626. {
  213627. XEvent ev;
  213628. zerostruct (ev);
  213629. ev.xclient.type = ClientMessage;
  213630. ev.xclient.window = managerWin;
  213631. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  213632. ev.xclient.format = 32;
  213633. ev.xclient.data.l[0] = CurrentTime;
  213634. ev.xclient.data.l[1] = SYSTEM_TRAY_REQUEST_DOCK;
  213635. ev.xclient.data.l[2] = windowH;
  213636. ev.xclient.data.l[3] = 0;
  213637. ev.xclient.data.l[4] = 0;
  213638. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  213639. XSync (display, False);
  213640. }
  213641. // For older KDE's ...
  213642. long atomData = 1;
  213643. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  213644. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  213645. // For more recent KDE's...
  213646. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  213647. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  213648. }
  213649. void deleteTaskBarIcon()
  213650. {
  213651. deleteAndZero (taskbarImage);
  213652. }
  213653. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  213654. juce_UseDebuggingNewOperator
  213655. bool dontRepaint;
  213656. private:
  213657. class LinuxRepaintManager : public Timer
  213658. {
  213659. public:
  213660. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  213661. : peer (peer_),
  213662. image (0),
  213663. lastTimeImageUsed (0)
  213664. {
  213665. #if JUCE_USE_XSHM
  213666. useARGBImagesForRendering = isShmAvailable();
  213667. if (useARGBImagesForRendering)
  213668. {
  213669. XShmSegmentInfo segmentinfo;
  213670. XImage* const testImage
  213671. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  213672. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  213673. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  213674. XDestroyImage (testImage);
  213675. }
  213676. #endif
  213677. }
  213678. ~LinuxRepaintManager()
  213679. {
  213680. delete image;
  213681. }
  213682. void timerCallback()
  213683. {
  213684. if (! regionsNeedingRepaint.isEmpty())
  213685. {
  213686. stopTimer();
  213687. performAnyPendingRepaintsNow();
  213688. }
  213689. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  213690. {
  213691. stopTimer();
  213692. deleteAndZero (image);
  213693. }
  213694. }
  213695. void repaint (int x, int y, int w, int h)
  213696. {
  213697. if (! isTimerRunning())
  213698. startTimer (repaintTimerPeriod);
  213699. regionsNeedingRepaint.add (x, y, w, h);
  213700. }
  213701. void performAnyPendingRepaintsNow()
  213702. {
  213703. peer->clearMaskedRegion();
  213704. const Rectangle totalArea (regionsNeedingRepaint.getBounds());
  213705. if (! totalArea.isEmpty())
  213706. {
  213707. if (image == 0 || image->getWidth() < totalArea.getWidth()
  213708. || image->getHeight() < totalArea.getHeight())
  213709. {
  213710. delete image;
  213711. #if JUCE_USE_XSHM
  213712. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  213713. : Image::RGB,
  213714. #else
  213715. image = new XBitmapImage (Image::RGB,
  213716. #endif
  213717. (totalArea.getWidth() + 31) & ~31,
  213718. (totalArea.getHeight() + 31) & ~31,
  213719. false,
  213720. peer->depthIs16Bit);
  213721. }
  213722. startTimer (repaintTimerPeriod);
  213723. LowLevelGraphicsSoftwareRenderer context (*image);
  213724. context.setOrigin (-totalArea.getX(), -totalArea.getY());
  213725. if (context.reduceClipRegion (regionsNeedingRepaint))
  213726. peer->handlePaint (context);
  213727. if (! peer->maskedRegion.isEmpty())
  213728. regionsNeedingRepaint.subtract (peer->maskedRegion);
  213729. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  213730. {
  213731. const Rectangle& r = *i.getRectangle();
  213732. image->blitToWindow (peer->windowH,
  213733. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  213734. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  213735. }
  213736. }
  213737. regionsNeedingRepaint.clear();
  213738. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  213739. startTimer (repaintTimerPeriod);
  213740. }
  213741. private:
  213742. LinuxComponentPeer* const peer;
  213743. XBitmapImage* image;
  213744. uint32 lastTimeImageUsed;
  213745. RectangleList regionsNeedingRepaint;
  213746. #if JUCE_USE_XSHM
  213747. bool useARGBImagesForRendering;
  213748. #endif
  213749. LinuxRepaintManager (const LinuxRepaintManager&);
  213750. const LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  213751. };
  213752. LinuxRepaintManager* repainter;
  213753. friend class LinuxRepaintManager;
  213754. Window windowH, parentWindow;
  213755. int wx, wy, ww, wh;
  213756. Image* taskbarImage;
  213757. bool fullScreen, entered, mapped, depthIs16Bit;
  213758. BorderSize windowBorder;
  213759. void removeWindowDecorations (Window wndH)
  213760. {
  213761. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  213762. if (hints != None)
  213763. {
  213764. typedef struct
  213765. {
  213766. unsigned long flags;
  213767. unsigned long functions;
  213768. unsigned long decorations;
  213769. long input_mode;
  213770. unsigned long status;
  213771. } MotifWmHints;
  213772. MotifWmHints motifHints;
  213773. zerostruct (motifHints);
  213774. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  213775. motifHints.decorations = 0;
  213776. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  213777. (unsigned char*) &motifHints, 4);
  213778. }
  213779. hints = XInternAtom (display, "_WIN_HINTS", True);
  213780. if (hints != None)
  213781. {
  213782. long gnomeHints = 0;
  213783. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  213784. (unsigned char*) &gnomeHints, 1);
  213785. }
  213786. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  213787. if (hints != None)
  213788. {
  213789. long kwmHints = 2; /*KDE_tinyDecoration*/
  213790. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  213791. (unsigned char*) &kwmHints, 1);
  213792. }
  213793. hints = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  213794. if (hints != None)
  213795. {
  213796. long netHints [2];
  213797. netHints[0] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  213798. if ((styleFlags & windowIsTemporary) != 0)
  213799. netHints[1] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_MENU", True);
  213800. else
  213801. netHints[1] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  213802. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  213803. (unsigned char*) &netHints, 2);
  213804. }
  213805. }
  213806. void addWindowButtons (Window wndH)
  213807. {
  213808. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  213809. if (hints != None)
  213810. {
  213811. typedef struct
  213812. {
  213813. unsigned long flags;
  213814. unsigned long functions;
  213815. unsigned long decorations;
  213816. long input_mode;
  213817. unsigned long status;
  213818. } MotifWmHints;
  213819. MotifWmHints motifHints;
  213820. zerostruct (motifHints);
  213821. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  213822. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  213823. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  213824. if ((styleFlags & windowHasCloseButton) != 0)
  213825. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  213826. if ((styleFlags & windowHasMinimiseButton) != 0)
  213827. {
  213828. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  213829. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  213830. }
  213831. if ((styleFlags & windowHasMaximiseButton) != 0)
  213832. {
  213833. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  213834. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  213835. }
  213836. if ((styleFlags & windowIsResizable) != 0)
  213837. {
  213838. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  213839. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  213840. }
  213841. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  213842. }
  213843. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  213844. if (hints != None)
  213845. {
  213846. long netHints [6];
  213847. int num = 0;
  213848. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  213849. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  213850. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  213851. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  213852. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  213853. (unsigned char*) &netHints, num);
  213854. }
  213855. }
  213856. void createWindow()
  213857. {
  213858. static bool atomsInitialised = false;
  213859. if (! atomsInitialised)
  213860. {
  213861. atomsInitialised = true;
  213862. wm_Protocols = XInternAtom (display, "WM_PROTOCOLS", 1);
  213863. wm_ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", 1);
  213864. wm_ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", 1);
  213865. wm_ChangeState = XInternAtom (display, "WM_CHANGE_STATE", 1);
  213866. wm_State = XInternAtom (display, "WM_STATE", 1);
  213867. wm_ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  213868. XA_XdndAware = XInternAtom (display, "XdndAware", 0);
  213869. XA_XdndEnter = XInternAtom (display, "XdndEnter", 0);
  213870. XA_XdndLeave = XInternAtom (display, "XdndLeave", 0);
  213871. XA_XdndPosition = XInternAtom (display, "XdndPosition", 0);
  213872. XA_XdndStatus = XInternAtom (display, "XdndStatus", 0);
  213873. XA_XdndDrop = XInternAtom (display, "XdndDrop", 0);
  213874. XA_XdndFinished = XInternAtom (display, "XdndFinished", 0);
  213875. XA_XdndSelection = XInternAtom (display, "XdndSelection", 0);
  213876. XA_XdndProxy = XInternAtom (display, "XdndProxy", 0);
  213877. XA_XdndTypeList = XInternAtom (display, "XdndTypeList", 0);
  213878. XA_XdndActionList = XInternAtom (display, "XdndActionList", 0);
  213879. XA_XdndActionCopy = XInternAtom (display, "XdndActionCopy", 0);
  213880. XA_XdndActionMove = XInternAtom (display, "XdndActionMove", 0);
  213881. XA_XdndActionLink = XInternAtom (display, "XdndActionLink", 0);
  213882. XA_XdndActionAsk = XInternAtom (display, "XdndActionAsk", 0);
  213883. XA_XdndActionPrivate = XInternAtom (display, "XdndActionPrivate", 0);
  213884. XA_XdndActionDescription = XInternAtom (display, "XdndActionDescription", 0);
  213885. XA_JXSelectionWindowProperty = XInternAtom (display, "JXSelectionWindowProperty", 0);
  213886. XA_MimeTextPlain = XInternAtom (display, "text/plain", 0);
  213887. XA_MimeTextUriList = XInternAtom (display, "text/uri-list", 0);
  213888. XA_MimeRootDrop = XInternAtom (display, "application/x-rootwindow-drop", 0);
  213889. }
  213890. resetDragAndDrop();
  213891. XA_OtherMime = XA_MimeTextPlain; // xxx why??
  213892. allowedMimeTypeAtoms [0] = XA_MimeTextPlain;
  213893. allowedMimeTypeAtoms [1] = XA_OtherMime;
  213894. allowedMimeTypeAtoms [2] = XA_MimeTextUriList;
  213895. allowedActions [0] = XA_XdndActionMove;
  213896. allowedActions [1] = XA_XdndActionCopy;
  213897. allowedActions [2] = XA_XdndActionLink;
  213898. allowedActions [3] = XA_XdndActionAsk;
  213899. allowedActions [4] = XA_XdndActionPrivate;
  213900. // Get defaults for various properties
  213901. const int screen = DefaultScreen (display);
  213902. Window root = RootWindow (display, screen);
  213903. // Attempt to create a 24-bit window on the default screen. If this is not
  213904. // possible then exit
  213905. XVisualInfo desiredVisual;
  213906. desiredVisual.screen = screen;
  213907. desiredVisual.depth = 24;
  213908. depthIs16Bit = false;
  213909. int numVisuals;
  213910. XVisualInfo* visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  213911. &desiredVisual, &numVisuals);
  213912. if (numVisuals < 1 || visuals == 0)
  213913. {
  213914. XFree (visuals);
  213915. desiredVisual.depth = 16;
  213916. visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  213917. &desiredVisual, &numVisuals);
  213918. if (numVisuals < 1 || visuals == 0)
  213919. {
  213920. Logger::outputDebugString ("ERROR: System doesn't support 24 or 16 bit RGB display.\n");
  213921. Process::terminate();
  213922. }
  213923. depthIs16Bit = true;
  213924. }
  213925. XFree (visuals);
  213926. // Set up the window attributes
  213927. XSetWindowAttributes swa;
  213928. swa.border_pixel = 0;
  213929. swa.background_pixmap = None;
  213930. swa.colormap = DefaultColormap (display, screen);
  213931. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  213932. swa.event_mask = eventMask;
  213933. Window wndH = XCreateWindow (display, root,
  213934. 0, 0, 1, 1,
  213935. 0, 0, InputOutput, (Visual*) CopyFromParent,
  213936. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  213937. &swa);
  213938. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  213939. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  213940. GrabModeAsync, GrabModeAsync, None, None);
  213941. // Set the window context to identify the window handle object
  213942. if (XSaveContext (display, (XID) wndH, improbableNumber, (XPointer) this))
  213943. {
  213944. // Failed
  213945. jassertfalse
  213946. Logger::outputDebugString ("Failed to create context information for window.\n");
  213947. XDestroyWindow (display, wndH);
  213948. wndH = 0;
  213949. }
  213950. // Set window manager hints
  213951. XWMHints* wmHints = XAllocWMHints();
  213952. wmHints->flags = InputHint | StateHint;
  213953. wmHints->input = True; // Locally active input model
  213954. wmHints->initial_state = NormalState;
  213955. XSetWMHints (display, wndH, wmHints);
  213956. XFree (wmHints);
  213957. if ((styleFlags & windowIsSemiTransparent) != 0)
  213958. {
  213959. //xxx
  213960. }
  213961. if ((styleFlags & windowAppearsOnTaskbar) != 0)
  213962. {
  213963. //xxx
  213964. }
  213965. //XSetTransientForHint (display, wndH, RootWindow (display, DefaultScreen (display)));
  213966. if ((styleFlags & windowHasTitleBar) == 0)
  213967. removeWindowDecorations (wndH);
  213968. else
  213969. addWindowButtons (wndH);
  213970. // Set window manager protocols
  213971. XChangeProperty (display, wndH, wm_Protocols, XA_ATOM, 32, PropModeReplace,
  213972. (unsigned char*) wm_ProtocolList, 2);
  213973. // Set drag and drop flags
  213974. XChangeProperty (display, wndH, XA_XdndTypeList, XA_ATOM, 32, PropModeReplace,
  213975. (const unsigned char*) allowedMimeTypeAtoms, numElementsInArray (allowedMimeTypeAtoms));
  213976. XChangeProperty (display, wndH, XA_XdndActionList, XA_ATOM, 32, PropModeReplace,
  213977. (const unsigned char*) allowedActions, numElementsInArray (allowedActions));
  213978. XChangeProperty (display, wndH, XA_XdndActionDescription, XA_STRING, 8, PropModeReplace,
  213979. (const unsigned char*) "", 0);
  213980. unsigned long dndVersion = ourDndVersion;
  213981. XChangeProperty (display, wndH, XA_XdndAware, XA_ATOM, 32, PropModeReplace,
  213982. (const unsigned char*) &dndVersion, 1);
  213983. // Set window name
  213984. setWindowTitle (wndH, getComponent()->getName());
  213985. // Initialise the pointer and keyboard mapping
  213986. // This is not the same as the logical pointer mapping the X server uses:
  213987. // we don't mess with this.
  213988. static bool mappingInitialised = false;
  213989. if (! mappingInitialised)
  213990. {
  213991. mappingInitialised = true;
  213992. const int numButtons = XGetPointerMapping (display, 0, 0);
  213993. if (numButtons == 2)
  213994. {
  213995. pointerMap[0] = LeftButton;
  213996. pointerMap[1] = RightButton;
  213997. pointerMap[2] = pointerMap[3] = pointerMap[4] = NoButton;
  213998. }
  213999. else if (numButtons >= 3)
  214000. {
  214001. pointerMap[0] = LeftButton;
  214002. pointerMap[1] = MiddleButton;
  214003. pointerMap[2] = RightButton;
  214004. if (numButtons >= 5)
  214005. {
  214006. pointerMap[3] = WheelUp;
  214007. pointerMap[4] = WheelDown;
  214008. }
  214009. }
  214010. getModifierMapping();
  214011. }
  214012. windowH = wndH;
  214013. }
  214014. void destroyWindow()
  214015. {
  214016. XPointer handlePointer;
  214017. if (! XFindContext (display, (XID) windowH, improbableNumber, &handlePointer))
  214018. XDeleteContext (display, (XID) windowH, improbableNumber);
  214019. XDestroyWindow (display, windowH);
  214020. // Wait for it to complete and then remove any events for this
  214021. // window from the event queue.
  214022. XSync (display, false);
  214023. XEvent event;
  214024. while (XCheckWindowEvent (display, windowH, eventMask, &event) == True)
  214025. {}
  214026. }
  214027. static int64 getEventTime (::Time t) throw()
  214028. {
  214029. static int64 eventTimeOffset = 0x12345678;
  214030. const int64 thisMessageTime = t;
  214031. if (eventTimeOffset == 0x12345678)
  214032. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  214033. return eventTimeOffset + thisMessageTime;
  214034. }
  214035. static void setWindowTitle (Window xwin, const char* const title) throw()
  214036. {
  214037. XTextProperty nameProperty;
  214038. char* strings[] = { (char*) title };
  214039. if (XStringListToTextProperty (strings, 1, &nameProperty))
  214040. {
  214041. XSetWMName (display, xwin, &nameProperty);
  214042. XSetWMIconName (display, xwin, &nameProperty);
  214043. XFree (nameProperty.value);
  214044. }
  214045. }
  214046. void updateBorderSize()
  214047. {
  214048. if ((styleFlags & windowHasTitleBar) == 0)
  214049. {
  214050. windowBorder = BorderSize (0);
  214051. }
  214052. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  214053. {
  214054. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  214055. if (hints != None)
  214056. {
  214057. unsigned char* data = 0;
  214058. unsigned long nitems, bytesLeft;
  214059. Atom actualType;
  214060. int actualFormat;
  214061. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  214062. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  214063. &data) == Success)
  214064. {
  214065. const unsigned long* const sizes = (const unsigned long*) data;
  214066. if (actualFormat == 32)
  214067. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  214068. (int) sizes[3], (int) sizes[1]);
  214069. XFree (data);
  214070. }
  214071. }
  214072. }
  214073. }
  214074. void updateBounds()
  214075. {
  214076. jassert (windowH != 0);
  214077. if (windowH != 0)
  214078. {
  214079. Window root, child;
  214080. unsigned int bw, depth;
  214081. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  214082. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  214083. &bw, &depth))
  214084. {
  214085. wx = wy = ww = wh = 0;
  214086. }
  214087. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  214088. {
  214089. wx = wy = 0;
  214090. }
  214091. }
  214092. }
  214093. void resetDragAndDrop()
  214094. {
  214095. dragAndDropFiles.clear();
  214096. lastDropX = lastDropY = -1;
  214097. dragAndDropCurrentMimeType = 0;
  214098. dragAndDropSourceWindow = 0;
  214099. srcMimeTypeAtomList.clear();
  214100. }
  214101. void sendDragAndDropMessage (XClientMessageEvent& msg)
  214102. {
  214103. msg.type = ClientMessage;
  214104. msg.display = display;
  214105. msg.window = dragAndDropSourceWindow;
  214106. msg.format = 32;
  214107. msg.data.l[0] = windowH;
  214108. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  214109. }
  214110. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  214111. {
  214112. XClientMessageEvent msg;
  214113. zerostruct (msg);
  214114. msg.message_type = XA_XdndStatus;
  214115. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  214116. msg.data.l[4] = dropAction;
  214117. sendDragAndDropMessage (msg);
  214118. }
  214119. void sendDragAndDropLeave()
  214120. {
  214121. XClientMessageEvent msg;
  214122. zerostruct (msg);
  214123. msg.message_type = XA_XdndLeave;
  214124. sendDragAndDropMessage (msg);
  214125. }
  214126. void sendDragAndDropFinish()
  214127. {
  214128. XClientMessageEvent msg;
  214129. zerostruct (msg);
  214130. msg.message_type = XA_XdndFinished;
  214131. sendDragAndDropMessage (msg);
  214132. }
  214133. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  214134. {
  214135. if ((clientMsg->data.l[1] & 1) == 0)
  214136. {
  214137. sendDragAndDropLeave();
  214138. if (dragAndDropFiles.size() > 0)
  214139. handleFileDragExit (dragAndDropFiles);
  214140. dragAndDropFiles.clear();
  214141. }
  214142. }
  214143. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  214144. {
  214145. if (dragAndDropSourceWindow == 0)
  214146. return;
  214147. dragAndDropSourceWindow = clientMsg->data.l[0];
  214148. const int dropX = ((int) clientMsg->data.l[2] >> 16) - getScreenX();
  214149. const int dropY = ((int) clientMsg->data.l[2] & 0xffff) - getScreenY();
  214150. if (lastDropX != dropX || lastDropY != dropY)
  214151. {
  214152. lastDropX = dropX;
  214153. lastDropY = dropY;
  214154. dragAndDropTimestamp = clientMsg->data.l[3];
  214155. Atom targetAction = XA_XdndActionCopy;
  214156. for (int i = numElementsInArray (allowedActions); --i >= 0;)
  214157. {
  214158. if ((Atom) clientMsg->data.l[4] == allowedActions[i])
  214159. {
  214160. targetAction = allowedActions[i];
  214161. break;
  214162. }
  214163. }
  214164. sendDragAndDropStatus (true, targetAction);
  214165. if (dragAndDropFiles.size() == 0)
  214166. updateDraggedFileList (clientMsg);
  214167. if (dragAndDropFiles.size() > 0)
  214168. handleFileDragMove (dragAndDropFiles, dropX, dropY);
  214169. }
  214170. }
  214171. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  214172. {
  214173. if (dragAndDropFiles.size() == 0)
  214174. updateDraggedFileList (clientMsg);
  214175. const StringArray files (dragAndDropFiles);
  214176. const int lastX = lastDropX, lastY = lastDropY;
  214177. sendDragAndDropFinish();
  214178. resetDragAndDrop();
  214179. if (files.size() > 0)
  214180. handleFileDragDrop (files, lastX, lastY);
  214181. }
  214182. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  214183. {
  214184. dragAndDropFiles.clear();
  214185. srcMimeTypeAtomList.clear();
  214186. dragAndDropCurrentMimeType = 0;
  214187. const int dndCurrentVersion = (int) (clientMsg->data.l[1] & 0xff000000) >> 24;
  214188. if (dndCurrentVersion < 3 || dndCurrentVersion > ourDndVersion)
  214189. {
  214190. dragAndDropSourceWindow = 0;
  214191. return;
  214192. }
  214193. dragAndDropSourceWindow = clientMsg->data.l[0];
  214194. if ((clientMsg->data.l[1] & 1) != 0)
  214195. {
  214196. Atom actual;
  214197. int format;
  214198. unsigned long count = 0, remaining = 0;
  214199. unsigned char* data = 0;
  214200. XGetWindowProperty (display, dragAndDropSourceWindow, XA_XdndTypeList,
  214201. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  214202. &count, &remaining, &data);
  214203. if (data != 0)
  214204. {
  214205. if (actual == XA_ATOM && format == 32 && count != 0)
  214206. {
  214207. const unsigned long* const types = (const unsigned long*) data;
  214208. for (unsigned int i = 0; i < count; ++i)
  214209. if (types[i] != None)
  214210. srcMimeTypeAtomList.add (types[i]);
  214211. }
  214212. XFree (data);
  214213. }
  214214. }
  214215. if (srcMimeTypeAtomList.size() == 0)
  214216. {
  214217. for (int i = 2; i < 5; ++i)
  214218. if (clientMsg->data.l[i] != None)
  214219. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  214220. if (srcMimeTypeAtomList.size() == 0)
  214221. {
  214222. dragAndDropSourceWindow = 0;
  214223. return;
  214224. }
  214225. }
  214226. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  214227. for (int j = 0; j < numElementsInArray (allowedMimeTypeAtoms); ++j)
  214228. if (srcMimeTypeAtomList[i] == allowedMimeTypeAtoms[j])
  214229. dragAndDropCurrentMimeType = allowedMimeTypeAtoms[j];
  214230. handleDragAndDropPosition (clientMsg);
  214231. }
  214232. void handleDragAndDropSelection (const XEvent* const evt)
  214233. {
  214234. dragAndDropFiles.clear();
  214235. if (evt->xselection.property != 0)
  214236. {
  214237. StringArray lines;
  214238. {
  214239. MemoryBlock dropData;
  214240. for (;;)
  214241. {
  214242. Atom actual;
  214243. uint8* data = 0;
  214244. unsigned long count = 0, remaining = 0;
  214245. int format = 0;
  214246. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  214247. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  214248. &format, &count, &remaining, &data) == Success)
  214249. {
  214250. dropData.append (data, count * format / 8);
  214251. XFree (data);
  214252. if (remaining == 0)
  214253. break;
  214254. }
  214255. else
  214256. {
  214257. XFree (data);
  214258. break;
  214259. }
  214260. }
  214261. lines.addLines (dropData.toString());
  214262. }
  214263. for (int i = 0; i < lines.size(); ++i)
  214264. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf (T("file://"), false, true)));
  214265. dragAndDropFiles.trim();
  214266. dragAndDropFiles.removeEmptyStrings();
  214267. }
  214268. }
  214269. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  214270. {
  214271. dragAndDropFiles.clear();
  214272. if (dragAndDropSourceWindow != None
  214273. && dragAndDropCurrentMimeType != 0)
  214274. {
  214275. dragAndDropTimestamp = clientMsg->data.l[2];
  214276. XConvertSelection (display,
  214277. XA_XdndSelection,
  214278. dragAndDropCurrentMimeType,
  214279. XA_JXSelectionWindowProperty,
  214280. windowH,
  214281. dragAndDropTimestamp);
  214282. }
  214283. }
  214284. StringArray dragAndDropFiles;
  214285. int dragAndDropTimestamp, lastDropX, lastDropY;
  214286. Atom XA_OtherMime, dragAndDropCurrentMimeType;
  214287. Window dragAndDropSourceWindow;
  214288. unsigned long allowedActions [5];
  214289. unsigned long allowedMimeTypeAtoms [3];
  214290. Array <Atom> srcMimeTypeAtomList;
  214291. };
  214292. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  214293. {
  214294. return new LinuxComponentPeer (this, styleFlags);
  214295. }
  214296. // (this callback is hooked up in the messaging code)
  214297. void juce_windowMessageReceive (XEvent* event)
  214298. {
  214299. if (event->xany.window != None)
  214300. {
  214301. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  214302. const MessageManagerLock messLock;
  214303. if (ComponentPeer::isValidPeer (peer))
  214304. peer->handleWindowMessage (event);
  214305. }
  214306. else
  214307. {
  214308. switch (event->xany.type)
  214309. {
  214310. case KeymapNotify:
  214311. {
  214312. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  214313. memcpy (keyStates, keymapEvent->key_vector, 32);
  214314. break;
  214315. }
  214316. default:
  214317. break;
  214318. }
  214319. }
  214320. }
  214321. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool /*clipToWorkArea*/) throw()
  214322. {
  214323. #if JUCE_USE_XINERAMA
  214324. int major_opcode, first_event, first_error;
  214325. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error)
  214326. && XineramaIsActive (display))
  214327. {
  214328. int numMonitors = 0;
  214329. XineramaScreenInfo* const screens = XineramaQueryScreens (display, &numMonitors);
  214330. if (screens != 0)
  214331. {
  214332. for (int i = numMonitors; --i >= 0;)
  214333. {
  214334. int index = screens[i].screen_number;
  214335. if (index >= 0)
  214336. {
  214337. while (monitorCoords.size() < index)
  214338. monitorCoords.add (Rectangle (0, 0, 0, 0));
  214339. monitorCoords.set (index, Rectangle (screens[i].x_org,
  214340. screens[i].y_org,
  214341. screens[i].width,
  214342. screens[i].height));
  214343. }
  214344. }
  214345. XFree (screens);
  214346. }
  214347. }
  214348. if (monitorCoords.size() == 0)
  214349. #endif
  214350. {
  214351. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  214352. if (hints != None)
  214353. {
  214354. const int numMonitors = ScreenCount (display);
  214355. for (int i = 0; i < numMonitors; ++i)
  214356. {
  214357. Window root = RootWindow (display, i);
  214358. unsigned long nitems, bytesLeft;
  214359. Atom actualType;
  214360. int actualFormat;
  214361. unsigned char* data = 0;
  214362. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  214363. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  214364. &data) == Success)
  214365. {
  214366. const long* const position = (const long*) data;
  214367. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  214368. monitorCoords.add (Rectangle (position[0], position[1],
  214369. position[2], position[3]));
  214370. XFree (data);
  214371. }
  214372. }
  214373. }
  214374. if (monitorCoords.size() == 0)
  214375. {
  214376. monitorCoords.add (Rectangle (0, 0,
  214377. DisplayWidth (display, DefaultScreen (display)),
  214378. DisplayHeight (display, DefaultScreen (display))));
  214379. }
  214380. }
  214381. }
  214382. bool Desktop::canUseSemiTransparentWindows() throw()
  214383. {
  214384. return false;
  214385. }
  214386. void Desktop::getMousePosition (int& x, int& y) throw()
  214387. {
  214388. int mouseMods;
  214389. getMousePos (x, y, mouseMods);
  214390. }
  214391. void Desktop::setMousePosition (int x, int y) throw()
  214392. {
  214393. Window root = RootWindow (display, DefaultScreen (display));
  214394. XWarpPointer (display, None, root, 0, 0, 0, 0, x, y);
  214395. }
  214396. static bool screenSaverAllowed = true;
  214397. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  214398. {
  214399. if (screenSaverAllowed != isEnabled)
  214400. {
  214401. screenSaverAllowed = isEnabled;
  214402. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  214403. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  214404. if (xScreenSaverSuspend == 0)
  214405. {
  214406. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  214407. if (h != 0)
  214408. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  214409. }
  214410. if (xScreenSaverSuspend != 0)
  214411. xScreenSaverSuspend (display, ! isEnabled);
  214412. }
  214413. }
  214414. bool Desktop::isScreenSaverEnabled() throw()
  214415. {
  214416. return screenSaverAllowed;
  214417. }
  214418. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  214419. {
  214420. Window root = RootWindow (display, DefaultScreen (display));
  214421. const unsigned int imageW = image.getWidth();
  214422. const unsigned int imageH = image.getHeight();
  214423. unsigned int cursorW, cursorH;
  214424. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  214425. return 0;
  214426. Image im (Image::ARGB, cursorW, cursorH, true);
  214427. Graphics g (im);
  214428. if (imageW > cursorW || imageH > cursorH)
  214429. {
  214430. hotspotX = (hotspotX * cursorW) / imageW;
  214431. hotspotY = (hotspotY * cursorH) / imageH;
  214432. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  214433. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  214434. false);
  214435. }
  214436. else
  214437. {
  214438. g.drawImageAt (&image, 0, 0);
  214439. }
  214440. const int stride = (cursorW + 7) >> 3;
  214441. uint8* const maskPlane = (uint8*) juce_calloc (stride * cursorH);
  214442. uint8* const sourcePlane = (uint8*) juce_calloc (stride * cursorH);
  214443. bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  214444. for (int y = cursorH; --y >= 0;)
  214445. {
  214446. for (int x = cursorW; --x >= 0;)
  214447. {
  214448. const uint8 mask = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  214449. const int offset = y * stride + (x >> 3);
  214450. const Colour c (im.getPixelAt (x, y));
  214451. if (c.getAlpha() >= 128)
  214452. maskPlane[offset] |= mask;
  214453. if (c.getBrightness() >= 0.5f)
  214454. sourcePlane[offset] |= mask;
  214455. }
  214456. }
  214457. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, (char*) sourcePlane, cursorW, cursorH, 0xffff, 0, 1);
  214458. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, (char*) maskPlane, cursorW, cursorH, 0xffff, 0, 1);
  214459. juce_free (maskPlane);
  214460. juce_free (sourcePlane);
  214461. XColor white, black;
  214462. black.red = black.green = black.blue = 0;
  214463. white.red = white.green = white.blue = 0xffff;
  214464. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  214465. XFreePixmap (display, sourcePixmap);
  214466. XFreePixmap (display, maskPixmap);
  214467. return result;
  214468. }
  214469. void juce_deleteMouseCursor (void* const cursorHandle, const bool) throw()
  214470. {
  214471. if (cursorHandle != None)
  214472. XFreeCursor (display, (Cursor) cursorHandle);
  214473. }
  214474. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  214475. {
  214476. unsigned int shape;
  214477. switch (type)
  214478. {
  214479. case MouseCursor::NoCursor:
  214480. {
  214481. const Image im (Image::ARGB, 16, 16, true);
  214482. return juce_createMouseCursorFromImage (im, 0, 0);
  214483. }
  214484. case MouseCursor::NormalCursor:
  214485. return (void*) None; // Use parent cursor
  214486. case MouseCursor::DraggingHandCursor:
  214487. {
  214488. static unsigned char dragHandData[] = {71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  214489. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  214490. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  214491. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  214492. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  214493. const int dragHandDataSize = 99;
  214494. Image* const im = ImageFileFormat::loadFrom ((const char*) dragHandData, dragHandDataSize);
  214495. void* const dragHandCursor = juce_createMouseCursorFromImage (*im, 8, 7);
  214496. delete im;
  214497. return dragHandCursor;
  214498. }
  214499. case MouseCursor::CopyingCursor:
  214500. {
  214501. static unsigned char copyCursorData[] = {71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  214502. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
  214503. 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  214504. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174,
  214505. 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  214506. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  214507. const int copyCursorSize = 119;
  214508. Image* const im = ImageFileFormat::loadFrom ((const char*) copyCursorData, copyCursorSize);
  214509. void* const copyCursor = juce_createMouseCursorFromImage (*im, 1, 3);
  214510. delete im;
  214511. return copyCursor;
  214512. }
  214513. case MouseCursor::WaitCursor:
  214514. shape = XC_watch;
  214515. break;
  214516. case MouseCursor::IBeamCursor:
  214517. shape = XC_xterm;
  214518. break;
  214519. case MouseCursor::PointingHandCursor:
  214520. shape = XC_hand2;
  214521. break;
  214522. case MouseCursor::LeftRightResizeCursor:
  214523. shape = XC_sb_h_double_arrow;
  214524. break;
  214525. case MouseCursor::UpDownResizeCursor:
  214526. shape = XC_sb_v_double_arrow;
  214527. break;
  214528. case MouseCursor::UpDownLeftRightResizeCursor:
  214529. shape = XC_fleur;
  214530. break;
  214531. case MouseCursor::TopEdgeResizeCursor:
  214532. shape = XC_top_side;
  214533. break;
  214534. case MouseCursor::BottomEdgeResizeCursor:
  214535. shape = XC_bottom_side;
  214536. break;
  214537. case MouseCursor::LeftEdgeResizeCursor:
  214538. shape = XC_left_side;
  214539. break;
  214540. case MouseCursor::RightEdgeResizeCursor:
  214541. shape = XC_right_side;
  214542. break;
  214543. case MouseCursor::TopLeftCornerResizeCursor:
  214544. shape = XC_top_left_corner;
  214545. break;
  214546. case MouseCursor::TopRightCornerResizeCursor:
  214547. shape = XC_top_right_corner;
  214548. break;
  214549. case MouseCursor::BottomLeftCornerResizeCursor:
  214550. shape = XC_bottom_left_corner;
  214551. break;
  214552. case MouseCursor::BottomRightCornerResizeCursor:
  214553. shape = XC_bottom_right_corner;
  214554. break;
  214555. case MouseCursor::CrosshairCursor:
  214556. shape = XC_crosshair;
  214557. break;
  214558. default:
  214559. return (void*) None; // Use parent cursor
  214560. }
  214561. return (void*) XCreateFontCursor (display, shape);
  214562. }
  214563. void MouseCursor::showInWindow (ComponentPeer* peer) const throw()
  214564. {
  214565. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  214566. if (lp != 0)
  214567. lp->showMouseCursor ((Cursor) getHandle());
  214568. }
  214569. void MouseCursor::showInAllWindows() const throw()
  214570. {
  214571. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  214572. showInWindow (ComponentPeer::getPeer (i));
  214573. }
  214574. Image* juce_createIconForFile (const File& file)
  214575. {
  214576. return 0;
  214577. }
  214578. #if JUCE_OPENGL
  214579. class WindowedGLContext : public OpenGLContext
  214580. {
  214581. public:
  214582. WindowedGLContext (Component* const component,
  214583. const OpenGLPixelFormat& pixelFormat_,
  214584. GLXContext sharedContext)
  214585. : renderContext (0),
  214586. embeddedWindow (0),
  214587. pixelFormat (pixelFormat_)
  214588. {
  214589. jassert (component != 0);
  214590. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  214591. if (peer == 0)
  214592. return;
  214593. XSync (display, False);
  214594. GLint attribs [64];
  214595. int n = 0;
  214596. attribs[n++] = GLX_RGBA;
  214597. attribs[n++] = GLX_DOUBLEBUFFER;
  214598. attribs[n++] = GLX_RED_SIZE;
  214599. attribs[n++] = pixelFormat.redBits;
  214600. attribs[n++] = GLX_GREEN_SIZE;
  214601. attribs[n++] = pixelFormat.greenBits;
  214602. attribs[n++] = GLX_BLUE_SIZE;
  214603. attribs[n++] = pixelFormat.blueBits;
  214604. attribs[n++] = GLX_ALPHA_SIZE;
  214605. attribs[n++] = pixelFormat.alphaBits;
  214606. attribs[n++] = GLX_DEPTH_SIZE;
  214607. attribs[n++] = pixelFormat.depthBufferBits;
  214608. attribs[n++] = GLX_STENCIL_SIZE;
  214609. attribs[n++] = pixelFormat.stencilBufferBits;
  214610. attribs[n++] = GLX_ACCUM_RED_SIZE;
  214611. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  214612. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  214613. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  214614. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  214615. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  214616. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  214617. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  214618. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  214619. attribs[n++] = None;
  214620. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  214621. if (bestVisual == 0)
  214622. return;
  214623. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  214624. Window windowH = (Window) peer->getNativeHandle();
  214625. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  214626. XSetWindowAttributes swa;
  214627. swa.colormap = colourMap;
  214628. swa.border_pixel = 0;
  214629. swa.event_mask = ExposureMask | StructureNotifyMask;
  214630. embeddedWindow = XCreateWindow (display, windowH,
  214631. 0, 0, 1, 1, 0,
  214632. bestVisual->depth,
  214633. InputOutput,
  214634. bestVisual->visual,
  214635. CWBorderPixel | CWColormap | CWEventMask,
  214636. &swa);
  214637. XSaveContext (display, (XID) embeddedWindow, improbableNumber, (XPointer) peer);
  214638. XMapWindow (display, embeddedWindow);
  214639. XFreeColormap (display, colourMap);
  214640. XFree (bestVisual);
  214641. XSync (display, False);
  214642. }
  214643. ~WindowedGLContext()
  214644. {
  214645. makeInactive();
  214646. glXDestroyContext (display, renderContext);
  214647. XUnmapWindow (display, embeddedWindow);
  214648. XDestroyWindow (display, embeddedWindow);
  214649. }
  214650. bool makeActive() const throw()
  214651. {
  214652. jassert (renderContext != 0);
  214653. return glXMakeCurrent (display, embeddedWindow, renderContext)
  214654. && XSync (display, False);
  214655. }
  214656. bool makeInactive() const throw()
  214657. {
  214658. return (! isActive()) || glXMakeCurrent (display, None, 0);
  214659. }
  214660. bool isActive() const throw()
  214661. {
  214662. return glXGetCurrentContext() == renderContext;
  214663. }
  214664. const OpenGLPixelFormat getPixelFormat() const
  214665. {
  214666. return pixelFormat;
  214667. }
  214668. void* getRawContext() const throw()
  214669. {
  214670. return renderContext;
  214671. }
  214672. void updateWindowPosition (int x, int y, int w, int h, int)
  214673. {
  214674. XMoveResizeWindow (display, embeddedWindow,
  214675. x, y, jmax (1, w), jmax (1, h));
  214676. }
  214677. void swapBuffers()
  214678. {
  214679. glXSwapBuffers (display, embeddedWindow);
  214680. }
  214681. bool setSwapInterval (const int numFramesPerSwap)
  214682. {
  214683. // xxx needs doing..
  214684. return false;
  214685. }
  214686. int getSwapInterval() const
  214687. {
  214688. // xxx needs doing..
  214689. return 0;
  214690. }
  214691. void repaint()
  214692. {
  214693. }
  214694. juce_UseDebuggingNewOperator
  214695. GLXContext renderContext;
  214696. private:
  214697. Window embeddedWindow;
  214698. OpenGLPixelFormat pixelFormat;
  214699. WindowedGLContext (const WindowedGLContext&);
  214700. const WindowedGLContext& operator= (const WindowedGLContext&);
  214701. };
  214702. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  214703. const OpenGLPixelFormat& pixelFormat,
  214704. const OpenGLContext* const contextToShareWith)
  214705. {
  214706. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  214707. contextToShareWith != 0 ? (GLXContext) contextToShareWith->getRawContext() : 0);
  214708. if (c->renderContext == 0)
  214709. deleteAndZero (c);
  214710. return c;
  214711. }
  214712. void juce_glViewport (const int w, const int h)
  214713. {
  214714. glViewport (0, 0, w, h);
  214715. }
  214716. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  214717. OwnedArray <OpenGLPixelFormat>& results)
  214718. {
  214719. results.add (new OpenGLPixelFormat()); // xxx
  214720. }
  214721. #endif
  214722. static void initClipboard (Window root, Atom* cutBuffers) throw()
  214723. {
  214724. static bool init = false;
  214725. if (! init)
  214726. {
  214727. init = true;
  214728. // Make sure all cut buffers exist before use
  214729. for (int i = 0; i < 8; i++)
  214730. {
  214731. XChangeProperty (display, root, cutBuffers[i],
  214732. XA_STRING, 8, PropModeAppend, NULL, 0);
  214733. }
  214734. }
  214735. }
  214736. // Clipboard implemented currently using cut buffers
  214737. // rather than the more powerful selection method
  214738. void SystemClipboard::copyTextToClipboard (const String& clipText) throw()
  214739. {
  214740. Window root = RootWindow (display, DefaultScreen (display));
  214741. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  214742. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  214743. initClipboard (root, cutBuffers);
  214744. XRotateWindowProperties (display, root, cutBuffers, 8, 1);
  214745. XChangeProperty (display, root, cutBuffers[0],
  214746. XA_STRING, 8, PropModeReplace, (const unsigned char*) (const char*) clipText,
  214747. clipText.length());
  214748. }
  214749. const String SystemClipboard::getTextFromClipboard() throw()
  214750. {
  214751. const int bufSize = 64; // in words
  214752. String returnData;
  214753. int byteOffset = 0;
  214754. Window root = RootWindow (display, DefaultScreen (display));
  214755. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  214756. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  214757. initClipboard (root, cutBuffers);
  214758. for (;;)
  214759. {
  214760. unsigned long bytesLeft = 0, nitems = 0;
  214761. unsigned char* clipData = 0;
  214762. int actualFormat = 0;
  214763. Atom actualType;
  214764. if (XGetWindowProperty (display, root, cutBuffers[0], byteOffset >> 2, bufSize,
  214765. False, XA_STRING, &actualType, &actualFormat, &nitems, &bytesLeft,
  214766. &clipData) == Success)
  214767. {
  214768. if (actualType == XA_STRING && actualFormat == 8)
  214769. {
  214770. byteOffset += nitems;
  214771. returnData += String ((const char*) clipData, nitems);
  214772. }
  214773. else
  214774. {
  214775. bytesLeft = 0;
  214776. }
  214777. if (clipData != 0)
  214778. XFree (clipData);
  214779. }
  214780. if (bytesLeft == 0)
  214781. break;
  214782. }
  214783. return returnData;
  214784. }
  214785. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  214786. {
  214787. jassertfalse // not implemented!
  214788. return false;
  214789. }
  214790. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  214791. {
  214792. jassertfalse // not implemented!
  214793. return false;
  214794. }
  214795. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  214796. {
  214797. if (! isOnDesktop ())
  214798. addToDesktop (0);
  214799. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  214800. if (wp != 0)
  214801. {
  214802. wp->setTaskBarIcon (newImage);
  214803. setVisible (true);
  214804. toFront (false);
  214805. repaint();
  214806. }
  214807. }
  214808. void SystemTrayIconComponent::paint (Graphics& g)
  214809. {
  214810. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  214811. if (wp != 0)
  214812. {
  214813. const Image* const image = wp->getTaskbarIcon();
  214814. if (image != 0)
  214815. g.drawImageAt (image, 0, 0, false);
  214816. }
  214817. }
  214818. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  214819. {
  214820. // xxx not yet implemented!
  214821. }
  214822. void PlatformUtilities::beep()
  214823. {
  214824. fprintf (stdout, "\a");
  214825. fflush (stdout);
  214826. }
  214827. bool AlertWindow::showNativeDialogBox (const String& title,
  214828. const String& bodyText,
  214829. bool isOkCancel)
  214830. {
  214831. // xxx this is supposed to pop up an alert!
  214832. Logger::outputDebugString (title + ": " + bodyText);
  214833. // use a non-native one for the time being..
  214834. if (isOkCancel)
  214835. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  214836. else
  214837. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  214838. return true;
  214839. }
  214840. const int KeyPress::spaceKey = XK_space & 0xff;
  214841. const int KeyPress::returnKey = XK_Return & 0xff;
  214842. const int KeyPress::escapeKey = XK_Escape & 0xff;
  214843. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  214844. const int KeyPress::leftKey = (XK_Left & 0xff) | extendedKeyModifier;
  214845. const int KeyPress::rightKey = (XK_Right & 0xff) | extendedKeyModifier;
  214846. const int KeyPress::upKey = (XK_Up & 0xff) | extendedKeyModifier;
  214847. const int KeyPress::downKey = (XK_Down & 0xff) | extendedKeyModifier;
  214848. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | extendedKeyModifier;
  214849. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | extendedKeyModifier;
  214850. const int KeyPress::endKey = (XK_End & 0xff) | extendedKeyModifier;
  214851. const int KeyPress::homeKey = (XK_Home & 0xff) | extendedKeyModifier;
  214852. const int KeyPress::insertKey = (XK_Insert & 0xff) | extendedKeyModifier;
  214853. const int KeyPress::deleteKey = (XK_Delete & 0xff) | extendedKeyModifier;
  214854. const int KeyPress::tabKey = XK_Tab & 0xff;
  214855. const int KeyPress::F1Key = (XK_F1 & 0xff) | extendedKeyModifier;
  214856. const int KeyPress::F2Key = (XK_F2 & 0xff) | extendedKeyModifier;
  214857. const int KeyPress::F3Key = (XK_F3 & 0xff) | extendedKeyModifier;
  214858. const int KeyPress::F4Key = (XK_F4 & 0xff) | extendedKeyModifier;
  214859. const int KeyPress::F5Key = (XK_F5 & 0xff) | extendedKeyModifier;
  214860. const int KeyPress::F6Key = (XK_F6 & 0xff) | extendedKeyModifier;
  214861. const int KeyPress::F7Key = (XK_F7 & 0xff) | extendedKeyModifier;
  214862. const int KeyPress::F8Key = (XK_F8 & 0xff) | extendedKeyModifier;
  214863. const int KeyPress::F9Key = (XK_F9 & 0xff) | extendedKeyModifier;
  214864. const int KeyPress::F10Key = (XK_F10 & 0xff) | extendedKeyModifier;
  214865. const int KeyPress::F11Key = (XK_F11 & 0xff) | extendedKeyModifier;
  214866. const int KeyPress::F12Key = (XK_F12 & 0xff) | extendedKeyModifier;
  214867. const int KeyPress::F13Key = (XK_F13 & 0xff) | extendedKeyModifier;
  214868. const int KeyPress::F14Key = (XK_F14 & 0xff) | extendedKeyModifier;
  214869. const int KeyPress::F15Key = (XK_F15 & 0xff) | extendedKeyModifier;
  214870. const int KeyPress::F16Key = (XK_F16 & 0xff) | extendedKeyModifier;
  214871. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | extendedKeyModifier;
  214872. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | extendedKeyModifier;
  214873. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | extendedKeyModifier;
  214874. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | extendedKeyModifier;
  214875. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | extendedKeyModifier;
  214876. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | extendedKeyModifier;
  214877. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | extendedKeyModifier;
  214878. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| extendedKeyModifier;
  214879. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| extendedKeyModifier;
  214880. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| extendedKeyModifier;
  214881. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| extendedKeyModifier;
  214882. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| extendedKeyModifier;
  214883. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| extendedKeyModifier;
  214884. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| extendedKeyModifier;
  214885. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| extendedKeyModifier;
  214886. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| extendedKeyModifier;
  214887. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| extendedKeyModifier;
  214888. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| extendedKeyModifier;
  214889. const int KeyPress::playKey = (0xffeeff00) | extendedKeyModifier;
  214890. const int KeyPress::stopKey = (0xffeeff01) | extendedKeyModifier;
  214891. const int KeyPress::fastForwardKey = (0xffeeff02) | extendedKeyModifier;
  214892. const int KeyPress::rewindKey = (0xffeeff03) | extendedKeyModifier;
  214893. END_JUCE_NAMESPACE
  214894. #endif
  214895. /********* End of inlined file: juce_linux_Windowing.cpp *********/
  214896. #endif
  214897. #endif
  214898. //==============================================================================
  214899. #if JUCE_MAC
  214900. /********* Start of inlined file: juce_mac_Files.cpp *********/
  214901. #include <ApplicationServices/ApplicationServices.h>
  214902. #include <sys/stat.h>
  214903. #include <sys/dir.h>
  214904. #include <sys/param.h>
  214905. #include <sys/mount.h>
  214906. #include <unistd.h>
  214907. #include <fnmatch.h>
  214908. #include <utime.h>
  214909. #include <pwd.h>
  214910. #include <fcntl.h>
  214911. BEGIN_JUCE_NAMESPACE
  214912. /*
  214913. Note that a lot of methods that you'd expect to find in this file actually
  214914. live in juce_posix_SharedCode.h!
  214915. */
  214916. /********* Start of inlined file: juce_posix_SharedCode.h *********/
  214917. /*
  214918. This file contains posix routines that are common to both the Linux and Mac builds.
  214919. It gets included directly in the cpp files for these platforms.
  214920. */
  214921. CriticalSection::CriticalSection() throw()
  214922. {
  214923. pthread_mutexattr_t atts;
  214924. pthread_mutexattr_init (&atts);
  214925. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  214926. pthread_mutex_init (&internal, &atts);
  214927. }
  214928. CriticalSection::~CriticalSection() throw()
  214929. {
  214930. pthread_mutex_destroy (&internal);
  214931. }
  214932. void CriticalSection::enter() const throw()
  214933. {
  214934. pthread_mutex_lock (&internal);
  214935. }
  214936. bool CriticalSection::tryEnter() const throw()
  214937. {
  214938. return pthread_mutex_trylock (&internal) == 0;
  214939. }
  214940. void CriticalSection::exit() const throw()
  214941. {
  214942. pthread_mutex_unlock (&internal);
  214943. }
  214944. struct EventStruct
  214945. {
  214946. pthread_cond_t condition;
  214947. pthread_mutex_t mutex;
  214948. bool triggered;
  214949. };
  214950. WaitableEvent::WaitableEvent() throw()
  214951. {
  214952. EventStruct* const es = new EventStruct();
  214953. es->triggered = false;
  214954. pthread_cond_init (&es->condition, 0);
  214955. pthread_mutex_init (&es->mutex, 0);
  214956. internal = es;
  214957. }
  214958. WaitableEvent::~WaitableEvent() throw()
  214959. {
  214960. EventStruct* const es = (EventStruct*) internal;
  214961. pthread_cond_destroy (&es->condition);
  214962. pthread_mutex_destroy (&es->mutex);
  214963. delete es;
  214964. }
  214965. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  214966. {
  214967. EventStruct* const es = (EventStruct*) internal;
  214968. bool ok = true;
  214969. pthread_mutex_lock (&es->mutex);
  214970. if (timeOutMillisecs < 0)
  214971. {
  214972. while (! es->triggered)
  214973. pthread_cond_wait (&es->condition, &es->mutex);
  214974. }
  214975. else
  214976. {
  214977. while (! es->triggered)
  214978. {
  214979. struct timeval t;
  214980. gettimeofday (&t, 0);
  214981. struct timespec time;
  214982. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  214983. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  214984. if (time.tv_nsec >= 1000000000)
  214985. {
  214986. time.tv_nsec -= 1000000000;
  214987. time.tv_sec++;
  214988. }
  214989. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  214990. {
  214991. ok = false;
  214992. break;
  214993. }
  214994. }
  214995. }
  214996. es->triggered = false;
  214997. pthread_mutex_unlock (&es->mutex);
  214998. return ok;
  214999. }
  215000. void WaitableEvent::signal() const throw()
  215001. {
  215002. EventStruct* const es = (EventStruct*) internal;
  215003. pthread_mutex_lock (&es->mutex);
  215004. es->triggered = true;
  215005. pthread_cond_broadcast (&es->condition);
  215006. pthread_mutex_unlock (&es->mutex);
  215007. }
  215008. void WaitableEvent::reset() const throw()
  215009. {
  215010. EventStruct* const es = (EventStruct*) internal;
  215011. pthread_mutex_lock (&es->mutex);
  215012. es->triggered = false;
  215013. pthread_mutex_unlock (&es->mutex);
  215014. }
  215015. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  215016. {
  215017. struct timespec time;
  215018. time.tv_sec = millisecs / 1000;
  215019. time.tv_nsec = (millisecs % 1000) * 1000000;
  215020. nanosleep (&time, 0);
  215021. }
  215022. const tchar File::separator = T('/');
  215023. const tchar* File::separatorString = T("/");
  215024. bool juce_copyFile (const String& s, const String& d) throw();
  215025. static bool juce_stat (const String& fileName, struct stat& info) throw()
  215026. {
  215027. return fileName.isNotEmpty()
  215028. && (stat (fileName.toUTF8(), &info) == 0);
  215029. }
  215030. bool juce_isDirectory (const String& fileName) throw()
  215031. {
  215032. struct stat info;
  215033. return fileName.isEmpty()
  215034. || (juce_stat (fileName, info)
  215035. && ((info.st_mode & S_IFDIR) != 0));
  215036. }
  215037. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  215038. {
  215039. if (fileName.isEmpty())
  215040. return false;
  215041. const char* const fileNameUTF8 = fileName.toUTF8();
  215042. bool exists = access (fileNameUTF8, F_OK) == 0;
  215043. if (exists && dontCountDirectories)
  215044. {
  215045. struct stat info;
  215046. const int res = stat (fileNameUTF8, &info);
  215047. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  215048. exists = false;
  215049. }
  215050. return exists;
  215051. }
  215052. int64 juce_getFileSize (const String& fileName) throw()
  215053. {
  215054. struct stat info;
  215055. return juce_stat (fileName, info) ? info.st_size : 0;
  215056. }
  215057. bool juce_canWriteToFile (const String& fileName) throw()
  215058. {
  215059. return access (fileName.toUTF8(), W_OK) == 0;
  215060. }
  215061. bool juce_deleteFile (const String& fileName) throw()
  215062. {
  215063. const char* const fileNameUTF8 = fileName.toUTF8();
  215064. if (juce_isDirectory (fileName))
  215065. return rmdir (fileNameUTF8) == 0;
  215066. else
  215067. return remove (fileNameUTF8) == 0;
  215068. }
  215069. bool juce_moveFile (const String& source, const String& dest) throw()
  215070. {
  215071. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  215072. return true;
  215073. if (juce_canWriteToFile (source)
  215074. && juce_copyFile (source, dest))
  215075. {
  215076. if (juce_deleteFile (source))
  215077. return true;
  215078. juce_deleteFile (dest);
  215079. }
  215080. return false;
  215081. }
  215082. void juce_createDirectory (const String& fileName) throw()
  215083. {
  215084. mkdir (fileName.toUTF8(), 0777);
  215085. }
  215086. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  215087. {
  215088. const char* const fileNameUTF8 = fileName.toUTF8();
  215089. int flags = O_RDONLY;
  215090. if (forWriting)
  215091. {
  215092. if (juce_fileExists (fileName, false))
  215093. {
  215094. const int f = open (fileNameUTF8, O_RDWR, 00644);
  215095. if (f != -1)
  215096. lseek (f, 0, SEEK_END);
  215097. return (void*) f;
  215098. }
  215099. else
  215100. {
  215101. flags = O_RDWR + O_CREAT;
  215102. }
  215103. }
  215104. return (void*) open (fileNameUTF8, flags, 00644);
  215105. }
  215106. void juce_fileClose (void* handle) throw()
  215107. {
  215108. if (handle != 0)
  215109. close ((int) (pointer_sized_int) handle);
  215110. }
  215111. int juce_fileRead (void* handle, void* buffer, int size) throw()
  215112. {
  215113. if (handle != 0)
  215114. return read ((int) (pointer_sized_int) handle, buffer, size);
  215115. return 0;
  215116. }
  215117. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  215118. {
  215119. if (handle != 0)
  215120. return write ((int) (pointer_sized_int) handle, buffer, size);
  215121. return 0;
  215122. }
  215123. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  215124. {
  215125. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  215126. return pos;
  215127. return -1;
  215128. }
  215129. int64 juce_fileGetPosition (void* handle) throw()
  215130. {
  215131. if (handle != 0)
  215132. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  215133. else
  215134. return -1;
  215135. }
  215136. void juce_fileFlush (void* handle) throw()
  215137. {
  215138. if (handle != 0)
  215139. fsync ((int) (pointer_sized_int) handle);
  215140. }
  215141. // if this file doesn't exist, find a parent of it that does..
  215142. static bool doStatFS (const File* file, struct statfs& result) throw()
  215143. {
  215144. File f (*file);
  215145. for (int i = 5; --i >= 0;)
  215146. {
  215147. if (f.exists())
  215148. break;
  215149. f = f.getParentDirectory();
  215150. }
  215151. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  215152. }
  215153. int64 File::getBytesFreeOnVolume() const throw()
  215154. {
  215155. int64 free_space = 0;
  215156. struct statfs buf;
  215157. if (doStatFS (this, buf))
  215158. // Note: this returns space available to non-super user
  215159. free_space = (int64) buf.f_bsize * (int64) buf.f_bavail;
  215160. return free_space;
  215161. }
  215162. const String juce_getVolumeLabel (const String& filenameOnVolume,
  215163. int& volumeSerialNumber) throw()
  215164. {
  215165. // There is no equivalent on Linux
  215166. volumeSerialNumber = 0;
  215167. return String::empty;
  215168. }
  215169. #if JUCE_64BIT
  215170. #define filedesc ((long long) internal)
  215171. #else
  215172. #define filedesc ((int) internal)
  215173. #endif
  215174. InterProcessLock::InterProcessLock (const String& name_) throw()
  215175. : internal (0),
  215176. name (name_),
  215177. reentrancyLevel (0)
  215178. {
  215179. #if JUCE_MAC
  215180. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  215181. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  215182. #else
  215183. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  215184. #endif
  215185. temp.create();
  215186. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  215187. }
  215188. InterProcessLock::~InterProcessLock() throw()
  215189. {
  215190. while (reentrancyLevel > 0)
  215191. this->exit();
  215192. close (filedesc);
  215193. }
  215194. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  215195. {
  215196. if (internal == 0)
  215197. return false;
  215198. if (reentrancyLevel != 0)
  215199. return true;
  215200. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  215201. struct flock fl;
  215202. zerostruct (fl);
  215203. fl.l_whence = SEEK_SET;
  215204. fl.l_type = F_WRLCK;
  215205. for (;;)
  215206. {
  215207. const int result = fcntl (filedesc, F_SETLK, &fl);
  215208. if (result >= 0)
  215209. {
  215210. ++reentrancyLevel;
  215211. return true;
  215212. }
  215213. if (errno != EINTR)
  215214. {
  215215. if (timeOutMillisecs == 0
  215216. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  215217. break;
  215218. Thread::sleep (10);
  215219. }
  215220. }
  215221. return false;
  215222. }
  215223. void InterProcessLock::exit() throw()
  215224. {
  215225. if (reentrancyLevel > 0 && internal != 0)
  215226. {
  215227. --reentrancyLevel;
  215228. struct flock fl;
  215229. zerostruct (fl);
  215230. fl.l_whence = SEEK_SET;
  215231. fl.l_type = F_UNLCK;
  215232. for (;;)
  215233. {
  215234. const int result = fcntl (filedesc, F_SETLKW, &fl);
  215235. if (result >= 0 || errno != EINTR)
  215236. break;
  215237. }
  215238. }
  215239. }
  215240. /********* End of inlined file: juce_posix_SharedCode.h *********/
  215241. static File executableFile;
  215242. void PlatformUtilities::copyToStr255 (Str255& d, const String& s)
  215243. {
  215244. unsigned char* t = (unsigned char*) d;
  215245. t[0] = jmin (254, s.length());
  215246. s.copyToBuffer ((char*) t + 1, 254);
  215247. }
  215248. void PlatformUtilities::copyToStr63 (Str63& d, const String& s)
  215249. {
  215250. unsigned char* t = (unsigned char*) d;
  215251. t[0] = jmin (62, s.length());
  215252. s.copyToBuffer ((char*) t + 1, 62);
  215253. }
  215254. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  215255. {
  215256. String result;
  215257. if (cfString != 0)
  215258. {
  215259. #if JUCE_STRINGS_ARE_UNICODE
  215260. CFRange range = { 0, CFStringGetLength (cfString) };
  215261. UniChar* const u = (UniChar*) juce_malloc (sizeof (UniChar) * (range.length + 1));
  215262. CFStringGetCharacters (cfString, range, u);
  215263. u[range.length] = 0;
  215264. result = convertUTF16ToString (u);
  215265. juce_free (u);
  215266. #else
  215267. const int len = CFStringGetLength (cfString);
  215268. char* buffer = (char*) juce_malloc (len + 1);
  215269. CFStringGetCString (cfString, buffer, len + 1, CFStringGetSystemEncoding());
  215270. result = buffer;
  215271. juce_free (buffer);
  215272. #endif
  215273. }
  215274. return result;
  215275. }
  215276. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  215277. {
  215278. #if JUCE_STRINGS_ARE_UNICODE
  215279. const int len = s.length();
  215280. const juce_wchar* t = (const juce_wchar*) s;
  215281. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  215282. for (int i = 0; i <= len; ++i)
  215283. temp[i] = t[i];
  215284. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  215285. juce_free (temp);
  215286. return result;
  215287. #else
  215288. return CFStringCreateWithCString (kCFAllocatorDefault,
  215289. (const char*) s,
  215290. CFStringGetSystemEncoding());
  215291. #endif
  215292. }
  215293. const String PlatformUtilities::convertUTF16ToString (const UniChar* utf16)
  215294. {
  215295. String s;
  215296. while (*utf16 != 0)
  215297. s += (juce_wchar) *utf16++;
  215298. return s;
  215299. }
  215300. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  215301. {
  215302. UnicodeMapping map;
  215303. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  215304. kUnicodeNoSubset,
  215305. kTextEncodingDefaultFormat);
  215306. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  215307. kUnicodeCanonicalCompVariant,
  215308. kTextEncodingDefaultFormat);
  215309. map.mappingVersion = kUnicodeUseLatestMapping;
  215310. UnicodeToTextInfo conversionInfo = 0;
  215311. String result;
  215312. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  215313. {
  215314. const int len = s.length();
  215315. UniChar* const tempIn = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  215316. UniChar* const tempOut = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  215317. for (int i = 0; i <= len; ++i)
  215318. tempIn[i] = s[i];
  215319. ByteCount bytesRead = 0;
  215320. ByteCount outputBufferSize = 0;
  215321. if (ConvertFromUnicodeToText (conversionInfo,
  215322. len * sizeof (UniChar), tempIn,
  215323. kUnicodeDefaultDirectionMask,
  215324. 0, 0, 0, 0,
  215325. len * sizeof (UniChar), &bytesRead,
  215326. &outputBufferSize, tempOut) == noErr)
  215327. {
  215328. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  215329. tchar* t = const_cast <tchar*> ((const tchar*) result);
  215330. int i;
  215331. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  215332. t[i] = (tchar) tempOut[i];
  215333. t[i] = 0;
  215334. }
  215335. juce_free (tempIn);
  215336. juce_free (tempOut);
  215337. DisposeUnicodeToTextInfo (&conversionInfo);
  215338. }
  215339. return result;
  215340. }
  215341. const unsigned int macTimeToUnixTimeDiff = 0x7c25be90;
  215342. static uint64 utcDateTimeToUnixTime (const UTCDateTime& d) throw()
  215343. {
  215344. if (d.highSeconds == 0 && d.lowSeconds == 0 && d.fraction == 0)
  215345. return 0;
  215346. return (((((uint64) d.highSeconds) << 32) | (uint64) d.lowSeconds) * 1000)
  215347. + ((d.fraction * 1000) >> 16)
  215348. - 2082844800000ll;
  215349. }
  215350. static void unixTimeToUtcDateTime (uint64 t, UTCDateTime& d) throw()
  215351. {
  215352. if (t != 0)
  215353. t += 2082844800000ll;
  215354. d.highSeconds = (t / 1000) >> 32;
  215355. d.lowSeconds = (t / 1000) & (uint64) 0xffffffff;
  215356. d.fraction = ((t % 1000) << 16) / 1000;
  215357. }
  215358. void juce_getFileTimes (const String& fileName,
  215359. int64& modificationTime,
  215360. int64& accessTime,
  215361. int64& creationTime) throw()
  215362. {
  215363. modificationTime = 0;
  215364. accessTime = 0;
  215365. creationTime = 0;
  215366. FSRef fileRef;
  215367. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  215368. {
  215369. FSRefParam info;
  215370. zerostruct (info);
  215371. info.ref = &fileRef;
  215372. info.whichInfo = kFSCatInfoAllDates;
  215373. FSCatalogInfo catInfo;
  215374. info.catInfo = &catInfo;
  215375. if (PBGetCatalogInfoSync (&info) == noErr)
  215376. {
  215377. creationTime = utcDateTimeToUnixTime (catInfo.createDate);
  215378. accessTime = utcDateTimeToUnixTime (catInfo.accessDate);
  215379. modificationTime = utcDateTimeToUnixTime (catInfo.contentModDate);
  215380. }
  215381. }
  215382. }
  215383. bool juce_setFileTimes (const String& fileName,
  215384. int64 modificationTime,
  215385. int64 accessTime,
  215386. int64 creationTime) throw()
  215387. {
  215388. FSRef fileRef;
  215389. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  215390. {
  215391. FSRefParam info;
  215392. zerostruct (info);
  215393. info.ref = &fileRef;
  215394. info.whichInfo = kFSCatInfoAllDates;
  215395. FSCatalogInfo catInfo;
  215396. info.catInfo = &catInfo;
  215397. if (PBGetCatalogInfoSync (&info) == noErr)
  215398. {
  215399. if (creationTime != 0)
  215400. unixTimeToUtcDateTime (creationTime, catInfo.createDate);
  215401. if (modificationTime != 0)
  215402. unixTimeToUtcDateTime (modificationTime, catInfo.contentModDate);
  215403. if (accessTime != 0)
  215404. unixTimeToUtcDateTime (accessTime, catInfo.accessDate);
  215405. return PBSetCatalogInfoSync (&info) == noErr;
  215406. }
  215407. }
  215408. return false;
  215409. }
  215410. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  215411. {
  215412. const char* const fileNameUTF8 = fileName.toUTF8();
  215413. struct stat info;
  215414. const int res = stat (fileNameUTF8, &info);
  215415. bool ok = false;
  215416. if (res == 0)
  215417. {
  215418. info.st_mode &= 0777; // Just permissions
  215419. if (isReadOnly)
  215420. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  215421. else
  215422. // Give everybody write permission?
  215423. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  215424. ok = chmod (fileNameUTF8, info.st_mode) == 0;
  215425. }
  215426. return ok;
  215427. }
  215428. bool juce_copyFile (const String& src, const String& dst) throw()
  215429. {
  215430. const File destFile (dst);
  215431. if (! destFile.create())
  215432. return false;
  215433. FSRef srcRef, dstRef;
  215434. if (! (PlatformUtilities::makeFSRefFromPath (&srcRef, src)
  215435. && PlatformUtilities::makeFSRefFromPath (&dstRef, dst)))
  215436. {
  215437. return false;
  215438. }
  215439. int okForks = 0;
  215440. CatPositionRec iter;
  215441. iter.initialize = 0;
  215442. HFSUniStr255 forkName;
  215443. // can't just copy the data because this is a bloody Mac, so we need to copy each
  215444. // fork separately...
  215445. while (FSIterateForks (&srcRef, &iter, &forkName, 0, 0) == noErr)
  215446. {
  215447. SInt16 srcForkNum = 0, dstForkNum = 0;
  215448. OSErr err = FSOpenFork (&srcRef, forkName.length, forkName.unicode, fsRdPerm, &srcForkNum);
  215449. if (err == noErr)
  215450. {
  215451. err = FSOpenFork (&dstRef, forkName.length, forkName.unicode, fsRdWrPerm, &dstForkNum);
  215452. if (err == noErr)
  215453. {
  215454. MemoryBlock buf (32768);
  215455. SInt64 pos = 0;
  215456. for (;;)
  215457. {
  215458. ByteCount bytesRead = 0;
  215459. err = FSReadFork (srcForkNum, fsFromStart, pos, buf.getSize(), (char*) buf, &bytesRead);
  215460. if (bytesRead > 0)
  215461. {
  215462. err = FSWriteFork (dstForkNum, fsFromStart, pos, bytesRead, (const char*) buf, &bytesRead);
  215463. pos += bytesRead;
  215464. }
  215465. if (err != noErr)
  215466. {
  215467. if (err == eofErr)
  215468. ++okForks;
  215469. break;
  215470. }
  215471. }
  215472. FSFlushFork (dstForkNum);
  215473. FSCloseFork (dstForkNum);
  215474. }
  215475. FSCloseFork (srcForkNum);
  215476. }
  215477. }
  215478. if (okForks > 0) // some files seem to be ok even if not all their forks get copied..
  215479. {
  215480. // copy permissions..
  215481. struct stat info;
  215482. if (juce_stat (src, info))
  215483. chmod (dst.toUTF8(), info.st_mode & 0777);
  215484. return true;
  215485. }
  215486. return false;
  215487. }
  215488. const StringArray juce_getFileSystemRoots() throw()
  215489. {
  215490. StringArray s;
  215491. s.add (T("/"));
  215492. return s;
  215493. }
  215494. static bool isFileOnDriveType (const File* const f, const char** types) throw()
  215495. {
  215496. struct statfs buf;
  215497. if (doStatFS (f, buf))
  215498. {
  215499. const String type (buf.f_fstypename);
  215500. while (*types != 0)
  215501. if (type.equalsIgnoreCase (*types++))
  215502. return true;
  215503. }
  215504. return false;
  215505. }
  215506. bool File::isOnCDRomDrive() const throw()
  215507. {
  215508. static const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  215509. return isFileOnDriveType (this, (const char**) cdTypes);
  215510. }
  215511. bool File::isOnHardDisk() const throw()
  215512. {
  215513. static const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  215514. return ! (isOnCDRomDrive() || isFileOnDriveType (this, (const char**) nonHDTypes));
  215515. }
  215516. bool File::isOnRemovableDrive() const throw()
  215517. {
  215518. jassertfalse // xxx not implemented for mac!
  215519. return false;
  215520. }
  215521. static bool juce_isHiddenFile (const String& path) throw()
  215522. {
  215523. FSRef ref;
  215524. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  215525. return false;
  215526. FSCatalogInfo info;
  215527. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  215528. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  215529. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  215530. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  215531. }
  215532. bool File::isHidden() const throw()
  215533. {
  215534. return juce_isHiddenFile (getFullPathName());
  215535. }
  215536. const File File::getSpecialLocation (const SpecialLocationType type)
  215537. {
  215538. const char* resultPath = 0;
  215539. switch (type)
  215540. {
  215541. case userHomeDirectory:
  215542. resultPath = getenv ("HOME");
  215543. if (resultPath == 0)
  215544. {
  215545. struct passwd* const pw = getpwuid (getuid());
  215546. if (pw != 0)
  215547. resultPath = pw->pw_dir;
  215548. }
  215549. break;
  215550. case userDocumentsDirectory:
  215551. resultPath = "~/Documents";
  215552. break;
  215553. case userDesktopDirectory:
  215554. resultPath = "~/Desktop";
  215555. break;
  215556. case userApplicationDataDirectory:
  215557. resultPath = "~/Library";
  215558. break;
  215559. case commonApplicationDataDirectory:
  215560. resultPath = "/Library";
  215561. break;
  215562. case globalApplicationsDirectory:
  215563. resultPath = "/Applications";
  215564. break;
  215565. case userMusicDirectory:
  215566. resultPath = "~/Music";
  215567. break;
  215568. case userMoviesDirectory:
  215569. resultPath = "~/Movies";
  215570. break;
  215571. case tempDirectory:
  215572. {
  215573. File tmp (T("~/Library/Caches/") + executableFile.getFileNameWithoutExtension());
  215574. tmp.createDirectory();
  215575. return tmp.getFullPathName();
  215576. }
  215577. case currentExecutableFile:
  215578. return executableFile;
  215579. case currentApplicationFile:
  215580. {
  215581. const File parent (executableFile.getParentDirectory());
  215582. return parent.getFullPathName().endsWithIgnoreCase (T("Contents/MacOS"))
  215583. ? parent.getParentDirectory().getParentDirectory()
  215584. : executableFile;
  215585. }
  215586. default:
  215587. jassertfalse // unknown type?
  215588. break;
  215589. }
  215590. if (resultPath != 0)
  215591. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  215592. return File::nonexistent;
  215593. }
  215594. void juce_setCurrentExecutableFileName (const String& filename) throw()
  215595. {
  215596. executableFile = File::getCurrentWorkingDirectory()
  215597. .getChildFile (PlatformUtilities::convertToPrecomposedUnicode (filename));
  215598. }
  215599. void juce_setCurrentExecutableFileNameFromBundleId (const String& bundleId) throw()
  215600. {
  215601. CFStringRef bundleIdStringRef = PlatformUtilities::juceStringToCFString (bundleId);
  215602. CFBundleRef bundleRef = CFBundleGetBundleWithIdentifier (bundleIdStringRef);
  215603. CFRelease (bundleIdStringRef);
  215604. if (bundleRef != 0)
  215605. {
  215606. CFURLRef exeURLRef = CFBundleCopyExecutableURL (bundleRef);
  215607. if (exeURLRef != 0)
  215608. {
  215609. CFStringRef pathStringRef = CFURLCopyFileSystemPath (exeURLRef, kCFURLPOSIXPathStyle);
  215610. CFRelease (exeURLRef);
  215611. if (pathStringRef != 0)
  215612. {
  215613. juce_setCurrentExecutableFileName (PlatformUtilities::cfStringToJuceString (pathStringRef));
  215614. CFRelease (pathStringRef);
  215615. }
  215616. }
  215617. }
  215618. }
  215619. const File File::getCurrentWorkingDirectory() throw()
  215620. {
  215621. char buf [2048];
  215622. getcwd (buf, sizeof(buf));
  215623. return File (PlatformUtilities::convertToPrecomposedUnicode (buf));
  215624. }
  215625. bool File::setAsCurrentWorkingDirectory() const throw()
  215626. {
  215627. return chdir (getFullPathName().toUTF8()) == 0;
  215628. }
  215629. struct FindFileStruct
  215630. {
  215631. String parentDir, wildCard;
  215632. DIR* dir;
  215633. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  215634. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  215635. {
  215636. const char* const wildCardUTF8 = wildCard.toUTF8();
  215637. for (;;)
  215638. {
  215639. struct dirent* const de = readdir (dir);
  215640. if (de == 0)
  215641. break;
  215642. if (fnmatch (wildCardUTF8, de->d_name, 0) == 0)
  215643. {
  215644. result = PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 ((const uint8*) de->d_name));
  215645. const String path (parentDir + result);
  215646. if (isDir != 0 || fileSize != 0)
  215647. {
  215648. struct stat info;
  215649. const bool statOk = juce_stat (path, info);
  215650. if (isDir != 0)
  215651. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  215652. if (isHidden != 0)
  215653. *isHidden = (de->d_name[0] == '.')
  215654. || juce_isHiddenFile (path);
  215655. if (fileSize != 0)
  215656. *fileSize = statOk ? info.st_size : 0;
  215657. }
  215658. if (modTime != 0 || creationTime != 0)
  215659. {
  215660. int64 m, a, c;
  215661. juce_getFileTimes (path, m, a, c);
  215662. if (modTime != 0)
  215663. *modTime = m;
  215664. if (creationTime != 0)
  215665. *creationTime = c;
  215666. }
  215667. if (isReadOnly != 0)
  215668. *isReadOnly = ! juce_canWriteToFile (path);
  215669. return true;
  215670. }
  215671. }
  215672. return false;
  215673. }
  215674. };
  215675. // returns 0 on failure
  215676. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  215677. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  215678. Time* creationTime, bool* isReadOnly) throw()
  215679. {
  215680. DIR* const d = opendir (directory.toUTF8());
  215681. if (d != 0)
  215682. {
  215683. FindFileStruct* const ff = new FindFileStruct();
  215684. ff->parentDir = directory;
  215685. if (!ff->parentDir.endsWithChar (File::separator))
  215686. ff->parentDir += File::separator;
  215687. ff->wildCard = wildCard;
  215688. ff->dir = d;
  215689. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  215690. {
  215691. return ff;
  215692. }
  215693. else
  215694. {
  215695. firstResultFile = String::empty;
  215696. isDir = false;
  215697. closedir (d);
  215698. delete ff;
  215699. }
  215700. }
  215701. return 0;
  215702. }
  215703. bool juce_findFileNext (void* handle, String& resultFile,
  215704. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  215705. {
  215706. FindFileStruct* const ff = (FindFileStruct*) handle;
  215707. if (ff != 0)
  215708. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  215709. return false;
  215710. }
  215711. void juce_findFileClose (void* handle) throw()
  215712. {
  215713. FindFileStruct* const ff = (FindFileStruct*)handle;
  215714. if (ff != 0)
  215715. {
  215716. closedir (ff->dir);
  215717. delete ff;
  215718. }
  215719. }
  215720. bool juce_launchExecutable (const String& pathAndArguments) throw()
  215721. {
  215722. char* const argv[4] = { "/bin/sh", "-c", (char*) (const char*) pathAndArguments, 0 };
  215723. const int cpid = fork();
  215724. if (cpid == 0)
  215725. {
  215726. // Child process
  215727. if (execve (argv[0], argv, 0) < 0)
  215728. exit (0);
  215729. }
  215730. else
  215731. {
  215732. if (cpid < 0)
  215733. return false;
  215734. }
  215735. return true;
  215736. }
  215737. bool juce_launchFile (const String& fileName,
  215738. const String& parameters) throw()
  215739. {
  215740. bool ok = false;
  215741. if (fileName.startsWithIgnoreCase (T("http:"))
  215742. || fileName.startsWithIgnoreCase (T("https:"))
  215743. || fileName.startsWithIgnoreCase (T("ftp:"))
  215744. || fileName.startsWithIgnoreCase (T("file:")))
  215745. {
  215746. CFStringRef urlString = PlatformUtilities::juceStringToCFString (fileName);
  215747. if (urlString != 0)
  215748. {
  215749. CFURLRef url = CFURLCreateWithString (kCFAllocatorDefault,
  215750. urlString, 0);
  215751. CFRelease (urlString);
  215752. if (url != 0)
  215753. {
  215754. ok = (LSOpenCFURLRef (url, 0) == noErr);
  215755. CFRelease (url);
  215756. }
  215757. }
  215758. }
  215759. else
  215760. {
  215761. FSRef ref;
  215762. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  215763. {
  215764. if (juce_isDirectory (fileName) && parameters.isNotEmpty())
  215765. {
  215766. // if we're launching a bundled app with a document..
  215767. StringArray docs;
  215768. docs.addTokens (parameters, true);
  215769. FSRef* docRefs = new FSRef [docs.size()];
  215770. for (int i = 0; i < docs.size(); ++i)
  215771. PlatformUtilities::makeFSRefFromPath (docRefs + i, docs[i]);
  215772. LSLaunchFSRefSpec ors;
  215773. ors.appRef = &ref;
  215774. ors.numDocs = docs.size();
  215775. ors.itemRefs = docRefs;
  215776. ors.passThruParams = 0;
  215777. ors.launchFlags = kLSLaunchDefaults;
  215778. ors.asyncRefCon = 0;
  215779. FSRef actual;
  215780. ok = (LSOpenFromRefSpec (&ors, &actual) == noErr);
  215781. delete docRefs;
  215782. }
  215783. else
  215784. {
  215785. if (parameters.isNotEmpty())
  215786. ok = juce_launchExecutable (T("\"") + fileName + T("\" ") + parameters);
  215787. else
  215788. ok = (LSOpenFSRef (&ref, 0) == noErr);
  215789. }
  215790. }
  215791. }
  215792. return ok;
  215793. }
  215794. bool PlatformUtilities::makeFSSpecFromPath (FSSpec* fs, const String& path)
  215795. {
  215796. FSRef ref;
  215797. return makeFSRefFromPath (&ref, path)
  215798. && FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, fs, 0) == noErr;
  215799. }
  215800. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  215801. {
  215802. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  215803. }
  215804. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  215805. {
  215806. uint8 path [2048];
  215807. zeromem (path, sizeof (path));
  215808. String result;
  215809. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  215810. result = String::fromUTF8 (path);
  215811. return PlatformUtilities::convertToPrecomposedUnicode (result);
  215812. }
  215813. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  215814. {
  215815. FSRef fs;
  215816. if (makeFSRefFromPath (&fs, filename))
  215817. {
  215818. LSItemInfoRecord info;
  215819. if (LSCopyItemInfoForRef (&fs, kLSRequestTypeCreator, &info) == noErr)
  215820. return info.filetype;
  215821. }
  215822. return 0;
  215823. }
  215824. bool PlatformUtilities::isBundle (const String& filename)
  215825. {
  215826. FSRef fs;
  215827. if (makeFSRefFromPath (&fs, filename))
  215828. {
  215829. LSItemInfoRecord info;
  215830. if (LSCopyItemInfoForRef (&fs, kLSItemInfoIsPackage, &info) == noErr)
  215831. return (info.flags & kLSItemInfoIsPackage) != 0;
  215832. }
  215833. return false;
  215834. }
  215835. END_JUCE_NAMESPACE
  215836. /********* End of inlined file: juce_mac_Files.cpp *********/
  215837. /********* Start of inlined file: juce_mac_NamedPipe.cpp *********/
  215838. #include <sys/stat.h>
  215839. #include <sys/dir.h>
  215840. #include <fcntl.h>
  215841. // As well as being for the mac, this file is included by the linux build.
  215842. #if ! JUCE_MAC
  215843. #include <sys/wait.h>
  215844. #include <errno.h>
  215845. #include <unistd.h>
  215846. #endif
  215847. BEGIN_JUCE_NAMESPACE
  215848. struct NamedPipeInternal
  215849. {
  215850. String pipeInName, pipeOutName;
  215851. int pipeIn, pipeOut;
  215852. bool volatile createdPipe, blocked, stopReadOperation;
  215853. static void signalHandler (int) {}
  215854. };
  215855. void NamedPipe::cancelPendingReads()
  215856. {
  215857. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  215858. {
  215859. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215860. intern->stopReadOperation = true;
  215861. char buffer [1] = { 0 };
  215862. ::write (intern->pipeIn, buffer, 1);
  215863. int timeout = 2000;
  215864. while (intern->blocked && --timeout >= 0)
  215865. Thread::sleep (2);
  215866. intern->stopReadOperation = false;
  215867. }
  215868. }
  215869. void NamedPipe::close()
  215870. {
  215871. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215872. if (intern != 0)
  215873. {
  215874. internal = 0;
  215875. if (intern->pipeIn != -1)
  215876. ::close (intern->pipeIn);
  215877. if (intern->pipeOut != -1)
  215878. ::close (intern->pipeOut);
  215879. if (intern->createdPipe)
  215880. {
  215881. unlink (intern->pipeInName);
  215882. unlink (intern->pipeOutName);
  215883. }
  215884. delete intern;
  215885. }
  215886. }
  215887. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  215888. {
  215889. close();
  215890. NamedPipeInternal* const intern = new NamedPipeInternal();
  215891. internal = intern;
  215892. intern->createdPipe = createPipe;
  215893. intern->blocked = false;
  215894. intern->stopReadOperation = false;
  215895. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  215896. siginterrupt (SIGPIPE, 1);
  215897. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  215898. intern->pipeInName = pipePath + T("_in");
  215899. intern->pipeOutName = pipePath + T("_out");
  215900. intern->pipeIn = -1;
  215901. intern->pipeOut = -1;
  215902. if (createPipe)
  215903. {
  215904. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  215905. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  215906. {
  215907. delete intern;
  215908. internal = 0;
  215909. return false;
  215910. }
  215911. }
  215912. return true;
  215913. }
  215914. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  215915. {
  215916. int bytesRead = -1;
  215917. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215918. if (intern != 0)
  215919. {
  215920. intern->blocked = true;
  215921. if (intern->pipeIn == -1)
  215922. {
  215923. if (intern->createdPipe)
  215924. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  215925. else
  215926. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  215927. if (intern->pipeIn == -1)
  215928. {
  215929. intern->blocked = false;
  215930. return -1;
  215931. }
  215932. }
  215933. bytesRead = 0;
  215934. char* p = (char*) destBuffer;
  215935. while (bytesRead < maxBytesToRead)
  215936. {
  215937. const int bytesThisTime = maxBytesToRead - bytesRead;
  215938. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  215939. if (numRead <= 0 || intern->stopReadOperation)
  215940. {
  215941. bytesRead = -1;
  215942. break;
  215943. }
  215944. bytesRead += numRead;
  215945. p += bytesRead;
  215946. }
  215947. intern->blocked = false;
  215948. }
  215949. return bytesRead;
  215950. }
  215951. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  215952. {
  215953. int bytesWritten = -1;
  215954. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215955. if (intern != 0)
  215956. {
  215957. if (intern->pipeOut == -1)
  215958. {
  215959. if (intern->createdPipe)
  215960. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  215961. else
  215962. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  215963. if (intern->pipeOut == -1)
  215964. {
  215965. return -1;
  215966. }
  215967. }
  215968. const char* p = (const char*) sourceBuffer;
  215969. bytesWritten = 0;
  215970. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  215971. while (bytesWritten < numBytesToWrite
  215972. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  215973. {
  215974. const int bytesThisTime = numBytesToWrite - bytesWritten;
  215975. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  215976. if (numWritten <= 0)
  215977. {
  215978. bytesWritten = -1;
  215979. break;
  215980. }
  215981. bytesWritten += numWritten;
  215982. p += bytesWritten;
  215983. }
  215984. }
  215985. return bytesWritten;
  215986. }
  215987. END_JUCE_NAMESPACE
  215988. /********* End of inlined file: juce_mac_NamedPipe.cpp *********/
  215989. /********* Start of inlined file: juce_mac_SystemStats.mm *********/
  215990. /********* Start of inlined file: juce_mac_NativeHeaders.h *********/
  215991. #ifndef __JUCE_MAC_NATIVEHEADERS_JUCEHEADER__
  215992. #define __JUCE_MAC_NATIVEHEADERS_JUCEHEADER__
  215993. #include <Cocoa/Cocoa.h>
  215994. BEGIN_JUCE_NAMESPACE
  215995. class AutoPool
  215996. {
  215997. public:
  215998. AutoPool() { pool = [[NSAutoreleasePool alloc] init]; }
  215999. ~AutoPool() { [pool release]; }
  216000. private:
  216001. NSAutoreleasePool* pool;
  216002. };
  216003. END_JUCE_NAMESPACE
  216004. static const JUCE_NAMESPACE::String nsStringToJuce (NSString* s)
  216005. {
  216006. return JUCE_NAMESPACE::String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [s UTF8String]);
  216007. }
  216008. static NSString* juceStringToNS (const JUCE_NAMESPACE::String& s)
  216009. {
  216010. return [NSString stringWithUTF8String: (const char*) s.toUTF8()];
  216011. }
  216012. #endif
  216013. /********* End of inlined file: juce_mac_NativeHeaders.h *********/
  216014. #include <AppKit/AppKit.h>
  216015. #include <CoreAudio/HostTime.h>
  216016. #include <ctime>
  216017. #include <sys/resource.h>
  216018. BEGIN_JUCE_NAMESPACE
  216019. static int64 highResTimerFrequency;
  216020. #if JUCE_INTEL
  216021. static void juce_getCpuVendor (char* const v) throw()
  216022. {
  216023. int vendor[4];
  216024. zerostruct (vendor);
  216025. int dummy = 0;
  216026. asm ("mov %%ebx, %%esi \n\t"
  216027. "cpuid \n\t"
  216028. "xchg %%esi, %%ebx"
  216029. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  216030. memcpy (v, vendor, 16);
  216031. }
  216032. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures) throw()
  216033. {
  216034. unsigned int cpu = 0;
  216035. unsigned int ext = 0;
  216036. unsigned int family = 0;
  216037. unsigned int dummy = 0;
  216038. asm ("mov %%ebx, %%esi \n\t"
  216039. "cpuid \n\t"
  216040. "xchg %%esi, %%ebx"
  216041. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  216042. familyModel = family;
  216043. extFeatures = ext;
  216044. return cpu;
  216045. }
  216046. struct CPUFlags
  216047. {
  216048. bool hasMMX : 1;
  216049. bool hasSSE : 1;
  216050. bool hasSSE2 : 1;
  216051. bool has3DNow : 1;
  216052. };
  216053. static CPUFlags cpuFlags;
  216054. #endif
  216055. void Logger::outputDebugString (const String& text) throw()
  216056. {
  216057. String withLineFeed (text + T("\n"));
  216058. const char* const utf8 = withLineFeed.toUTF8();
  216059. fwrite (utf8, strlen (utf8), 1, stdout);
  216060. }
  216061. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  216062. {
  216063. String text;
  216064. va_list args;
  216065. va_start (args, format);
  216066. text.vprintf(format, args);
  216067. outputDebugString (text);
  216068. }
  216069. int SystemStats::getMemorySizeInMegabytes() throw()
  216070. {
  216071. long bytes;
  216072. if (Gestalt (gestaltPhysicalRAMSize, &bytes) == noErr)
  216073. return (int) (((unsigned long) bytes) / (1024 * 1024));
  216074. return 0;
  216075. }
  216076. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  216077. {
  216078. return MacOSX;
  216079. }
  216080. const String SystemStats::getOperatingSystemName() throw()
  216081. {
  216082. return T("Mac OS X");
  216083. }
  216084. bool SystemStats::isOperatingSystem64Bit() throw()
  216085. {
  216086. #if JUCE_64BIT
  216087. return true;
  216088. #else
  216089. //xxx not sure how to find this out?..
  216090. return false;
  216091. #endif
  216092. }
  216093. void SystemStats::initialiseStats() throw()
  216094. {
  216095. static bool initialised = false;
  216096. if (! initialised)
  216097. {
  216098. initialised = true;
  216099. //[NSApplication sharedApplication];
  216100. NSApplicationLoad();
  216101. #if JUCE_INTEL
  216102. {
  216103. unsigned int familyModel, extFeatures;
  216104. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  216105. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  216106. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  216107. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  216108. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  216109. }
  216110. #endif
  216111. highResTimerFrequency = (int64) AudioGetHostClockFrequency();
  216112. String s (SystemStats::getJUCEVersion());
  216113. rlimit lim;
  216114. getrlimit (RLIMIT_NOFILE, &lim);
  216115. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  216116. setrlimit (RLIMIT_NOFILE, &lim);
  216117. }
  216118. }
  216119. bool SystemStats::hasMMX() throw()
  216120. {
  216121. #if JUCE_INTEL
  216122. return cpuFlags.hasMMX;
  216123. #else
  216124. return false;
  216125. #endif
  216126. }
  216127. bool SystemStats::hasSSE() throw()
  216128. {
  216129. #if JUCE_INTEL
  216130. return cpuFlags.hasSSE;
  216131. #else
  216132. return false;
  216133. #endif
  216134. }
  216135. bool SystemStats::hasSSE2() throw()
  216136. {
  216137. #if JUCE_INTEL
  216138. return cpuFlags.hasSSE2;
  216139. #else
  216140. return false;
  216141. #endif
  216142. }
  216143. bool SystemStats::has3DNow() throw()
  216144. {
  216145. #if JUCE_INTEL
  216146. return cpuFlags.has3DNow;
  216147. #else
  216148. return false;
  216149. #endif
  216150. }
  216151. const String SystemStats::getCpuVendor() throw()
  216152. {
  216153. #if JUCE_INTEL
  216154. char v [16];
  216155. juce_getCpuVendor (v);
  216156. return String (v, 16);
  216157. #else
  216158. return String::empty;
  216159. #endif
  216160. }
  216161. int SystemStats::getCpuSpeedInMegaherz() throw()
  216162. {
  216163. return GetCPUSpeed();
  216164. }
  216165. int SystemStats::getNumCpus() throw()
  216166. {
  216167. return MPProcessors();
  216168. }
  216169. static int64 juce_getMicroseconds() throw()
  216170. {
  216171. UnsignedWide t;
  216172. Microseconds (&t);
  216173. return (((int64) t.hi) << 32) | t.lo;
  216174. }
  216175. uint32 juce_millisecondsSinceStartup() throw()
  216176. {
  216177. return (uint32) (juce_getMicroseconds() / 1000);
  216178. }
  216179. double Time::getMillisecondCounterHiRes() throw()
  216180. {
  216181. // xxx might be more accurate to use a scaled AudioGetCurrentHostTime?
  216182. return juce_getMicroseconds() * 0.001;
  216183. }
  216184. int64 Time::getHighResolutionTicks() throw()
  216185. {
  216186. return (int64) AudioGetCurrentHostTime();
  216187. }
  216188. int64 Time::getHighResolutionTicksPerSecond() throw()
  216189. {
  216190. return highResTimerFrequency;
  216191. }
  216192. int64 SystemStats::getClockCycleCounter() throw()
  216193. {
  216194. jassertfalse
  216195. return 0;
  216196. }
  216197. bool Time::setSystemTimeToThisTime() const throw()
  216198. {
  216199. jassertfalse
  216200. return false;
  216201. }
  216202. int SystemStats::getPageSize() throw()
  216203. {
  216204. jassertfalse
  216205. return 512; //xxx
  216206. }
  216207. void PlatformUtilities::fpuReset()
  216208. {
  216209. }
  216210. END_JUCE_NAMESPACE
  216211. /********* End of inlined file: juce_mac_SystemStats.mm *********/
  216212. /********* Start of inlined file: juce_mac_Threads.cpp *********/
  216213. #include <pthread.h>
  216214. #include <sched.h>
  216215. #include <sys/file.h>
  216216. #include <sys/types.h>
  216217. #include <sys/sysctl.h>
  216218. BEGIN_JUCE_NAMESPACE
  216219. /*
  216220. Note that a lot of methods that you'd expect to find in this file actually
  216221. live in juce_posix_SharedCode.h!
  216222. */
  216223. void JUCE_API juce_threadEntryPoint (void*);
  216224. void* threadEntryProc (void* userData) throw()
  216225. {
  216226. juce_threadEntryPoint (userData);
  216227. return 0;
  216228. }
  216229. void* juce_createThread (void* userData) throw()
  216230. {
  216231. pthread_t handle = 0;
  216232. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  216233. {
  216234. pthread_detach (handle);
  216235. return (void*) handle;
  216236. }
  216237. return 0;
  216238. }
  216239. void juce_killThread (void* handle) throw()
  216240. {
  216241. if (handle != 0)
  216242. pthread_cancel ((pthread_t) handle);
  216243. }
  216244. void juce_setCurrentThreadName (const String& /*name*/) throw()
  216245. {
  216246. }
  216247. int Thread::getCurrentThreadId() throw()
  216248. {
  216249. return (int) pthread_self();
  216250. }
  216251. void juce_setThreadPriority (void* handle, int priority) throw()
  216252. {
  216253. if (handle == 0)
  216254. handle = (void*) pthread_self();
  216255. struct sched_param param;
  216256. int policy;
  216257. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  216258. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  216259. pthread_setschedparam ((pthread_t) handle, policy, &param);
  216260. }
  216261. void Thread::yield() throw()
  216262. {
  216263. sched_yield();
  216264. }
  216265. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  216266. {
  216267. // xxx
  216268. jassertfalse
  216269. }
  216270. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  216271. {
  216272. static char testResult = 0;
  216273. if (testResult == 0)
  216274. {
  216275. struct kinfo_proc info;
  216276. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  216277. size_t sz = sizeof (info);
  216278. sysctl (m, 4, &info, &sz, 0, 0);
  216279. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  216280. }
  216281. return testResult > 0;
  216282. }
  216283. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  216284. {
  216285. return juce_isRunningUnderDebugger();
  216286. }
  216287. void Process::raisePrivilege()
  216288. {
  216289. jassertfalse
  216290. }
  216291. void Process::lowerPrivilege()
  216292. {
  216293. jassertfalse
  216294. }
  216295. void Process::terminate()
  216296. {
  216297. exit (0);
  216298. }
  216299. void Process::setPriority (ProcessPriority p)
  216300. {
  216301. // xxx
  216302. }
  216303. void* Process::loadDynamicLibrary (const String& name)
  216304. {
  216305. // xxx needs to use bundles
  216306. FSSpec fs;
  216307. if (PlatformUtilities::makeFSSpecFromPath (&fs, name))
  216308. {
  216309. CFragConnectionID connID;
  216310. Ptr mainPtr;
  216311. Str255 errorMessage;
  216312. Str63 nm;
  216313. PlatformUtilities::copyToStr63 (nm, name);
  216314. const OSErr err = GetDiskFragment (&fs, 0, kCFragGoesToEOF, nm, kReferenceCFrag, &connID, &mainPtr, errorMessage);
  216315. if (err == noErr)
  216316. return (void*)connID;
  216317. }
  216318. return 0;
  216319. }
  216320. void Process::freeDynamicLibrary (void* handle)
  216321. {
  216322. if (handle != 0)
  216323. CloseConnection ((CFragConnectionID*)&handle);
  216324. }
  216325. void* Process::getProcedureEntryPoint (void* h, const String& procedureName)
  216326. {
  216327. if (h != 0)
  216328. {
  216329. CFragSymbolClass cl;
  216330. Ptr ptr;
  216331. Str255 name;
  216332. PlatformUtilities::copyToStr255 (name, procedureName);
  216333. if (FindSymbol ((CFragConnectionID) h, name, &ptr, &cl) == noErr)
  216334. {
  216335. return ptr;
  216336. }
  216337. }
  216338. return 0;
  216339. }
  216340. END_JUCE_NAMESPACE
  216341. /********* End of inlined file: juce_mac_Threads.cpp *********/
  216342. /********* Start of inlined file: juce_mac_Network.mm *********/
  216343. #include <IOKit/IOKitLib.h>
  216344. #include <IOKit/network/IOEthernetInterface.h>
  216345. #include <IOKit/network/IONetworkInterface.h>
  216346. #include <IOKit/network/IOEthernetController.h>
  216347. #include <netdb.h>
  216348. #include <arpa/inet.h>
  216349. #include <netinet/in.h>
  216350. #include <sys/types.h>
  216351. #include <sys/socket.h>
  216352. #include <sys/wait.h>
  216353. BEGIN_JUCE_NAMESPACE
  216354. /********* Start of inlined file: juce_mac_HTTPStream.h *********/
  216355. // (This file gets included by the mac + linux networking code)
  216356. /** A HTTP input stream that uses sockets.
  216357. */
  216358. class JUCE_HTTPSocketStream
  216359. {
  216360. public:
  216361. JUCE_HTTPSocketStream()
  216362. : readPosition (0),
  216363. socketHandle (-1),
  216364. levelsOfRedirection (0),
  216365. timeoutSeconds (15)
  216366. {
  216367. }
  216368. ~JUCE_HTTPSocketStream()
  216369. {
  216370. closeSocket();
  216371. }
  216372. bool open (const String& url,
  216373. const String& headers,
  216374. const MemoryBlock& postData,
  216375. const bool isPost,
  216376. URL::OpenStreamProgressCallback* callback,
  216377. void* callbackContext,
  216378. int timeOutMs)
  216379. {
  216380. closeSocket();
  216381. uint32 timeOutTime = Time::getMillisecondCounter();
  216382. if (timeOutMs == 0)
  216383. timeOutTime += 60000;
  216384. else if (timeOutMs < 0)
  216385. timeOutTime = 0xffffffff;
  216386. else
  216387. timeOutTime += timeOutMs;
  216388. String hostName, hostPath;
  216389. int hostPort;
  216390. if (! decomposeURL (url, hostName, hostPath, hostPort))
  216391. return false;
  216392. const struct hostent* host = 0;
  216393. int port = 0;
  216394. String proxyName, proxyPath;
  216395. int proxyPort = 0;
  216396. String proxyURL (getenv ("http_proxy"));
  216397. if (proxyURL.startsWithIgnoreCase (T("http://")))
  216398. {
  216399. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  216400. return false;
  216401. host = gethostbyname ((const char*) proxyName.toUTF8());
  216402. port = proxyPort;
  216403. }
  216404. else
  216405. {
  216406. host = gethostbyname ((const char*) hostName.toUTF8());
  216407. port = hostPort;
  216408. }
  216409. if (host == 0)
  216410. return false;
  216411. struct sockaddr_in address;
  216412. zerostruct (address);
  216413. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  216414. address.sin_family = host->h_addrtype;
  216415. address.sin_port = htons (port);
  216416. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  216417. if (socketHandle == -1)
  216418. return false;
  216419. int receiveBufferSize = 16384;
  216420. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  216421. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  216422. #if JUCE_MAC
  216423. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  216424. #endif
  216425. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  216426. {
  216427. closeSocket();
  216428. return false;
  216429. }
  216430. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  216431. proxyName, proxyPort,
  216432. hostPath, url,
  216433. headers, postData,
  216434. isPost));
  216435. int totalHeaderSent = 0;
  216436. while (totalHeaderSent < requestHeader.getSize())
  216437. {
  216438. if (Time::getMillisecondCounter() > timeOutTime)
  216439. {
  216440. closeSocket();
  216441. return false;
  216442. }
  216443. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  216444. if (send (socketHandle,
  216445. ((const char*) requestHeader.getData()) + totalHeaderSent,
  216446. numToSend, 0)
  216447. != numToSend)
  216448. {
  216449. closeSocket();
  216450. return false;
  216451. }
  216452. totalHeaderSent += numToSend;
  216453. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  216454. {
  216455. closeSocket();
  216456. return false;
  216457. }
  216458. }
  216459. const String responseHeader (readResponse (timeOutTime));
  216460. if (responseHeader.isNotEmpty())
  216461. {
  216462. //DBG (responseHeader);
  216463. StringArray lines;
  216464. lines.addLines (responseHeader);
  216465. // NB - using charToString() here instead of just T(" "), because that was
  216466. // causing a mysterious gcc internal compiler error...
  216467. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  216468. .substring (0, 3)
  216469. .getIntValue();
  216470. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  216471. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  216472. String location (findHeaderItem (lines, T("Location:")));
  216473. if (statusCode >= 300 && statusCode < 400
  216474. && location.isNotEmpty())
  216475. {
  216476. if (! location.startsWithIgnoreCase (T("http://")))
  216477. location = T("http://") + location;
  216478. if (levelsOfRedirection++ < 3)
  216479. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  216480. }
  216481. else
  216482. {
  216483. levelsOfRedirection = 0;
  216484. return true;
  216485. }
  216486. }
  216487. closeSocket();
  216488. return false;
  216489. }
  216490. int read (void* buffer, int bytesToRead)
  216491. {
  216492. fd_set readbits;
  216493. FD_ZERO (&readbits);
  216494. FD_SET (socketHandle, &readbits);
  216495. struct timeval tv;
  216496. tv.tv_sec = timeoutSeconds;
  216497. tv.tv_usec = 0;
  216498. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216499. return 0; // (timeout)
  216500. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  216501. readPosition += bytesRead;
  216502. return bytesRead;
  216503. }
  216504. int readPosition;
  216505. juce_UseDebuggingNewOperator
  216506. private:
  216507. int socketHandle, levelsOfRedirection;
  216508. const int timeoutSeconds;
  216509. void closeSocket()
  216510. {
  216511. if (socketHandle >= 0)
  216512. close (socketHandle);
  216513. socketHandle = -1;
  216514. }
  216515. const MemoryBlock createRequestHeader (const String& hostName,
  216516. const int hostPort,
  216517. const String& proxyName,
  216518. const int proxyPort,
  216519. const String& hostPath,
  216520. const String& originalURL,
  216521. const String& headers,
  216522. const MemoryBlock& postData,
  216523. const bool isPost)
  216524. {
  216525. String header (isPost ? "POST " : "GET ");
  216526. if (proxyName.isEmpty())
  216527. {
  216528. header << hostPath << " HTTP/1.0\r\nHost: "
  216529. << hostName << ':' << hostPort;
  216530. }
  216531. else
  216532. {
  216533. header << originalURL << " HTTP/1.0\r\nHost: "
  216534. << proxyName << ':' << proxyPort;
  216535. }
  216536. header << "\r\nUser-Agent: JUCE/"
  216537. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  216538. << "\r\nConnection: Close\r\nContent-Length: "
  216539. << postData.getSize() << "\r\n"
  216540. << headers << "\r\n";
  216541. MemoryBlock mb;
  216542. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  216543. mb.append (postData.getData(), postData.getSize());
  216544. return mb;
  216545. }
  216546. const String readResponse (const uint32 timeOutTime)
  216547. {
  216548. int bytesRead = 0, numConsecutiveLFs = 0;
  216549. MemoryBlock buffer (1024, true);
  216550. while (numConsecutiveLFs < 2 && bytesRead < 32768
  216551. && Time::getMillisecondCounter() <= timeOutTime)
  216552. {
  216553. fd_set readbits;
  216554. FD_ZERO (&readbits);
  216555. FD_SET (socketHandle, &readbits);
  216556. struct timeval tv;
  216557. tv.tv_sec = timeoutSeconds;
  216558. tv.tv_usec = 0;
  216559. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216560. return String::empty; // (timeout)
  216561. buffer.ensureSize (bytesRead + 8, true);
  216562. char* const dest = (char*) buffer.getData() + bytesRead;
  216563. if (recv (socketHandle, dest, 1, 0) == -1)
  216564. return String::empty;
  216565. const char lastByte = *dest;
  216566. ++bytesRead;
  216567. if (lastByte == '\n')
  216568. ++numConsecutiveLFs;
  216569. else if (lastByte != '\r')
  216570. numConsecutiveLFs = 0;
  216571. }
  216572. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  216573. if (header.startsWithIgnoreCase (T("HTTP/")))
  216574. return header.trimEnd();
  216575. return String::empty;
  216576. }
  216577. static bool decomposeURL (const String& url,
  216578. String& host, String& path, int& port)
  216579. {
  216580. if (! url.startsWithIgnoreCase (T("http://")))
  216581. return false;
  216582. const int nextSlash = url.indexOfChar (7, '/');
  216583. int nextColon = url.indexOfChar (7, ':');
  216584. if (nextColon > nextSlash && nextSlash > 0)
  216585. nextColon = -1;
  216586. if (nextColon >= 0)
  216587. {
  216588. host = url.substring (7, nextColon);
  216589. if (nextSlash >= 0)
  216590. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  216591. else
  216592. port = url.substring (nextColon + 1).getIntValue();
  216593. }
  216594. else
  216595. {
  216596. port = 80;
  216597. if (nextSlash >= 0)
  216598. host = url.substring (7, nextSlash);
  216599. else
  216600. host = url.substring (7);
  216601. }
  216602. if (nextSlash >= 0)
  216603. path = url.substring (nextSlash);
  216604. else
  216605. path = T("/");
  216606. return true;
  216607. }
  216608. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  216609. {
  216610. for (int i = 0; i < lines.size(); ++i)
  216611. if (lines[i].startsWithIgnoreCase (itemName))
  216612. return lines[i].substring (itemName.length()).trim();
  216613. return String::empty;
  216614. }
  216615. };
  216616. bool juce_isOnLine()
  216617. {
  216618. return true;
  216619. }
  216620. void* juce_openInternetFile (const String& url,
  216621. const String& headers,
  216622. const MemoryBlock& postData,
  216623. const bool isPost,
  216624. URL::OpenStreamProgressCallback* callback,
  216625. void* callbackContext,
  216626. int timeOutMs)
  216627. {
  216628. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  216629. if (s->open (url, headers, postData, isPost,
  216630. callback, callbackContext, timeOutMs))
  216631. return s;
  216632. delete s;
  216633. return 0;
  216634. }
  216635. void juce_closeInternetFile (void* handle)
  216636. {
  216637. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  216638. if (s != 0)
  216639. delete s;
  216640. }
  216641. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  216642. {
  216643. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  216644. if (s != 0)
  216645. return s->read (buffer, bytesToRead);
  216646. return 0;
  216647. }
  216648. int juce_seekInInternetFile (void* handle, int newPosition)
  216649. {
  216650. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  216651. if (s != 0)
  216652. return s->readPosition;
  216653. return 0;
  216654. }
  216655. /********* End of inlined file: juce_mac_HTTPStream.h *********/
  216656. static bool GetEthernetIterator (io_iterator_t* matchingServices) throw()
  216657. {
  216658. mach_port_t masterPort;
  216659. if (IOMasterPort (MACH_PORT_NULL, &masterPort) == KERN_SUCCESS)
  216660. {
  216661. CFMutableDictionaryRef dict = IOServiceMatching (kIOEthernetInterfaceClass);
  216662. if (dict != 0)
  216663. {
  216664. CFMutableDictionaryRef propDict = CFDictionaryCreateMutable (kCFAllocatorDefault,
  216665. 0,
  216666. &kCFTypeDictionaryKeyCallBacks,
  216667. &kCFTypeDictionaryValueCallBacks);
  216668. if (propDict != 0)
  216669. {
  216670. CFDictionarySetValue (propDict, CFSTR (kIOPrimaryInterface), kCFBooleanTrue);
  216671. CFDictionarySetValue (dict, CFSTR (kIOPropertyMatchKey), propDict);
  216672. CFRelease (propDict);
  216673. }
  216674. }
  216675. return IOServiceGetMatchingServices (masterPort, dict, matchingServices) == KERN_SUCCESS;
  216676. }
  216677. return false;
  216678. }
  216679. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  216680. {
  216681. int numResults = 0;
  216682. io_iterator_t it;
  216683. if (GetEthernetIterator (&it))
  216684. {
  216685. io_object_t i;
  216686. while ((i = IOIteratorNext (it)) != 0)
  216687. {
  216688. io_object_t controller;
  216689. if (IORegistryEntryGetParentEntry (i, kIOServicePlane, &controller) == KERN_SUCCESS)
  216690. {
  216691. CFTypeRef data = IORegistryEntryCreateCFProperty (controller,
  216692. CFSTR (kIOMACAddress),
  216693. kCFAllocatorDefault,
  216694. 0);
  216695. if (data != 0)
  216696. {
  216697. UInt8 addr [kIOEthernetAddressSize];
  216698. zeromem (addr, sizeof (addr));
  216699. CFDataGetBytes ((CFDataRef) data, CFRangeMake (0, sizeof (addr)), addr);
  216700. CFRelease (data);
  216701. int64 a = 0;
  216702. for (int i = 6; --i >= 0;)
  216703. a = (a << 8) | addr[i];
  216704. if (! littleEndian)
  216705. a = (int64) swapByteOrder ((uint64) a);
  216706. if (numResults < maxNum)
  216707. {
  216708. *addresses++ = a;
  216709. ++numResults;
  216710. }
  216711. }
  216712. IOObjectRelease (controller);
  216713. }
  216714. IOObjectRelease (i);
  216715. }
  216716. IOObjectRelease (it);
  216717. }
  216718. return numResults;
  216719. }
  216720. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  216721. const String& emailSubject,
  216722. const String& bodyText,
  216723. const StringArray& filesToAttach)
  216724. {
  216725. const AutoPool pool;
  216726. String script;
  216727. script << "tell application \"Mail\"\r\n"
  216728. "set newMessage to make new outgoing message with properties {subject:\""
  216729. << emailSubject.replace (T("\""), T("\\\""))
  216730. << "\", content:\""
  216731. << bodyText.replace (T("\""), T("\\\""))
  216732. << "\" & return & return}\r\n"
  216733. "tell newMessage\r\n"
  216734. "set visible to true\r\n"
  216735. "set sender to \"sdfsdfsdfewf\"\r\n"
  216736. "make new to recipient at end of to recipients with properties {address:\""
  216737. << targetEmailAddress
  216738. << "\"}\r\n";
  216739. for (int i = 0; i < filesToAttach.size(); ++i)
  216740. {
  216741. script << "tell content\r\n"
  216742. "make new attachment with properties {file name:\""
  216743. << filesToAttach[i].replace (T("\""), T("\\\""))
  216744. << "\"} at after the last paragraph\r\n"
  216745. "end tell\r\n";
  216746. }
  216747. script << "end tell\r\n"
  216748. "end tell\r\n";
  216749. NSAppleScript* s = [[NSAppleScript alloc]
  216750. initWithSource: [NSString stringWithUTF8String: (const char*) script.toUTF8()]];
  216751. NSDictionary* error = 0;
  216752. const bool ok = [s executeAndReturnError: &error] != nil;
  216753. [s release];
  216754. return ok;
  216755. }
  216756. END_JUCE_NAMESPACE
  216757. /********* End of inlined file: juce_mac_Network.mm *********/
  216758. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  216759. /********* Start of inlined file: juce_mac_AudioCDBurner.mm *********/
  216760. #if JUCE_USE_CDBURNER
  216761. #import <DiscRecording/DiscRecording.h>
  216762. BEGIN_JUCE_NAMESPACE
  216763. END_JUCE_NAMESPACE
  216764. @interface OpenDiskDevice : NSObject
  216765. {
  216766. DRDevice* device;
  216767. NSMutableArray* tracks;
  216768. }
  216769. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device;
  216770. - (void) dealloc;
  216771. - (bool) isDiskPresent;
  216772. - (int) getNumAvailableAudioBlocks;
  216773. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  216774. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  216775. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting;
  216776. @end
  216777. @interface AudioTrackProducer : NSObject
  216778. {
  216779. JUCE_NAMESPACE::AudioSource* source;
  216780. int readPosition, lengthInFrames;
  216781. }
  216782. - (AudioTrackProducer*) init: (int) lengthInFrames;
  216783. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  216784. - (void) dealloc;
  216785. - (void) setupTrackProperties: (DRTrack*) track;
  216786. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  216787. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  216788. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  216789. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  216790. toMedia:(NSDictionary*)mediaInfo;
  216791. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  216792. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  216793. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  216794. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  216795. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  216796. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  216797. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  216798. ioFlags:(uint32_t*)flags;
  216799. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  216800. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  216801. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  216802. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  216803. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  216804. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  216805. ioFlags:(uint32_t*)flags;
  216806. @end
  216807. @implementation OpenDiskDevice
  216808. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device_
  216809. {
  216810. [super init];
  216811. device = device_;
  216812. tracks = [[NSMutableArray alloc] init];
  216813. return self;
  216814. }
  216815. - (void) dealloc
  216816. {
  216817. [tracks release];
  216818. [super dealloc];
  216819. }
  216820. - (bool) isDiskPresent
  216821. {
  216822. return [device isValid]
  216823. && [[[device status] objectForKey: DRDeviceMediaStateKey]
  216824. isEqualTo: DRDeviceMediaStateMediaPresent];
  216825. }
  216826. - (int) getNumAvailableAudioBlocks
  216827. {
  216828. return [[[[device status] objectForKey: DRDeviceMediaInfoKey]
  216829. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  216830. }
  216831. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  216832. {
  216833. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  216834. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  216835. [p setupTrackProperties: t];
  216836. [tracks addObject: t];
  216837. [t release];
  216838. [p release];
  216839. }
  216840. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  216841. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting
  216842. {
  216843. DRBurn* burn = [DRBurn burnForDevice: device];
  216844. if (! [device acquireExclusiveAccess])
  216845. {
  216846. *error = "Couldn't open or write to the CD device";
  216847. return;
  216848. }
  216849. [device acquireMediaReservation];
  216850. NSMutableDictionary* d = [[burn properties] mutableCopy];
  216851. [d autorelease];
  216852. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  216853. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  216854. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount)
  216855. forKey: DRBurnCompletionActionKey];
  216856. [burn setProperties: d];
  216857. [burn writeLayout: tracks];
  216858. for (;;)
  216859. {
  216860. JUCE_NAMESPACE::Thread::sleep (300);
  216861. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  216862. NSLog ([[burn status] description]);
  216863. if (listener != 0 && listener->audioCDBurnProgress (progress))
  216864. {
  216865. [burn abort];
  216866. *error = "User cancelled the write operation";
  216867. break;
  216868. }
  216869. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  216870. {
  216871. *error = "Write operation failed";
  216872. break;
  216873. }
  216874. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  216875. {
  216876. break;
  216877. }
  216878. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  216879. objectForKey: DRErrorStatusErrorStringKey];
  216880. if ([err length] > 0)
  216881. {
  216882. *error = JUCE_NAMESPACE::String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [err UTF8String]);
  216883. break;
  216884. }
  216885. }
  216886. [device releaseMediaReservation];
  216887. [device releaseExclusiveAccess];
  216888. }
  216889. @end
  216890. @implementation AudioTrackProducer
  216891. - (AudioTrackProducer*) init: (int) lengthInFrames_
  216892. {
  216893. lengthInFrames = lengthInFrames_;
  216894. readPosition = 0;
  216895. return self;
  216896. }
  216897. - (void) setupTrackProperties: (DRTrack*) track
  216898. {
  216899. NSMutableDictionary* p = [[track properties] mutableCopy];
  216900. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  216901. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  216902. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  216903. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  216904. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  216905. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  216906. [track setProperties: p];
  216907. [p release];
  216908. }
  216909. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  216910. {
  216911. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  216912. if (s != nil)
  216913. s->source = source_;
  216914. return s;
  216915. }
  216916. - (void) dealloc
  216917. {
  216918. if (source != 0)
  216919. {
  216920. source->releaseResources();
  216921. delete source;
  216922. }
  216923. [super dealloc];
  216924. }
  216925. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  216926. {
  216927. }
  216928. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track
  216929. {
  216930. return true;
  216931. }
  216932. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track
  216933. {
  216934. return lengthInFrames;
  216935. }
  216936. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  216937. toMedia:(NSDictionary*)mediaInfo
  216938. {
  216939. if (source != 0)
  216940. source->prepareToPlay (44100 / 75, 44100);
  216941. readPosition = 0;
  216942. return true;
  216943. }
  216944. - (BOOL) prepareTrackForVerification:(DRTrack*)track
  216945. {
  216946. if (source != 0)
  216947. source->prepareToPlay (44100 / 75, 44100);
  216948. return true;
  216949. }
  216950. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  216951. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  216952. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags
  216953. {
  216954. if (source != 0)
  216955. {
  216956. const int numSamples = JUCE_NAMESPACE::jmin (bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  216957. if (numSamples > 0)
  216958. {
  216959. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  216960. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  216961. info.buffer = &tempBuffer;
  216962. info.startSample = 0;
  216963. info.numSamples = numSamples;
  216964. source->getNextAudioBlock (info);
  216965. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  216966. buffer, numSamples, 4);
  216967. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  216968. buffer + 2, numSamples, 4);
  216969. readPosition += numSamples;
  216970. }
  216971. return numSamples * 4;
  216972. }
  216973. return 0;
  216974. }
  216975. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  216976. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  216977. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  216978. ioFlags:(uint32_t*)flags
  216979. {
  216980. zeromem (buffer, bufferLength);
  216981. return bufferLength;
  216982. }
  216983. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  216984. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  216985. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags
  216986. {
  216987. return true;
  216988. }
  216989. @end
  216990. BEGIN_JUCE_NAMESPACE
  216991. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  216992. : internal (0)
  216993. {
  216994. const AutoPool pool;
  216995. OpenDiskDevice* dev = [[OpenDiskDevice alloc] initWithDevice: [[DRDevice devices] objectAtIndex: deviceIndex]];
  216996. internal = (void*) dev;
  216997. }
  216998. AudioCDBurner::~AudioCDBurner()
  216999. {
  217000. const AutoPool pool;
  217001. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  217002. if (dev != 0)
  217003. [dev release];
  217004. }
  217005. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  217006. {
  217007. const AutoPool pool;
  217008. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  217009. if (b->internal == 0)
  217010. deleteAndZero (b);
  217011. return b;
  217012. }
  217013. static NSArray* findDiskBurnerDevices()
  217014. {
  217015. NSMutableArray* results = [NSMutableArray array];
  217016. NSArray* devs = [DRDevice devices];
  217017. if (devs != 0)
  217018. {
  217019. int num = [devs count];
  217020. int i;
  217021. for (i = 0; i < num; ++i)
  217022. {
  217023. NSDictionary* dic = [[devs objectAtIndex: i] info];
  217024. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  217025. if (name != nil)
  217026. [results addObject: name];
  217027. }
  217028. }
  217029. return results;
  217030. }
  217031. const StringArray AudioCDBurner::findAvailableDevices()
  217032. {
  217033. const AutoPool pool;
  217034. NSArray* names = findDiskBurnerDevices();
  217035. StringArray s;
  217036. for (int i = 0; i < [names count]; ++i)
  217037. s.add (String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [[names objectAtIndex: i] UTF8String]));
  217038. return s;
  217039. }
  217040. bool AudioCDBurner::isDiskPresent() const
  217041. {
  217042. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  217043. return dev != 0 && [dev isDiskPresent];
  217044. }
  217045. int AudioCDBurner::getNumAvailableAudioBlocks() const
  217046. {
  217047. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  217048. return [dev getNumAvailableAudioBlocks];
  217049. }
  217050. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  217051. {
  217052. const AutoPool pool;
  217053. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  217054. if (dev != 0)
  217055. {
  217056. [dev addSourceTrack: source numSamples: numSamps];
  217057. return true;
  217058. }
  217059. return false;
  217060. }
  217061. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  217062. const bool ejectDiscAfterwards,
  217063. const bool peformFakeBurnForTesting)
  217064. {
  217065. const AutoPool pool;
  217066. JUCE_NAMESPACE::String error ("Couldn't open or write to the CD device");
  217067. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  217068. if (dev != 0)
  217069. {
  217070. error = JUCE_NAMESPACE::String::empty;
  217071. [dev burn: listener
  217072. errorString: &error
  217073. ejectAfterwards: ejectDiscAfterwards
  217074. isFake: peformFakeBurnForTesting];
  217075. }
  217076. return error;
  217077. }
  217078. END_JUCE_NAMESPACE
  217079. #endif
  217080. /********* End of inlined file: juce_mac_AudioCDBurner.mm *********/
  217081. /********* Start of inlined file: juce_mac_CoreAudio.cpp *********/
  217082. #include <CoreAudio/AudioHardware.h>
  217083. BEGIN_JUCE_NAMESPACE
  217084. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  217085. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  217086. #endif
  217087. #undef log
  217088. #if JUCE_COREAUDIO_LOGGING_ENABLED
  217089. #define log(a) Logger::writeToLog (a)
  217090. #else
  217091. #define log(a)
  217092. #endif
  217093. #undef OK
  217094. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  217095. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  217096. {
  217097. if (err == noErr)
  217098. return true;
  217099. Logger::writeToLog (T("CoreAudio error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  217100. jassertfalse
  217101. return false;
  217102. }
  217103. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  217104. #else
  217105. #define OK(a) (a == noErr)
  217106. #endif
  217107. static const int maxNumChans = 96;
  217108. class CoreAudioInternal : public Timer
  217109. {
  217110. public:
  217111. CoreAudioInternal (AudioDeviceID id)
  217112. : deviceID (id),
  217113. started (false),
  217114. audioBuffer (0),
  217115. numInputChans (0),
  217116. numOutputChans (0),
  217117. callbacksAllowed (true),
  217118. numInputChannelInfos (0),
  217119. numOutputChannelInfos (0),
  217120. inputLatency (0),
  217121. outputLatency (0),
  217122. callback (0),
  217123. inputDevice (0),
  217124. isSlaveDevice (false)
  217125. {
  217126. sampleRate = 0;
  217127. bufferSize = 512;
  217128. if (deviceID == 0)
  217129. {
  217130. error = TRANS("can't open device");
  217131. }
  217132. else
  217133. {
  217134. updateDetailsFromDevice();
  217135. AudioDeviceAddPropertyListener (deviceID,
  217136. kAudioPropertyWildcardChannel,
  217137. kAudioPropertyWildcardSection,
  217138. kAudioPropertyWildcardPropertyID,
  217139. deviceListenerProc, this);
  217140. }
  217141. }
  217142. ~CoreAudioInternal()
  217143. {
  217144. AudioDeviceRemovePropertyListener (deviceID,
  217145. kAudioPropertyWildcardChannel,
  217146. kAudioPropertyWildcardSection,
  217147. kAudioPropertyWildcardPropertyID,
  217148. deviceListenerProc);
  217149. stop (false);
  217150. juce_free (audioBuffer);
  217151. delete inputDevice;
  217152. }
  217153. void setTempBufferSize (const int numChannels, const int numSamples)
  217154. {
  217155. juce_free (audioBuffer);
  217156. audioBuffer = (float*) juce_calloc (32 + numChannels * numSamples * sizeof (float));
  217157. zeromem (tempInputBuffers, sizeof (tempInputBuffers));
  217158. zeromem (tempOutputBuffers, sizeof (tempOutputBuffers));
  217159. int count = 0;
  217160. int i;
  217161. for (i = 0; i < numInputChans; ++i)
  217162. tempInputBuffers[i] = audioBuffer + count++ * numSamples;
  217163. for (i = 0; i < numOutputChans; ++i)
  217164. tempOutputBuffers[i] = audioBuffer + count++ * numSamples;
  217165. }
  217166. // returns the number of actual available channels
  217167. void fillInChannelInfo (bool input)
  217168. {
  217169. int chanNum = 0, activeChans = 0;
  217170. UInt32 size;
  217171. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, 0)))
  217172. {
  217173. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  217174. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, bufList)))
  217175. {
  217176. const int numStreams = bufList->mNumberBuffers;
  217177. for (int i = 0; i < numStreams; ++i)
  217178. {
  217179. const AudioBuffer& b = bufList->mBuffers[i];
  217180. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  217181. {
  217182. if (input)
  217183. {
  217184. if (activeInputChans[chanNum])
  217185. {
  217186. inputChannelInfo [activeChans].sourceChannelNum = chanNum;
  217187. inputChannelInfo [activeChans].streamNum = i;
  217188. inputChannelInfo [activeChans].dataOffsetSamples = j;
  217189. inputChannelInfo [activeChans].dataStrideSamples = b.mNumberChannels;
  217190. ++activeChans;
  217191. numInputChannelInfos = activeChans;
  217192. }
  217193. inChanNames.add (T("input ") + String (chanNum + 1));
  217194. }
  217195. else
  217196. {
  217197. if (activeOutputChans[chanNum])
  217198. {
  217199. outputChannelInfo [activeChans].sourceChannelNum = chanNum;
  217200. outputChannelInfo [activeChans].streamNum = i;
  217201. outputChannelInfo [activeChans].dataOffsetSamples = j;
  217202. outputChannelInfo [activeChans].dataStrideSamples = b.mNumberChannels;
  217203. ++activeChans;
  217204. numOutputChannelInfos = activeChans;
  217205. }
  217206. outChanNames.add (T("output ") + String (chanNum + 1));
  217207. }
  217208. ++chanNum;
  217209. }
  217210. }
  217211. }
  217212. juce_free (bufList);
  217213. }
  217214. }
  217215. void updateDetailsFromDevice()
  217216. {
  217217. stopTimer();
  217218. if (deviceID == 0)
  217219. return;
  217220. const ScopedLock sl (callbackLock);
  217221. Float64 sr;
  217222. UInt32 size = sizeof (Float64);
  217223. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyNominalSampleRate, &size, &sr)))
  217224. sampleRate = sr;
  217225. UInt32 framesPerBuf;
  217226. size = sizeof (framesPerBuf);
  217227. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSize, &size, &framesPerBuf)))
  217228. {
  217229. bufferSize = framesPerBuf;
  217230. if (bufferSize > 0)
  217231. setTempBufferSize (numInputChans + numOutputChans, bufferSize);
  217232. }
  217233. bufferSizes.clear();
  217234. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, 0)))
  217235. {
  217236. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  217237. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, ranges)))
  217238. {
  217239. bufferSizes.add ((int) ranges[0].mMinimum);
  217240. for (int i = 32; i < 8192; i += 32)
  217241. {
  217242. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  217243. {
  217244. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  217245. {
  217246. bufferSizes.addIfNotAlreadyThere (i);
  217247. break;
  217248. }
  217249. }
  217250. }
  217251. if (bufferSize > 0)
  217252. bufferSizes.addIfNotAlreadyThere (bufferSize);
  217253. }
  217254. juce_free (ranges);
  217255. }
  217256. if (bufferSizes.size() == 0 && bufferSize > 0)
  217257. bufferSizes.add (bufferSize);
  217258. sampleRates.clear();
  217259. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  217260. String rates;
  217261. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, 0)))
  217262. {
  217263. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  217264. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, ranges)))
  217265. {
  217266. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  217267. {
  217268. bool ok = false;
  217269. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  217270. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  217271. ok = true;
  217272. if (ok)
  217273. {
  217274. sampleRates.add (possibleRates[i]);
  217275. rates << possibleRates[i] << T(" ");
  217276. }
  217277. }
  217278. }
  217279. juce_free (ranges);
  217280. }
  217281. if (sampleRates.size() == 0 && sampleRate > 0)
  217282. {
  217283. sampleRates.add (sampleRate);
  217284. rates << sampleRate;
  217285. }
  217286. log (T("sr: ") + rates);
  217287. inputLatency = 0;
  217288. outputLatency = 0;
  217289. UInt32 lat;
  217290. size = sizeof (UInt32);
  217291. if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  217292. inputLatency = (int) lat;
  217293. if (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  217294. outputLatency = (int) lat;
  217295. log (T("lat: ") + String (inputLatency) + T(" ") + String (outputLatency));
  217296. inChanNames.clear();
  217297. outChanNames.clear();
  217298. zeromem (inputChannelInfo, sizeof (inputChannelInfo));
  217299. zeromem (outputChannelInfo, sizeof (outputChannelInfo));
  217300. fillInChannelInfo (true);
  217301. fillInChannelInfo (false);
  217302. }
  217303. const StringArray getSources (bool input)
  217304. {
  217305. StringArray s;
  217306. int num = 0;
  217307. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  217308. if (types != 0)
  217309. {
  217310. for (int i = 0; i < num; ++i)
  217311. {
  217312. AudioValueTranslation avt;
  217313. char buffer[256];
  217314. avt.mInputData = (void*) &(types[i]);
  217315. avt.mInputDataSize = sizeof (UInt32);
  217316. avt.mOutputData = buffer;
  217317. avt.mOutputDataSize = 256;
  217318. UInt32 transSize = sizeof (avt);
  217319. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSourceNameForID, &transSize, &avt)))
  217320. {
  217321. DBG (buffer);
  217322. s.add (buffer);
  217323. }
  217324. }
  217325. juce_free (types);
  217326. }
  217327. return s;
  217328. }
  217329. int getCurrentSourceIndex (bool input) const
  217330. {
  217331. OSType currentSourceID = 0;
  217332. UInt32 size = 0;
  217333. int result = -1;
  217334. if (deviceID != 0
  217335. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, 0)))
  217336. {
  217337. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, &currentSourceID)))
  217338. {
  217339. int num = 0;
  217340. OSType* const types = getAllDataSourcesForDevice (deviceID, input, num);
  217341. if (types != 0)
  217342. {
  217343. for (int i = 0; i < num; ++i)
  217344. {
  217345. if (types[num] == currentSourceID)
  217346. {
  217347. result = i;
  217348. break;
  217349. }
  217350. }
  217351. juce_free (types);
  217352. }
  217353. }
  217354. }
  217355. return result;
  217356. }
  217357. void setCurrentSourceIndex (int index, bool input)
  217358. {
  217359. if (deviceID != 0)
  217360. {
  217361. int num = 0;
  217362. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  217363. if (types != 0)
  217364. {
  217365. if (((unsigned int) index) < num)
  217366. {
  217367. OSType typeId = types[index];
  217368. AudioDeviceSetProperty (deviceID, 0, 0, input, kAudioDevicePropertyDataSource, sizeof (typeId), &typeId);
  217369. }
  217370. juce_free (types);
  217371. }
  217372. }
  217373. }
  217374. const String reopen (const BitArray& inputChannels,
  217375. const BitArray& outputChannels,
  217376. double newSampleRate,
  217377. int bufferSizeSamples)
  217378. {
  217379. error = String::empty;
  217380. log ("CoreAudio reopen");
  217381. callbacksAllowed = false;
  217382. stopTimer();
  217383. stop (false);
  217384. activeInputChans = inputChannels;
  217385. activeOutputChans = outputChannels;
  217386. activeInputChans.setRange (inChanNames.size(),
  217387. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  217388. false);
  217389. activeOutputChans.setRange (outChanNames.size(),
  217390. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  217391. false);
  217392. numInputChans = activeInputChans.countNumberOfSetBits();
  217393. numOutputChans = activeOutputChans.countNumberOfSetBits();
  217394. // set sample rate
  217395. Float64 sr = newSampleRate;
  217396. UInt32 size = sizeof (sr);
  217397. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyNominalSampleRate, size, &sr));
  217398. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyNominalSampleRate, size, &sr));
  217399. // change buffer size
  217400. UInt32 framesPerBuf = bufferSizeSamples;
  217401. size = sizeof (framesPerBuf);
  217402. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  217403. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  217404. // wait for the changes to happen (on some devices)
  217405. int i = 30;
  217406. while (--i >= 0)
  217407. {
  217408. updateDetailsFromDevice();
  217409. if (sampleRate == newSampleRate && bufferSizeSamples == bufferSize)
  217410. break;
  217411. Thread::sleep (100);
  217412. }
  217413. if (i < 0)
  217414. error = "Couldn't change sample rate/buffer size";
  217415. if (sampleRates.size() == 0)
  217416. error = "Device has no available sample-rates";
  217417. if (bufferSizes.size() == 0)
  217418. error = "Device has no available buffer-sizes";
  217419. if (inputDevice != 0 && error.isEmpty())
  217420. error = inputDevice->reopen (inputChannels,
  217421. outputChannels,
  217422. newSampleRate,
  217423. bufferSizeSamples);
  217424. callbacksAllowed = true;
  217425. return error;
  217426. }
  217427. bool start (AudioIODeviceCallback* cb)
  217428. {
  217429. if (! started)
  217430. {
  217431. callback = 0;
  217432. if (deviceID != 0)
  217433. {
  217434. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, (void*) this)))
  217435. {
  217436. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  217437. {
  217438. started = true;
  217439. }
  217440. else
  217441. {
  217442. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  217443. }
  217444. }
  217445. }
  217446. }
  217447. if (started)
  217448. {
  217449. const ScopedLock sl (callbackLock);
  217450. callback = cb;
  217451. }
  217452. if (inputDevice != 0)
  217453. return started && inputDevice->start (cb);
  217454. else
  217455. return started;
  217456. }
  217457. void stop (bool leaveInterruptRunning)
  217458. {
  217459. callbackLock.enter();
  217460. callback = 0;
  217461. callbackLock.exit();
  217462. if (started
  217463. && (deviceID != 0)
  217464. && ! leaveInterruptRunning)
  217465. {
  217466. OK (AudioDeviceStop (deviceID, audioIOProc));
  217467. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  217468. started = false;
  217469. callbackLock.enter();
  217470. callbackLock.exit();
  217471. // wait until it's definately stopped calling back..
  217472. for (int i = 40; --i >= 0;)
  217473. {
  217474. Thread::sleep (50);
  217475. UInt32 running = 0;
  217476. UInt32 size = sizeof (running);
  217477. OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyDeviceIsRunning, &size, &running));
  217478. if (running == 0)
  217479. break;
  217480. }
  217481. callbackLock.enter();
  217482. callbackLock.exit();
  217483. }
  217484. if (inputDevice != 0)
  217485. inputDevice->stop (leaveInterruptRunning);
  217486. }
  217487. double getSampleRate() const
  217488. {
  217489. return sampleRate;
  217490. }
  217491. int getBufferSize() const
  217492. {
  217493. return bufferSize;
  217494. }
  217495. void audioCallback (const AudioBufferList* inInputData,
  217496. AudioBufferList* outOutputData)
  217497. {
  217498. int i;
  217499. const ScopedLock sl (callbackLock);
  217500. if (callback != 0)
  217501. {
  217502. if (inputDevice == 0)
  217503. {
  217504. for (i = numInputChans; --i >= 0;)
  217505. {
  217506. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  217507. float* dest = tempInputBuffers [info.sourceChannelNum];
  217508. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  217509. + info.dataOffsetSamples;
  217510. const int stride = info.dataStrideSamples;
  217511. if (stride != 0) // if this is zero, info is invalid
  217512. {
  217513. for (int j = bufferSize; --j >= 0;)
  217514. {
  217515. *dest++ = *src;
  217516. src += stride;
  217517. }
  217518. }
  217519. }
  217520. }
  217521. if (! isSlaveDevice)
  217522. {
  217523. if (inputDevice == 0)
  217524. {
  217525. callback->audioDeviceIOCallback ((const float**) tempInputBuffers,
  217526. numInputChans,
  217527. tempOutputBuffers,
  217528. numOutputChans,
  217529. bufferSize);
  217530. }
  217531. else
  217532. {
  217533. jassert (inputDevice->bufferSize == bufferSize);
  217534. callback->audioDeviceIOCallback ((const float**) inputDevice->tempInputBuffers,
  217535. inputDevice->numInputChans,
  217536. tempOutputBuffers,
  217537. numOutputChans,
  217538. bufferSize);
  217539. }
  217540. for (i = numOutputChans; --i >= 0;)
  217541. {
  217542. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  217543. const float* src = tempOutputBuffers [i];
  217544. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  217545. + info.dataOffsetSamples;
  217546. const int stride = info.dataStrideSamples;
  217547. if (stride != 0) // if this is zero, info is invalid
  217548. {
  217549. for (int j = bufferSize; --j >= 0;)
  217550. {
  217551. *dest = *src++;
  217552. dest += stride;
  217553. }
  217554. }
  217555. }
  217556. }
  217557. }
  217558. else
  217559. {
  217560. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  217561. {
  217562. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  217563. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  217564. + info.dataOffsetSamples;
  217565. const int stride = info.dataStrideSamples;
  217566. if (stride != 0) // if this is zero, info is invalid
  217567. {
  217568. for (int j = bufferSize; --j >= 0;)
  217569. {
  217570. *dest = 0.0f;
  217571. dest += stride;
  217572. }
  217573. }
  217574. }
  217575. }
  217576. }
  217577. // called by callbacks
  217578. void deviceDetailsChanged()
  217579. {
  217580. if (callbacksAllowed)
  217581. startTimer (100);
  217582. }
  217583. void timerCallback()
  217584. {
  217585. stopTimer();
  217586. log ("CoreAudio device changed callback");
  217587. const double oldSampleRate = sampleRate;
  217588. const int oldBufferSize = bufferSize;
  217589. updateDetailsFromDevice();
  217590. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  217591. {
  217592. callbacksAllowed = false;
  217593. stop (false);
  217594. updateDetailsFromDevice();
  217595. callbacksAllowed = true;
  217596. }
  217597. }
  217598. CoreAudioInternal* getRelatedDevice() const
  217599. {
  217600. UInt32 size = 0;
  217601. CoreAudioInternal* result = 0;
  217602. if (deviceID != 0
  217603. && AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, 0) == noErr
  217604. && size > 0)
  217605. {
  217606. AudioDeviceID* devs = (AudioDeviceID*) juce_calloc (size);
  217607. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, devs)))
  217608. {
  217609. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  217610. {
  217611. if (devs[i] != deviceID && devs[i] != 0)
  217612. {
  217613. result = new CoreAudioInternal (devs[i]);
  217614. if (result->error.isEmpty())
  217615. {
  217616. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  217617. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  217618. if (thisIsInput != otherIsInput
  217619. || (inChanNames.size() + outChanNames.size() == 0)
  217620. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  217621. break;
  217622. }
  217623. deleteAndZero (result);
  217624. }
  217625. }
  217626. }
  217627. juce_free (devs);
  217628. }
  217629. return result;
  217630. }
  217631. juce_UseDebuggingNewOperator
  217632. String error;
  217633. int inputLatency, outputLatency;
  217634. BitArray activeInputChans, activeOutputChans;
  217635. StringArray inChanNames, outChanNames;
  217636. Array <double> sampleRates;
  217637. Array <int> bufferSizes;
  217638. AudioIODeviceCallback* callback;
  217639. CoreAudioInternal* inputDevice;
  217640. bool isSlaveDevice;
  217641. private:
  217642. CriticalSection callbackLock;
  217643. AudioDeviceID deviceID;
  217644. bool started;
  217645. double sampleRate;
  217646. int bufferSize;
  217647. float* audioBuffer;
  217648. int numInputChans, numOutputChans;
  217649. bool callbacksAllowed;
  217650. struct CallbackDetailsForChannel
  217651. {
  217652. int sourceChannelNum;
  217653. int streamNum;
  217654. int dataOffsetSamples;
  217655. int dataStrideSamples;
  217656. };
  217657. int numInputChannelInfos, numOutputChannelInfos;
  217658. CallbackDetailsForChannel inputChannelInfo [maxNumChans];
  217659. CallbackDetailsForChannel outputChannelInfo [maxNumChans];
  217660. float* tempInputBuffers [maxNumChans];
  217661. float* tempOutputBuffers [maxNumChans];
  217662. CoreAudioInternal (const CoreAudioInternal&);
  217663. const CoreAudioInternal& operator= (const CoreAudioInternal&);
  217664. static OSStatus audioIOProc (AudioDeviceID inDevice,
  217665. const AudioTimeStamp* inNow,
  217666. const AudioBufferList* inInputData,
  217667. const AudioTimeStamp* inInputTime,
  217668. AudioBufferList* outOutputData,
  217669. const AudioTimeStamp* inOutputTime,
  217670. void* device)
  217671. {
  217672. ((CoreAudioInternal*) device)->audioCallback (inInputData, outOutputData);
  217673. return noErr;
  217674. }
  217675. static OSStatus deviceListenerProc (AudioDeviceID inDevice,
  217676. UInt32 inLine,
  217677. Boolean isInput,
  217678. AudioDevicePropertyID inPropertyID,
  217679. void* inClientData)
  217680. {
  217681. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  217682. switch (inPropertyID)
  217683. {
  217684. case kAudioDevicePropertyBufferSize:
  217685. case kAudioDevicePropertyBufferFrameSize:
  217686. case kAudioDevicePropertyNominalSampleRate:
  217687. case kAudioDevicePropertyStreamFormat:
  217688. case kAudioDevicePropertyDeviceIsAlive:
  217689. intern->deviceDetailsChanged();
  217690. break;
  217691. case kAudioDevicePropertyBufferSizeRange:
  217692. case kAudioDevicePropertyVolumeScalar:
  217693. case kAudioDevicePropertyMute:
  217694. case kAudioDevicePropertyPlayThru:
  217695. case kAudioDevicePropertyDataSource:
  217696. case kAudioDevicePropertyDeviceIsRunning:
  217697. break;
  217698. }
  217699. return noErr;
  217700. }
  217701. static OSType* getAllDataSourcesForDevice (AudioDeviceID deviceID, const bool input, int& num)
  217702. {
  217703. OSType* types = 0;
  217704. UInt32 size = 0;
  217705. num = 0;
  217706. if (deviceID != 0
  217707. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, 0)))
  217708. {
  217709. types = (OSType*) juce_calloc (size);
  217710. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, types)))
  217711. {
  217712. num = size / sizeof (OSType);
  217713. }
  217714. else
  217715. {
  217716. juce_free (types);
  217717. types = 0;
  217718. }
  217719. }
  217720. return types;
  217721. }
  217722. };
  217723. class CoreAudioIODevice : public AudioIODevice
  217724. {
  217725. public:
  217726. CoreAudioIODevice (const String& deviceName,
  217727. AudioDeviceID inputDeviceId,
  217728. const int inputIndex_,
  217729. AudioDeviceID outputDeviceId,
  217730. const int outputIndex_)
  217731. : AudioIODevice (deviceName, "CoreAudio"),
  217732. inputIndex (inputIndex_),
  217733. outputIndex (outputIndex_),
  217734. isOpen_ (false),
  217735. isStarted (false)
  217736. {
  217737. internal = 0;
  217738. CoreAudioInternal* device = 0;
  217739. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  217740. {
  217741. jassert (inputDeviceId != 0);
  217742. device = new CoreAudioInternal (inputDeviceId);
  217743. lastError = device->error;
  217744. if (lastError.isNotEmpty())
  217745. deleteAndZero (device);
  217746. }
  217747. else
  217748. {
  217749. device = new CoreAudioInternal (outputDeviceId);
  217750. lastError = device->error;
  217751. if (lastError.isNotEmpty())
  217752. {
  217753. deleteAndZero (device);
  217754. }
  217755. else if (inputDeviceId != 0)
  217756. {
  217757. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  217758. lastError = device->error;
  217759. if (lastError.isNotEmpty())
  217760. {
  217761. delete secondDevice;
  217762. }
  217763. else
  217764. {
  217765. device->inputDevice = secondDevice;
  217766. secondDevice->isSlaveDevice = true;
  217767. }
  217768. }
  217769. }
  217770. internal = device;
  217771. AudioHardwareAddPropertyListener (kAudioPropertyWildcardPropertyID,
  217772. hardwareListenerProc, internal);
  217773. }
  217774. ~CoreAudioIODevice()
  217775. {
  217776. AudioHardwareRemovePropertyListener (kAudioPropertyWildcardPropertyID,
  217777. hardwareListenerProc);
  217778. delete internal;
  217779. }
  217780. const StringArray getOutputChannelNames()
  217781. {
  217782. return internal->outChanNames;
  217783. }
  217784. const StringArray getInputChannelNames()
  217785. {
  217786. if (internal->inputDevice != 0)
  217787. return internal->inputDevice->inChanNames;
  217788. else
  217789. return internal->inChanNames;
  217790. }
  217791. int getNumSampleRates()
  217792. {
  217793. return internal->sampleRates.size();
  217794. }
  217795. double getSampleRate (int index)
  217796. {
  217797. return internal->sampleRates [index];
  217798. }
  217799. int getNumBufferSizesAvailable()
  217800. {
  217801. return internal->bufferSizes.size();
  217802. }
  217803. int getBufferSizeSamples (int index)
  217804. {
  217805. return internal->bufferSizes [index];
  217806. }
  217807. int getDefaultBufferSize()
  217808. {
  217809. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  217810. if (getBufferSizeSamples(i) >= 512)
  217811. return getBufferSizeSamples(i);
  217812. return 512;
  217813. }
  217814. const String open (const BitArray& inputChannels,
  217815. const BitArray& outputChannels,
  217816. double sampleRate,
  217817. int bufferSizeSamples)
  217818. {
  217819. isOpen_ = true;
  217820. if (bufferSizeSamples <= 0)
  217821. bufferSizeSamples = getDefaultBufferSize();
  217822. internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  217823. lastError = internal->error;
  217824. return lastError;
  217825. }
  217826. void close()
  217827. {
  217828. isOpen_ = false;
  217829. }
  217830. bool isOpen()
  217831. {
  217832. return isOpen_;
  217833. }
  217834. int getCurrentBufferSizeSamples()
  217835. {
  217836. return internal != 0 ? internal->getBufferSize() : 512;
  217837. }
  217838. double getCurrentSampleRate()
  217839. {
  217840. return internal != 0 ? internal->getSampleRate() : 0;
  217841. }
  217842. int getCurrentBitDepth()
  217843. {
  217844. return 32; // no way to find out, so just assume it's high..
  217845. }
  217846. const BitArray getActiveOutputChannels() const
  217847. {
  217848. return internal != 0 ? internal->activeOutputChans : BitArray();
  217849. }
  217850. const BitArray getActiveInputChannels() const
  217851. {
  217852. BitArray chans;
  217853. if (internal != 0)
  217854. {
  217855. chans = internal->activeInputChans;
  217856. if (internal->inputDevice != 0)
  217857. chans.orWith (internal->inputDevice->activeInputChans);
  217858. }
  217859. return chans;
  217860. }
  217861. int getOutputLatencyInSamples()
  217862. {
  217863. if (internal == 0)
  217864. return 0;
  217865. // this seems like a good guess at getting the latency right - comparing
  217866. // this with a round-trip measurement, it gets it to within a few millisecs
  217867. // for the built-in mac soundcard
  217868. return internal->outputLatency + internal->getBufferSize() * 2;
  217869. }
  217870. int getInputLatencyInSamples()
  217871. {
  217872. if (internal == 0)
  217873. return 0;
  217874. return internal->inputLatency + internal->getBufferSize() * 2;
  217875. }
  217876. void start (AudioIODeviceCallback* callback)
  217877. {
  217878. if (internal != 0 && ! isStarted)
  217879. {
  217880. if (callback != 0)
  217881. callback->audioDeviceAboutToStart (this);
  217882. isStarted = true;
  217883. internal->start (callback);
  217884. }
  217885. }
  217886. void stop()
  217887. {
  217888. if (isStarted && internal != 0)
  217889. {
  217890. AudioIODeviceCallback* const lastCallback = internal->callback;
  217891. isStarted = false;
  217892. internal->stop (true);
  217893. if (lastCallback != 0)
  217894. lastCallback->audioDeviceStopped();
  217895. }
  217896. }
  217897. bool isPlaying()
  217898. {
  217899. if (internal->callback == 0)
  217900. isStarted = false;
  217901. return isStarted;
  217902. }
  217903. const String getLastError()
  217904. {
  217905. return lastError;
  217906. }
  217907. int inputIndex, outputIndex;
  217908. juce_UseDebuggingNewOperator
  217909. private:
  217910. CoreAudioInternal* internal;
  217911. bool isOpen_, isStarted;
  217912. String lastError;
  217913. static OSStatus hardwareListenerProc (AudioHardwarePropertyID inPropertyID, void* inClientData)
  217914. {
  217915. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  217916. switch (inPropertyID)
  217917. {
  217918. case kAudioHardwarePropertyDevices:
  217919. intern->deviceDetailsChanged();
  217920. break;
  217921. case kAudioHardwarePropertyDefaultOutputDevice:
  217922. case kAudioHardwarePropertyDefaultInputDevice:
  217923. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  217924. break;
  217925. }
  217926. return noErr;
  217927. }
  217928. CoreAudioIODevice (const CoreAudioIODevice&);
  217929. const CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  217930. };
  217931. class CoreAudioIODeviceType : public AudioIODeviceType
  217932. {
  217933. public:
  217934. CoreAudioIODeviceType()
  217935. : AudioIODeviceType (T("CoreAudio")),
  217936. hasScanned (false)
  217937. {
  217938. }
  217939. ~CoreAudioIODeviceType()
  217940. {
  217941. }
  217942. void scanForDevices()
  217943. {
  217944. hasScanned = true;
  217945. inputDeviceNames.clear();
  217946. outputDeviceNames.clear();
  217947. inputIds.clear();
  217948. outputIds.clear();
  217949. UInt32 size;
  217950. if (OK (AudioHardwareGetPropertyInfo (kAudioHardwarePropertyDevices, &size, 0)))
  217951. {
  217952. AudioDeviceID* const devs = (AudioDeviceID*) juce_calloc (size);
  217953. if (OK (AudioHardwareGetProperty (kAudioHardwarePropertyDevices, &size, devs)))
  217954. {
  217955. static bool alreadyLogged = false;
  217956. const int num = size / sizeof (AudioDeviceID);
  217957. for (int i = 0; i < num; ++i)
  217958. {
  217959. char name[1024];
  217960. size = sizeof (name);
  217961. if (OK (AudioDeviceGetProperty (devs[i], 0, false, kAudioDevicePropertyDeviceName, &size, name)))
  217962. {
  217963. const String nameString (String::fromUTF8 ((const uint8*) name, strlen (name)));
  217964. if (! alreadyLogged)
  217965. log (T("CoreAudio device: ") + nameString);
  217966. const int numIns = getNumChannels (devs[i], true);
  217967. const int numOuts = getNumChannels (devs[i], false);
  217968. if (numIns > 0)
  217969. {
  217970. inputDeviceNames.add (nameString);
  217971. inputIds.add (devs[i]);
  217972. }
  217973. if (numOuts > 0)
  217974. {
  217975. outputDeviceNames.add (nameString);
  217976. outputIds.add (devs[i]);
  217977. }
  217978. }
  217979. }
  217980. alreadyLogged = true;
  217981. }
  217982. juce_free (devs);
  217983. }
  217984. inputDeviceNames.appendNumbersToDuplicates (false, true);
  217985. outputDeviceNames.appendNumbersToDuplicates (false, true);
  217986. }
  217987. const StringArray getDeviceNames (const bool wantInputNames) const
  217988. {
  217989. jassert (hasScanned); // need to call scanForDevices() before doing this
  217990. if (wantInputNames)
  217991. return inputDeviceNames;
  217992. else
  217993. return outputDeviceNames;
  217994. }
  217995. int getDefaultDeviceIndex (const bool forInput) const
  217996. {
  217997. jassert (hasScanned); // need to call scanForDevices() before doing this
  217998. AudioDeviceID deviceID;
  217999. UInt32 size = sizeof (deviceID);
  218000. // if they're asking for any input channels at all, use the default input, so we
  218001. // get the built-in mic rather than the built-in output with no inputs..
  218002. if (AudioHardwareGetProperty (forInput ? kAudioHardwarePropertyDefaultInputDevice
  218003. : kAudioHardwarePropertyDefaultOutputDevice,
  218004. &size, &deviceID) == noErr)
  218005. {
  218006. if (forInput)
  218007. {
  218008. for (int i = inputIds.size(); --i >= 0;)
  218009. if (inputIds[i] == deviceID)
  218010. return i;
  218011. }
  218012. else
  218013. {
  218014. for (int i = outputIds.size(); --i >= 0;)
  218015. if (outputIds[i] == deviceID)
  218016. return i;
  218017. }
  218018. }
  218019. return 0;
  218020. }
  218021. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  218022. {
  218023. jassert (hasScanned); // need to call scanForDevices() before doing this
  218024. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  218025. if (d == 0)
  218026. return -1;
  218027. return asInput ? d->inputIndex
  218028. : d->outputIndex;
  218029. }
  218030. bool hasSeparateInputsAndOutputs() const { return true; }
  218031. AudioIODevice* createDevice (const String& outputDeviceName,
  218032. const String& inputDeviceName)
  218033. {
  218034. jassert (hasScanned); // need to call scanForDevices() before doing this
  218035. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  218036. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  218037. String deviceName (outputDeviceName);
  218038. if (deviceName.isEmpty())
  218039. deviceName = inputDeviceName;
  218040. if (index >= 0)
  218041. return new CoreAudioIODevice (deviceName,
  218042. inputIds [inputIndex],
  218043. inputIndex,
  218044. outputIds [outputIndex],
  218045. outputIndex);
  218046. return 0;
  218047. }
  218048. juce_UseDebuggingNewOperator
  218049. private:
  218050. StringArray inputDeviceNames, outputDeviceNames;
  218051. Array <AudioDeviceID> inputIds, outputIds;
  218052. bool hasScanned;
  218053. static int getNumChannels (AudioDeviceID deviceID, bool input)
  218054. {
  218055. int total = 0;
  218056. UInt32 size;
  218057. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, 0)))
  218058. {
  218059. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  218060. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, bufList)))
  218061. {
  218062. const int numStreams = bufList->mNumberBuffers;
  218063. for (int i = 0; i < numStreams; ++i)
  218064. {
  218065. const AudioBuffer& b = bufList->mBuffers[i];
  218066. total += b.mNumberChannels;
  218067. }
  218068. }
  218069. juce_free (bufList);
  218070. }
  218071. return total;
  218072. }
  218073. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  218074. const CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  218075. };
  218076. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  218077. {
  218078. return new CoreAudioIODeviceType();
  218079. }
  218080. #undef log
  218081. END_JUCE_NAMESPACE
  218082. /********* End of inlined file: juce_mac_CoreAudio.cpp *********/
  218083. /********* Start of inlined file: juce_mac_CoreMidi.cpp *********/
  218084. #include <CoreMIDI/MIDIServices.h>
  218085. BEGIN_JUCE_NAMESPACE
  218086. #undef log
  218087. #define log(a) Logger::writeToLog(a)
  218088. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  218089. {
  218090. if (err == noErr)
  218091. return true;
  218092. log (T("CoreMidi error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  218093. jassertfalse
  218094. return false;
  218095. }
  218096. #undef OK
  218097. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  218098. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  218099. {
  218100. String result;
  218101. CFStringRef str = 0;
  218102. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  218103. if (str != 0)
  218104. {
  218105. result = PlatformUtilities::cfStringToJuceString (str);
  218106. CFRelease (str);
  218107. str = 0;
  218108. }
  218109. MIDIEntityRef entity = 0;
  218110. MIDIEndpointGetEntity (endpoint, &entity);
  218111. if (entity == 0)
  218112. return result; // probably virtual
  218113. if (result.isEmpty())
  218114. {
  218115. // endpoint name has zero length - try the entity
  218116. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  218117. if (str != 0)
  218118. {
  218119. result += PlatformUtilities::cfStringToJuceString (str);
  218120. CFRelease (str);
  218121. str = 0;
  218122. }
  218123. }
  218124. // now consider the device's name
  218125. MIDIDeviceRef device = 0;
  218126. MIDIEntityGetDevice (entity, &device);
  218127. if (device == 0)
  218128. return result;
  218129. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  218130. if (str != 0)
  218131. {
  218132. const String s (PlatformUtilities::cfStringToJuceString (str));
  218133. CFRelease (str);
  218134. // if an external device has only one entity, throw away
  218135. // the endpoint name and just use the device name
  218136. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  218137. {
  218138. result = s;
  218139. }
  218140. else if (! result.startsWithIgnoreCase (s))
  218141. {
  218142. // prepend the device name to the entity name
  218143. result = (s + T(" ") + result).trimEnd();
  218144. }
  218145. }
  218146. return result;
  218147. }
  218148. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  218149. {
  218150. String result;
  218151. // Does the endpoint have connections?
  218152. CFDataRef connections = 0;
  218153. int numConnections = 0;
  218154. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  218155. if (connections != 0)
  218156. {
  218157. numConnections = CFDataGetLength (connections) / sizeof (MIDIUniqueID);
  218158. if (numConnections > 0)
  218159. {
  218160. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  218161. for (int i = 0; i < numConnections; ++i, ++pid)
  218162. {
  218163. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  218164. MIDIObjectRef connObject;
  218165. MIDIObjectType connObjectType;
  218166. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  218167. if (err == noErr)
  218168. {
  218169. String s;
  218170. if (connObjectType == kMIDIObjectType_ExternalSource
  218171. || connObjectType == kMIDIObjectType_ExternalDestination)
  218172. {
  218173. // Connected to an external device's endpoint (10.3 and later).
  218174. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  218175. }
  218176. else
  218177. {
  218178. // Connected to an external device (10.2) (or something else, catch-all)
  218179. CFStringRef str = 0;
  218180. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  218181. if (str != 0)
  218182. {
  218183. s = PlatformUtilities::cfStringToJuceString (str);
  218184. CFRelease (str);
  218185. }
  218186. }
  218187. if (s.isNotEmpty())
  218188. {
  218189. if (result.isNotEmpty())
  218190. result += (", ");
  218191. result += s;
  218192. }
  218193. }
  218194. }
  218195. }
  218196. CFRelease (connections);
  218197. }
  218198. if (result.isNotEmpty())
  218199. return result;
  218200. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  218201. return getEndpointName (endpoint, false);
  218202. }
  218203. const StringArray MidiOutput::getDevices()
  218204. {
  218205. StringArray s;
  218206. const ItemCount num = MIDIGetNumberOfDestinations();
  218207. for (ItemCount i = 0; i < num; ++i)
  218208. {
  218209. MIDIEndpointRef dest = MIDIGetDestination (i);
  218210. if (dest != 0)
  218211. {
  218212. String name (getConnectedEndpointName (dest));
  218213. if (name.isEmpty())
  218214. name = "<error>";
  218215. s.add (name);
  218216. }
  218217. else
  218218. {
  218219. s.add ("<error>");
  218220. }
  218221. }
  218222. return s;
  218223. }
  218224. int MidiOutput::getDefaultDeviceIndex()
  218225. {
  218226. return 0;
  218227. }
  218228. static MIDIClientRef globalMidiClient;
  218229. static bool hasGlobalClientBeenCreated = false;
  218230. static bool makeSureClientExists()
  218231. {
  218232. if (! hasGlobalClientBeenCreated)
  218233. {
  218234. String name (T("JUCE"));
  218235. if (JUCEApplication::getInstance() != 0)
  218236. name = JUCEApplication::getInstance()->getApplicationName();
  218237. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  218238. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  218239. CFRelease (appName);
  218240. }
  218241. return hasGlobalClientBeenCreated;
  218242. }
  218243. struct MidiPortAndEndpoint
  218244. {
  218245. MIDIPortRef port;
  218246. MIDIEndpointRef endPoint;
  218247. };
  218248. MidiOutput* MidiOutput::openDevice (int index)
  218249. {
  218250. MidiOutput* mo = 0;
  218251. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  218252. {
  218253. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  218254. CFStringRef pname;
  218255. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  218256. {
  218257. log (T("CoreMidi - opening out: ") + PlatformUtilities::cfStringToJuceString (pname));
  218258. if (makeSureClientExists())
  218259. {
  218260. MIDIPortRef port;
  218261. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  218262. {
  218263. MidiPortAndEndpoint* mpe = new MidiPortAndEndpoint();
  218264. mpe->port = port;
  218265. mpe->endPoint = endPoint;
  218266. mo = new MidiOutput();
  218267. mo->internal = (void*)mpe;
  218268. }
  218269. }
  218270. CFRelease (pname);
  218271. }
  218272. }
  218273. return mo;
  218274. }
  218275. MidiOutput::~MidiOutput()
  218276. {
  218277. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  218278. MIDIPortDispose (mpe->port);
  218279. delete mpe;
  218280. }
  218281. void MidiOutput::reset()
  218282. {
  218283. }
  218284. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  218285. {
  218286. return false;
  218287. }
  218288. void MidiOutput::setVolume (float leftVol, float rightVol)
  218289. {
  218290. }
  218291. void MidiOutput::sendMessageNow (const MidiMessage& message)
  218292. {
  218293. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  218294. if (message.isSysEx())
  218295. {
  218296. MIDIPacketList* const packets = (MIDIPacketList*) juce_malloc (32 + message.getRawDataSize());
  218297. packets->numPackets = 1;
  218298. packets->packet[0].timeStamp = 0;
  218299. packets->packet[0].length = message.getRawDataSize();
  218300. memcpy (packets->packet[0].data, message.getRawData(), message.getRawDataSize());
  218301. MIDISend (mpe->port, mpe->endPoint, packets);
  218302. juce_free (packets);
  218303. }
  218304. else
  218305. {
  218306. MIDIPacketList packets;
  218307. packets.numPackets = 1;
  218308. packets.packet[0].timeStamp = 0;
  218309. packets.packet[0].length = message.getRawDataSize();
  218310. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  218311. MIDISend (mpe->port, mpe->endPoint, &packets);
  218312. }
  218313. }
  218314. const StringArray MidiInput::getDevices()
  218315. {
  218316. StringArray s;
  218317. const ItemCount num = MIDIGetNumberOfSources();
  218318. for (ItemCount i = 0; i < num; ++i)
  218319. {
  218320. MIDIEndpointRef source = MIDIGetSource (i);
  218321. if (source != 0)
  218322. {
  218323. String name (getConnectedEndpointName (source));
  218324. if (name.isEmpty())
  218325. name = "<error>";
  218326. s.add (name);
  218327. }
  218328. else
  218329. {
  218330. s.add ("<error>");
  218331. }
  218332. }
  218333. return s;
  218334. }
  218335. int MidiInput::getDefaultDeviceIndex()
  218336. {
  218337. return 0;
  218338. }
  218339. struct MidiPortAndCallback
  218340. {
  218341. MidiInput* input;
  218342. MIDIPortRef port;
  218343. MIDIEndpointRef endPoint;
  218344. MidiInputCallback* callback;
  218345. MemoryBlock pendingData;
  218346. int pendingBytes;
  218347. double pendingDataTime;
  218348. bool active;
  218349. };
  218350. static CriticalSection callbackLock;
  218351. static VoidArray activeCallbacks;
  218352. static void processSysex (MidiPortAndCallback* const mpe, const uint8*& d, int& size, const double time)
  218353. {
  218354. if (*d == 0xf0)
  218355. {
  218356. mpe->pendingBytes = 0;
  218357. mpe->pendingDataTime = time;
  218358. }
  218359. mpe->pendingData.ensureSize (mpe->pendingBytes + size, false);
  218360. uint8* totalMessage = (uint8*) mpe->pendingData.getData();
  218361. uint8* dest = totalMessage + mpe->pendingBytes;
  218362. while (size > 0)
  218363. {
  218364. if (mpe->pendingBytes > 0 && *d >= 0x80)
  218365. {
  218366. if (*d >= 0xfa || *d == 0xf8)
  218367. {
  218368. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (*d, time));
  218369. ++d;
  218370. --size;
  218371. }
  218372. else
  218373. {
  218374. if (*d == 0xf7)
  218375. {
  218376. *dest++ = *d++;
  218377. mpe->pendingBytes++;
  218378. --size;
  218379. }
  218380. break;
  218381. }
  218382. }
  218383. else
  218384. {
  218385. *dest++ = *d++;
  218386. mpe->pendingBytes++;
  218387. --size;
  218388. }
  218389. }
  218390. if (totalMessage [mpe->pendingBytes - 1] == 0xf7)
  218391. {
  218392. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (totalMessage,
  218393. mpe->pendingBytes,
  218394. mpe->pendingDataTime));
  218395. mpe->pendingBytes = 0;
  218396. }
  218397. else
  218398. {
  218399. mpe->callback->handlePartialSysexMessage (mpe->input,
  218400. totalMessage,
  218401. mpe->pendingBytes,
  218402. mpe->pendingDataTime);
  218403. }
  218404. }
  218405. static void midiInputProc (const MIDIPacketList* pktlist,
  218406. void* readProcRefCon,
  218407. void* srcConnRefCon)
  218408. {
  218409. double time = Time::getMillisecondCounterHiRes() * 0.001;
  218410. const double originalTime = time;
  218411. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) readProcRefCon;
  218412. const ScopedLock sl (callbackLock);
  218413. if (activeCallbacks.contains (mpe) && mpe->active)
  218414. {
  218415. const MIDIPacket* packet = &pktlist->packet[0];
  218416. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  218417. {
  218418. const uint8* d = (const uint8*) (packet->data);
  218419. int size = packet->length;
  218420. while (size > 0)
  218421. {
  218422. time = originalTime;
  218423. if (mpe->pendingBytes > 0 || d[0] == 0xf0)
  218424. {
  218425. processSysex (mpe, d, size, time);
  218426. }
  218427. else
  218428. {
  218429. int used = 0;
  218430. const MidiMessage m (d, size, used, 0, time);
  218431. if (used <= 0)
  218432. {
  218433. jassertfalse // malformed midi message
  218434. break;
  218435. }
  218436. else
  218437. {
  218438. mpe->callback->handleIncomingMidiMessage (mpe->input, m);
  218439. }
  218440. size -= used;
  218441. d += used;
  218442. }
  218443. }
  218444. packet = MIDIPacketNext (packet);
  218445. }
  218446. }
  218447. }
  218448. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  218449. {
  218450. MidiInput* mi = 0;
  218451. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  218452. {
  218453. MIDIEndpointRef endPoint = MIDIGetSource (index);
  218454. if (endPoint != 0)
  218455. {
  218456. CFStringRef pname;
  218457. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  218458. {
  218459. log (T("CoreMidi - opening inp: ") + PlatformUtilities::cfStringToJuceString (pname));
  218460. if (makeSureClientExists())
  218461. {
  218462. MIDIPortRef port;
  218463. MidiPortAndCallback* const mpe = new MidiPortAndCallback();
  218464. mpe->active = false;
  218465. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpe, &port)))
  218466. {
  218467. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  218468. {
  218469. mpe->port = port;
  218470. mpe->endPoint = endPoint;
  218471. mpe->callback = callback;
  218472. mpe->pendingBytes = 0;
  218473. mpe->pendingData.ensureSize (128);
  218474. mi = new MidiInput (getDevices() [index]);
  218475. mpe->input = mi;
  218476. mi->internal = (void*) mpe;
  218477. const ScopedLock sl (callbackLock);
  218478. activeCallbacks.add (mpe);
  218479. }
  218480. else
  218481. {
  218482. OK (MIDIPortDispose (port));
  218483. delete mpe;
  218484. }
  218485. }
  218486. else
  218487. {
  218488. delete mpe;
  218489. }
  218490. }
  218491. }
  218492. CFRelease (pname);
  218493. }
  218494. }
  218495. return mi;
  218496. }
  218497. MidiInput::MidiInput (const String& name_)
  218498. : name (name_)
  218499. {
  218500. }
  218501. MidiInput::~MidiInput()
  218502. {
  218503. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  218504. mpe->active = false;
  218505. callbackLock.enter();
  218506. activeCallbacks.removeValue (mpe);
  218507. callbackLock.exit();
  218508. OK (MIDIPortDisconnectSource (mpe->port, mpe->endPoint));
  218509. OK (MIDIPortDispose (mpe->port));
  218510. delete mpe;
  218511. }
  218512. void MidiInput::start()
  218513. {
  218514. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  218515. const ScopedLock sl (callbackLock);
  218516. mpe->active = true;
  218517. }
  218518. void MidiInput::stop()
  218519. {
  218520. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  218521. const ScopedLock sl (callbackLock);
  218522. mpe->active = false;
  218523. }
  218524. #undef log
  218525. END_JUCE_NAMESPACE
  218526. /********* End of inlined file: juce_mac_CoreMidi.cpp *********/
  218527. /********* Start of inlined file: juce_mac_FileChooser.mm *********/
  218528. #include <fnmatch.h>
  218529. BEGIN_JUCE_NAMESPACE
  218530. END_JUCE_NAMESPACE
  218531. @interface JuceFileChooserDelegate : NSObject
  218532. {
  218533. JUCE_NAMESPACE::StringArray* filters;
  218534. }
  218535. - (JuceFileChooserDelegate*) initWithFilters: (JUCE_NAMESPACE::StringArray*) filters_;
  218536. - (void) dealloc;
  218537. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  218538. @end
  218539. @implementation JuceFileChooserDelegate
  218540. - (JuceFileChooserDelegate*) initWithFilters: (JUCE_NAMESPACE::StringArray*) filters_
  218541. {
  218542. [super init];
  218543. filters = filters_;
  218544. return self;
  218545. }
  218546. - (void) dealloc
  218547. {
  218548. delete filters;
  218549. [super dealloc];
  218550. }
  218551. - (BOOL) panel:(id) sender shouldShowFilename: (NSString*) filename
  218552. {
  218553. const JUCE_NAMESPACE::String fname (nsStringToJuce (filename));
  218554. for (int i = filters->size(); --i >= 0;)
  218555. {
  218556. const JUCE_NAMESPACE::String wildcard ((*filters)[i]);
  218557. if (fnmatch (wildcard.toLowerCase().toUTF8(),
  218558. fname.toLowerCase().toUTF8(), 0) == 0)
  218559. return true;
  218560. }
  218561. return JUCE_NAMESPACE::File (fname).isDirectory();
  218562. }
  218563. @end
  218564. BEGIN_JUCE_NAMESPACE
  218565. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  218566. const String& title,
  218567. const File& currentFileOrDirectory,
  218568. const String& filter,
  218569. bool selectsDirectory,
  218570. bool isSaveDialogue,
  218571. bool warnAboutOverwritingExistingFiles,
  218572. bool selectMultipleFiles,
  218573. FilePreviewComponent* extraInfoComponent)
  218574. {
  218575. const AutoPool pool;
  218576. StringArray* filters = new StringArray();
  218577. filters->addTokens (filter.replaceCharacters (T(",:"), T(";;")), T(";"), 0);
  218578. filters->trim();
  218579. filters->removeEmptyStrings();
  218580. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  218581. [delegate autorelease];
  218582. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  218583. : [NSOpenPanel openPanel];
  218584. [panel setTitle: juceStringToNS (title)];
  218585. if (! isSaveDialogue)
  218586. {
  218587. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  218588. [openPanel setCanChooseDirectories: selectsDirectory];
  218589. [openPanel setCanChooseFiles: ! selectsDirectory];
  218590. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  218591. }
  218592. [panel setDelegate: delegate];
  218593. String directory, filename;
  218594. if (currentFileOrDirectory.isDirectory())
  218595. {
  218596. directory = currentFileOrDirectory.getFullPathName();
  218597. }
  218598. else
  218599. {
  218600. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  218601. filename = currentFileOrDirectory.getFileName();
  218602. }
  218603. if ([panel runModalForDirectory: juceStringToNS (directory)
  218604. file: juceStringToNS (filename)]
  218605. == NSOKButton)
  218606. {
  218607. if (isSaveDialogue)
  218608. {
  218609. results.add (new File (nsStringToJuce ([panel filename])));
  218610. }
  218611. else
  218612. {
  218613. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  218614. NSArray* urls = [openPanel filenames];
  218615. for (int i = 0; i < [urls count]; ++i)
  218616. {
  218617. NSString* f = [urls objectAtIndex: i];
  218618. results.add (new File (nsStringToJuce (f)));
  218619. }
  218620. }
  218621. }
  218622. [panel setDelegate: nil];
  218623. }
  218624. END_JUCE_NAMESPACE
  218625. /********* End of inlined file: juce_mac_FileChooser.mm *********/
  218626. /********* Start of inlined file: juce_mac_Fonts.mm *********/
  218627. #include <ApplicationServices/ApplicationServices.h>
  218628. BEGIN_JUCE_NAMESPACE
  218629. static OSStatus pascal CubicMoveTo (const Float32Point *pt,
  218630. void* callBackDataPtr)
  218631. {
  218632. Path* const p = (Path*) callBackDataPtr;
  218633. p->startNewSubPath (pt->x, pt->y);
  218634. return noErr;
  218635. }
  218636. static OSStatus pascal CubicLineTo (const Float32Point *pt,
  218637. void* callBackDataPtr)
  218638. {
  218639. Path* const p = (Path*) callBackDataPtr;
  218640. p->lineTo (pt->x, pt->y);
  218641. return noErr;
  218642. }
  218643. static OSStatus pascal CubicCurveTo (const Float32Point *pt1,
  218644. const Float32Point *pt2,
  218645. const Float32Point *pt3,
  218646. void* callBackDataPtr)
  218647. {
  218648. Path* const p = (Path*) callBackDataPtr;
  218649. p->cubicTo (pt1->x, pt1->y,
  218650. pt2->x, pt2->y,
  218651. pt3->x, pt3->y);
  218652. return noErr;
  218653. }
  218654. static OSStatus pascal CubicClosePath (void* callBackDataPtr)
  218655. {
  218656. Path* const p = (Path*) callBackDataPtr;
  218657. p->closeSubPath();
  218658. return noErr;
  218659. }
  218660. class ATSFontHelper
  218661. {
  218662. ATSUFontID fontId;
  218663. ATSUStyle style;
  218664. ATSCubicMoveToUPP moveToProc;
  218665. ATSCubicLineToUPP lineToProc;
  218666. ATSCubicCurveToUPP curveToProc;
  218667. ATSCubicClosePathUPP closePathProc;
  218668. float totalSize, ascent;
  218669. TextToUnicodeInfo encodingInfo;
  218670. public:
  218671. String name;
  218672. bool isBold, isItalic;
  218673. float fontSize;
  218674. int refCount;
  218675. ATSFontHelper (const String& name_,
  218676. const bool bold_,
  218677. const bool italic_,
  218678. const float size_)
  218679. : fontId (0),
  218680. name (name_),
  218681. isBold (bold_),
  218682. isItalic (italic_),
  218683. fontSize (size_),
  218684. refCount (1)
  218685. {
  218686. const char* const nameUtf8 = name_.toUTF8();
  218687. ATSUFindFontFromName (const_cast <char*> (nameUtf8),
  218688. strlen (nameUtf8),
  218689. kFontFullName,
  218690. kFontNoPlatformCode,
  218691. kFontNoScriptCode,
  218692. kFontNoLanguageCode,
  218693. &fontId);
  218694. ATSUCreateStyle (&style);
  218695. ATSUAttributeTag attTypes[] = { kATSUFontTag,
  218696. kATSUQDBoldfaceTag,
  218697. kATSUQDItalicTag,
  218698. kATSUSizeTag };
  218699. ByteCount attSizes[] = { sizeof (ATSUFontID),
  218700. sizeof (Boolean),
  218701. sizeof (Boolean),
  218702. sizeof (Fixed) };
  218703. Boolean bold = bold_, italic = italic_;
  218704. Fixed size = X2Fix (size_);
  218705. ATSUAttributeValuePtr attValues[] = { &fontId,
  218706. &bold,
  218707. &italic,
  218708. &size };
  218709. ATSUSetAttributes (style, 4, attTypes, attSizes, attValues);
  218710. moveToProc = NewATSCubicMoveToUPP (CubicMoveTo);
  218711. lineToProc = NewATSCubicLineToUPP (CubicLineTo);
  218712. curveToProc = NewATSCubicCurveToUPP (CubicCurveTo);
  218713. closePathProc = NewATSCubicClosePathUPP (CubicClosePath);
  218714. ascent = 0.0f;
  218715. float kern, descent = 0.0f;
  218716. getPathAndKerning (T('N'), T('O'), 0, kern, &ascent, &descent);
  218717. totalSize = ascent + descent;
  218718. }
  218719. ~ATSFontHelper()
  218720. {
  218721. ATSUDisposeStyle (style);
  218722. DisposeATSCubicMoveToUPP (moveToProc);
  218723. DisposeATSCubicLineToUPP (lineToProc);
  218724. DisposeATSCubicCurveToUPP (curveToProc);
  218725. DisposeATSCubicClosePathUPP (closePathProc);
  218726. }
  218727. bool getPathAndKerning (const juce_wchar char1,
  218728. const juce_wchar char2,
  218729. Path* path,
  218730. float& kerning,
  218731. float* ascent,
  218732. float* descent)
  218733. {
  218734. bool ok = false;
  218735. UniChar buffer[4];
  218736. buffer[0] = T(' ');
  218737. buffer[1] = char1;
  218738. buffer[2] = char2;
  218739. buffer[3] = 0;
  218740. UniCharCount count = kATSUToTextEnd;
  218741. ATSUTextLayout layout;
  218742. OSStatus err = ATSUCreateTextLayoutWithTextPtr (buffer,
  218743. 0,
  218744. 2,
  218745. 2,
  218746. 1,
  218747. &count,
  218748. &style,
  218749. &layout);
  218750. if (err == noErr)
  218751. {
  218752. ATSUSetTransientFontMatching (layout, true);
  218753. ATSLayoutRecord* layoutRecords;
  218754. ItemCount numRecords;
  218755. Fixed* deltaYs;
  218756. ItemCount numDeltaYs;
  218757. ATSUDirectGetLayoutDataArrayPtrFromTextLayout (layout,
  218758. 0,
  218759. kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
  218760. (void**) &layoutRecords,
  218761. &numRecords);
  218762. ATSUDirectGetLayoutDataArrayPtrFromTextLayout (layout,
  218763. 0,
  218764. kATSUDirectDataBaselineDeltaFixedArray,
  218765. (void**) &deltaYs,
  218766. &numDeltaYs);
  218767. if (numRecords > 2)
  218768. {
  218769. kerning = (float) (Fix2X (layoutRecords[2].realPos)
  218770. - Fix2X (layoutRecords[1].realPos));
  218771. if (ascent != 0)
  218772. {
  218773. ATSUTextMeasurement asc;
  218774. ByteCount actualSize;
  218775. ATSUGetLineControl (layout,
  218776. 0,
  218777. kATSULineAscentTag,
  218778. sizeof (ATSUTextMeasurement),
  218779. &asc,
  218780. &actualSize);
  218781. *ascent = (float) Fix2X (asc);
  218782. }
  218783. if (descent != 0)
  218784. {
  218785. ATSUTextMeasurement desc;
  218786. ByteCount actualSize;
  218787. ATSUGetLineControl (layout,
  218788. 0,
  218789. kATSULineDescentTag,
  218790. sizeof (ATSUTextMeasurement),
  218791. &desc,
  218792. &actualSize);
  218793. *descent = (float) Fix2X (desc);
  218794. }
  218795. if (path != 0)
  218796. {
  218797. OSStatus callbackResult;
  218798. ok = (ATSUGlyphGetCubicPaths (style,
  218799. layoutRecords[1].glyphID,
  218800. moveToProc,
  218801. lineToProc,
  218802. curveToProc,
  218803. closePathProc,
  218804. (void*) path,
  218805. &callbackResult) == noErr);
  218806. if (numDeltaYs > 0 && ok)
  218807. {
  218808. const float dy = (float) Fix2X (deltaYs[1]);
  218809. path->applyTransform (AffineTransform::translation (0.0f, dy));
  218810. }
  218811. }
  218812. else
  218813. {
  218814. ok = true;
  218815. }
  218816. }
  218817. if (deltaYs != 0)
  218818. ATSUDirectReleaseLayoutDataArrayPtr (0, kATSUDirectDataBaselineDeltaFixedArray,
  218819. (void**) &deltaYs);
  218820. if (layoutRecords != 0)
  218821. ATSUDirectReleaseLayoutDataArrayPtr (0, kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
  218822. (void**) &layoutRecords);
  218823. ATSUDisposeTextLayout (layout);
  218824. }
  218825. return kerning;
  218826. }
  218827. float getAscent()
  218828. {
  218829. return ascent;
  218830. }
  218831. float getTotalHeight()
  218832. {
  218833. return totalSize;
  218834. }
  218835. juce_wchar getDefaultChar()
  218836. {
  218837. return 0;
  218838. }
  218839. };
  218840. class ATSFontHelperCache : public Timer,
  218841. public DeletedAtShutdown
  218842. {
  218843. VoidArray cache;
  218844. public:
  218845. ATSFontHelperCache()
  218846. {
  218847. }
  218848. ~ATSFontHelperCache()
  218849. {
  218850. for (int i = cache.size(); --i >= 0;)
  218851. {
  218852. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  218853. delete f;
  218854. }
  218855. clearSingletonInstance();
  218856. }
  218857. ATSFontHelper* getFont (const String& name,
  218858. const bool bold,
  218859. const bool italic,
  218860. const float size = 1024)
  218861. {
  218862. for (int i = cache.size(); --i >= 0;)
  218863. {
  218864. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  218865. if (f->name == name
  218866. && f->isBold == bold
  218867. && f->isItalic == italic
  218868. && f->fontSize == size)
  218869. {
  218870. f->refCount++;
  218871. return f;
  218872. }
  218873. }
  218874. ATSFontHelper* const f = new ATSFontHelper (name, bold, italic, size);
  218875. cache.add (f);
  218876. return f;
  218877. }
  218878. void releaseFont (ATSFontHelper* f)
  218879. {
  218880. for (int i = cache.size(); --i >= 0;)
  218881. {
  218882. ATSFontHelper* const f2 = (ATSFontHelper*) cache.getUnchecked(i);
  218883. if (f == f2)
  218884. {
  218885. f->refCount--;
  218886. if (f->refCount == 0)
  218887. startTimer (5000);
  218888. break;
  218889. }
  218890. }
  218891. }
  218892. void timerCallback()
  218893. {
  218894. stopTimer();
  218895. for (int i = cache.size(); --i >= 0;)
  218896. {
  218897. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  218898. if (f->refCount == 0)
  218899. {
  218900. cache.remove (i);
  218901. delete f;
  218902. }
  218903. }
  218904. if (cache.size() == 0)
  218905. delete this;
  218906. }
  218907. juce_DeclareSingleton_SingleThreaded_Minimal (ATSFontHelperCache)
  218908. };
  218909. juce_ImplementSingleton_SingleThreaded (ATSFontHelperCache)
  218910. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  218911. bool bold,
  218912. bool italic,
  218913. bool addAllGlyphsToFont) throw()
  218914. {
  218915. // This method is only safe to be called from the normal UI thread..
  218916. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  218917. ATSFontHelper* const helper = ATSFontHelperCache::getInstance()
  218918. ->getFont (fontName, bold, italic);
  218919. clear();
  218920. setAscent (helper->getAscent() / helper->getTotalHeight());
  218921. setName (fontName);
  218922. setDefaultCharacter (helper->getDefaultChar());
  218923. setBold (bold);
  218924. setItalic (italic);
  218925. if (addAllGlyphsToFont)
  218926. {
  218927. //xxx
  218928. jassertfalse
  218929. }
  218930. ATSFontHelperCache::getInstance()->releaseFont (helper);
  218931. }
  218932. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  218933. {
  218934. // This method is only safe to be called from the normal UI thread..
  218935. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  218936. ATSFontHelper* const helper = ATSFontHelperCache::getInstance()
  218937. ->getFont (getName(), isBold(), isItalic());
  218938. Path path;
  218939. float width;
  218940. bool foundOne = false;
  218941. if (helper->getPathAndKerning (character, T('I'), &path, width, 0, 0))
  218942. {
  218943. path.applyTransform (AffineTransform::scale (1.0f / helper->getTotalHeight(),
  218944. 1.0f / helper->getTotalHeight()));
  218945. addGlyph (character, path, width / helper->getTotalHeight());
  218946. for (int i = 0; i < glyphs.size(); ++i)
  218947. {
  218948. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  218949. float kerning;
  218950. if (helper->getPathAndKerning (character, g->getCharacter(), 0, kerning, 0, 0))
  218951. {
  218952. kerning = (kerning - width) / helper->getTotalHeight();
  218953. if (kerning != 0)
  218954. addKerningPair (character, g->getCharacter(), kerning);
  218955. }
  218956. if (helper->getPathAndKerning (g->getCharacter(), character, 0, kerning, 0, 0))
  218957. {
  218958. kerning = kerning / helper->getTotalHeight() - g->width;
  218959. if (kerning != 0)
  218960. addKerningPair (g->getCharacter(), character, kerning);
  218961. }
  218962. }
  218963. foundOne = true;
  218964. }
  218965. ATSFontHelperCache::getInstance()->releaseFont (helper);
  218966. return foundOne;
  218967. }
  218968. const StringArray Font::findAllTypefaceNames() throw()
  218969. {
  218970. StringArray names;
  218971. ATSFontIterator iter;
  218972. if (ATSFontIteratorCreate (kATSFontContextGlobal,
  218973. 0,
  218974. 0,
  218975. kATSOptionFlagsRestrictedScope,
  218976. &iter) == noErr)
  218977. {
  218978. ATSFontRef font;
  218979. while (ATSFontIteratorNext (iter, &font) == noErr)
  218980. {
  218981. CFStringRef name;
  218982. if (ATSFontGetName (font,
  218983. kATSOptionFlagsDefault,
  218984. &name) == noErr)
  218985. {
  218986. const String nm (PlatformUtilities::cfStringToJuceString (name));
  218987. if (nm.isNotEmpty())
  218988. names.add (nm);
  218989. CFRelease (name);
  218990. }
  218991. }
  218992. ATSFontIteratorRelease (&iter);
  218993. }
  218994. // Use some totuous logic to eliminate bold/italic versions of fonts that we've already got
  218995. // a plain version of. This is only necessary because of Carbon's total lack of support
  218996. // for dealing with font families...
  218997. for (int j = names.size(); --j >= 0;)
  218998. {
  218999. const char* const endings[] = { " bold", " italic", " bold italic", " bolditalic",
  219000. " oblque", " bold oblique", " boldoblique" };
  219001. for (int i = 0; i < numElementsInArray (endings); ++i)
  219002. {
  219003. const String ending (endings[i]);
  219004. if (names[j].endsWithIgnoreCase (ending))
  219005. {
  219006. const String root (names[j].dropLastCharacters (ending.length()).trimEnd());
  219007. if (names.contains (root)
  219008. || names.contains (root + T(" plain"), true))
  219009. {
  219010. names.remove (j);
  219011. break;
  219012. }
  219013. }
  219014. }
  219015. }
  219016. names.sort (true);
  219017. return names;
  219018. }
  219019. void Font::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  219020. {
  219021. defaultSans = "Lucida Grande";
  219022. defaultSerif = "Times New Roman";
  219023. defaultFixed = "Monaco";
  219024. }
  219025. END_JUCE_NAMESPACE
  219026. /********* End of inlined file: juce_mac_Fonts.mm *********/
  219027. /********* Start of inlined file: juce_mac_Messaging.mm *********/
  219028. #include <Carbon/Carbon.h>
  219029. BEGIN_JUCE_NAMESPACE
  219030. #undef Point
  219031. extern void juce_HandleProcessFocusChange();
  219032. extern void juce_maximiseAllMinimisedWindows();
  219033. extern void juce_InvokeMainMenuCommand (const HICommand& command);
  219034. extern void juce_MainMenuAboutToBeUsed();
  219035. struct CallbackMessagePayload
  219036. {
  219037. MessageCallbackFunction* function;
  219038. void* parameter;
  219039. void* volatile result;
  219040. bool volatile hasBeenExecuted;
  219041. };
  219042. END_JUCE_NAMESPACE
  219043. #if JUCE_COCOA
  219044. NSString* juceMessageName = 0;
  219045. @interface JuceAppDelegate : NSObject
  219046. id oldDelegate;
  219047. - (JuceAppDelegate*) init;
  219048. - (void) dealloc;
  219049. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  219050. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  219051. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  219052. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  219053. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  219054. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  219055. - (void) customEvent: (NSNotification*) aNotification;
  219056. - (void) performCallback: (id) info;
  219057. @end
  219058. @implementation JuceAppDelegate
  219059. - (JuceAppDelegate*) init
  219060. {
  219061. [super init];
  219062. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  219063. if (JUCE_NAMESPACE::JUCEApplication::getInstance() != 0)
  219064. {
  219065. oldDelegate = [NSApp delegate];
  219066. [NSApp setDelegate: self];
  219067. }
  219068. else
  219069. {
  219070. oldDelegate = 0;
  219071. [center addObserver: self selector: @selector (applicationDidResignActive:)
  219072. name: NSApplicationDidResignActiveNotification object: NSApp];
  219073. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  219074. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  219075. [center addObserver: self selector: @selector (applicationWillUnhide:)
  219076. name: NSApplicationWillUnhideNotification object: NSApp];
  219077. }
  219078. [center addObserver: self selector: @selector (customEvent:)
  219079. name: juceMessageName object: nil];
  219080. return self;
  219081. }
  219082. - (void) dealloc
  219083. {
  219084. if (oldDelegate != 0)
  219085. [NSApp setDelegate: oldDelegate];
  219086. [[NSNotificationCenter defaultCenter] removeObserver: self];
  219087. [super dealloc];
  219088. }
  219089. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  219090. {
  219091. if (JUCE_NAMESPACE::JUCEApplication::getInstance() != 0)
  219092. JUCE_NAMESPACE::JUCEApplication::getInstance()->systemRequestedQuit();
  219093. return NSTerminateLater;
  219094. }
  219095. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  219096. {
  219097. if (JUCE_NAMESPACE::JUCEApplication::getInstance() != 0)
  219098. {
  219099. JUCE_NAMESPACE::JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  219100. return YES;
  219101. }
  219102. return NO;
  219103. }
  219104. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  219105. {
  219106. JUCE_NAMESPACE::StringArray files;
  219107. for (int i = 0; i < [filenames count]; ++i)
  219108. files.add (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  219109. if (files.size() > 0 && JUCE_NAMESPACE::JUCEApplication::getInstance() != 0)
  219110. JUCE_NAMESPACE::JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (T(" ")));
  219111. }
  219112. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  219113. {
  219114. JUCE_NAMESPACE::juce_HandleProcessFocusChange();
  219115. }
  219116. - (void) applicationDidResignActive: (NSNotification*) aNotification
  219117. {
  219118. JUCE_NAMESPACE::juce_HandleProcessFocusChange();
  219119. }
  219120. - (void) applicationWillUnhide: (NSNotification*) aNotification
  219121. {
  219122. JUCE_NAMESPACE::juce_maximiseAllMinimisedWindows();
  219123. }
  219124. - (void) customEvent: (NSNotification*) n
  219125. {
  219126. void* message = 0;
  219127. [((NSData*) [n object]) getBytes: &message length: sizeof (message)];
  219128. if (message != 0)
  219129. JUCE_NAMESPACE::MessageManager::getInstance()->deliverMessage (message);
  219130. }
  219131. - (void) performCallback: (id) info
  219132. {
  219133. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) info;
  219134. if (pl != 0)
  219135. {
  219136. pl->result = (*pl->function) (pl->parameter);
  219137. pl->hasBeenExecuted = true;
  219138. }
  219139. }
  219140. @end
  219141. #endif
  219142. BEGIN_JUCE_NAMESPACE
  219143. #if JUCE_COCOA
  219144. static JuceAppDelegate* juceAppDelegate = 0;
  219145. #else
  219146. static int kJUCEClass = FOUR_CHAR_CODE ('JUCE');
  219147. const int kJUCEKind = 1;
  219148. const int kCallbackKind = 2;
  219149. static pascal OSStatus EventHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  219150. {
  219151. void* event = 0;
  219152. GetEventParameter (theEvent, 'mess', typeVoidPtr, 0, sizeof (void*), 0, &event);
  219153. if (event != 0)
  219154. MessageManager::getInstance()->deliverMessage (event);
  219155. return noErr;
  219156. }
  219157. static pascal OSStatus CallbackHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  219158. {
  219159. CallbackMessagePayload* pl = 0;
  219160. GetEventParameter (theEvent, 'mess', typeVoidPtr, 0, sizeof(pl), 0, &pl);
  219161. if (pl != 0)
  219162. {
  219163. pl->result = (*pl->function) (pl->parameter);
  219164. pl->hasBeenExecuted = true;
  219165. }
  219166. return noErr;
  219167. }
  219168. static pascal OSStatus MouseClickHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  219169. {
  219170. ::Point where;
  219171. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof(::Point), 0, &where);
  219172. WindowRef window;
  219173. if (FindWindow (where, &window) == inMenuBar)
  219174. {
  219175. // turn off the wait cursor before going in here..
  219176. const int oldTimeBeforeWaitCursor = MessageManager::getInstance()->getTimeBeforeShowingWaitCursor();
  219177. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (0);
  219178. if (Component::getCurrentlyModalComponent() != 0)
  219179. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  219180. juce_MainMenuAboutToBeUsed();
  219181. MenuSelect (where);
  219182. HiliteMenu (0);
  219183. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (oldTimeBeforeWaitCursor);
  219184. return noErr;
  219185. }
  219186. return eventNotHandledErr;
  219187. }
  219188. static pascal OSErr QuitAppleEventHandler (const AppleEvent *appleEvt, AppleEvent* reply, long refcon)
  219189. {
  219190. if (JUCEApplication::getInstance() != 0)
  219191. JUCEApplication::getInstance()->systemRequestedQuit();
  219192. return noErr;
  219193. }
  219194. static pascal OSErr OpenDocEventHandler (const AppleEvent *appleEvt, AppleEvent* reply, long refcon)
  219195. {
  219196. AEDescList docs;
  219197. StringArray files;
  219198. if (AEGetParamDesc (appleEvt, keyDirectObject, typeAEList, &docs) == noErr)
  219199. {
  219200. long num;
  219201. if (AECountItems (&docs, &num) == noErr)
  219202. {
  219203. for (int i = 1; i <= num; ++i)
  219204. {
  219205. FSRef file;
  219206. AEKeyword keyword;
  219207. DescType type;
  219208. Size size;
  219209. if (AEGetNthPtr (&docs, i, typeFSRef, &keyword, &type,
  219210. &file, sizeof (file), &size) == noErr)
  219211. {
  219212. const String path (PlatformUtilities::makePathFromFSRef (&file));
  219213. if (path.isNotEmpty())
  219214. files.add (path.quoted());
  219215. }
  219216. }
  219217. if (files.size() > 0
  219218. && JUCEApplication::getInstance() != 0)
  219219. {
  219220. JUCE_TRY
  219221. {
  219222. JUCEApplication::getInstance()
  219223. ->anotherInstanceStarted (files.joinIntoString (T(" ")));
  219224. }
  219225. JUCE_CATCH_ALL
  219226. }
  219227. }
  219228. AEDisposeDesc (&docs);
  219229. };
  219230. return noErr;
  219231. }
  219232. static pascal OSStatus AppEventHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  219233. {
  219234. const UInt32 eventClass = GetEventClass (theEvent);
  219235. if (eventClass == kEventClassCommand)
  219236. {
  219237. HICommand command;
  219238. if (GetEventParameter (theEvent, kEventParamHICommand, typeHICommand, 0, sizeof (command), 0, &command) == noErr
  219239. || GetEventParameter (theEvent, kEventParamDirectObject, typeHICommand, 0, sizeof (command), 0, &command) == noErr)
  219240. {
  219241. if (command.commandID == kHICommandQuit)
  219242. {
  219243. if (JUCEApplication::getInstance() != 0)
  219244. JUCEApplication::getInstance()->systemRequestedQuit();
  219245. return noErr;
  219246. }
  219247. else if (command.commandID == kHICommandMaximizeAll
  219248. || command.commandID == kHICommandMaximizeWindow
  219249. || command.commandID == kHICommandBringAllToFront)
  219250. {
  219251. juce_maximiseAllMinimisedWindows();
  219252. return noErr;
  219253. }
  219254. else
  219255. {
  219256. juce_InvokeMainMenuCommand (command);
  219257. }
  219258. }
  219259. }
  219260. else if (eventClass == kEventClassApplication)
  219261. {
  219262. if (GetEventKind (theEvent) == kEventAppFrontSwitched)
  219263. {
  219264. juce_HandleProcessFocusChange();
  219265. }
  219266. else if (GetEventKind (theEvent) == kEventAppShown)
  219267. {
  219268. // this seems to blank the windows, so we need to do a repaint..
  219269. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  219270. {
  219271. Component* const c = Desktop::getInstance().getComponent (i);
  219272. if (c != 0)
  219273. c->repaint();
  219274. }
  219275. }
  219276. }
  219277. return eventNotHandledErr;
  219278. }
  219279. static EventQueueRef mainQueue;
  219280. static EventHandlerRef juceEventHandler = 0;
  219281. static EventHandlerRef callbackEventHandler = 0;
  219282. #endif
  219283. void MessageManager::doPlatformSpecificInitialisation()
  219284. {
  219285. static bool initialised = false;
  219286. if (! initialised)
  219287. {
  219288. initialised = true;
  219289. #if JUCE_COCOA
  219290. // if we're linking a Juce app to one or more dynamic libraries, we'll need different values
  219291. // for this so each module doesn't interfere with the others.
  219292. UnsignedWide t;
  219293. Microseconds (&t);
  219294. kJUCEClass ^= t.lo;
  219295. juceMessageName = juceStringToNS ("juce_" + String::toHexString ((int) t.lo));
  219296. juceAppDelegate = [[JuceAppDelegate alloc] init];
  219297. #else
  219298. mainQueue = GetMainEventQueue();
  219299. #endif
  219300. }
  219301. #if ! JUCE_COCOA
  219302. const EventTypeSpec type1 = { kJUCEClass, kJUCEKind };
  219303. InstallApplicationEventHandler (NewEventHandlerUPP (EventHandlerProc), 1, &type1, 0, &juceEventHandler);
  219304. const EventTypeSpec type2 = { kJUCEClass, kCallbackKind };
  219305. InstallApplicationEventHandler (NewEventHandlerUPP (CallbackHandlerProc), 1, &type2, 0, &callbackEventHandler);
  219306. // only do this stuff if we're running as an application rather than a library..
  219307. if (JUCEApplication::getInstance() != 0)
  219308. {
  219309. const EventTypeSpec type3 = { kEventClassMouse, kEventMouseDown };
  219310. InstallApplicationEventHandler (NewEventHandlerUPP (MouseClickHandlerProc), 1, &type3, 0, 0);
  219311. const EventTypeSpec type4[] = { { kEventClassApplication, kEventAppShown },
  219312. { kEventClassApplication, kEventAppFrontSwitched },
  219313. { kEventClassCommand, kEventProcessCommand } };
  219314. InstallApplicationEventHandler (NewEventHandlerUPP (AppEventHandlerProc), 3, type4, 0, 0);
  219315. AEInstallEventHandler (kCoreEventClass, kAEQuitApplication,
  219316. NewAEEventHandlerUPP (QuitAppleEventHandler), 0, false);
  219317. AEInstallEventHandler (kCoreEventClass, kAEOpenDocuments,
  219318. NewAEEventHandlerUPP (OpenDocEventHandler), 0, false);
  219319. }
  219320. #endif
  219321. }
  219322. void MessageManager::doPlatformSpecificShutdown()
  219323. {
  219324. if (juceEventHandler != 0)
  219325. {
  219326. RemoveEventHandler (juceEventHandler);
  219327. juceEventHandler = 0;
  219328. }
  219329. if (callbackEventHandler != 0)
  219330. {
  219331. RemoveEventHandler (callbackEventHandler);
  219332. callbackEventHandler = 0;
  219333. }
  219334. }
  219335. bool juce_postMessageToSystemQueue (void* message)
  219336. {
  219337. #if JUCE_COCOA
  219338. [[NSNotificationCenter defaultCenter] postNotificationName: juceMessageName
  219339. object: [NSData dataWithBytes: &message
  219340. length: (int) sizeof (message)]];
  219341. return true;
  219342. #else
  219343. jassert (mainQueue == GetMainEventQueue());
  219344. EventRef event;
  219345. if (CreateEvent (0, kJUCEClass, kJUCEKind, 0, kEventAttributeUserEvent, &event) == noErr)
  219346. {
  219347. SetEventParameter (event, 'mess', typeVoidPtr, sizeof (void*), &message);
  219348. const bool ok = PostEventToQueue (mainQueue, event, kEventPriorityStandard) == noErr;
  219349. ReleaseEvent (event);
  219350. return ok;
  219351. }
  219352. return false;
  219353. #endif
  219354. }
  219355. void MessageManager::broadcastMessage (const String& value) throw()
  219356. {
  219357. }
  219358. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  219359. void* data)
  219360. {
  219361. if (isThisTheMessageThread())
  219362. {
  219363. return (*callback) (data);
  219364. }
  219365. else
  219366. {
  219367. CallbackMessagePayload cmp;
  219368. cmp.function = callback;
  219369. cmp.parameter = data;
  219370. cmp.result = 0;
  219371. cmp.hasBeenExecuted = false;
  219372. #if JUCE_COCOA
  219373. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  219374. withObject: (id) &cmp
  219375. waitUntilDone: YES];
  219376. return cmp.result;
  219377. #else
  219378. jassert (mainQueue == GetMainEventQueue());
  219379. EventRef event;
  219380. if (CreateEvent (0, kJUCEClass, kCallbackKind, 0, kEventAttributeUserEvent, &event) == noErr)
  219381. {
  219382. void* v = &cmp;
  219383. SetEventParameter (event, 'mess', typeVoidPtr, sizeof (void*), &v);
  219384. if (PostEventToQueue (mainQueue, event, kEventPriorityStandard) == noErr)
  219385. {
  219386. while (! cmp.hasBeenExecuted)
  219387. Thread::yield();
  219388. return cmp.result;
  219389. }
  219390. }
  219391. return 0;
  219392. #endif
  219393. }
  219394. }
  219395. END_JUCE_NAMESPACE
  219396. /********* End of inlined file: juce_mac_Messaging.mm *********/
  219397. /********* Start of inlined file: juce_mac_WebBrowserComponent.mm *********/
  219398. #include <Cocoa/Cocoa.h>
  219399. #include <WebKit/WebKit.h>
  219400. #include <WebKit/HIWebView.h>
  219401. #include <WebKit/WebPolicyDelegate.h>
  219402. #include <WebKit/CarbonUtils.h>
  219403. BEGIN_JUCE_NAMESPACE
  219404. END_JUCE_NAMESPACE
  219405. @interface DownloadClickDetector : NSObject
  219406. {
  219407. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  219408. }
  219409. - (DownloadClickDetector*) initWithOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  219410. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  219411. request: (NSURLRequest*) request
  219412. frame: (WebFrame*) frame
  219413. decisionListener: (id<WebPolicyDecisionListener>) listener;
  219414. @end
  219415. @implementation DownloadClickDetector
  219416. - (DownloadClickDetector*) initWithOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  219417. {
  219418. [super init];
  219419. ownerComponent = ownerComponent_;
  219420. return self;
  219421. }
  219422. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id < WebPolicyDecisionListener >)listener
  219423. {
  219424. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  219425. if (ownerComponent->pageAboutToLoad (JUCE_NAMESPACE::String::fromUTF8 ((const JUCE_NAMESPACE::uint8*) [[url absoluteString] UTF8String])))
  219426. [listener use];
  219427. else
  219428. [listener ignore];
  219429. }
  219430. @end
  219431. BEGIN_JUCE_NAMESPACE
  219432. class WebBrowserComponentInternal : public Timer
  219433. {
  219434. public:
  219435. WebBrowserComponentInternal (WebBrowserComponent* owner_)
  219436. : owner (owner_),
  219437. view (0),
  219438. webView (0)
  219439. {
  219440. HIWebViewCreate (&view);
  219441. ComponentPeer* const peer = owner_->getPeer();
  219442. jassert (peer != 0);
  219443. if (view != 0 && peer != 0)
  219444. {
  219445. WindowRef parentWindow = (WindowRef) peer->getNativeHandle();
  219446. WindowAttributes attributes;
  219447. GetWindowAttributes (parentWindow, &attributes);
  219448. HIViewRef parentView = 0;
  219449. if ((attributes & kWindowCompositingAttribute) != 0)
  219450. {
  219451. HIViewRef root = HIViewGetRoot (parentWindow);
  219452. HIViewFindByID (root, kHIViewWindowContentID, &parentView);
  219453. if (parentView == 0)
  219454. parentView = root;
  219455. }
  219456. else
  219457. {
  219458. GetRootControl (parentWindow, (ControlRef*) &parentView);
  219459. if (parentView == 0)
  219460. CreateRootControl (parentWindow, (ControlRef*) &parentView);
  219461. }
  219462. HIViewAddSubview (parentView, view);
  219463. updateBounds();
  219464. show();
  219465. webView = HIWebViewGetWebView (view);
  219466. clickListener = [[DownloadClickDetector alloc] initWithOwner: owner_];
  219467. [webView setPolicyDelegate: clickListener];
  219468. }
  219469. startTimer (500);
  219470. }
  219471. ~WebBrowserComponentInternal()
  219472. {
  219473. [webView setPolicyDelegate: nil];
  219474. [clickListener release];
  219475. if (view != 0)
  219476. CFRelease (view);
  219477. }
  219478. // Horrific bodge-workaround for the fact that the webview somehow hangs onto key
  219479. // focus when you pop up a new window, no matter what that window does to
  219480. // try to grab focus for itself. This catches such a situation and forces
  219481. // focus away from the webview, then back to the place it should be..
  219482. void timerCallback()
  219483. {
  219484. WindowRef viewWindow = HIViewGetWindow (view);
  219485. WindowRef focusedWindow = GetUserFocusWindow();
  219486. if (focusedWindow != viewWindow)
  219487. {
  219488. if (HIViewSubtreeContainsFocus (view))
  219489. {
  219490. HIViewAdvanceFocus (HIViewGetRoot (viewWindow), 0);
  219491. HIViewAdvanceFocus (HIViewGetRoot (focusedWindow), 0);
  219492. }
  219493. }
  219494. }
  219495. void show()
  219496. {
  219497. HIViewSetVisible (view, true);
  219498. }
  219499. void hide()
  219500. {
  219501. HIViewSetVisible (view, false);
  219502. }
  219503. void goToURL (const String& url,
  219504. const StringArray* headers,
  219505. const MemoryBlock* postData)
  219506. {
  219507. char** headerNamesAsChars = 0;
  219508. char** headerValuesAsChars = 0;
  219509. int numHeaders = 0;
  219510. if (headers != 0)
  219511. {
  219512. numHeaders = headers->size();
  219513. headerNamesAsChars = (char**) juce_malloc (sizeof (char*) * numHeaders);
  219514. headerValuesAsChars = (char**) juce_malloc (sizeof (char*) * numHeaders);
  219515. int i;
  219516. for (i = 0; i < numHeaders; ++i)
  219517. {
  219518. const String headerName ((*headers)[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  219519. headerNamesAsChars[i] = (char*) juce_calloc (headerName.copyToUTF8 (0));
  219520. headerName.copyToUTF8 ((JUCE_NAMESPACE::uint8*) headerNamesAsChars[i]);
  219521. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  219522. headerValuesAsChars[i] = (char*) juce_calloc (headerValue.copyToUTF8 (0));
  219523. headerValue.copyToUTF8 ((JUCE_NAMESPACE::uint8*) headerValuesAsChars[i]);
  219524. }
  219525. }
  219526. sendWebViewToURL ((const char*) url.toUTF8(),
  219527. (const char**) headerNamesAsChars,
  219528. (const char**) headerValuesAsChars,
  219529. numHeaders,
  219530. postData != 0 ? (const char*) postData->getData() : 0,
  219531. postData != 0 ? postData->getSize() : 0);
  219532. for (int i = 0; i < numHeaders; ++i)
  219533. {
  219534. juce_free (headerNamesAsChars[i]);
  219535. juce_free (headerValuesAsChars[i]);
  219536. }
  219537. juce_free (headerNamesAsChars);
  219538. juce_free (headerValuesAsChars);
  219539. }
  219540. void goBack()
  219541. {
  219542. [webView goBack];
  219543. }
  219544. void goForward()
  219545. {
  219546. [webView goForward];
  219547. }
  219548. void stop()
  219549. {
  219550. [webView stopLoading: nil];
  219551. }
  219552. void updateBounds()
  219553. {
  219554. HIRect r;
  219555. r.origin.x = (float) owner->getScreenX() - owner->getTopLevelComponent()->getScreenX();
  219556. r.origin.y = (float) owner->getScreenY() - owner->getTopLevelComponent()->getScreenY();
  219557. r.size.width = (float) owner->getWidth();
  219558. r.size.height = (float) owner->getHeight();
  219559. HIViewSetFrame (view, &r);
  219560. }
  219561. private:
  219562. WebBrowserComponent* const owner;
  219563. HIViewRef view;
  219564. WebView* webView;
  219565. DownloadClickDetector* clickListener;
  219566. void sendWebViewToURL (const char* utf8URL,
  219567. const char** headerNames,
  219568. const char** headerValues,
  219569. int numHeaders,
  219570. const char* postData,
  219571. int postDataSize)
  219572. {
  219573. NSMutableURLRequest* r = [NSMutableURLRequest
  219574. requestWithURL: [NSURL URLWithString: [NSString stringWithUTF8String: utf8URL]]
  219575. cachePolicy: NSURLRequestUseProtocolCachePolicy
  219576. timeoutInterval: 30.0];
  219577. if (postDataSize > 0)
  219578. {
  219579. [ r setHTTPMethod: @"POST"];
  219580. [ r setHTTPBody: [NSData dataWithBytes: postData length: postDataSize]];
  219581. }
  219582. int i;
  219583. for (i = 0; i < numHeaders; ++i)
  219584. {
  219585. [ r setValue: [NSString stringWithUTF8String: headerValues[i]]
  219586. forHTTPHeaderField: [NSString stringWithUTF8String: headerNames[i]]];
  219587. }
  219588. [[webView mainFrame] stopLoading ];
  219589. [[webView mainFrame] loadRequest: r];
  219590. }
  219591. WebBrowserComponentInternal (const WebBrowserComponentInternal&);
  219592. const WebBrowserComponentInternal& operator= (const WebBrowserComponentInternal&);
  219593. };
  219594. WebBrowserComponent::WebBrowserComponent()
  219595. : browser (0),
  219596. associatedWindow (0),
  219597. blankPageShown (false)
  219598. {
  219599. setOpaque (true);
  219600. }
  219601. WebBrowserComponent::~WebBrowserComponent()
  219602. {
  219603. deleteBrowser();
  219604. }
  219605. void WebBrowserComponent::goToURL (const String& url,
  219606. const StringArray* headers,
  219607. const MemoryBlock* postData)
  219608. {
  219609. lastURL = url;
  219610. lastHeaders.clear();
  219611. if (headers != 0)
  219612. lastHeaders = *headers;
  219613. lastPostData.setSize (0);
  219614. if (postData != 0)
  219615. lastPostData = *postData;
  219616. blankPageShown = false;
  219617. if (browser != 0)
  219618. browser->goToURL (url, headers, postData);
  219619. }
  219620. void WebBrowserComponent::stop()
  219621. {
  219622. if (browser != 0)
  219623. browser->stop();
  219624. }
  219625. void WebBrowserComponent::goBack()
  219626. {
  219627. lastURL = String::empty;
  219628. blankPageShown = false;
  219629. if (browser != 0)
  219630. browser->goBack();
  219631. }
  219632. void WebBrowserComponent::goForward()
  219633. {
  219634. lastURL = String::empty;
  219635. if (browser != 0)
  219636. browser->goForward();
  219637. }
  219638. void WebBrowserComponent::paint (Graphics& g)
  219639. {
  219640. if (browser == 0)
  219641. g.fillAll (Colours::white);
  219642. }
  219643. void WebBrowserComponent::checkWindowAssociation()
  219644. {
  219645. void* const window = getWindowHandle();
  219646. if (window != associatedWindow
  219647. || (browser == 0 && window != 0))
  219648. {
  219649. associatedWindow = window;
  219650. deleteBrowser();
  219651. createBrowser();
  219652. }
  219653. if (browser != 0)
  219654. {
  219655. if (associatedWindow != 0 && isShowing())
  219656. {
  219657. browser->show();
  219658. if (blankPageShown)
  219659. goBack();
  219660. }
  219661. else
  219662. {
  219663. if (! blankPageShown)
  219664. {
  219665. // when the component becomes invisible, some stuff like flash
  219666. // carries on playing audio, so we need to force it onto a blank
  219667. // page to avoid this..
  219668. blankPageShown = true;
  219669. browser->goToURL ("about:blank", 0, 0);
  219670. }
  219671. browser->hide();
  219672. }
  219673. }
  219674. }
  219675. void WebBrowserComponent::createBrowser()
  219676. {
  219677. deleteBrowser();
  219678. if (isShowing())
  219679. {
  219680. WebInitForCarbon();
  219681. browser = new WebBrowserComponentInternal (this);
  219682. reloadLastURL();
  219683. }
  219684. }
  219685. void WebBrowserComponent::deleteBrowser()
  219686. {
  219687. deleteAndZero (browser);
  219688. }
  219689. void WebBrowserComponent::reloadLastURL()
  219690. {
  219691. if (lastURL.isNotEmpty())
  219692. {
  219693. goToURL (lastURL, &lastHeaders, &lastPostData);
  219694. lastURL = String::empty;
  219695. }
  219696. }
  219697. void WebBrowserComponent::updateBrowserPosition()
  219698. {
  219699. if (getPeer() != 0 && browser != 0)
  219700. browser->updateBounds();
  219701. }
  219702. void WebBrowserComponent::parentHierarchyChanged()
  219703. {
  219704. checkWindowAssociation();
  219705. }
  219706. void WebBrowserComponent::moved()
  219707. {
  219708. updateBrowserPosition();
  219709. }
  219710. void WebBrowserComponent::resized()
  219711. {
  219712. updateBrowserPosition();
  219713. }
  219714. void WebBrowserComponent::visibilityChanged()
  219715. {
  219716. checkWindowAssociation();
  219717. }
  219718. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  219719. {
  219720. return true;
  219721. }
  219722. END_JUCE_NAMESPACE
  219723. /********* End of inlined file: juce_mac_WebBrowserComponent.mm *********/
  219724. /********* Start of inlined file: juce_mac_Windowing.mm *********/
  219725. #include <Carbon/Carbon.h>
  219726. #include <IOKit/IOKitLib.h>
  219727. #include <IOKit/IOCFPlugIn.h>
  219728. #include <IOKit/hid/IOHIDLib.h>
  219729. #include <IOKit/hid/IOHIDKeys.h>
  219730. #include <fnmatch.h>
  219731. #if JUCE_OPENGL
  219732. #include <AGL/agl.h>
  219733. #endif
  219734. BEGIN_JUCE_NAMESPACE
  219735. #undef Point
  219736. const WindowRegionCode windowRegionToUse = kWindowContentRgn;
  219737. static HIObjectClassRef viewClassRef = 0;
  219738. static CFStringRef juceHiViewClassNameCFString = 0;
  219739. static ComponentPeer* juce_currentMouseTrackingPeer = 0;
  219740. static VoidArray keysCurrentlyDown;
  219741. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  219742. {
  219743. if (keysCurrentlyDown.contains ((void*) keyCode))
  219744. return true;
  219745. if (keyCode >= 'A' && keyCode <= 'Z'
  219746. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toLowerCase ((tchar) keyCode)))
  219747. return true;
  219748. if (keyCode >= 'a' && keyCode <= 'z'
  219749. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toUpperCase ((tchar) keyCode)))
  219750. return true;
  219751. return false;
  219752. }
  219753. static VoidArray minimisedWindows;
  219754. static void setWindowMinimised (WindowRef ref, const bool isMinimised)
  219755. {
  219756. if (isMinimised != minimisedWindows.contains (ref))
  219757. CollapseWindow (ref, isMinimised);
  219758. }
  219759. void juce_maximiseAllMinimisedWindows()
  219760. {
  219761. const VoidArray minWin (minimisedWindows);
  219762. for (int i = minWin.size(); --i >= 0;)
  219763. setWindowMinimised ((WindowRef) (minWin[i]), false);
  219764. }
  219765. class HIViewComponentPeer;
  219766. static HIViewComponentPeer* currentlyFocusedPeer = 0;
  219767. static int currentModifiers = 0;
  219768. static void updateModifiers (EventRef theEvent)
  219769. {
  219770. currentModifiers &= ~ (ModifierKeys::shiftModifier | ModifierKeys::ctrlModifier
  219771. | ModifierKeys::altModifier | ModifierKeys::commandModifier);
  219772. UInt32 m;
  219773. if (theEvent != 0)
  219774. GetEventParameter (theEvent, kEventParamKeyModifiers, typeUInt32, 0, sizeof(m), 0, &m);
  219775. else
  219776. m = GetCurrentEventKeyModifiers();
  219777. if ((m & (shiftKey | rightShiftKey)) != 0)
  219778. currentModifiers |= ModifierKeys::shiftModifier;
  219779. if ((m & (controlKey | rightControlKey)) != 0)
  219780. currentModifiers |= ModifierKeys::ctrlModifier;
  219781. if ((m & (optionKey | rightOptionKey)) != 0)
  219782. currentModifiers |= ModifierKeys::altModifier;
  219783. if ((m & cmdKey) != 0)
  219784. currentModifiers |= ModifierKeys::commandModifier;
  219785. }
  219786. void ModifierKeys::updateCurrentModifiers() throw()
  219787. {
  219788. currentModifierFlags = currentModifiers;
  219789. }
  219790. static int64 getEventTime (EventRef event)
  219791. {
  219792. const int64 millis = (int64) (1000.0 * (event != 0 ? GetEventTime (event)
  219793. : GetCurrentEventTime()));
  219794. static int64 offset = 0;
  219795. if (offset == 0)
  219796. offset = Time::currentTimeMillis() - millis;
  219797. return offset + millis;
  219798. }
  219799. class MacBitmapImage : public Image
  219800. {
  219801. public:
  219802. CGColorSpaceRef colourspace;
  219803. CGDataProviderRef provider;
  219804. MacBitmapImage (const PixelFormat format_,
  219805. const int w, const int h, const bool clearImage)
  219806. : Image (format_, w, h)
  219807. {
  219808. jassert (format_ == RGB || format_ == ARGB);
  219809. pixelStride = (format_ == RGB) ? 3 : 4;
  219810. lineStride = (w * pixelStride + 3) & ~3;
  219811. const int imageSize = lineStride * h;
  219812. if (clearImage)
  219813. imageData = (uint8*) juce_calloc (imageSize);
  219814. else
  219815. imageData = (uint8*) juce_malloc (imageSize);
  219816. //colourspace = CGColorSpaceCreateWithName (kCGColorSpaceUserRGB);
  219817. CMProfileRef prof;
  219818. CMGetSystemProfile (&prof);
  219819. colourspace = CGColorSpaceCreateWithPlatformColorSpace (prof);
  219820. provider = CGDataProviderCreateWithData (0, imageData, h * lineStride, 0);
  219821. CMCloseProfile (prof);
  219822. }
  219823. MacBitmapImage::~MacBitmapImage()
  219824. {
  219825. CGDataProviderRelease (provider);
  219826. CGColorSpaceRelease (colourspace);
  219827. juce_free (imageData);
  219828. imageData = 0; // to stop the base class freeing this
  219829. }
  219830. void blitToContext (CGContextRef context, const float dx, const float dy)
  219831. {
  219832. CGImageRef tempImage = CGImageCreate (getWidth(), getHeight(),
  219833. 8, pixelStride << 3, lineStride, colourspace,
  219834. #if MACOS_10_3_OR_EARLIER || JUCE_BIG_ENDIAN
  219835. hasAlphaChannel() ? kCGImageAlphaPremultipliedFirst
  219836. : kCGImageAlphaNone,
  219837. #else
  219838. hasAlphaChannel() ? kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst
  219839. : kCGImageAlphaNone,
  219840. #endif
  219841. provider, 0, false,
  219842. kCGRenderingIntentDefault);
  219843. HIRect r;
  219844. r.origin.x = dx;
  219845. r.origin.y = dy;
  219846. r.size.width = (float) getWidth();
  219847. r.size.height = (float) getHeight();
  219848. HIViewDrawCGImage (context, &r, tempImage);
  219849. CGImageRelease (tempImage);
  219850. }
  219851. juce_UseDebuggingNewOperator
  219852. };
  219853. class MouseCheckTimer : private Timer,
  219854. private DeletedAtShutdown
  219855. {
  219856. public:
  219857. MouseCheckTimer()
  219858. : lastX (0),
  219859. lastY (0)
  219860. {
  219861. lastPeerUnderMouse = 0;
  219862. resetMouseMoveChecker();
  219863. #if ! MACOS_10_2_OR_EARLIER
  219864. // Just putting this in here because it's a convenient object that'll get deleted at shutdown
  219865. CGDisplayRegisterReconfigurationCallback (&displayChangeCallback, 0);
  219866. #endif
  219867. }
  219868. ~MouseCheckTimer()
  219869. {
  219870. #if ! MACOS_10_2_OR_EARLIER
  219871. CGDisplayRemoveReconfigurationCallback (&displayChangeCallback, 0);
  219872. #endif
  219873. clearSingletonInstance();
  219874. }
  219875. juce_DeclareSingleton_SingleThreaded_Minimal (MouseCheckTimer)
  219876. bool hasEverHadAMouseMove;
  219877. void moved (HIViewComponentPeer* const peer)
  219878. {
  219879. if (hasEverHadAMouseMove)
  219880. startTimer (200);
  219881. lastPeerUnderMouse = peer;
  219882. }
  219883. void resetMouseMoveChecker()
  219884. {
  219885. hasEverHadAMouseMove = false;
  219886. startTimer (1000 / 16);
  219887. }
  219888. void timerCallback();
  219889. private:
  219890. HIViewComponentPeer* lastPeerUnderMouse;
  219891. int lastX, lastY;
  219892. #if ! MACOS_10_2_OR_EARLIER
  219893. static void displayChangeCallback (CGDirectDisplayID, CGDisplayChangeSummaryFlags flags, void*)
  219894. {
  219895. Desktop::getInstance().refreshMonitorSizes();
  219896. }
  219897. #endif
  219898. };
  219899. juce_ImplementSingleton_SingleThreaded (MouseCheckTimer)
  219900. #if JUCE_QUICKTIME
  219901. extern void OfferMouseClickToQuickTime (WindowRef window, ::Point where, long when, long modifiers,
  219902. Component* topLevelComp);
  219903. #endif
  219904. class HIViewComponentPeer : public ComponentPeer,
  219905. private Timer
  219906. {
  219907. public:
  219908. HIViewComponentPeer (Component* const component,
  219909. const int windowStyleFlags,
  219910. HIViewRef viewToAttachTo)
  219911. : ComponentPeer (component, windowStyleFlags),
  219912. fullScreen (false),
  219913. isCompositingWindow (false),
  219914. windowRef (0),
  219915. viewRef (0)
  219916. {
  219917. repainter = new RepaintManager (this);
  219918. eventHandlerRef = 0;
  219919. if (viewToAttachTo != 0)
  219920. {
  219921. isSharedWindow = true;
  219922. }
  219923. else
  219924. {
  219925. isSharedWindow = false;
  219926. WindowRef newWindow = createNewWindow (windowStyleFlags);
  219927. GetRootControl (newWindow, (ControlRef*) &viewToAttachTo);
  219928. jassert (viewToAttachTo != 0);
  219929. HIViewRef growBox = 0;
  219930. HIViewFindByID (HIViewGetRoot (newWindow), kHIViewWindowGrowBoxID, &growBox);
  219931. if (growBox != 0)
  219932. HIGrowBoxViewSetTransparent (growBox, true);
  219933. }
  219934. createNewHIView();
  219935. HIViewAddSubview (viewToAttachTo, viewRef);
  219936. HIViewSetVisible (viewRef, component->isVisible());
  219937. setTitle (component->getName());
  219938. if (component->isVisible() && ! isSharedWindow)
  219939. {
  219940. ShowWindow (windowRef);
  219941. ActivateWindow (windowRef, component->getWantsKeyboardFocus());
  219942. }
  219943. }
  219944. ~HIViewComponentPeer()
  219945. {
  219946. minimisedWindows.removeValue (windowRef);
  219947. if (IsValidWindowPtr (windowRef))
  219948. {
  219949. if (! isSharedWindow)
  219950. {
  219951. CFRelease (viewRef);
  219952. viewRef = 0;
  219953. DisposeWindow (windowRef);
  219954. }
  219955. else
  219956. {
  219957. if (eventHandlerRef != 0)
  219958. RemoveEventHandler (eventHandlerRef);
  219959. CFRelease (viewRef);
  219960. viewRef = 0;
  219961. }
  219962. windowRef = 0;
  219963. }
  219964. if (currentlyFocusedPeer == this)
  219965. currentlyFocusedPeer = 0;
  219966. delete repainter;
  219967. }
  219968. void* getNativeHandle() const
  219969. {
  219970. return windowRef;
  219971. }
  219972. void setVisible (bool shouldBeVisible)
  219973. {
  219974. HIViewSetVisible (viewRef, shouldBeVisible);
  219975. if ((! isSharedWindow) && IsValidWindowPtr (windowRef))
  219976. {
  219977. if (shouldBeVisible)
  219978. ShowWindow (windowRef);
  219979. else
  219980. HideWindow (windowRef);
  219981. resizeViewToFitWindow();
  219982. // If nothing else is focused, then grab the focus too
  219983. if (shouldBeVisible
  219984. && Component::getCurrentlyFocusedComponent() == 0
  219985. && Process::isForegroundProcess())
  219986. {
  219987. component->toFront (true);
  219988. }
  219989. }
  219990. }
  219991. void setTitle (const String& title)
  219992. {
  219993. if ((! isSharedWindow) && IsValidWindowPtr (windowRef))
  219994. {
  219995. CFStringRef t = PlatformUtilities::juceStringToCFString (title);
  219996. SetWindowTitleWithCFString (windowRef, t);
  219997. CFRelease (t);
  219998. }
  219999. }
  220000. void setPosition (int x, int y)
  220001. {
  220002. if (isSharedWindow)
  220003. {
  220004. HIViewPlaceInSuperviewAt (viewRef, x, y);
  220005. }
  220006. else if (IsValidWindowPtr (windowRef))
  220007. {
  220008. Rect r;
  220009. GetWindowBounds (windowRef, windowRegionToUse, &r);
  220010. r.right += x - r.left;
  220011. r.bottom += y - r.top;
  220012. r.left = x;
  220013. r.top = y;
  220014. SetWindowBounds (windowRef, windowRegionToUse, &r);
  220015. }
  220016. }
  220017. void setSize (int w, int h)
  220018. {
  220019. w = jmax (0, w);
  220020. h = jmax (0, h);
  220021. if (w != getComponent()->getWidth()
  220022. || h != getComponent()->getHeight())
  220023. {
  220024. repainter->repaint (0, 0, w, h);
  220025. }
  220026. if (isSharedWindow)
  220027. {
  220028. HIRect r;
  220029. HIViewGetFrame (viewRef, &r);
  220030. r.size.width = (float) w;
  220031. r.size.height = (float) h;
  220032. HIViewSetFrame (viewRef, &r);
  220033. }
  220034. else if (IsValidWindowPtr (windowRef))
  220035. {
  220036. Rect r;
  220037. GetWindowBounds (windowRef, windowRegionToUse, &r);
  220038. r.right = r.left + w;
  220039. r.bottom = r.top + h;
  220040. SetWindowBounds (windowRef, windowRegionToUse, &r);
  220041. }
  220042. }
  220043. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  220044. {
  220045. fullScreen = isNowFullScreen;
  220046. w = jmax (0, w);
  220047. h = jmax (0, h);
  220048. if (w != getComponent()->getWidth()
  220049. || h != getComponent()->getHeight())
  220050. {
  220051. repainter->repaint (0, 0, w, h);
  220052. }
  220053. if (isSharedWindow)
  220054. {
  220055. HIRect r;
  220056. r.origin.x = (float) x;
  220057. r.origin.y = (float) y;
  220058. r.size.width = (float) w;
  220059. r.size.height = (float) h;
  220060. HIViewSetFrame (viewRef, &r);
  220061. }
  220062. else if (IsValidWindowPtr (windowRef))
  220063. {
  220064. Rect r;
  220065. r.left = x;
  220066. r.top = y;
  220067. r.right = x + w;
  220068. r.bottom = y + h;
  220069. SetWindowBounds (windowRef, windowRegionToUse, &r);
  220070. }
  220071. }
  220072. void getBounds (int& x, int& y, int& w, int& h, const bool global) const
  220073. {
  220074. HIRect hiViewPos;
  220075. HIViewGetFrame (viewRef, &hiViewPos);
  220076. if (global)
  220077. {
  220078. HIViewRef content = 0;
  220079. HIViewFindByID (HIViewGetRoot (windowRef), kHIViewWindowContentID, &content);
  220080. HIPoint p = { 0.0f, 0.0f };
  220081. HIViewConvertPoint (&p, viewRef, content);
  220082. x = (int) p.x;
  220083. y = (int) p.y;
  220084. if (IsValidWindowPtr (windowRef))
  220085. {
  220086. Rect windowPos;
  220087. GetWindowBounds (windowRef, kWindowContentRgn, &windowPos);
  220088. x += windowPos.left;
  220089. y += windowPos.top;
  220090. }
  220091. }
  220092. else
  220093. {
  220094. x = (int) hiViewPos.origin.x;
  220095. y = (int) hiViewPos.origin.y;
  220096. }
  220097. w = (int) hiViewPos.size.width;
  220098. h = (int) hiViewPos.size.height;
  220099. }
  220100. void getBounds (int& x, int& y, int& w, int& h) const
  220101. {
  220102. getBounds (x, y, w, h, ! isSharedWindow);
  220103. }
  220104. int getScreenX() const
  220105. {
  220106. int x, y, w, h;
  220107. getBounds (x, y, w, h, true);
  220108. return x;
  220109. }
  220110. int getScreenY() const
  220111. {
  220112. int x, y, w, h;
  220113. getBounds (x, y, w, h, true);
  220114. return y;
  220115. }
  220116. void relativePositionToGlobal (int& x, int& y)
  220117. {
  220118. int wx, wy, ww, wh;
  220119. getBounds (wx, wy, ww, wh, true);
  220120. x += wx;
  220121. y += wy;
  220122. }
  220123. void globalPositionToRelative (int& x, int& y)
  220124. {
  220125. int wx, wy, ww, wh;
  220126. getBounds (wx, wy, ww, wh, true);
  220127. x -= wx;
  220128. y -= wy;
  220129. }
  220130. void setMinimised (bool shouldBeMinimised)
  220131. {
  220132. if (! isSharedWindow)
  220133. setWindowMinimised (windowRef, shouldBeMinimised);
  220134. }
  220135. bool isMinimised() const
  220136. {
  220137. return minimisedWindows.contains (windowRef);
  220138. }
  220139. void setFullScreen (bool shouldBeFullScreen)
  220140. {
  220141. if (! isSharedWindow)
  220142. {
  220143. Rectangle r (lastNonFullscreenBounds);
  220144. setMinimised (false);
  220145. if (fullScreen != shouldBeFullScreen)
  220146. {
  220147. if (shouldBeFullScreen)
  220148. r = Desktop::getInstance().getMainMonitorArea();
  220149. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  220150. if (r != getComponent()->getBounds() && ! r.isEmpty())
  220151. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220152. }
  220153. }
  220154. }
  220155. bool isFullScreen() const
  220156. {
  220157. return fullScreen;
  220158. }
  220159. bool contains (int x, int y, bool trueIfInAChildWindow) const
  220160. {
  220161. if (((unsigned int) x) >= (unsigned int) component->getWidth()
  220162. || ((unsigned int) y) >= (unsigned int) component->getHeight()
  220163. || ! IsValidWindowPtr (windowRef))
  220164. return false;
  220165. Rect r;
  220166. GetWindowBounds (windowRef, windowRegionToUse, &r);
  220167. ::Point p;
  220168. p.h = r.left + x;
  220169. p.v = r.top + y;
  220170. WindowRef ref2 = 0;
  220171. FindWindow (p, &ref2);
  220172. if (windowRef != ref2)
  220173. return false;
  220174. if (trueIfInAChildWindow)
  220175. return true;
  220176. HIPoint p2;
  220177. p2.x = (float) x;
  220178. p2.y = (float) y;
  220179. HIViewRef hit;
  220180. HIViewGetSubviewHit (viewRef, &p2, true, &hit);
  220181. return hit == 0 || hit == viewRef;
  220182. }
  220183. const BorderSize getFrameSize() const
  220184. {
  220185. return BorderSize();
  220186. }
  220187. bool setAlwaysOnTop (bool alwaysOnTop)
  220188. {
  220189. // can't do this so return false and let the component create a new window
  220190. return false;
  220191. }
  220192. void toFront (bool makeActiveWindow)
  220193. {
  220194. makeActiveWindow = makeActiveWindow
  220195. && component->isValidComponent()
  220196. && (component->getWantsKeyboardFocus()
  220197. || component->isCurrentlyModal());
  220198. if (windowRef != FrontWindow()
  220199. || (makeActiveWindow && ! IsWindowActive (windowRef))
  220200. || ! Process::isForegroundProcess())
  220201. {
  220202. if (! Process::isForegroundProcess())
  220203. {
  220204. ProcessSerialNumber psn;
  220205. GetCurrentProcess (&psn);
  220206. SetFrontProcessWithOptions (&psn, kSetFrontProcessFrontWindowOnly);
  220207. }
  220208. if (IsValidWindowPtr (windowRef))
  220209. {
  220210. if (makeActiveWindow)
  220211. {
  220212. SelectWindow (windowRef);
  220213. SetUserFocusWindow (windowRef);
  220214. HIViewAdvanceFocus (viewRef, 0);
  220215. }
  220216. else
  220217. {
  220218. BringToFront (windowRef);
  220219. }
  220220. handleBroughtToFront();
  220221. }
  220222. }
  220223. }
  220224. void toBehind (ComponentPeer* other)
  220225. {
  220226. HIViewComponentPeer* const otherWindow = dynamic_cast <HIViewComponentPeer*> (other);
  220227. if (other != 0 && windowRef != 0 && otherWindow->windowRef != 0)
  220228. {
  220229. if (windowRef == otherWindow->windowRef)
  220230. {
  220231. HIViewSetZOrder (viewRef, kHIViewZOrderBelow, otherWindow->viewRef);
  220232. }
  220233. else
  220234. {
  220235. SendBehind (windowRef, otherWindow->windowRef);
  220236. }
  220237. }
  220238. }
  220239. void setIcon (const Image& /*newIcon*/)
  220240. {
  220241. // to do..
  220242. }
  220243. void viewFocusGain()
  220244. {
  220245. const MessageManagerLock messLock;
  220246. if (currentlyFocusedPeer != this)
  220247. {
  220248. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  220249. currentlyFocusedPeer->handleFocusLoss();
  220250. currentlyFocusedPeer = this;
  220251. handleFocusGain();
  220252. }
  220253. }
  220254. void viewFocusLoss()
  220255. {
  220256. if (currentlyFocusedPeer == this)
  220257. {
  220258. currentlyFocusedPeer = 0;
  220259. handleFocusLoss();
  220260. }
  220261. }
  220262. bool isFocused() const
  220263. {
  220264. return windowRef == GetUserFocusWindow()
  220265. && HIViewSubtreeContainsFocus (viewRef);
  220266. }
  220267. void grabFocus()
  220268. {
  220269. if ((! isFocused()) && IsValidWindowPtr (windowRef))
  220270. {
  220271. SetUserFocusWindow (windowRef);
  220272. HIViewAdvanceFocus (viewRef, 0);
  220273. }
  220274. }
  220275. void textInputRequired (int /*x*/, int /*y*/)
  220276. {
  220277. }
  220278. void repaint (int x, int y, int w, int h)
  220279. {
  220280. if (Rectangle::intersectRectangles (x, y, w, h,
  220281. 0, 0,
  220282. getComponent()->getWidth(),
  220283. getComponent()->getHeight()))
  220284. {
  220285. if ((getStyleFlags() & windowRepaintedExplictly) == 0)
  220286. {
  220287. if (isCompositingWindow)
  220288. {
  220289. #if MACOS_10_3_OR_EARLIER
  220290. RgnHandle rgn = NewRgn();
  220291. SetRectRgn (rgn, x, y, x + w, y + h);
  220292. HIViewSetNeedsDisplayInRegion (viewRef, rgn, true);
  220293. DisposeRgn (rgn);
  220294. #else
  220295. HIRect r;
  220296. r.origin.x = x;
  220297. r.origin.y = y;
  220298. r.size.width = w;
  220299. r.size.height = h;
  220300. HIViewSetNeedsDisplayInRect (viewRef, &r, true);
  220301. #endif
  220302. }
  220303. else
  220304. {
  220305. if (! isTimerRunning())
  220306. startTimer (20);
  220307. }
  220308. }
  220309. repainter->repaint (x, y, w, h);
  220310. }
  220311. }
  220312. void timerCallback()
  220313. {
  220314. performAnyPendingRepaintsNow();
  220315. }
  220316. void performAnyPendingRepaintsNow()
  220317. {
  220318. stopTimer();
  220319. if (component->isVisible())
  220320. {
  220321. #if MACOS_10_2_OR_EARLIER
  220322. if (! isCompositingWindow)
  220323. {
  220324. Rect w;
  220325. GetWindowBounds (windowRef, windowRegionToUse, &w);
  220326. const int offsetInWindowX = component->getScreenX() - getScreenX();
  220327. const int offsetInWindowY = component->getScreenY() - getScreenY();
  220328. for (RectangleList::Iterator i (repainter->getRegionsNeedingRepaint()); i.next();)
  220329. {
  220330. const Rectangle& r = *i.getRectangle();
  220331. w.left = offsetInWindowX + r.getX();
  220332. w.top = offsetInWindowY + r.getY();
  220333. w.right = offsetInWindowX + r.getRight();
  220334. w.bottom = offsetInWindowY + r.getBottom();
  220335. InvalWindowRect (windowRef, &w);
  220336. }
  220337. }
  220338. else
  220339. {
  220340. EventRef theEvent;
  220341. EventTypeSpec eventTypes[1];
  220342. eventTypes[0].eventClass = kEventClassControl;
  220343. eventTypes[0].eventKind = kEventControlDraw;
  220344. int n = 3;
  220345. while (--n >= 0
  220346. && ReceiveNextEvent (1, eventTypes, kEventDurationNoWait, true, &theEvent) == noErr)
  220347. {
  220348. if (GetEventClass (theEvent) == kEventClassAppleEvent)
  220349. {
  220350. EventRecord eventRec;
  220351. if (ConvertEventRefToEventRecord (theEvent, &eventRec))
  220352. AEProcessAppleEvent (&eventRec);
  220353. }
  220354. else
  220355. {
  220356. EventTargetRef theTarget = GetEventDispatcherTarget();
  220357. SendEventToEventTarget (theEvent, theTarget);
  220358. }
  220359. ReleaseEvent (theEvent);
  220360. }
  220361. }
  220362. #else
  220363. if (HIViewGetNeedsDisplay (viewRef) || repainter->isRepaintNeeded())
  220364. HIViewRender (viewRef);
  220365. #endif
  220366. }
  220367. }
  220368. juce_UseDebuggingNewOperator
  220369. WindowRef windowRef;
  220370. HIViewRef viewRef;
  220371. private:
  220372. EventHandlerRef eventHandlerRef;
  220373. bool fullScreen, isSharedWindow, isCompositingWindow;
  220374. StringArray dragAndDropFiles;
  220375. class RepaintManager : public Timer
  220376. {
  220377. public:
  220378. RepaintManager (HIViewComponentPeer* const peer_)
  220379. : peer (peer_),
  220380. image (0)
  220381. {
  220382. }
  220383. ~RepaintManager()
  220384. {
  220385. delete image;
  220386. }
  220387. void timerCallback()
  220388. {
  220389. stopTimer();
  220390. deleteAndZero (image);
  220391. }
  220392. void repaint (int x, int y, int w, int h)
  220393. {
  220394. regionsNeedingRepaint.add (x, y, w, h);
  220395. }
  220396. bool isRepaintNeeded() const throw()
  220397. {
  220398. return ! regionsNeedingRepaint.isEmpty();
  220399. }
  220400. void repaintAnyRemainingRegions()
  220401. {
  220402. // if any regions have been invaldated during the paint callback,
  220403. // we need to repaint them explicitly because the mac throws this
  220404. // stuff away
  220405. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  220406. {
  220407. const Rectangle& r = *i.getRectangle();
  220408. peer->repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  220409. }
  220410. }
  220411. void paint (CGContextRef cgContext, int x, int y, int w, int h)
  220412. {
  220413. if (w > 0 && h > 0)
  220414. {
  220415. bool refresh = false;
  220416. int imW = image != 0 ? image->getWidth() : 0;
  220417. int imH = image != 0 ? image->getHeight() : 0;
  220418. if (imW < w || imH < h)
  220419. {
  220420. imW = jmin (peer->getComponent()->getWidth(), (w + 31) & ~31);
  220421. imH = jmin (peer->getComponent()->getHeight(), (h + 31) & ~31);
  220422. delete image;
  220423. image = new MacBitmapImage (peer->getComponent()->isOpaque() ? Image::RGB
  220424. : Image::ARGB,
  220425. imW, imH, false);
  220426. refresh = true;
  220427. }
  220428. else if (imageX > x || imageY > y
  220429. || imageX + imW < x + w
  220430. || imageY + imH < y + h)
  220431. {
  220432. refresh = true;
  220433. }
  220434. if (refresh)
  220435. {
  220436. regionsNeedingRepaint.clear();
  220437. regionsNeedingRepaint.addWithoutMerging (Rectangle (x, y, imW, imH));
  220438. imageX = x;
  220439. imageY = y;
  220440. }
  220441. LowLevelGraphicsSoftwareRenderer context (*image);
  220442. context.setOrigin (-imageX, -imageY);
  220443. if (context.reduceClipRegion (regionsNeedingRepaint))
  220444. {
  220445. regionsNeedingRepaint.clear();
  220446. if (! peer->getComponent()->isOpaque())
  220447. {
  220448. for (RectangleList::Iterator i (*context.getRawClipRegion()); i.next();)
  220449. {
  220450. const Rectangle& r = *i.getRectangle();
  220451. image->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  220452. }
  220453. }
  220454. regionsNeedingRepaint.clear();
  220455. peer->clearMaskedRegion();
  220456. peer->handlePaint (context);
  220457. }
  220458. else
  220459. {
  220460. regionsNeedingRepaint.clear();
  220461. }
  220462. if (! peer->maskedRegion.isEmpty())
  220463. {
  220464. RectangleList total (Rectangle (x, y, w, h));
  220465. total.subtract (peer->maskedRegion);
  220466. CGRect* rects = (CGRect*) juce_malloc (sizeof (CGRect) * total.getNumRectangles());
  220467. int n = 0;
  220468. for (RectangleList::Iterator i (total); i.next();)
  220469. {
  220470. const Rectangle& r = *i.getRectangle();
  220471. rects[n].origin.x = (int) r.getX();
  220472. rects[n].origin.y = (int) r.getY();
  220473. rects[n].size.width = roundFloatToInt (r.getWidth());
  220474. rects[n++].size.height = roundFloatToInt (r.getHeight());
  220475. }
  220476. CGContextClipToRects (cgContext, rects, n);
  220477. juce_free (rects);
  220478. }
  220479. if (peer->isSharedWindow)
  220480. {
  220481. CGRect clip;
  220482. clip.origin.x = x;
  220483. clip.origin.y = y;
  220484. clip.size.width = jmin (w, peer->getComponent()->getWidth() - x);
  220485. clip.size.height = jmin (h, peer->getComponent()->getHeight() - y);
  220486. CGContextClipToRect (cgContext, clip);
  220487. }
  220488. image->blitToContext (cgContext, imageX, imageY);
  220489. }
  220490. startTimer (3000);
  220491. }
  220492. private:
  220493. HIViewComponentPeer* const peer;
  220494. MacBitmapImage* image;
  220495. int imageX, imageY;
  220496. RectangleList regionsNeedingRepaint;
  220497. RepaintManager (const RepaintManager&);
  220498. const RepaintManager& operator= (const RepaintManager&);
  220499. };
  220500. RepaintManager* repainter;
  220501. friend class RepaintManager;
  220502. static OSStatus handleFrameRepaintEvent (EventHandlerCallRef myHandler,
  220503. EventRef theEvent,
  220504. void* userData)
  220505. {
  220506. // don't draw the frame..
  220507. return noErr;
  220508. }
  220509. OSStatus handleKeyEvent (EventRef theEvent, juce_wchar textCharacter)
  220510. {
  220511. updateModifiers (theEvent);
  220512. UniChar unicodeChars [4];
  220513. zeromem (unicodeChars, sizeof (unicodeChars));
  220514. GetEventParameter (theEvent, kEventParamKeyUnicodes, typeUnicodeText, 0, sizeof (unicodeChars), 0, unicodeChars);
  220515. int keyCode = (int) (unsigned int) unicodeChars[0];
  220516. UInt32 rawKey = 0;
  220517. GetEventParameter (theEvent, kEventParamKeyCode, typeUInt32, 0, sizeof (UInt32), 0, &rawKey);
  220518. if ((currentModifiers & ModifierKeys::ctrlModifier) != 0
  220519. && keyCode >= 1 && keyCode <= 26)
  220520. {
  220521. keyCode += ('A' - 1);
  220522. }
  220523. else
  220524. {
  220525. static const int keyTranslations[] =
  220526. {
  220527. 0, 's', 'd', 'f', 'h', 'g', 'z', 'x', 'c', 'v', 0xa7, 'b',
  220528. 'q', 'w', 'e', 'r', 'y', 't', '1', '2', '3', '4', '6', '5',
  220529. '=', '9', '7', '-', '8', '0', ']', 'o', 'u', '[', 'i', 'p',
  220530. KeyPress::returnKey, 'l', 'j', '\'', 'k', ';', '\\', ',', '/',
  220531. 'n', 'm', '.', 0, KeyPress::spaceKey, '`', KeyPress::backspaceKey, 0, 0, 0, 0,
  220532. 0, 0, 0, 0, 0, 0, 0, 0, 0, KeyPress::numberPadDecimalPoint,
  220533. 0, KeyPress::numberPadMultiply, 0, KeyPress::numberPadAdd,
  220534. 0, KeyPress::numberPadDelete, 0, 0, 0, KeyPress::numberPadDivide, KeyPress::returnKey,
  220535. 0, KeyPress::numberPadSubtract, 0, 0, KeyPress::numberPadEquals, KeyPress::numberPad0,
  220536. KeyPress::numberPad1, KeyPress::numberPad2, KeyPress::numberPad3,
  220537. KeyPress::numberPad4, KeyPress::numberPad5, KeyPress::numberPad6,
  220538. KeyPress::numberPad7, 0, KeyPress::numberPad8, KeyPress::numberPad9,
  220539. 0, 0, 0, KeyPress::F5Key, KeyPress::F6Key, KeyPress::F7Key, KeyPress::F3Key,
  220540. KeyPress::F8Key, KeyPress::F9Key, 0, KeyPress::F11Key, 0, KeyPress::F13Key,
  220541. KeyPress::F16Key, KeyPress::F14Key, 0, KeyPress::F10Key, 0, KeyPress::F12Key,
  220542. 0, KeyPress::F15Key, 0, KeyPress::homeKey, KeyPress::pageUpKey, 0, KeyPress::F4Key,
  220543. KeyPress::endKey, KeyPress::F2Key, KeyPress::pageDownKey, KeyPress::F1Key,
  220544. KeyPress::leftKey, KeyPress::rightKey, KeyPress::downKey, KeyPress::upKey, 0
  220545. };
  220546. if (((unsigned int) rawKey) < (unsigned int) numElementsInArray (keyTranslations)
  220547. && keyTranslations [rawKey] != 0)
  220548. {
  220549. keyCode = keyTranslations [rawKey];
  220550. }
  220551. if ((rawKey == 0 && textCharacter != 0)
  220552. || (CharacterFunctions::isLetterOrDigit ((juce_wchar) keyCode)
  220553. && CharacterFunctions::isLetterOrDigit (textCharacter))) // correction for azerty-type layouts..
  220554. {
  220555. keyCode = CharacterFunctions::toLowerCase (textCharacter);
  220556. }
  220557. }
  220558. if ((currentModifiers & (ModifierKeys::commandModifier | ModifierKeys::ctrlModifier)) != 0)
  220559. textCharacter = 0;
  220560. static juce_wchar lastTextCharacter = 0;
  220561. switch (GetEventKind (theEvent))
  220562. {
  220563. case kEventRawKeyDown:
  220564. {
  220565. keysCurrentlyDown.addIfNotAlreadyThere ((void*) keyCode);
  220566. lastTextCharacter = textCharacter;
  220567. const bool used1 = handleKeyUpOrDown();
  220568. const bool used2 = handleKeyPress (keyCode, textCharacter);
  220569. if (used1 || used2)
  220570. return noErr;
  220571. break;
  220572. }
  220573. case kEventRawKeyUp:
  220574. keysCurrentlyDown.removeValue ((void*) keyCode);
  220575. lastTextCharacter = 0;
  220576. if (handleKeyUpOrDown())
  220577. return noErr;
  220578. break;
  220579. case kEventRawKeyRepeat:
  220580. if (handleKeyPress (keyCode, lastTextCharacter))
  220581. return noErr;
  220582. break;
  220583. case kEventRawKeyModifiersChanged:
  220584. handleModifierKeysChange();
  220585. break;
  220586. default:
  220587. jassertfalse
  220588. break;
  220589. }
  220590. return eventNotHandledErr;
  220591. }
  220592. OSStatus handleTextInputEvent (EventRef theEvent)
  220593. {
  220594. UInt32 numBytesRequired = 0;
  220595. GetEventParameter (theEvent, kEventParamTextInputSendText, typeUnicodeText, 0, 0, &numBytesRequired, 0);
  220596. MemoryBlock buffer (numBytesRequired, true);
  220597. UniChar* const uc = (UniChar*) buffer.getData();
  220598. GetEventParameter (theEvent, kEventParamTextInputSendText, typeUnicodeText, 0, numBytesRequired, &numBytesRequired, uc);
  220599. EventRef originalEvent;
  220600. GetEventParameter (theEvent, kEventParamTextInputSendKeyboardEvent, typeEventRef, 0, sizeof (originalEvent), 0, &originalEvent);
  220601. OSStatus res = noErr;
  220602. for (int i = 0; i < numBytesRequired / sizeof (UniChar); ++i)
  220603. res = handleKeyEvent (originalEvent, (juce_wchar) uc[i]);
  220604. return res;
  220605. }
  220606. OSStatus handleMouseEvent (EventHandlerCallRef callRef, EventRef theEvent)
  220607. {
  220608. MouseCheckTimer::getInstance()->moved (this);
  220609. ::Point where;
  220610. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof (::Point), 0, &where);
  220611. int x = where.h;
  220612. int y = where.v;
  220613. globalPositionToRelative (x, y);
  220614. int64 time = getEventTime (theEvent);
  220615. switch (GetEventKind (theEvent))
  220616. {
  220617. case kEventMouseMoved:
  220618. MouseCheckTimer::getInstance()->hasEverHadAMouseMove = true;
  220619. updateModifiers (theEvent);
  220620. handleMouseMove (x, y, time);
  220621. break;
  220622. case kEventMouseDragged:
  220623. updateModifiers (theEvent);
  220624. handleMouseDrag (x, y, time);
  220625. break;
  220626. case kEventMouseDown:
  220627. {
  220628. if (! Process::isForegroundProcess())
  220629. {
  220630. ProcessSerialNumber psn;
  220631. GetCurrentProcess (&psn);
  220632. SetFrontProcessWithOptions (&psn, kSetFrontProcessFrontWindowOnly);
  220633. toFront (true);
  220634. }
  220635. #if JUCE_QUICKTIME
  220636. {
  220637. long mods;
  220638. GetEventParameter (theEvent, kEventParamKeyModifiers, typeUInt32, 0, sizeof (mods), 0, &mods);
  220639. ::Point where;
  220640. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof (::Point), 0, &where);
  220641. OfferMouseClickToQuickTime (windowRef, where, EventTimeToTicks (GetEventTime (theEvent)), mods, component);
  220642. }
  220643. #endif
  220644. if (component->isBroughtToFrontOnMouseClick()
  220645. && ! component->isCurrentlyBlockedByAnotherModalComponent())
  220646. {
  220647. //ActivateWindow (windowRef, true);
  220648. SelectWindow (windowRef);
  220649. }
  220650. EventMouseButton button;
  220651. GetEventParameter (theEvent, kEventParamMouseButton, typeMouseButton, 0, sizeof (EventMouseButton), 0, &button);
  220652. // need to clear all these flags because sometimes the mac can swallow (right) mouse-up events and
  220653. // this makes a button get stuck down. Since there's no other way to tell what buttons are down,
  220654. // this is all I can think of doing about it..
  220655. currentModifiers &= ~(ModifierKeys::leftButtonModifier | ModifierKeys::rightButtonModifier | ModifierKeys::middleButtonModifier);
  220656. if (button == kEventMouseButtonPrimary)
  220657. currentModifiers |= ModifierKeys::leftButtonModifier;
  220658. else if (button == kEventMouseButtonSecondary)
  220659. currentModifiers |= ModifierKeys::rightButtonModifier;
  220660. else if (button == kEventMouseButtonTertiary)
  220661. currentModifiers |= ModifierKeys::middleButtonModifier;
  220662. updateModifiers (theEvent);
  220663. juce_currentMouseTrackingPeer = this; // puts the message dispatcher into mouse-tracking mode..
  220664. handleMouseDown (x, y, time);
  220665. break;
  220666. }
  220667. case kEventMouseUp:
  220668. {
  220669. const int oldModifiers = currentModifiers;
  220670. EventMouseButton button;
  220671. GetEventParameter (theEvent, kEventParamMouseButton, typeMouseButton, 0, sizeof (EventMouseButton), 0, &button);
  220672. if (button == kEventMouseButtonPrimary)
  220673. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  220674. else if (button == kEventMouseButtonSecondary)
  220675. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  220676. updateModifiers (theEvent);
  220677. juce_currentMouseTrackingPeer = 0;
  220678. handleMouseUp (oldModifiers, x, y, time);
  220679. break;
  220680. }
  220681. case kEventMouseWheelMoved:
  220682. {
  220683. EventMouseWheelAxis axis;
  220684. GetEventParameter (theEvent, kEventParamMouseWheelAxis, typeMouseWheelAxis, 0, sizeof (axis), 0, &axis);
  220685. SInt32 delta;
  220686. GetEventParameter (theEvent, kEventParamMouseWheelDelta,
  220687. typeLongInteger, 0, sizeof (delta), 0, &delta);
  220688. updateModifiers (theEvent);
  220689. handleMouseWheel (axis == kEventMouseWheelAxisX ? delta * 10 : 0,
  220690. axis == kEventMouseWheelAxisX ? 0 : delta * 10,
  220691. time);
  220692. break;
  220693. }
  220694. }
  220695. return noErr;
  220696. }
  220697. void doDragDropEnter (EventRef theEvent)
  220698. {
  220699. updateDragAndDropFileList (theEvent);
  220700. if (dragAndDropFiles.size() > 0)
  220701. {
  220702. int x, y;
  220703. component->getMouseXYRelative (x, y);
  220704. handleFileDragMove (dragAndDropFiles, x, y);
  220705. }
  220706. }
  220707. void doDragDropMove (EventRef theEvent)
  220708. {
  220709. if (dragAndDropFiles.size() > 0)
  220710. {
  220711. int x, y;
  220712. component->getMouseXYRelative (x, y);
  220713. handleFileDragMove (dragAndDropFiles, x, y);
  220714. }
  220715. }
  220716. void doDragDropExit (EventRef theEvent)
  220717. {
  220718. if (dragAndDropFiles.size() > 0)
  220719. handleFileDragExit (dragAndDropFiles);
  220720. }
  220721. void doDragDrop (EventRef theEvent)
  220722. {
  220723. updateDragAndDropFileList (theEvent);
  220724. if (dragAndDropFiles.size() > 0)
  220725. {
  220726. int x, y;
  220727. component->getMouseXYRelative (x, y);
  220728. handleFileDragDrop (dragAndDropFiles, x, y);
  220729. }
  220730. }
  220731. void updateDragAndDropFileList (EventRef theEvent)
  220732. {
  220733. dragAndDropFiles.clear();
  220734. DragRef dragRef;
  220735. if (GetEventParameter (theEvent, kEventParamDragRef, typeDragRef, 0, sizeof (dragRef), 0, &dragRef) == noErr)
  220736. {
  220737. UInt16 numItems = 0;
  220738. if (CountDragItems (dragRef, &numItems) == noErr)
  220739. {
  220740. for (int i = 0; i < (int) numItems; ++i)
  220741. {
  220742. DragItemRef ref;
  220743. if (GetDragItemReferenceNumber (dragRef, i + 1, &ref) == noErr)
  220744. {
  220745. const FlavorType flavorType = kDragFlavorTypeHFS;
  220746. Size size = 0;
  220747. if (GetFlavorDataSize (dragRef, ref, flavorType, &size) == noErr)
  220748. {
  220749. void* data = juce_calloc (size);
  220750. if (GetFlavorData (dragRef, ref, flavorType, data, &size, 0) == noErr)
  220751. {
  220752. HFSFlavor* f = (HFSFlavor*) data;
  220753. FSRef fsref;
  220754. if (FSpMakeFSRef (&f->fileSpec, &fsref) == noErr)
  220755. {
  220756. const String path (PlatformUtilities::makePathFromFSRef (&fsref));
  220757. if (path.isNotEmpty())
  220758. dragAndDropFiles.add (path);
  220759. }
  220760. }
  220761. juce_free (data);
  220762. }
  220763. }
  220764. }
  220765. dragAndDropFiles.trim();
  220766. dragAndDropFiles.removeEmptyStrings();
  220767. }
  220768. }
  220769. }
  220770. void resizeViewToFitWindow()
  220771. {
  220772. HIRect r;
  220773. if (isSharedWindow)
  220774. {
  220775. HIViewGetFrame (viewRef, &r);
  220776. r.size.width = (float) component->getWidth();
  220777. r.size.height = (float) component->getHeight();
  220778. }
  220779. else
  220780. {
  220781. r.origin.x = 0;
  220782. r.origin.y = 0;
  220783. Rect w;
  220784. GetWindowBounds (windowRef, windowRegionToUse, &w);
  220785. r.size.width = (float) (w.right - w.left);
  220786. r.size.height = (float) (w.bottom - w.top);
  220787. }
  220788. HIViewSetFrame (viewRef, &r);
  220789. #if MACOS_10_3_OR_EARLIER
  220790. component->repaint();
  220791. #endif
  220792. }
  220793. OSStatus hiViewDraw (EventRef theEvent)
  220794. {
  220795. CGContextRef context = 0;
  220796. GetEventParameter (theEvent, kEventParamCGContextRef, typeCGContextRef, 0, sizeof (CGContextRef), 0, &context);
  220797. CGrafPtr oldPort;
  220798. CGrafPtr port = 0;
  220799. if (context == 0)
  220800. {
  220801. GetEventParameter (theEvent, kEventParamGrafPort, typeGrafPtr, 0, sizeof (CGrafPtr), 0, &port);
  220802. GetPort (&oldPort);
  220803. SetPort (port);
  220804. if (port != 0)
  220805. QDBeginCGContext (port, &context);
  220806. if (! isCompositingWindow)
  220807. {
  220808. Rect bounds;
  220809. GetWindowBounds (windowRef, windowRegionToUse, &bounds);
  220810. CGContextTranslateCTM (context, 0, bounds.bottom - bounds.top);
  220811. CGContextScaleCTM (context, 1.0, -1.0);
  220812. }
  220813. if (isSharedWindow)
  220814. {
  220815. // NB - Had terrible problems trying to correctly get the position
  220816. // of this view relative to the window, and this seems wrong, but
  220817. // works better than any other method I've tried..
  220818. HIRect hiViewPos;
  220819. HIViewGetFrame (viewRef, &hiViewPos);
  220820. CGContextTranslateCTM (context, hiViewPos.origin.x, hiViewPos.origin.y);
  220821. }
  220822. }
  220823. #if MACOS_10_2_OR_EARLIER
  220824. RgnHandle rgn = 0;
  220825. GetEventParameter (theEvent, kEventParamRgnHandle, typeQDRgnHandle, 0, sizeof (RgnHandle), 0, &rgn);
  220826. CGRect clip;
  220827. // (avoid doing this in plugins because of some strange redraw bugs..)
  220828. if (rgn != 0 && JUCEApplication::getInstance() != 0)
  220829. {
  220830. Rect bounds;
  220831. GetRegionBounds (rgn, &bounds);
  220832. clip.origin.x = bounds.left;
  220833. clip.origin.y = bounds.top;
  220834. clip.size.width = bounds.right - bounds.left;
  220835. clip.size.height = bounds.bottom - bounds.top;
  220836. }
  220837. else
  220838. {
  220839. HIViewGetBounds (viewRef, &clip);
  220840. clip.origin.x = 0;
  220841. clip.origin.y = 0;
  220842. }
  220843. #else
  220844. CGRect clip (CGContextGetClipBoundingBox (context));
  220845. #endif
  220846. clip = CGRectIntegral (clip);
  220847. if (clip.origin.x < 0)
  220848. {
  220849. clip.size.width += clip.origin.x;
  220850. clip.origin.x = 0;
  220851. }
  220852. if (clip.origin.y < 0)
  220853. {
  220854. clip.size.height += clip.origin.y;
  220855. clip.origin.y = 0;
  220856. }
  220857. if (! component->isOpaque())
  220858. CGContextClearRect (context, clip);
  220859. repainter->paint (context,
  220860. (int) clip.origin.x, (int) clip.origin.y,
  220861. (int) clip.size.width, (int) clip.size.height);
  220862. if (port != 0)
  220863. {
  220864. CGContextFlush (context);
  220865. QDEndCGContext (port, &context);
  220866. SetPort (oldPort);
  220867. }
  220868. repainter->repaintAnyRemainingRegions();
  220869. return noErr;
  220870. }
  220871. OSStatus handleWindowClassEvent (EventRef theEvent)
  220872. {
  220873. switch (GetEventKind (theEvent))
  220874. {
  220875. case kEventWindowBoundsChanged:
  220876. resizeViewToFitWindow();
  220877. break; // allow other handlers in the event chain to also get a look at the events
  220878. case kEventWindowBoundsChanging:
  220879. if ((styleFlags & (windowIsResizable | windowHasTitleBar)) == (windowIsResizable | windowHasTitleBar))
  220880. {
  220881. UInt32 atts = 0;
  220882. GetEventParameter (theEvent, kEventParamAttributes, typeUInt32,
  220883. 0, sizeof (UInt32), 0, &atts);
  220884. if ((atts & (kWindowBoundsChangeUserDrag | kWindowBoundsChangeUserResize)) != 0)
  220885. {
  220886. if (component->isCurrentlyBlockedByAnotherModalComponent())
  220887. {
  220888. Component* const modal = Component::getCurrentlyModalComponent();
  220889. if (modal != 0)
  220890. {
  220891. static uint32 lastDragTime = 0;
  220892. const uint32 now = Time::currentTimeMillis();
  220893. if (now > lastDragTime + 1000)
  220894. {
  220895. lastDragTime = now;
  220896. modal->inputAttemptWhenModal();
  220897. }
  220898. const Rectangle currentRect (getComponent()->getBounds());
  220899. Rect current;
  220900. current.left = currentRect.getX();
  220901. current.top = currentRect.getY();
  220902. current.right = currentRect.getRight();
  220903. current.bottom = currentRect.getBottom();
  220904. // stop the window getting dragged..
  220905. SetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  220906. sizeof (Rect), &current);
  220907. return noErr;
  220908. }
  220909. }
  220910. if ((atts & kWindowBoundsChangeUserResize) != 0
  220911. && constrainer != 0 && ! isSharedWindow)
  220912. {
  220913. Rect current;
  220914. GetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  220915. 0, sizeof (Rect), 0, &current);
  220916. int x = current.left;
  220917. int y = current.top;
  220918. int w = current.right - current.left;
  220919. int h = current.bottom - current.top;
  220920. const Rectangle currentRect (getComponent()->getBounds());
  220921. constrainer->checkBounds (x, y, w, h, currentRect,
  220922. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  220923. y != currentRect.getY() && y + h == currentRect.getBottom(),
  220924. x != currentRect.getX() && x + w == currentRect.getRight(),
  220925. y == currentRect.getY() && y + h != currentRect.getBottom(),
  220926. x == currentRect.getX() && x + w != currentRect.getRight());
  220927. current.left = x;
  220928. current.top = y;
  220929. current.right = x + w;
  220930. current.bottom = y + h;
  220931. SetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  220932. sizeof (Rect), &current);
  220933. return noErr;
  220934. }
  220935. }
  220936. }
  220937. break;
  220938. case kEventWindowFocusAcquired:
  220939. keysCurrentlyDown.clear();
  220940. if ((! isSharedWindow) || HIViewSubtreeContainsFocus (viewRef))
  220941. viewFocusGain();
  220942. break; // allow other handlers in the event chain to also get a look at the events
  220943. case kEventWindowFocusRelinquish:
  220944. keysCurrentlyDown.clear();
  220945. viewFocusLoss();
  220946. break; // allow other handlers in the event chain to also get a look at the events
  220947. case kEventWindowCollapsed:
  220948. minimisedWindows.addIfNotAlreadyThere (windowRef);
  220949. handleMovedOrResized();
  220950. break; // allow other handlers in the event chain to also get a look at the events
  220951. case kEventWindowExpanded:
  220952. minimisedWindows.removeValue (windowRef);
  220953. handleMovedOrResized();
  220954. break; // allow other handlers in the event chain to also get a look at the events
  220955. case kEventWindowShown:
  220956. break; // allow other handlers in the event chain to also get a look at the events
  220957. case kEventWindowClose:
  220958. if (isSharedWindow)
  220959. break; // break to let the OS delete the window
  220960. handleUserClosingWindow();
  220961. return noErr; // avoids letting the OS to delete the window, we'll do that ourselves.
  220962. default:
  220963. break;
  220964. }
  220965. return eventNotHandledErr;
  220966. }
  220967. OSStatus handleWindowEventForPeer (EventHandlerCallRef callRef, EventRef theEvent)
  220968. {
  220969. switch (GetEventClass (theEvent))
  220970. {
  220971. case kEventClassMouse:
  220972. {
  220973. static HIViewComponentPeer* lastMouseDownPeer = 0;
  220974. const UInt32 eventKind = GetEventKind (theEvent);
  220975. HIViewRef view = 0;
  220976. if (eventKind == kEventMouseDragged)
  220977. {
  220978. view = viewRef;
  220979. }
  220980. else
  220981. {
  220982. HIViewGetViewForMouseEvent (HIViewGetRoot (windowRef), theEvent, &view);
  220983. if (view != viewRef)
  220984. {
  220985. if ((eventKind == kEventMouseUp
  220986. || eventKind == kEventMouseExited)
  220987. && ComponentPeer::isValidPeer (lastMouseDownPeer))
  220988. {
  220989. return lastMouseDownPeer->handleMouseEvent (callRef, theEvent);
  220990. }
  220991. return eventNotHandledErr;
  220992. }
  220993. }
  220994. if (eventKind == kEventMouseDown
  220995. || eventKind == kEventMouseDragged
  220996. || eventKind == kEventMouseEntered)
  220997. {
  220998. lastMouseDownPeer = this;
  220999. }
  221000. return handleMouseEvent (callRef, theEvent);
  221001. }
  221002. break;
  221003. case kEventClassWindow:
  221004. return handleWindowClassEvent (theEvent);
  221005. case kEventClassKeyboard:
  221006. if (isFocused())
  221007. return handleKeyEvent (theEvent, 0);
  221008. break;
  221009. case kEventClassTextInput:
  221010. if (isFocused())
  221011. return handleTextInputEvent (theEvent);
  221012. break;
  221013. default:
  221014. break;
  221015. }
  221016. return eventNotHandledErr;
  221017. }
  221018. static pascal OSStatus handleWindowEvent (EventHandlerCallRef callRef, EventRef theEvent, void* userData)
  221019. {
  221020. MessageManager::delayWaitCursor();
  221021. HIViewComponentPeer* const peer = (HIViewComponentPeer*) userData;
  221022. const MessageManagerLock messLock;
  221023. if (ComponentPeer::isValidPeer (peer))
  221024. return peer->handleWindowEventForPeer (callRef, theEvent);
  221025. return eventNotHandledErr;
  221026. }
  221027. static pascal OSStatus hiViewEventHandler (EventHandlerCallRef myHandler, EventRef theEvent, void* userData)
  221028. {
  221029. MessageManager::delayWaitCursor();
  221030. const UInt32 eventKind = GetEventKind (theEvent);
  221031. const UInt32 eventClass = GetEventClass (theEvent);
  221032. if (eventClass == kEventClassHIObject)
  221033. {
  221034. switch (eventKind)
  221035. {
  221036. case kEventHIObjectConstruct:
  221037. {
  221038. void* data = juce_calloc (sizeof (void*));
  221039. SetEventParameter (theEvent, kEventParamHIObjectInstance,
  221040. typeVoidPtr, sizeof (void*), &data);
  221041. return noErr;
  221042. }
  221043. case kEventHIObjectInitialize:
  221044. GetEventParameter (theEvent, 'peer', typeVoidPtr, 0, sizeof (void*), 0, (void**) userData);
  221045. return noErr;
  221046. case kEventHIObjectDestruct:
  221047. juce_free (userData);
  221048. return noErr;
  221049. default:
  221050. break;
  221051. }
  221052. }
  221053. else if (eventClass == kEventClassControl)
  221054. {
  221055. HIViewComponentPeer* const peer = *(HIViewComponentPeer**) userData;
  221056. const MessageManagerLock messLock;
  221057. if (! ComponentPeer::isValidPeer (peer))
  221058. return eventNotHandledErr;
  221059. switch (eventKind)
  221060. {
  221061. case kEventControlDraw:
  221062. return peer->hiViewDraw (theEvent);
  221063. case kEventControlBoundsChanged:
  221064. {
  221065. HIRect bounds;
  221066. HIViewGetBounds (peer->viewRef, &bounds);
  221067. peer->repaint (0, 0, roundFloatToInt (bounds.size.width), roundFloatToInt (bounds.size.height));
  221068. peer->handleMovedOrResized();
  221069. return noErr;
  221070. }
  221071. case kEventControlHitTest:
  221072. {
  221073. HIPoint where;
  221074. GetEventParameter (theEvent, kEventParamMouseLocation, typeHIPoint, 0, sizeof (HIPoint), 0, &where);
  221075. HIRect bounds;
  221076. HIViewGetBounds (peer->viewRef, &bounds);
  221077. ControlPartCode part = kControlNoPart;
  221078. if (CGRectContainsPoint (bounds, where))
  221079. part = 1;
  221080. SetEventParameter (theEvent, kEventParamControlPart, typeControlPartCode, sizeof (ControlPartCode), &part);
  221081. return noErr;
  221082. }
  221083. break;
  221084. case kEventControlSetFocusPart:
  221085. {
  221086. ControlPartCode desiredFocus;
  221087. if (GetEventParameter (theEvent, kEventParamControlPart, typeControlPartCode, 0, sizeof (ControlPartCode), 0, &desiredFocus) != noErr)
  221088. break;
  221089. if (desiredFocus == kControlNoPart)
  221090. peer->viewFocusLoss();
  221091. else
  221092. peer->viewFocusGain();
  221093. return noErr;
  221094. }
  221095. break;
  221096. case kEventControlDragEnter:
  221097. {
  221098. #if MACOS_10_2_OR_EARLIER
  221099. enum { kEventParamControlWouldAcceptDrop = 'cldg' };
  221100. #endif
  221101. Boolean accept = true;
  221102. SetEventParameter (theEvent, kEventParamControlWouldAcceptDrop, typeBoolean, sizeof (accept), &accept);
  221103. peer->doDragDropEnter (theEvent);
  221104. return noErr;
  221105. }
  221106. case kEventControlDragWithin:
  221107. peer->doDragDropMove (theEvent);
  221108. return noErr;
  221109. case kEventControlDragLeave:
  221110. peer->doDragDropExit (theEvent);
  221111. return noErr;
  221112. case kEventControlDragReceive:
  221113. peer->doDragDrop (theEvent);
  221114. return noErr;
  221115. case kEventControlOwningWindowChanged:
  221116. return peer->ownerWindowChanged (theEvent);
  221117. #if ! MACOS_10_2_OR_EARLIER
  221118. case kEventControlGetFrameMetrics:
  221119. {
  221120. CallNextEventHandler (myHandler, theEvent);
  221121. HIViewFrameMetrics metrics;
  221122. GetEventParameter (theEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, 0, sizeof (metrics), 0, &metrics);
  221123. metrics.top = metrics.bottom = 0;
  221124. SetEventParameter (theEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, sizeof (metrics), &metrics);
  221125. return noErr;
  221126. }
  221127. #endif
  221128. case kEventControlInitialize:
  221129. {
  221130. UInt32 features = kControlSupportsDragAndDrop
  221131. | kControlSupportsFocus
  221132. | kControlHandlesTracking
  221133. | kControlSupportsEmbedding
  221134. | (1 << 8) /*kHIViewFeatureGetsFocusOnClick*/;
  221135. SetEventParameter (theEvent, kEventParamControlFeatures, typeUInt32, sizeof (UInt32), &features);
  221136. return noErr;
  221137. }
  221138. default:
  221139. break;
  221140. }
  221141. }
  221142. return eventNotHandledErr;
  221143. }
  221144. WindowRef createNewWindow (const int windowStyleFlags)
  221145. {
  221146. jassert (windowRef == 0);
  221147. static ToolboxObjectClassRef customWindowClass = 0;
  221148. if (customWindowClass == 0)
  221149. {
  221150. // Register our window class
  221151. const EventTypeSpec customTypes[] = { { kEventClassWindow, kEventWindowDrawFrame } };
  221152. UnsignedWide t;
  221153. Microseconds (&t);
  221154. const String randomString ((int) (t.lo & 0x7ffffff));
  221155. const String juceWindowClassName (T("JUCEWindowClass_") + randomString);
  221156. CFStringRef juceWindowClassNameCFString = PlatformUtilities::juceStringToCFString (juceWindowClassName);
  221157. RegisterToolboxObjectClass (juceWindowClassNameCFString,
  221158. 0, 1, customTypes,
  221159. NewEventHandlerUPP (handleFrameRepaintEvent),
  221160. 0, &customWindowClass);
  221161. CFRelease (juceWindowClassNameCFString);
  221162. }
  221163. Rect pos;
  221164. pos.left = getComponent()->getX();
  221165. pos.top = getComponent()->getY();
  221166. pos.right = getComponent()->getRight();
  221167. pos.bottom = getComponent()->getBottom();
  221168. int attributes = kWindowStandardHandlerAttribute | kWindowCompositingAttribute;
  221169. if ((windowStyleFlags & windowHasDropShadow) == 0)
  221170. attributes |= kWindowNoShadowAttribute;
  221171. if ((windowStyleFlags & windowIgnoresMouseClicks) != 0)
  221172. attributes |= kWindowIgnoreClicksAttribute;
  221173. #if ! MACOS_10_3_OR_EARLIER
  221174. if ((windowStyleFlags & windowIsTemporary) != 0)
  221175. attributes |= kWindowDoesNotCycleAttribute;
  221176. #endif
  221177. WindowRef newWindow = 0;
  221178. if ((windowStyleFlags & windowHasTitleBar) == 0)
  221179. {
  221180. attributes |= kWindowCollapseBoxAttribute;
  221181. WindowDefSpec customWindowSpec;
  221182. customWindowSpec.defType = kWindowDefObjectClass;
  221183. customWindowSpec.u.classRef = customWindowClass;
  221184. CreateCustomWindow (&customWindowSpec,
  221185. ((windowStyleFlags & windowIsTemporary) != 0) ? kUtilityWindowClass :
  221186. (getComponent()->isAlwaysOnTop() ? kUtilityWindowClass
  221187. : kDocumentWindowClass),
  221188. attributes,
  221189. &pos,
  221190. &newWindow);
  221191. }
  221192. else
  221193. {
  221194. if ((windowStyleFlags & windowHasCloseButton) != 0)
  221195. attributes |= kWindowCloseBoxAttribute;
  221196. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  221197. attributes |= kWindowCollapseBoxAttribute;
  221198. if ((windowStyleFlags & windowHasMaximiseButton) != 0)
  221199. attributes |= kWindowFullZoomAttribute;
  221200. if ((windowStyleFlags & windowIsResizable) != 0)
  221201. attributes |= kWindowResizableAttribute | kWindowLiveResizeAttribute;
  221202. CreateNewWindow (kDocumentWindowClass, attributes, &pos, &newWindow);
  221203. }
  221204. jassert (newWindow != 0);
  221205. if (newWindow != 0)
  221206. {
  221207. HideWindow (newWindow);
  221208. SetAutomaticControlDragTrackingEnabledForWindow (newWindow, true);
  221209. if (! getComponent()->isOpaque())
  221210. SetWindowAlpha (newWindow, 0.9999999f); // to fool it into giving the window an alpha-channel
  221211. }
  221212. return newWindow;
  221213. }
  221214. OSStatus ownerWindowChanged (EventRef theEvent)
  221215. {
  221216. WindowRef newWindow = 0;
  221217. GetEventParameter (theEvent, kEventParamControlCurrentOwningWindow, typeWindowRef, 0, sizeof (newWindow), 0, &newWindow);
  221218. if (windowRef != newWindow)
  221219. {
  221220. if (eventHandlerRef != 0)
  221221. {
  221222. RemoveEventHandler (eventHandlerRef);
  221223. eventHandlerRef = 0;
  221224. }
  221225. windowRef = newWindow;
  221226. if (windowRef != 0)
  221227. {
  221228. const EventTypeSpec eventTypes[] =
  221229. {
  221230. { kEventClassWindow, kEventWindowBoundsChanged },
  221231. { kEventClassWindow, kEventWindowBoundsChanging },
  221232. { kEventClassWindow, kEventWindowFocusAcquired },
  221233. { kEventClassWindow, kEventWindowFocusRelinquish },
  221234. { kEventClassWindow, kEventWindowCollapsed },
  221235. { kEventClassWindow, kEventWindowExpanded },
  221236. { kEventClassWindow, kEventWindowShown },
  221237. { kEventClassWindow, kEventWindowClose },
  221238. { kEventClassMouse, kEventMouseDown },
  221239. { kEventClassMouse, kEventMouseUp },
  221240. { kEventClassMouse, kEventMouseMoved },
  221241. { kEventClassMouse, kEventMouseDragged },
  221242. { kEventClassMouse, kEventMouseEntered },
  221243. { kEventClassMouse, kEventMouseExited },
  221244. { kEventClassMouse, kEventMouseWheelMoved },
  221245. { kEventClassKeyboard, kEventRawKeyUp },
  221246. { kEventClassKeyboard, kEventRawKeyRepeat },
  221247. { kEventClassKeyboard, kEventRawKeyModifiersChanged },
  221248. { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent }
  221249. };
  221250. static EventHandlerUPP handleWindowEventUPP = 0;
  221251. if (handleWindowEventUPP == 0)
  221252. handleWindowEventUPP = NewEventHandlerUPP (handleWindowEvent);
  221253. InstallWindowEventHandler (windowRef, handleWindowEventUPP,
  221254. GetEventTypeCount (eventTypes), eventTypes,
  221255. (void*) this, (EventHandlerRef*) &eventHandlerRef);
  221256. WindowAttributes attributes;
  221257. GetWindowAttributes (windowRef, &attributes);
  221258. #if MACOS_10_3_OR_EARLIER
  221259. isCompositingWindow = ((attributes & kWindowCompositingAttribute) != 0);
  221260. #else
  221261. isCompositingWindow = HIViewIsCompositingEnabled (viewRef);
  221262. #endif
  221263. SetAutomaticControlDragTrackingEnabledForWindow (newWindow, true);
  221264. MouseCheckTimer::getInstance()->resetMouseMoveChecker();
  221265. }
  221266. }
  221267. resizeViewToFitWindow();
  221268. return noErr;
  221269. }
  221270. void createNewHIView()
  221271. {
  221272. jassert (viewRef == 0);
  221273. if (viewClassRef == 0)
  221274. {
  221275. // Register our HIView class
  221276. EventTypeSpec viewEvents[] =
  221277. {
  221278. { kEventClassHIObject, kEventHIObjectConstruct },
  221279. { kEventClassHIObject, kEventHIObjectInitialize },
  221280. { kEventClassHIObject, kEventHIObjectDestruct },
  221281. { kEventClassControl, kEventControlInitialize },
  221282. { kEventClassControl, kEventControlDraw },
  221283. { kEventClassControl, kEventControlBoundsChanged },
  221284. { kEventClassControl, kEventControlSetFocusPart },
  221285. { kEventClassControl, kEventControlHitTest },
  221286. { kEventClassControl, kEventControlDragEnter },
  221287. { kEventClassControl, kEventControlDragLeave },
  221288. { kEventClassControl, kEventControlDragWithin },
  221289. { kEventClassControl, kEventControlDragReceive },
  221290. { kEventClassControl, kEventControlOwningWindowChanged }
  221291. };
  221292. UnsignedWide t;
  221293. Microseconds (&t);
  221294. const String randomString ((int) (t.lo & 0x7ffffff));
  221295. const String juceHiViewClassName (T("JUCEHIViewClass_") + randomString);
  221296. juceHiViewClassNameCFString = PlatformUtilities::juceStringToCFString (juceHiViewClassName);
  221297. HIObjectRegisterSubclass (juceHiViewClassNameCFString,
  221298. kHIViewClassID, 0,
  221299. NewEventHandlerUPP (hiViewEventHandler),
  221300. GetEventTypeCount (viewEvents),
  221301. viewEvents, 0,
  221302. &viewClassRef);
  221303. }
  221304. EventRef event;
  221305. CreateEvent (0, kEventClassHIObject, kEventHIObjectInitialize, GetCurrentEventTime(), kEventAttributeNone, &event);
  221306. void* thisPointer = this;
  221307. SetEventParameter (event, 'peer', typeVoidPtr, sizeof (void*), &thisPointer);
  221308. HIObjectCreate (juceHiViewClassNameCFString, event, (HIObjectRef*) &viewRef);
  221309. SetControlDragTrackingEnabled (viewRef, true);
  221310. if (isSharedWindow)
  221311. {
  221312. setBounds (component->getX(), component->getY(),
  221313. component->getWidth(), component->getHeight(), false);
  221314. }
  221315. }
  221316. };
  221317. bool juce_isHIViewCreatedByJuce (HIViewRef view)
  221318. {
  221319. return juceHiViewClassNameCFString != 0
  221320. && HIObjectIsOfClass ((HIObjectRef) view, juceHiViewClassNameCFString);
  221321. }
  221322. bool juce_isWindowCreatedByJuce (WindowRef window)
  221323. {
  221324. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221325. if (ComponentPeer::getPeer(i)->getNativeHandle() == window)
  221326. return true;
  221327. return false;
  221328. }
  221329. static void trackNextMouseEvent()
  221330. {
  221331. UInt32 mods;
  221332. MouseTrackingResult result;
  221333. ::Point where;
  221334. if (TrackMouseLocationWithOptions ((GrafPtr) -1, 0, 0.01, //kEventDurationForever,
  221335. &where, &mods, &result) != noErr
  221336. || ! ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  221337. {
  221338. juce_currentMouseTrackingPeer = 0;
  221339. return;
  221340. }
  221341. if (result == kMouseTrackingTimedOut)
  221342. return;
  221343. #if MACOS_10_3_OR_EARLIER
  221344. const int x = where.h - juce_currentMouseTrackingPeer->getScreenX();
  221345. const int y = where.v - juce_currentMouseTrackingPeer->getScreenY();
  221346. #else
  221347. HIPoint p;
  221348. p.x = where.h;
  221349. p.y = where.v;
  221350. HIPointConvert (&p, kHICoordSpaceScreenPixel, 0,
  221351. kHICoordSpaceView, ((HIViewComponentPeer*) juce_currentMouseTrackingPeer)->viewRef);
  221352. const int x = p.x;
  221353. const int y = p.y;
  221354. #endif
  221355. if (result == kMouseTrackingMouseDragged)
  221356. {
  221357. updateModifiers (0);
  221358. juce_currentMouseTrackingPeer->handleMouseDrag (x, y, getEventTime (0));
  221359. if (! ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  221360. {
  221361. juce_currentMouseTrackingPeer = 0;
  221362. return;
  221363. }
  221364. }
  221365. else if (result == kMouseTrackingMouseUp
  221366. || result == kMouseTrackingUserCancelled
  221367. || result == kMouseTrackingMouseMoved)
  221368. {
  221369. ComponentPeer* const oldPeer = juce_currentMouseTrackingPeer;
  221370. juce_currentMouseTrackingPeer = 0;
  221371. if (ComponentPeer::isValidPeer (oldPeer))
  221372. {
  221373. const int oldModifiers = currentModifiers;
  221374. currentModifiers &= ~(ModifierKeys::leftButtonModifier | ModifierKeys::rightButtonModifier | ModifierKeys::middleButtonModifier);
  221375. updateModifiers (0);
  221376. oldPeer->handleMouseUp (oldModifiers, x, y, getEventTime (0));
  221377. }
  221378. }
  221379. }
  221380. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  221381. {
  221382. if (juce_currentMouseTrackingPeer != 0)
  221383. trackNextMouseEvent();
  221384. /* [[NSRunLoop mainRunLoop] acceptInputForMode: NSDefaultRunLoopMode
  221385. beforeDate: returnIfNoPendingMessages
  221386. ? [[NSDate date] addTimeInterval: 0.01]
  221387. : [NSDate distantFuture]];
  221388. */
  221389. EventRef theEvent;
  221390. if (ReceiveNextEvent (0, 0, (returnIfNoPendingMessages) ? kEventDurationNoWait
  221391. : kEventDurationForever,
  221392. true, &theEvent) == noErr)
  221393. {
  221394. if (GetEventClass (theEvent) == kEventClassAppleEvent)
  221395. {
  221396. EventRecord eventRec;
  221397. if (ConvertEventRefToEventRecord (theEvent, &eventRec))
  221398. AEProcessAppleEvent (&eventRec);
  221399. }
  221400. else
  221401. {
  221402. EventTargetRef theTarget = GetEventDispatcherTarget();
  221403. SendEventToEventTarget (theEvent, theTarget);
  221404. }
  221405. ReleaseEvent (theEvent);
  221406. return true;
  221407. }
  221408. return false;
  221409. }
  221410. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  221411. {
  221412. return new HIViewComponentPeer (this, styleFlags, (HIViewRef) windowToAttachTo);
  221413. }
  221414. void MouseCheckTimer::timerCallback()
  221415. {
  221416. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  221417. return;
  221418. if (Process::isForegroundProcess())
  221419. {
  221420. bool stillOver = false;
  221421. int x = 0, y = 0, w = 0, h = 0;
  221422. int mx = 0, my = 0;
  221423. const bool validWindow = ComponentPeer::isValidPeer (lastPeerUnderMouse);
  221424. if (validWindow)
  221425. {
  221426. lastPeerUnderMouse->getBounds (x, y, w, h, true);
  221427. Desktop::getMousePosition (mx, my);
  221428. stillOver = (mx >= x && my >= y && mx < x + w && my < y + h);
  221429. if (stillOver)
  221430. {
  221431. // check if it's over an embedded HIView
  221432. int rx = mx, ry = my;
  221433. lastPeerUnderMouse->globalPositionToRelative (rx, ry);
  221434. HIPoint hipoint;
  221435. hipoint.x = rx;
  221436. hipoint.y = ry;
  221437. HIViewRef root;
  221438. GetRootControl ((WindowRef) lastPeerUnderMouse->getNativeHandle(), &root);
  221439. HIViewRef hitview;
  221440. if (HIViewGetSubviewHit (root, &hipoint, true, &hitview) == noErr && hitview != 0)
  221441. {
  221442. stillOver = HIObjectIsOfClass ((HIObjectRef) hitview, juceHiViewClassNameCFString);
  221443. }
  221444. }
  221445. }
  221446. if (! stillOver)
  221447. {
  221448. // mouse is outside our windows so set a normal cursor (only
  221449. // if we're running as an app, not a plugin)
  221450. if (JUCEApplication::getInstance() != 0)
  221451. SetThemeCursor (kThemeArrowCursor);
  221452. if (validWindow)
  221453. lastPeerUnderMouse->handleMouseExit (mx - x, my - y, Time::currentTimeMillis());
  221454. if (hasEverHadAMouseMove)
  221455. stopTimer();
  221456. }
  221457. if ((! hasEverHadAMouseMove) && validWindow
  221458. && (mx != lastX || my != lastY))
  221459. {
  221460. lastX = mx;
  221461. lastY = my;
  221462. if (stillOver)
  221463. lastPeerUnderMouse->handleMouseMove (mx - x, my - y, Time::currentTimeMillis());
  221464. }
  221465. }
  221466. }
  221467. // called from juce_Messaging.cpp
  221468. void juce_HandleProcessFocusChange()
  221469. {
  221470. keysCurrentlyDown.clear();
  221471. if (HIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  221472. {
  221473. if (Process::isForegroundProcess())
  221474. currentlyFocusedPeer->handleFocusGain();
  221475. else
  221476. currentlyFocusedPeer->handleFocusLoss();
  221477. }
  221478. }
  221479. static bool performDrag (DragRef drag)
  221480. {
  221481. EventRecord event;
  221482. event.what = mouseDown;
  221483. event.message = 0;
  221484. event.when = TickCount();
  221485. int x, y;
  221486. Desktop::getMousePosition (x, y);
  221487. event.where.h = x;
  221488. event.where.v = y;
  221489. event.modifiers = GetCurrentKeyModifiers();
  221490. RgnHandle rgn = NewRgn();
  221491. RgnHandle rgn2 = NewRgn();
  221492. SetRectRgn (rgn,
  221493. event.where.h - 8, event.where.v - 8,
  221494. event.where.h + 8, event.where.v + 8);
  221495. CopyRgn (rgn, rgn2);
  221496. InsetRgn (rgn2, 1, 1);
  221497. DiffRgn (rgn, rgn2, rgn);
  221498. DisposeRgn (rgn2);
  221499. bool result = TrackDrag (drag, &event, rgn) == noErr;
  221500. DisposeRgn (rgn);
  221501. return result;
  221502. }
  221503. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221504. {
  221505. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221506. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  221507. DragRef drag;
  221508. bool result = false;
  221509. if (NewDrag (&drag) == noErr)
  221510. {
  221511. for (int i = 0; i < files.size(); ++i)
  221512. {
  221513. HFSFlavor hfsData;
  221514. if (PlatformUtilities::makeFSSpecFromPath (&hfsData.fileSpec, files[i]))
  221515. {
  221516. FInfo info;
  221517. if (FSpGetFInfo (&hfsData.fileSpec, &info) == noErr)
  221518. {
  221519. hfsData.fileType = info.fdType;
  221520. hfsData.fileCreator = info.fdCreator;
  221521. hfsData.fdFlags = info.fdFlags;
  221522. AddDragItemFlavor (drag, i + 1, kDragFlavorTypeHFS, &hfsData, sizeof (hfsData), 0);
  221523. result = true;
  221524. }
  221525. }
  221526. }
  221527. SetDragAllowableActions (drag, canMoveFiles ? kDragActionAll
  221528. : kDragActionCopy, false);
  221529. if (result)
  221530. result = performDrag (drag);
  221531. DisposeDrag (drag);
  221532. }
  221533. return result;
  221534. }
  221535. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221536. {
  221537. jassertfalse // not implemented!
  221538. return false;
  221539. }
  221540. bool Process::isForegroundProcess() throw()
  221541. {
  221542. ProcessSerialNumber psn, front;
  221543. GetCurrentProcess (&psn);
  221544. GetFrontProcess (&front);
  221545. Boolean b;
  221546. return (SameProcess (&psn, &front, &b) == noErr) && b;
  221547. }
  221548. bool Desktop::canUseSemiTransparentWindows() throw()
  221549. {
  221550. return true;
  221551. }
  221552. void Desktop::getMousePosition (int& x, int& y) throw()
  221553. {
  221554. CGrafPtr currentPort;
  221555. GetPort (&currentPort);
  221556. if (! IsValidPort (currentPort))
  221557. {
  221558. WindowRef front = FrontWindow();
  221559. if (front != 0)
  221560. {
  221561. SetPortWindowPort (front);
  221562. }
  221563. else
  221564. {
  221565. x = y = 0;
  221566. return;
  221567. }
  221568. }
  221569. ::Point p;
  221570. GetMouse (&p);
  221571. LocalToGlobal (&p);
  221572. x = p.h;
  221573. y = p.v;
  221574. SetPort (currentPort);
  221575. }
  221576. void Desktop::setMousePosition (int x, int y) throw()
  221577. {
  221578. // this rubbish needs to be done around the warp call, to avoid causing a
  221579. // bizarre glitch..
  221580. CGAssociateMouseAndMouseCursorPosition (false);
  221581. CGSetLocalEventsSuppressionInterval (0);
  221582. CGPoint pos = { x, y };
  221583. CGWarpMouseCursorPosition (pos);
  221584. CGAssociateMouseAndMouseCursorPosition (true);
  221585. }
  221586. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221587. {
  221588. return ModifierKeys (currentModifiers);
  221589. }
  221590. class ScreenSaverDefeater : public Timer,
  221591. public DeletedAtShutdown
  221592. {
  221593. public:
  221594. ScreenSaverDefeater() throw()
  221595. {
  221596. startTimer (10000);
  221597. timerCallback();
  221598. }
  221599. ~ScreenSaverDefeater()
  221600. {
  221601. }
  221602. void timerCallback()
  221603. {
  221604. if (Process::isForegroundProcess())
  221605. UpdateSystemActivity (UsrActivity);
  221606. }
  221607. };
  221608. static ScreenSaverDefeater* screenSaverDefeater = 0;
  221609. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  221610. {
  221611. if (screenSaverDefeater == 0)
  221612. screenSaverDefeater = new ScreenSaverDefeater();
  221613. }
  221614. bool Desktop::isScreenSaverEnabled() throw()
  221615. {
  221616. return screenSaverDefeater == 0;
  221617. }
  221618. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  221619. {
  221620. int mainMonitorIndex = 0;
  221621. CGDirectDisplayID mainDisplayID = CGMainDisplayID();
  221622. CGDisplayCount count = 0;
  221623. CGDirectDisplayID disps [8];
  221624. if (CGGetOnlineDisplayList (numElementsInArray (disps), disps, &count) == noErr)
  221625. {
  221626. for (int i = 0; i < count; ++i)
  221627. {
  221628. if (mainDisplayID == disps[i])
  221629. mainMonitorIndex = monitorCoords.size();
  221630. GDHandle hGDevice;
  221631. if (clipToWorkArea
  221632. && DMGetGDeviceByDisplayID ((DisplayIDType) disps[i], &hGDevice, false) == noErr)
  221633. {
  221634. Rect rect;
  221635. GetAvailableWindowPositioningBounds (hGDevice, &rect);
  221636. monitorCoords.add (Rectangle (rect.left,
  221637. rect.top,
  221638. rect.right - rect.left,
  221639. rect.bottom - rect.top));
  221640. }
  221641. else
  221642. {
  221643. const CGRect r (CGDisplayBounds (disps[i]));
  221644. monitorCoords.add (Rectangle ((int) r.origin.x,
  221645. (int) r.origin.y,
  221646. (int) r.size.width,
  221647. (int) r.size.height));
  221648. }
  221649. }
  221650. }
  221651. // make sure the first in the list is the main monitor
  221652. if (mainMonitorIndex > 0)
  221653. monitorCoords.swap (mainMonitorIndex, 0);
  221654. jassert (monitorCoords.size() > 0);
  221655. if (monitorCoords.size() == 0)
  221656. monitorCoords.add (Rectangle (0, 0, 1024, 768));
  221657. }
  221658. static NSImage* juceImageToNSImage (const Image& image)
  221659. {
  221660. int lineStride, pixelStride;
  221661. const uint8* pixels = image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(),
  221662. lineStride, pixelStride);
  221663. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  221664. initWithBitmapDataPlanes: NULL
  221665. pixelsWide: image.getWidth()
  221666. pixelsHigh: image.getHeight()
  221667. bitsPerSample: 8
  221668. samplesPerPixel: image.hasAlphaChannel() ? 4 : 3
  221669. hasAlpha: image.hasAlphaChannel()
  221670. isPlanar: NO
  221671. colorSpaceName: NSCalibratedRGBColorSpace
  221672. bitmapFormat: (NSBitmapFormat) 0
  221673. bytesPerRow: lineStride
  221674. bitsPerPixel: pixelStride * 8];
  221675. unsigned char* newData = [rep bitmapData];
  221676. memcpy (newData, pixels, lineStride * image.getHeight());
  221677. image.releasePixelDataReadOnly (pixels);
  221678. NSImage* im = [[NSImage alloc] init];
  221679. [im addRepresentation: rep];
  221680. [rep release];
  221681. return im;
  221682. }
  221683. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  221684. {
  221685. NSImage* im = juceImageToNSImage (image);
  221686. [im autorelease];
  221687. NSPoint hs;
  221688. hs.x = (int) hotspotX;
  221689. hs.y = (int) hotspotY;
  221690. NSCursor* c = [[NSCursor alloc] initWithImage: im hotSpot: hs];
  221691. return (void*) c;
  221692. }
  221693. static void* juce_cursorFromData (const unsigned char* data, const int size, float hx, float hy) throw()
  221694. {
  221695. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  221696. jassert (im != 0);
  221697. if (im == 0)
  221698. return 0;
  221699. void* const curs = juce_createMouseCursorFromImage (*im,
  221700. (int) (hx * im->getWidth()),
  221701. (int) (hy * im->getHeight()));
  221702. delete im;
  221703. return curs;
  221704. }
  221705. static void* juce_cursorFromWebKitFile (const char* filename, float hx, float hy)
  221706. {
  221707. File f ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources");
  221708. MemoryBlock mb;
  221709. if (f.getChildFile (filename).loadFileAsData (mb))
  221710. return juce_cursorFromData ((const unsigned char*) mb.getData(), mb.getSize(), hx, hy);
  221711. return 0;
  221712. }
  221713. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  221714. {
  221715. NSCursor* c = 0;
  221716. switch (type)
  221717. {
  221718. case MouseCursor::NormalCursor:
  221719. c = [NSCursor arrowCursor];
  221720. break;
  221721. case MouseCursor::NoCursor:
  221722. {
  221723. Image blank (Image::ARGB, 8, 8, true);
  221724. return juce_createMouseCursorFromImage (blank, 0, 0);
  221725. }
  221726. case MouseCursor::DraggingHandCursor:
  221727. c = [NSCursor openHandCursor];
  221728. break;
  221729. case MouseCursor::CopyingCursor:
  221730. return juce_cursorFromWebKitFile ("copyCursor.png", 0, 0);
  221731. case MouseCursor::WaitCursor:
  221732. c = [NSCursor arrowCursor]; // avoid this on the mac, let the OS provide the beachball
  221733. break;
  221734. //return juce_cursorFromWebKitFile ("waitCursor.png", 0.5f, 0.5f);
  221735. case MouseCursor::IBeamCursor:
  221736. c = [NSCursor IBeamCursor];
  221737. break;
  221738. case MouseCursor::PointingHandCursor:
  221739. c = [NSCursor pointingHandCursor];
  221740. break;
  221741. case MouseCursor::LeftRightResizeCursor:
  221742. c = [NSCursor resizeLeftRightCursor];
  221743. break;
  221744. case MouseCursor::LeftEdgeResizeCursor:
  221745. c = [NSCursor resizeLeftCursor];
  221746. break;
  221747. case MouseCursor::RightEdgeResizeCursor:
  221748. c = [NSCursor resizeRightCursor];
  221749. break;
  221750. case MouseCursor::UpDownResizeCursor:
  221751. case MouseCursor::TopEdgeResizeCursor:
  221752. case MouseCursor::BottomEdgeResizeCursor:
  221753. return juce_cursorFromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  221754. case MouseCursor::TopLeftCornerResizeCursor:
  221755. case MouseCursor::BottomRightCornerResizeCursor:
  221756. return juce_cursorFromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  221757. case MouseCursor::TopRightCornerResizeCursor:
  221758. case MouseCursor::BottomLeftCornerResizeCursor:
  221759. return juce_cursorFromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  221760. case MouseCursor::UpDownLeftRightResizeCursor:
  221761. return juce_cursorFromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  221762. case MouseCursor::CrosshairCursor:
  221763. c = [NSCursor crosshairCursor];
  221764. break;
  221765. }
  221766. [c retain];
  221767. return (void*) c;
  221768. }
  221769. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  221770. {
  221771. NSCursor* c = (NSCursor*) cursorHandle;
  221772. [c release];
  221773. }
  221774. void MouseCursor::showInAllWindows() const throw()
  221775. {
  221776. showInWindow (0);
  221777. }
  221778. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  221779. {
  221780. NSCursor* const c = (NSCursor*) getHandle();
  221781. if (c != 0)
  221782. [c set];
  221783. }
  221784. Image* juce_createIconForFile (const File& file)
  221785. {
  221786. return 0;
  221787. }
  221788. class MainMenuHandler;
  221789. static MainMenuHandler* mainMenu = 0;
  221790. class MainMenuHandler : private MenuBarModelListener,
  221791. private DeletedAtShutdown
  221792. {
  221793. public:
  221794. MainMenuHandler() throw()
  221795. : currentModel (0)
  221796. {
  221797. }
  221798. ~MainMenuHandler() throw()
  221799. {
  221800. setMenu (0);
  221801. jassert (mainMenu == this);
  221802. mainMenu = 0;
  221803. }
  221804. void setMenu (MenuBarModel* const newMenuBarModel) throw()
  221805. {
  221806. if (currentModel != newMenuBarModel)
  221807. {
  221808. if (currentModel != 0)
  221809. currentModel->removeListener (this);
  221810. currentModel = newMenuBarModel;
  221811. if (currentModel != 0)
  221812. currentModel->addListener (this);
  221813. menuBarItemsChanged (0);
  221814. }
  221815. }
  221816. void menuBarItemsChanged (MenuBarModel*)
  221817. {
  221818. ClearMenuBar();
  221819. if (currentModel != 0)
  221820. {
  221821. int menuId = 1000;
  221822. const StringArray menuNames (currentModel->getMenuBarNames());
  221823. for (int i = 0; i < menuNames.size(); ++i)
  221824. {
  221825. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  221826. MenuRef m = createMenu (menu, menuNames [i], menuId, i);
  221827. InsertMenu (m, 0);
  221828. CFRelease (m);
  221829. }
  221830. }
  221831. }
  221832. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  221833. {
  221834. MenuRef menu = 0;
  221835. MenuItemIndex index = 0;
  221836. GetIndMenuItemWithCommandID (0, info.commandID, 1, &menu, &index);
  221837. if (menu != 0)
  221838. {
  221839. FlashMenuBar (GetMenuID (menu));
  221840. FlashMenuBar (GetMenuID (menu));
  221841. }
  221842. }
  221843. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  221844. {
  221845. if (currentModel != 0)
  221846. {
  221847. if (commandManager != 0)
  221848. {
  221849. ApplicationCommandTarget::InvocationInfo info (commandId);
  221850. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  221851. commandManager->invoke (info, true);
  221852. }
  221853. currentModel->menuItemSelected (commandId, topLevelIndex);
  221854. }
  221855. }
  221856. MenuBarModel* currentModel;
  221857. private:
  221858. static MenuRef createMenu (const PopupMenu menu,
  221859. const String& menuName,
  221860. int& id,
  221861. const int topLevelIndex)
  221862. {
  221863. MenuRef m = 0;
  221864. if (CreateNewMenu (id++, kMenuAttrAutoDisable, &m) == noErr)
  221865. {
  221866. CFStringRef name = PlatformUtilities::juceStringToCFString (menuName);
  221867. SetMenuTitleWithCFString (m, name);
  221868. CFRelease (name);
  221869. PopupMenu::MenuItemIterator iter (menu);
  221870. while (iter.next())
  221871. {
  221872. MenuItemIndex index = 0;
  221873. int flags = kMenuAttrAutoDisable | kMenuItemAttrIgnoreMeta | kMenuItemAttrNotPreviousAlternate;
  221874. if (! iter.isEnabled)
  221875. flags |= kMenuItemAttrDisabled;
  221876. CFStringRef text = PlatformUtilities::juceStringToCFString (iter.itemName.upToFirstOccurrenceOf (T("<end>"), false, true));
  221877. if (iter.isSeparator)
  221878. {
  221879. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSeparator, 0, &index);
  221880. }
  221881. else if (iter.isSectionHeader)
  221882. {
  221883. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSectionHeader, 0, &index);
  221884. }
  221885. else if (iter.subMenu != 0)
  221886. {
  221887. AppendMenuItemTextWithCFString (m, text, flags, id++, &index);
  221888. MenuRef sub = createMenu (*iter.subMenu, iter.itemName, id, topLevelIndex);
  221889. SetMenuItemHierarchicalMenu (m, index, sub);
  221890. CFRelease (sub);
  221891. }
  221892. else
  221893. {
  221894. AppendMenuItemTextWithCFString (m, text, flags, iter.itemId, &index);
  221895. if (iter.isTicked)
  221896. CheckMenuItem (m, index, true);
  221897. SetMenuItemProperty (m, index, 'juce', 'apcm', sizeof (void*), &iter.commandManager);
  221898. SetMenuItemProperty (m, index, 'juce', 'topi', sizeof (int), &topLevelIndex);
  221899. if (iter.commandManager != 0)
  221900. {
  221901. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  221902. ->getKeyPressesAssignedToCommand (iter.itemId));
  221903. if (keyPresses.size() > 0)
  221904. {
  221905. const KeyPress& kp = keyPresses.getReference(0);
  221906. int mods = 0;
  221907. if (kp.getModifiers().isShiftDown())
  221908. mods |= kMenuShiftModifier;
  221909. if (kp.getModifiers().isCtrlDown())
  221910. mods |= kMenuControlModifier;
  221911. if (kp.getModifiers().isAltDown())
  221912. mods |= kMenuOptionModifier;
  221913. if (! kp.getModifiers().isCommandDown())
  221914. mods |= kMenuNoCommandModifier;
  221915. tchar keyCode = (tchar) kp.getKeyCode();
  221916. if (kp.getKeyCode() >= KeyPress::numberPad0
  221917. && kp.getKeyCode() <= KeyPress::numberPad9)
  221918. {
  221919. keyCode = (tchar) ((T('0') - KeyPress::numberPad0) + kp.getKeyCode());
  221920. }
  221921. SetMenuItemCommandKey (m, index, true, 255);
  221922. if (CharacterFunctions::isLetterOrDigit (keyCode)
  221923. || CharacterFunctions::indexOfChar (T(",.;/\\'[]=-+_<>?{}\":"), keyCode, false) >= 0)
  221924. {
  221925. SetMenuItemModifiers (m, index, mods);
  221926. SetMenuItemCommandKey (m, index, false, CharacterFunctions::toUpperCase (keyCode));
  221927. }
  221928. else
  221929. {
  221930. const SInt16 glyph = getGlyphForKeyCode (kp.getKeyCode());
  221931. if (glyph != 0)
  221932. {
  221933. SetMenuItemModifiers (m, index, mods);
  221934. SetMenuItemKeyGlyph (m, index, glyph);
  221935. }
  221936. }
  221937. // if we set the key glyph to be a text char, and enable virtual
  221938. // key triggering, it stops the menu automatically triggering the callback
  221939. ChangeMenuItemAttributes (m, index, kMenuItemAttrUseVirtualKey, 0);
  221940. }
  221941. }
  221942. }
  221943. CFRelease (text);
  221944. }
  221945. }
  221946. return m;
  221947. }
  221948. static SInt16 getGlyphForKeyCode (const int keyCode) throw()
  221949. {
  221950. if (keyCode == KeyPress::spaceKey)
  221951. return kMenuSpaceGlyph;
  221952. else if (keyCode == KeyPress::returnKey)
  221953. return kMenuReturnGlyph;
  221954. else if (keyCode == KeyPress::escapeKey)
  221955. return kMenuEscapeGlyph;
  221956. else if (keyCode == KeyPress::backspaceKey)
  221957. return kMenuDeleteLeftGlyph;
  221958. else if (keyCode == KeyPress::leftKey)
  221959. return kMenuLeftArrowGlyph;
  221960. else if (keyCode == KeyPress::rightKey)
  221961. return kMenuRightArrowGlyph;
  221962. else if (keyCode == KeyPress::upKey)
  221963. return kMenuUpArrowGlyph;
  221964. else if (keyCode == KeyPress::downKey)
  221965. return kMenuDownArrowGlyph;
  221966. else if (keyCode == KeyPress::pageUpKey)
  221967. return kMenuPageUpGlyph;
  221968. else if (keyCode == KeyPress::pageDownKey)
  221969. return kMenuPageDownGlyph;
  221970. else if (keyCode == KeyPress::endKey)
  221971. return kMenuSoutheastArrowGlyph;
  221972. else if (keyCode == KeyPress::homeKey)
  221973. return kMenuNorthwestArrowGlyph;
  221974. else if (keyCode == KeyPress::deleteKey)
  221975. return kMenuDeleteRightGlyph;
  221976. else if (keyCode == KeyPress::tabKey)
  221977. return kMenuTabRightGlyph;
  221978. else if (keyCode == KeyPress::F1Key)
  221979. return kMenuF1Glyph;
  221980. else if (keyCode == KeyPress::F2Key)
  221981. return kMenuF2Glyph;
  221982. else if (keyCode == KeyPress::F3Key)
  221983. return kMenuF3Glyph;
  221984. else if (keyCode == KeyPress::F4Key)
  221985. return kMenuF4Glyph;
  221986. else if (keyCode == KeyPress::F5Key)
  221987. return kMenuF5Glyph;
  221988. else if (keyCode == KeyPress::F6Key)
  221989. return kMenuF6Glyph;
  221990. else if (keyCode == KeyPress::F7Key)
  221991. return kMenuF7Glyph;
  221992. else if (keyCode == KeyPress::F8Key)
  221993. return kMenuF8Glyph;
  221994. else if (keyCode == KeyPress::F9Key)
  221995. return kMenuF9Glyph;
  221996. else if (keyCode == KeyPress::F10Key)
  221997. return kMenuF10Glyph;
  221998. else if (keyCode == KeyPress::F11Key)
  221999. return kMenuF11Glyph;
  222000. else if (keyCode == KeyPress::F12Key)
  222001. return kMenuF12Glyph;
  222002. else if (keyCode == KeyPress::F13Key)
  222003. return kMenuF13Glyph;
  222004. else if (keyCode == KeyPress::F14Key)
  222005. return kMenuF14Glyph;
  222006. else if (keyCode == KeyPress::F15Key)
  222007. return kMenuF15Glyph;
  222008. return 0;
  222009. }
  222010. };
  222011. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel) throw()
  222012. {
  222013. if (getMacMainMenu() != newMenuBarModel)
  222014. {
  222015. if (newMenuBarModel == 0)
  222016. {
  222017. delete mainMenu;
  222018. jassert (mainMenu == 0); // should be zeroed in the destructor
  222019. }
  222020. else
  222021. {
  222022. if (mainMenu == 0)
  222023. mainMenu = new MainMenuHandler();
  222024. mainMenu->setMenu (newMenuBarModel);
  222025. }
  222026. }
  222027. }
  222028. MenuBarModel* MenuBarModel::getMacMainMenu() throw()
  222029. {
  222030. return mainMenu != 0 ? mainMenu->currentModel : 0;
  222031. }
  222032. // these functions are called externally from the message handling code
  222033. void juce_MainMenuAboutToBeUsed()
  222034. {
  222035. // force an update of the items just before the menu appears..
  222036. if (mainMenu != 0)
  222037. mainMenu->menuBarItemsChanged (0);
  222038. }
  222039. void juce_InvokeMainMenuCommand (const HICommand& command)
  222040. {
  222041. if (mainMenu != 0)
  222042. {
  222043. ApplicationCommandManager* commandManager = 0;
  222044. int topLevelIndex = 0;
  222045. if (GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  222046. 'juce', 'apcm', sizeof (commandManager), 0, &commandManager) == noErr
  222047. && GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  222048. 'juce', 'topi', sizeof (topLevelIndex), 0, &topLevelIndex) == noErr)
  222049. {
  222050. mainMenu->invoke (command.commandID, commandManager, topLevelIndex);
  222051. }
  222052. }
  222053. }
  222054. void PlatformUtilities::beep()
  222055. {
  222056. SysBeep (30);
  222057. }
  222058. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  222059. {
  222060. ClearCurrentScrap();
  222061. ScrapRef ref;
  222062. GetCurrentScrap (&ref);
  222063. const int len = text.length();
  222064. const int numBytes = sizeof (UniChar) * len;
  222065. UniChar* const temp = (UniChar*) juce_calloc (numBytes);
  222066. for (int i = 0; i < len; ++i)
  222067. temp[i] = (UniChar) text[i];
  222068. PutScrapFlavor (ref,
  222069. kScrapFlavorTypeUnicode,
  222070. kScrapFlavorMaskNone,
  222071. numBytes,
  222072. temp);
  222073. juce_free (temp);
  222074. }
  222075. const String SystemClipboard::getTextFromClipboard() throw()
  222076. {
  222077. String result;
  222078. ScrapRef ref;
  222079. GetCurrentScrap (&ref);
  222080. Size size = 0;
  222081. if (GetScrapFlavorSize (ref, kScrapFlavorTypeUnicode, &size) == noErr
  222082. && size > 0)
  222083. {
  222084. void* const data = juce_calloc (size + 8);
  222085. if (GetScrapFlavorData (ref, kScrapFlavorTypeUnicode, &size, data) == noErr)
  222086. {
  222087. result = PlatformUtilities::convertUTF16ToString ((UniChar*) data);
  222088. }
  222089. juce_free (data);
  222090. }
  222091. return result;
  222092. }
  222093. bool AlertWindow::showNativeDialogBox (const String& title,
  222094. const String& bodyText,
  222095. bool isOkCancel)
  222096. {
  222097. Str255 tit, txt;
  222098. PlatformUtilities::copyToStr255 (tit, title);
  222099. PlatformUtilities::copyToStr255 (txt, bodyText);
  222100. AlertStdAlertParamRec ar;
  222101. ar.movable = true;
  222102. ar.helpButton = false;
  222103. ar.filterProc = 0;
  222104. ar.defaultText = (const unsigned char*)-1;
  222105. ar.cancelText = (const unsigned char*)((isOkCancel) ? -1 : 0);
  222106. ar.otherText = 0;
  222107. ar.defaultButton = kAlertStdAlertOKButton;
  222108. ar.cancelButton = 0;
  222109. ar.position = kWindowDefaultPosition;
  222110. SInt16 result;
  222111. StandardAlert (kAlertNoteAlert, tit, txt, &ar, &result);
  222112. return result == kAlertStdAlertOKButton;
  222113. }
  222114. const int KeyPress::spaceKey = ' ';
  222115. const int KeyPress::returnKey = kReturnCharCode;
  222116. const int KeyPress::escapeKey = kEscapeCharCode;
  222117. const int KeyPress::backspaceKey = kBackspaceCharCode;
  222118. const int KeyPress::leftKey = kLeftArrowCharCode;
  222119. const int KeyPress::rightKey = kRightArrowCharCode;
  222120. const int KeyPress::upKey = kUpArrowCharCode;
  222121. const int KeyPress::downKey = kDownArrowCharCode;
  222122. const int KeyPress::pageUpKey = kPageUpCharCode;
  222123. const int KeyPress::pageDownKey = kPageDownCharCode;
  222124. const int KeyPress::endKey = kEndCharCode;
  222125. const int KeyPress::homeKey = kHomeCharCode;
  222126. const int KeyPress::deleteKey = kDeleteCharCode;
  222127. const int KeyPress::insertKey = -1;
  222128. const int KeyPress::tabKey = kTabCharCode;
  222129. const int KeyPress::F1Key = 0x10110;
  222130. const int KeyPress::F2Key = 0x10111;
  222131. const int KeyPress::F3Key = 0x10112;
  222132. const int KeyPress::F4Key = 0x10113;
  222133. const int KeyPress::F5Key = 0x10114;
  222134. const int KeyPress::F6Key = 0x10115;
  222135. const int KeyPress::F7Key = 0x10116;
  222136. const int KeyPress::F8Key = 0x10117;
  222137. const int KeyPress::F9Key = 0x10118;
  222138. const int KeyPress::F10Key = 0x10119;
  222139. const int KeyPress::F11Key = 0x1011a;
  222140. const int KeyPress::F12Key = 0x1011b;
  222141. const int KeyPress::F13Key = 0x1011c;
  222142. const int KeyPress::F14Key = 0x1011d;
  222143. const int KeyPress::F15Key = 0x1011e;
  222144. const int KeyPress::F16Key = 0x1011f;
  222145. const int KeyPress::numberPad0 = 0x30020;
  222146. const int KeyPress::numberPad1 = 0x30021;
  222147. const int KeyPress::numberPad2 = 0x30022;
  222148. const int KeyPress::numberPad3 = 0x30023;
  222149. const int KeyPress::numberPad4 = 0x30024;
  222150. const int KeyPress::numberPad5 = 0x30025;
  222151. const int KeyPress::numberPad6 = 0x30026;
  222152. const int KeyPress::numberPad7 = 0x30027;
  222153. const int KeyPress::numberPad8 = 0x30028;
  222154. const int KeyPress::numberPad9 = 0x30029;
  222155. const int KeyPress::numberPadAdd = 0x3002a;
  222156. const int KeyPress::numberPadSubtract = 0x3002b;
  222157. const int KeyPress::numberPadMultiply = 0x3002c;
  222158. const int KeyPress::numberPadDivide = 0x3002d;
  222159. const int KeyPress::numberPadSeparator = 0x3002e;
  222160. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  222161. const int KeyPress::numberPadEquals = 0x30030;
  222162. const int KeyPress::numberPadDelete = 0x30031;
  222163. const int KeyPress::playKey = 0x30000;
  222164. const int KeyPress::stopKey = 0x30001;
  222165. const int KeyPress::fastForwardKey = 0x30002;
  222166. const int KeyPress::rewindKey = 0x30003;
  222167. AppleRemoteDevice::AppleRemoteDevice()
  222168. : device (0),
  222169. queue (0),
  222170. remoteId (0)
  222171. {
  222172. }
  222173. AppleRemoteDevice::~AppleRemoteDevice()
  222174. {
  222175. stop();
  222176. }
  222177. static io_object_t getAppleRemoteDevice() throw()
  222178. {
  222179. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  222180. io_iterator_t iter = 0;
  222181. io_object_t iod = 0;
  222182. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  222183. && iter != 0)
  222184. {
  222185. iod = IOIteratorNext (iter);
  222186. }
  222187. IOObjectRelease (iter);
  222188. return iod;
  222189. }
  222190. static bool createAppleRemoteInterface (io_object_t iod, void** device) throw()
  222191. {
  222192. jassert (*device == 0);
  222193. io_name_t classname;
  222194. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  222195. {
  222196. IOCFPlugInInterface** cfPlugInInterface = 0;
  222197. SInt32 score = 0;
  222198. if (IOCreatePlugInInterfaceForService (iod,
  222199. kIOHIDDeviceUserClientTypeID,
  222200. kIOCFPlugInInterfaceID,
  222201. &cfPlugInInterface,
  222202. &score) == kIOReturnSuccess)
  222203. {
  222204. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  222205. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  222206. device);
  222207. (void) hr;
  222208. (*cfPlugInInterface)->Release (cfPlugInInterface);
  222209. }
  222210. }
  222211. return *device != 0;
  222212. }
  222213. bool AppleRemoteDevice::start (const bool inExclusiveMode) throw()
  222214. {
  222215. if (queue != 0)
  222216. return true;
  222217. stop();
  222218. bool result = false;
  222219. io_object_t iod = getAppleRemoteDevice();
  222220. if (iod != 0)
  222221. {
  222222. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  222223. result = true;
  222224. else
  222225. stop();
  222226. IOObjectRelease (iod);
  222227. }
  222228. return result;
  222229. }
  222230. void AppleRemoteDevice::stop() throw()
  222231. {
  222232. if (queue != 0)
  222233. {
  222234. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  222235. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  222236. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  222237. queue = 0;
  222238. }
  222239. if (device != 0)
  222240. {
  222241. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  222242. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  222243. device = 0;
  222244. }
  222245. }
  222246. bool AppleRemoteDevice::isActive() const throw()
  222247. {
  222248. return queue != 0;
  222249. }
  222250. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  222251. {
  222252. if (result == kIOReturnSuccess)
  222253. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  222254. }
  222255. bool AppleRemoteDevice::open (const bool openInExclusiveMode) throw()
  222256. {
  222257. #if ! MACOS_10_2_OR_EARLIER
  222258. Array <int> cookies;
  222259. CFArrayRef elements;
  222260. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  222261. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  222262. return false;
  222263. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  222264. {
  222265. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  222266. // get the cookie
  222267. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  222268. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  222269. continue;
  222270. long number;
  222271. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  222272. continue;
  222273. cookies.add ((int) number);
  222274. }
  222275. CFRelease (elements);
  222276. if ((*(IOHIDDeviceInterface**) device)
  222277. ->open ((IOHIDDeviceInterface**) device,
  222278. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  222279. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  222280. {
  222281. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  222282. if (queue != 0)
  222283. {
  222284. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  222285. for (int i = 0; i < cookies.size(); ++i)
  222286. {
  222287. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  222288. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  222289. }
  222290. CFRunLoopSourceRef eventSource;
  222291. if ((*(IOHIDQueueInterface**) queue)
  222292. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  222293. {
  222294. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  222295. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  222296. {
  222297. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  222298. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  222299. return true;
  222300. }
  222301. }
  222302. }
  222303. }
  222304. #endif
  222305. return false;
  222306. }
  222307. void AppleRemoteDevice::handleCallbackInternal()
  222308. {
  222309. int totalValues = 0;
  222310. AbsoluteTime nullTime = { 0, 0 };
  222311. char cookies [12];
  222312. int numCookies = 0;
  222313. while (numCookies < numElementsInArray (cookies))
  222314. {
  222315. IOHIDEventStruct e;
  222316. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  222317. break;
  222318. if ((int) e.elementCookie == 19)
  222319. {
  222320. remoteId = e.value;
  222321. buttonPressed (switched, false);
  222322. }
  222323. else
  222324. {
  222325. totalValues += e.value;
  222326. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  222327. }
  222328. }
  222329. cookies [numCookies++] = 0;
  222330. static const char buttonPatterns[] =
  222331. {
  222332. 14, 7, 6, 5, 14, 7, 6, 5, 0,
  222333. 14, 8, 6, 5, 14, 8, 6, 5, 0,
  222334. 14, 12, 11, 6, 5, 0,
  222335. 14, 13, 11, 6, 5, 0,
  222336. 14, 9, 6, 5, 14, 9, 6, 5, 0,
  222337. 14, 10, 6, 5, 14, 10, 6, 5, 0,
  222338. 14, 6, 5, 4, 2, 0,
  222339. 14, 6, 5, 3, 2, 0,
  222340. 14, 6, 5, 14, 6, 5, 0,
  222341. 18, 14, 6, 5, 18, 14, 6, 5, 0,
  222342. 19, 0
  222343. };
  222344. int buttonNum = (int) menuButton;
  222345. int i = 0;
  222346. while (i < numElementsInArray (buttonPatterns))
  222347. {
  222348. if (strcmp (cookies, buttonPatterns + i) == 0)
  222349. {
  222350. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  222351. break;
  222352. }
  222353. i += strlen (buttonPatterns + i) + 1;
  222354. ++buttonNum;
  222355. }
  222356. }
  222357. #if JUCE_OPENGL
  222358. class WindowedGLContext : public OpenGLContext
  222359. {
  222360. public:
  222361. WindowedGLContext (Component* const component,
  222362. const OpenGLPixelFormat& pixelFormat_,
  222363. AGLContext sharedContext)
  222364. : renderContext (0),
  222365. pixelFormat (pixelFormat_)
  222366. {
  222367. jassert (component != 0);
  222368. HIViewComponentPeer* const peer = dynamic_cast <HIViewComponentPeer*> (component->getTopLevelComponent()->getPeer());
  222369. if (peer == 0)
  222370. return;
  222371. GLint attribs [64];
  222372. int n = 0;
  222373. attribs[n++] = AGL_RGBA;
  222374. attribs[n++] = AGL_DOUBLEBUFFER;
  222375. attribs[n++] = AGL_ACCELERATED;
  222376. attribs[n++] = AGL_RED_SIZE;
  222377. attribs[n++] = pixelFormat.redBits;
  222378. attribs[n++] = AGL_GREEN_SIZE;
  222379. attribs[n++] = pixelFormat.greenBits;
  222380. attribs[n++] = AGL_BLUE_SIZE;
  222381. attribs[n++] = pixelFormat.blueBits;
  222382. attribs[n++] = AGL_ALPHA_SIZE;
  222383. attribs[n++] = pixelFormat.alphaBits;
  222384. attribs[n++] = AGL_DEPTH_SIZE;
  222385. attribs[n++] = pixelFormat.depthBufferBits;
  222386. attribs[n++] = AGL_STENCIL_SIZE;
  222387. attribs[n++] = pixelFormat.stencilBufferBits;
  222388. attribs[n++] = AGL_ACCUM_RED_SIZE;
  222389. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  222390. attribs[n++] = AGL_ACCUM_GREEN_SIZE;
  222391. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  222392. attribs[n++] = AGL_ACCUM_BLUE_SIZE;
  222393. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  222394. attribs[n++] = AGL_ACCUM_ALPHA_SIZE;
  222395. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  222396. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  222397. attribs[n++] = AGL_SAMPLE_BUFFERS_ARB;
  222398. attribs[n++] = 1;
  222399. attribs[n++] = AGL_SAMPLES_ARB;
  222400. attribs[n++] = 4;
  222401. attribs[n++] = AGL_CLOSEST_POLICY;
  222402. attribs[n++] = AGL_NO_RECOVERY;
  222403. attribs[n++] = AGL_NONE;
  222404. renderContext = aglCreateContext (aglChoosePixelFormat (0, 0, attribs),
  222405. sharedContext);
  222406. aglSetDrawable (renderContext, GetWindowPort (peer->windowRef));
  222407. }
  222408. ~WindowedGLContext()
  222409. {
  222410. makeInactive();
  222411. aglSetDrawable (renderContext, 0);
  222412. aglDestroyContext (renderContext);
  222413. }
  222414. bool makeActive() const throw()
  222415. {
  222416. jassert (renderContext != 0);
  222417. return aglSetCurrentContext (renderContext);
  222418. }
  222419. bool makeInactive() const throw()
  222420. {
  222421. return (! isActive()) || aglSetCurrentContext (0);
  222422. }
  222423. bool isActive() const throw()
  222424. {
  222425. return aglGetCurrentContext() == renderContext;
  222426. }
  222427. const OpenGLPixelFormat getPixelFormat() const
  222428. {
  222429. return pixelFormat;
  222430. }
  222431. void* getRawContext() const throw()
  222432. {
  222433. return renderContext;
  222434. }
  222435. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  222436. {
  222437. GLint bufferRect[4];
  222438. bufferRect[0] = x;
  222439. bufferRect[1] = outerWindowHeight - (y + h);
  222440. bufferRect[2] = w;
  222441. bufferRect[3] = h;
  222442. aglSetInteger (renderContext, AGL_BUFFER_RECT, bufferRect);
  222443. aglEnable (renderContext, AGL_BUFFER_RECT);
  222444. }
  222445. void swapBuffers()
  222446. {
  222447. aglSwapBuffers (renderContext);
  222448. }
  222449. bool setSwapInterval (const int numFramesPerSwap)
  222450. {
  222451. return aglSetInteger (renderContext, AGL_SWAP_INTERVAL, (const GLint*) &numFramesPerSwap);
  222452. }
  222453. int getSwapInterval() const
  222454. {
  222455. GLint numFrames = 0;
  222456. aglGetInteger (renderContext, AGL_SWAP_INTERVAL, &numFrames);
  222457. return numFrames;
  222458. }
  222459. void repaint()
  222460. {
  222461. }
  222462. juce_UseDebuggingNewOperator
  222463. AGLContext renderContext;
  222464. private:
  222465. OpenGLPixelFormat pixelFormat;
  222466. WindowedGLContext (const WindowedGLContext&);
  222467. const WindowedGLContext& operator= (const WindowedGLContext&);
  222468. };
  222469. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  222470. const OpenGLPixelFormat& pixelFormat,
  222471. const OpenGLContext* const contextToShareWith)
  222472. {
  222473. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  222474. contextToShareWith != 0 ? (AGLContext) contextToShareWith->getRawContext() : 0);
  222475. if (c->renderContext == 0)
  222476. deleteAndZero (c);
  222477. return c;
  222478. }
  222479. void juce_glViewport (const int w, const int h)
  222480. {
  222481. glViewport (0, 0, w, h);
  222482. }
  222483. static int getAGLAttribute (AGLPixelFormat p, const GLint attrib)
  222484. {
  222485. GLint result = 0;
  222486. aglDescribePixelFormat (p, attrib, &result);
  222487. return result;
  222488. }
  222489. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  222490. OwnedArray <OpenGLPixelFormat>& results)
  222491. {
  222492. GLint attribs [64];
  222493. int n = 0;
  222494. attribs[n++] = AGL_RGBA;
  222495. attribs[n++] = AGL_DOUBLEBUFFER;
  222496. attribs[n++] = AGL_ACCELERATED;
  222497. attribs[n++] = AGL_NO_RECOVERY;
  222498. attribs[n++] = AGL_NONE;
  222499. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  222500. while (p != 0)
  222501. {
  222502. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  222503. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  222504. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  222505. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  222506. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  222507. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  222508. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  222509. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  222510. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  222511. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  222512. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  222513. results.add (pf);
  222514. p = aglNextPixelFormat (p);
  222515. }
  222516. }
  222517. #endif
  222518. END_JUCE_NAMESPACE
  222519. /********* End of inlined file: juce_mac_Windowing.mm *********/
  222520. #endif
  222521. #endif